working on it ...

Filters

Explore Public Snippets

Sort by

Found 83 snippets matching: cxf

    public by cghersi  468645  7  8  2

    Load a SOAP endpoint with Apache CXF using JMS transport provided by Apache ActiveMQ

    This is an example on how to load a SOAP web service in order to be able to invoke its methods via JMS transport
    private JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    public MyInterface loadEndPoint() {
    	//try to load from local, if available:
    	boolean loadOK = false;
    	MyInterface result = null;
    	try {
    		Class<?> c = Class.forName("MyImplClass");
    		Method fact = c.getMethod("get");
    		result = (MyInterface) fact.invoke(null);
    		loadOK = true;
    	} catch (ClassNotFoundException e) {
    		log.info("Cannot find MyImplClass, redirecting to  remote access...", e);		
    	} catch (Exception e) {
    		log.warn("Error searching MyImplClass, , redirecting to remote access. Exception is " + e, e);
    	}
    		
    	//load remote endpoint:
    	if (!loadOK) {
    		//detect transport protocol for web services:
    		String brokerAddr = "127.0.0.1"; //the right broker address
    		String queueName = "MyQueueName";
    		String address = "jms:jndi:dynamicQueues/" + queueName + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory&jndiConnectionFactoryName=ConnectionFactory&jndiURL=" + brokerAddr;
    
    		log.info("Connecting to " + address);
    		String connString = "tcp://" + brokerAddr + ":61616";
    		ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory("Myusername", "Mypassword", connString);
    
    		SoapBindingConfiguration conf = new SoapBindingConfiguration();
    		//MTOM not supported! .net does not interoperate with cxf mtom impl.
    //		conf.setMtomEnabled(true);
    		conf.setVersion(Soap12.getInstance());
    		factory.setBindingConfig(conf);
    
    		factory.setServiceClass(MyInterface.class);
    		factory.setAddress(address);
    		factory.getFeatures().add(new WSAddressingFeature());
    		factory.getFeatures().add(getJMSConfigFeature(queueName, connFactory, 10000)));
    		Object resObj = factory.create();
    		if ((resObj != null) && (resObj instanceof MyInterface))
    			result = (MyInterface) resObj;
    		}
    
    		return result;
    	}
    }
    
    public static JMSConfigFeature getJMSConfigFeature(String queueName, ActiveMQConnectionFactory connectionFactory, Long receiveTimeout) {
    	JMSConfigFeature jmsConfigFeature = new JMSConfigFeature();
    	JMSConfiguration jmsConfig = new JMSConfiguration();
    	jmsConfig.setUseJms11(true);
    	jmsConfig.setTargetDestination(queueName);
    	jmsConfig.setConnectionFactory(connectionFactory);
    	if (receiveTimeout != null)
    		jmsConfig.setReceiveTimeout(receiveTimeout);
    	jmsConfigFeature.setJmsConfig(jmsConfig);
    	return jmsConfigFeature;
    }

    public by cghersi  3137  0  7  1

    Expose an Apache CXF Server in Java

    Apache CXF make VERY simple the exposure of a basic web service. Then, a lot of other feature may be added, like security, REST-ification, re-routing, etc.
    import javax.jws.WebService;
    
    @WebService(targetNamespace = "http://com.snip2code.api")
    public interface IMyAPI {
    
    	public boolean save(String values);
    
    	public String getStringVal();
    }
    
    
    @WebService(serviceName="MyAPIService", portName="apiName")
    public class MyAPI implements IMyAPI {
    	public boolean save(String values) {
    		//do stuff here...
    	}
    
    	public String getStringVal() {
    		return "Hello world";
    	}
    }
    

    public by cghersi  3172  1  7  0

    Consume a web service using Apache CXF client library

    Apache CXF may also be used to consume a web service. Obviously, the match of client and server both with CXF make the development very simple, as the same IMyAPI interface may be used as a contract between server and client.
    import java.net.MalformedURLException;
    import java.net.URL;
    
    
    public class CxfClientImpl {
    
        private static final QName SERVICE_NAME = new QName("http://com.snip2code.api", "MyAPIService");
        private static final QName PORT_NAME_DB = new QName("http://com.snip2code.api", "apiName");
    	
    	private IMyAPI portAPI;
    
    	public CxfClientImpl() {
    		//initialize web service utilities:
    		URL wsdlURL = null;
    		String location = "http://192.168.1.5:1572/MyAPIService";
    		try {
    			wsdlURL = new URL(location);
    		} catch (MalformedURLException e) {
    			log.error("Malformed Url:" + location + ", due to:" + e.getMessage());
    			return;
    		}
            Service service = Service.create(SERVICE_NAME);
            service.addPort(SERVICE_NAME, SOAPBinding.SOAP11HTTP_BINDING, wsdlURL.toString());
    
            portAPI = service.getPort(PORT_NAME, IMyAPI.class); 
    	}
    }
    

    external by cchacin  442  3  3  0

    TomEE + CXF Json configuration (org.apache.cxf.jaxrs.provider.json.JSONProvider)

    TomEE + CXF Json configuration (org.apache.cxf.jaxrs.provider.json.JSONProvider): resource.xml
    <resources>
        <Service id="jsonProvider" class-name="org.apache.cxf.jaxrs.provider.json.JSONProvider">
            dropRootElement=true 
            supportUnwrapped = true 
            dropCollectionWrapperElement=true 
            serializeAsArray = true 
        </Service>
    </resources>
    
    

    external by jonashackt  196  0  2  0

    Activate Logging of SOAP-Messages with Apache CXF seperately on exposed CXF-Endpoint

    Activate Logging of SOAP-Messages with Apache CXF seperately on exposed CXF-Endpoint: WebServiceConfiguration.java
    @Bean
    public Endpoint endpoint() {
      EndpointImpl endpoint = new EndpointImpl(springBus(), weatherService());
      endpoint.publish(SERVICE_NAME_URL_PATH);
      endpoint.setWsdlLocation("Weather1.0.wsdl");
      LoggingFeature logFeature = new LoggingFeature();
      logFeature.setPrettyLogging(true);
      logFeature.initialize(springBus());
      endpoint.getFeatures().add(logFeature);
      return endpoint;
    }
    
    

    external by avvero  59  0  1  0

    cxf-servlet.xml for CXF

    cxf-servlet.xml for CXF: cxf-servlet.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:jaxws="http://cxf.apache.org/jaxws"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
    		http://www.springframework.org/schema/beans/spring-beans.xsd
    		http://cxf.apache.org/jaxws
    		http://cxf.apache.org/schemas/jaxws.xsd">
        <import resource="classpath:META-INF/cxf/cxf.xml"/>
        <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
    
        <jaxws:endpoint id="helloWorldService" implementor="ru.dorofeev22.hospitalcare.ws.HelloWorldServiceBean" address="/helloWorldService"/>
    </beans>
    
    
    

    external by Jonas Hecht  114  0  2  0

    Configure SOAP-Message Logging in Apache CXF JaxWsProxyFactoryBean on Client Side

    Configure SOAP-Message Logging in Apache CXF JaxWsProxyFactoryBean on Client Side: Config.java
    @Bean
    public WeatherService weatherService() {
    	JaxWsProxyFactoryBean jaxWsFactory = new JaxWsProxyFactoryBean();
    	jaxWsFactory.setServiceClass(WeatherService.class);
    	jaxWsFactory.setAddress(buildUrl());
    
    	LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor();
    	loggingInInterceptor.setPrettyLogging(true);
    	LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor();
    	loggingOutInterceptor.setPrettyLogging(true);
    
    	jaxWsFactory.getInInterceptors().add(loggingInInterceptor);
    	jaxWsFactory.getOutInterceptors().add(loggingOutInterceptor);
    	jaxWsFactory.getInFaultInterceptors().add(loggingInInterceptor);
    	jaxWsFactory.getOutFaultInterceptors().add(loggingOutInterceptor);
    
    	return (WeatherService) jaxWsFactory.create();
    }
    
    
    

    external by Rafael T. C. Soares (A.K.A Tuelho)  91  0  1  0

    Apache CXF notes: differences between jaxws:endpointand

    Apache CXF notes: differences between jaxws:endpointand: apachecxf-notes-endpoints.md
    from https://access.redhat.com/documentation/en-US/Fuse_ESB_Enterprise/7.0/html-single/Web_Services_and_Routing_with_Camel_CXF/index.html:
    
    > Came CXF endpoints—which are instantiated using the cxf:cxfEndpoint XML element and are implemented by the Apache Camel project—are not to be confused with the Apache CXF JAX-WS endpoints—which are instantiated using the jaxws:endpoint XML element and are implemented by the Apache CXF project.
    
    > The cxf:cxfEndpoint element
    The cxf:cxfEndpoint element is used to define a WS endpoint that binds either to the start (consumer endpoint) or the end (producer endpoint) of a route. For example, to define the customer-ws WS endpoint referenced in the preceding route, you would define a cxf:cxfEndpoint element as follows:
    
    > 	Important
    Remember that the cxf:cxfEndpoint element and the jaxws:endpoint element use different XML schemas (although the syntax looks superficially similar). These elements bind a WS endpoint in different ways: the cxf:cxfEndpoint element instantiates and binds a WS endpoint to an Apache Camel route, whereas the jaxws:endpoint element instantiates and binds a WS endpoint to a Java class (using the JAX-WS mapping).
    
    more information: https://access.redhat.com/documentation/en-US/Red_Hat_JBoss_Fuse/6.2/html-single/Apache_Camel_Component_Reference/index.html#IDU-CXF
    
    ---
    
    >   Take care not to confuse the jaxws:endpoint element with the cxf:cxfEndpoint element, which you meet later in this guide: the jaxws:endpoint element is used to integrate a WS endpoint with a Java implementation class; whereas the cxf:cxfEndpoint is used to integrate a WS endpoint with a Camel route.
    
    
    

    external by Jonas Hecht  57  0  1  0

    Apache CXF Interceptor for Custom SoapFaults Part 2. - Checking for relevant Exceptions

    Apache CXF Interceptor for Custom SoapFaults Part 2. - Checking for relevant Exceptions: WeatherServiceXmlValidationInterceptor.java
    //...
    private boolean containsFaultIndicatingNotSchemeCompliantXml(Throwable faultCause, String faultMessage) {
    	if(faultCause instanceof UnmarshalException
        	// 1.) If the root-Element of the SoapBody is syntactically correct, but not scheme-compliant,
    		// 		there is no UnmarshalException and we have to look for
    		// 2.) Missing / lead to Faults without Causes, but to Messages like "Unexpected wrapper element XYZ found. Expected"
    		// 		One could argue, that this is syntactically incorrect, but here we just take it as Non-Scheme-compliant
        	|| isNotNull(faultMessage) && faultMessage.contains("Unexpected wrapper element")) {
    		return true;
    	}
    	return false;
    }
    
    private boolean containsFaultIndicatingSyntacticallyIncorrectXml(Throwable faultCause, String faultMessage) {
    	if(faultCause instanceof WstxException
    		// If Xml-Header is invalid, there is a wrapped Cause in the original Cause we have to check
    		|| isNotNull(faultCause) && faultCause.getCause() instanceof WstxUnexpectedCharException
        	|| faultCause instanceof IllegalArgumentException) {
    		return true;
    	}
    	return false;
    }
    //...
    
    

    external by vegaasen  57  0  1  0

    Simple example on how to get CXF to work with Jetty and stuff

    Simple example on how to get CXF to work with Jetty and stuff: cxf-standalone-jetty.md
    CXF Standalone
    ==============
    
    # Introduction
    
    This is a simple example on how to get Jetty & CXF to play along with an embedded mind. Quite simple example :-). Please note that all of the stuff here is an excertp :-).
    
    # Maven configration
    
          <dependencies>
                <!--DIFI-->
                <dependency>
                    <groupId>no.difi.vefa</groupId>
                    <artifactId>validate-lib</artifactId>
                    <version>1.0.0</version>
                </dependency>
                <!--JETTY-->
                <dependency>
                    <groupId>org.eclipse.jetty</groupId>
                    <artifactId>jetty-server</artifactId>
                    <version>${server.jetty.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.eclipse.jetty</groupId>
                    <artifactId>jetty-webapp</artifactId>
                    <version>${server.jetty.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.eclipse.jetty</groupId>
                    <artifactId>jetty-io</artifactId>
                    <version>${server.jetty.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.eclipse.jetty</groupId>
                    <artifactId>jetty-util</artifactId>
                    <version>${server.jetty.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.eclipse.jetty</groupId>
                    <artifactId>jetty-servlet</artifactId>
                    <version>${server.jetty.version}</version>
                </dependency>
                <!--SERVLET-->
                <dependency>
                    <groupId>javax.servlet</groupId>
                    <artifactId>javax.servlet-api</artifactId>
                    <version>${server.javax.servlet-api.version}</version>
                </dependency>
                <!--CXF-->
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-rt-frontend-jaxws</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-rt-transports-http</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-web</artifactId>
                    <version>4.1.5.RELEASE</version>
                </dependency>
            </dependencies>
            
                <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-shade-plugin</artifactId>
                        <version>2.1</version>
                        <configuration>
                            <createDependencyReducedPom>true</createDependencyReducedPom>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.vegaasen.web.run.StartApplication</mainClass>
                                    <manifestEntries>
                                        <Specification-Version>${project.parent.version}</Specification-Version>
                                        <Specification-Title>${name}</Specification-Title>
                                        <Specification-Vendor>${manifest.spec-vendor}</Specification-Vendor>
                                    </manifestEntries>
                                </transformer>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/cxf/bus-extensions.txt</resource>
                                </transformer>
                            </transformers>
                        </configuration>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>shade</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
    
    # Java: Web Service setup
    
    ## The abstract service
    
        package no.difi.vefa.soap.ws.abs;
        
        /**
         * _what_
         *
         * @author <a href="mailto:???">vegaraa</a>
         */
        public abstract class AbstractWebService {
        }
    
    ## The service
    
          package no.difi.vefa.soap.ws;
          
          import no.difi.vefa.message.Messages;
          import no.difi.vefa.soap.common.WebServiceAttributes;
          import no.difi.vefa.soap.ws.abs.AbstractWebService;
          
          import javax.jws.WebMethod;
          import javax.jws.WebParam;
          import javax.jws.WebResult;
          import javax.jws.WebService;
          import javax.jws.soap.SOAPBinding;
          import javax.xml.bind.annotation.XmlElement;
          
          /**
           * ..what..
           *
           * @author <a href="mailto:vegaasen@gmail.com">vegaasen</a>
           */
          @WebService(targetNamespace = WebServiceAttributes.NAMESPACE, name = WebServiceAttributes.Services.VALIDATION)
          @SOAPBinding(
                  style = SOAPBinding.Style.DOCUMENT,
                  use = SOAPBinding.Use.LITERAL,
                  parameterStyle = SOAPBinding.ParameterStyle.WRAPPED
          )
          public class ValidationService extends AbstractWebService {
          
              @WebMethod(operationName = "validateInvoiceRequest")
              @WebResult(
                      name = "validateInvoiceResponse",
                      targetNamespace = WebServiceAttributes.NAMESPACE
              )
              public Messages validateInvoice(
                      @WebParam(name = "invoice",
                              mode = WebParam.Mode.IN,
                              targetNamespace = WebServiceAttributes.NAMESPACE
                      ) @XmlElement(required = true) final String invoice) {
                  System.out.println("Heisann");
                  return null;
              }
          }
    
    # Jetty controller:
    
          package no.difi.vefa.soap.run.container;
          
          import com.sun.jersey.spi.container.servlet.ServletContainer;
          import no.difi.vefa.soap.ws.ValidationService;
          import no.difi.vefa.soap.ws.abs.AbstractWebService;
          import org.apache.cxf.Bus;
          import org.apache.cxf.BusFactory;
          import org.apache.cxf.bus.CXFBusFactory;
          import org.apache.cxf.transport.servlet.CXFServlet;
          import org.eclipse.jetty.server.Connector;
          import org.eclipse.jetty.server.Server;
          import org.eclipse.jetty.server.ServerConnector;
          import org.eclipse.jetty.server.session.SessionHandler;
          import org.eclipse.jetty.servlet.ServletContextHandler;
          import org.eclipse.jetty.servlet.ServletHolder;
          import org.slf4j.Logger;
          import org.slf4j.LoggerFactory;
          
          import javax.xml.ws.Endpoint;
          import java.util.ArrayList;
          import java.util.List;
          
          /**
           * This controls the application server itself. It exposes two key methods ; stop() + start().
           *
           * @author <a href="????">vegaraa</a>
           */
          public enum JettyContainer {
          
              INSTANCE;
          
              private static final Logger LOG = LoggerFactory.getLogger(JettyContainer.class);
              private static final String SLASH = "/";
              private static final String CONTEXT_PATH = SLASH;
              private static final String PATH_SPEC = "/*";
              private static final String ENDPOINT_URI = "iam", WEB_SERVICE_URI = "services";
              private static final String WS_PATH_SPEC = "/" + WEB_SERVICE_URI + "/*";
          
              private Server webServer;
              private Bus bus;
          
              public void start(int port) {
                  try {
                      if (port <= 0) {
                          port = ContainerDefaults.DEFAULT_PORT;
                      }
                      webServer = new Server();
                      webServer.setConnectors(assembleConnectors(port, webServer));
                      final ServletContextHandler applicationContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
                      applicationContext.setContextPath(CONTEXT_PATH);
                      applicationContext.setSessionHandler(new SessionHandler());
                      configureCxf(applicationContext);
                      webServer.setHandler(applicationContext);
                      webServer.start();
                      LOG.info(String.format("Server now running on http://localhost:%s", port));
                      LOG.info(String.format("Access SOAP-services on http://localhost:%s/%s", port, WEB_SERVICE_URI));
                      LOG.info(String.format("Access REST-services on anywhereBut(http://localhost:%s/%s/*)", port, WEB_SERVICE_URI));
                  } catch (Exception e) {
                      LOG.error("Unable to start webserver", e);
                      stop();
                      LOG.error("The webServer was not started.");
                  }
              }
          
              public void stop() {
                  if (webServer != null) {
                      if (!webServer.isRunning()) {
                          return;
                      }
                      try {
                          while (!webServer.isStopped()) {
                              webServer.stop();
                          }
                      } catch (Exception e) {
                          LOG.error("Unable to stop the running server.", e);
                      }
                  }
              }
          
              protected Connector[] assembleConnectors(final int port, final Server server) {
                  if (port == 0) {
                      throw new IllegalArgumentException("The arguments is null.");
                  }
                  final List<Connector> connectors = new ArrayList<>();
                  final ServerConnector httpConnector = new ServerConnector(server);
                  httpConnector.setPort(port);
                  connectors.add(httpConnector);
                  if (connectors.isEmpty()) {
                      throw new RuntimeException("No controllers defined, even though they were expected to be.");
                  }
                  return connectors.toArray(new Connector[connectors.size()]);
              }
          
              protected void configureCxf(final ServletContextHandler applicationContext) {
                  System.setProperty(BusFactory.BUS_FACTORY_PROPERTY_NAME, CXFBusFactory.class.getName());
                  bus = BusFactory.getDefaultBus(true);
                  final CXFServlet cxfServlet = new CXFServlet();
                  cxfServlet.setBus(bus);
                  final ServletHolder cxfServletHolder = new ServletHolder(cxfServlet);
                  cxfServletHolder.setName(WEB_SERVICE_URI);
                  cxfServletHolder.setForcedPath(WEB_SERVICE_URI);
                  applicationContext.addServlet(cxfServletHolder, WS_PATH_SPEC);
                  LOG.info("Found request listners. Adding to the context.");
                  BusFactory.setDefaultBus(bus);
                  initializeSoapServices();
              }
          
              private void initializeSoapServices() {
                  final ValidationService kdaIamWebService = new ValidationService();
                  publishService(kdaIamWebService);
              }
          
              private void publishService(final AbstractWebService service) {
                  Endpoint.publish(String.format("%s%s", SLASH, ENDPOINT_URI), service);
              }
          
          }
    
    # Conclusion
    
    It was quite easy :) Good luck!
    
    
    • Public Snippets
    • Channels Snippets