working on it ...


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) {"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 = ""; //the right broker address
    		String queueName = "MyQueueName";
    		String address = "jms:jndi:dynamicQueues/" + queueName + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory&jndiConnectionFactoryName=ConnectionFactory&jndiURL=" + brokerAddr;
 "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);
    		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();
    	if (receiveTimeout != null)
    	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.
    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 = "";
    		try {
    			wsdlURL = new URL(location);
    		} catch (MalformedURLException e) {
    			log.error("Malformed Url:" + location + ", due to:" + e.getMessage());
            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
        <Service id="jsonProvider" class-name="org.apache.cxf.jaxrs.provider.json.JSONProvider">
            supportUnwrapped = true 
            serializeAsArray = true 

    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:
    public Endpoint endpoint() {
      EndpointImpl endpoint = new EndpointImpl(springBus(), weatherService());
      LoggingFeature logFeature = new LoggingFeature();
      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=""
        <import resource="classpath:META-INF/cxf/cxf.xml"/>
        <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
        <jaxws:endpoint id="helloWorldService" implementor="" address="/helloWorldService"/>

    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:
    public WeatherService weatherService() {
    	JaxWsProxyFactoryBean jaxWsFactory = new JaxWsProxyFactoryBean();
    	LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor();
    	LoggingOutInterceptor loggingOutInterceptor = new 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:
    > 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:
    >   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:
    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
    # 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
                                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
    # Java: Web Service setup
    ## The abstract service
         * _what_
         * @author <a href="mailto:???">vegaraa</a>
        public abstract class AbstractWebService {
    ## The service
          import no.difi.vefa.message.Messages;
          import no.difi.vefa.soap.common.WebServiceAttributes;
          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="">vegaasen</a>
          @WebService(targetNamespace = WebServiceAttributes.NAMESPACE, name = WebServiceAttributes.Services.VALIDATION)
                  style = SOAPBinding.Style.DOCUMENT,
                  use = SOAPBinding.Use.LITERAL,
                  parameterStyle = SOAPBinding.ParameterStyle.WRAPPED
          public class ValidationService extends AbstractWebService {
              @WebMethod(operationName = "validateInvoiceRequest")
                      name = "validateInvoiceResponse",
                      targetNamespace = WebServiceAttributes.NAMESPACE
              public Messages validateInvoice(
                      @WebParam(name = "invoice",
                              mode = WebParam.Mode.IN,
                              targetNamespace = WebServiceAttributes.NAMESPACE
                      ) @XmlElement(required = true) final String invoice) {
                  return null;
    # Jetty controller:
          import com.sun.jersey.spi.container.servlet.ServletContainer;
          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 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 {
              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.setSessionHandler(new SessionHandler());
            "Server now running on http://localhost:%s", port));
            "Access SOAP-services on http://localhost:%s/%s", port, WEB_SERVICE_URI));
            "Access REST-services on anywhereBut(http://localhost:%s/%s/*)", port, WEB_SERVICE_URI));
                  } catch (Exception e) {
                      LOG.error("Unable to start webserver", e);
                      LOG.error("The webServer was not started.");
              public void stop() {
                  if (webServer != null) {
                      if (!webServer.isRunning()) {
                      try {
                          while (!webServer.isStopped()) {
                      } 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);
                  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();
                  final ServletHolder cxfServletHolder = new ServletHolder(cxfServlet);
                  applicationContext.addServlet(cxfServletHolder, WS_PATH_SPEC);
        "Found request listners. Adding to the context.");
              private void initializeSoapServices() {
                  final ValidationService kdaIamWebService = new ValidationService();
              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