d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

Consuming SOAP Service With Apache CXF and Spring

Apache CXF and Spring Boot.

Soap web services are not popular anymore but if you are working with old applications you probably still have to deal with soap web services. I am going to give you an example of how to consume a soap service with CXF, how to make a configuration for it, and how to log requests and responses to it.

A Simple Web Service

Before I can consume a web service, I need a simple web service to work with. For the project, I am going to use spring boot version 2.5.0 and java 11. You can use another version if you like, it does not matter as long as the versions are not too old. You can easily create a spring boot project with a spring initializer. If you use maven, pom.xml should be like this. If you use Java 8, you do not need to have a “jaxb-runtime” dependency.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cfxconsumer</groupId>
    <artifactId>soapcxfconsumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>soapcxfconsumer</name>
    <description>Demo spring project for soap consuming with apache cxf</description>
    <properties>
        <java.version>11</java.version>
        <cxf.version>3.3.3</cxf.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-features-logging</artifactId>
            <version>${cxf.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

First of all, I will create an interface for my simple web service like below. As you see, it will get a single string parameter and returns a string response.

@WebService
public interface HelloWorldWS {
    @WebMethod
    String createMessage(@WebParam(name = "createMessageRequest", mode = WebParam.Mode.IN) String name);
}

And, now, I need an implementation of this interface. It will just add “Hello” in front of the input parameter and return it. 

@Component
public class HelloWorldWSImpl implements HelloWorldWS{
    @Override
    public String createMessage(String name){
        return "Hello "+name;
    }
}

This is not the topic of this article, that’s why I am not going into detail with CXF configuration. You just have to configure CXF like below.   

import javax.xml.ws.Endpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import com.cfxconsumer.soapcxfconsumer.ws.HelloWorldWS;

@Configuration
@ImportResource({ "classpath:META-INF/cxf/cxf.xml" })
public class CxfWebServiceConfig {
    @Autowired
    private Bus cxfBus;

    @Bean
    public ServletRegistrationBean cxfServlet() {
        org.apache.cxf.transport.servlet.CXFServlet cxfServlet = new org.apache.cxf.transport.servlet.CXFServlet();
        ServletRegistrationBean servletDef = new ServletRegistrationBean<>(cxfServlet, "/ws/*");
        servletDef.setLoadOnStartup(1);
        return servletDef;
    }

    @Bean
    public Endpoint helloWorldWebService(HelloWorldWS helloWorldWS) {
        EndpointImpl endpoint = new EndpointImpl(cxfBus, helloWorldWS);
        endpoint.setAddress("/helloWorldWS");
        endpoint.publish();
        return endpoint;
    }
}

Now, if I start my spring boot application, I can reach WSDL of my simple web service like this.

I will just write a test class to test my simple web service as below:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class HelloWorldWSIT {

    private HelloWorldWS testClient;

    @BeforeEach
    public void init(){
        JaxWsProxyFactoryBean jaxWsProxyFactory = new JaxWsProxyFactoryBean();
        jaxWsProxyFactory.setServiceClass(HelloWorldWS.class);
        jaxWsProxyFactory.setServiceName(new QName(
                "http://ws.soapcxfconsumer.cfxconsumer.com/",
                "HelloWorldWSImplService"
        ));
        jaxWsProxyFactory.setAddress("http://localhost:8080/ws/helloWorldWS");
        testClient = jaxWsProxyFactory.create(HelloWorldWS.class);
    }

    @Test
    void name() {
        System.out.println("soap response: "+ testClient.createMessage("General Kenobi"));
    }
}

As I run it, I see the below output. My web service works, now let’s get to the point.

Web Service Client Consumer Configuration

If you like, you can start a new project like the previous one to consume the HelloWorld web service. Before consuming a web service, I need a client jar file. I am going to use wsimport utility to create a client jar file, with a command like this; 

wsimport -clientjar helloWorldWSClient.jar “http://localhost:8080/ws/helloWorldWS?wsdl”

Client jar is created and I need to add it to the project as a dependency. After that, I can create a CXF configuration for it like below:

import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import org.apache.cxf.ext.logging.LoggingFeature;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HelloWorldWSClientConfig {

    @Bean
    public LoggingFeature loggingFeature() {
        LoggingFeature loggingFeature = new LoggingFeature();
        loggingFeature.setPrettyLogging(true);
        return loggingFeature;
    }

    @Bean(name = "helloWorldWSClient")
    public HelloWorldWS helloWorldWSService(@Autowired LoggingFeature loggingFeature){
        JaxWsProxyFactoryBean fb = new JaxWsProxyFactoryBean();
        fb.setServiceClass(HelloWorldWS.class);
        fb.setWsdlLocation("/META-INF/wsdl/HelloWorldWSService.wsdl");
        fb.setServiceName(new QName("http://ws.soapcxfconsumer.cfxconsumer.com/",
                "HelloWorldWSImplService"));

        Map<String, Object> properties = fb.getProperties();
        if(properties == null){
            properties = new HashMap<>();
        }

        properties.put("javax.xml.ws.client.connectionTimeout", 5000);
        properties.put("javax.xml.ws.client.receiveTimeout", 3000);

        fb.setProperties(properties);

        fb.getFeatures().add(loggingFeature);

        HelloWorldWS theService = (HelloWorldWS) fb.create();
        BindingProvider bindingProvider = (BindingProvider) theService;
        bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8080/ws/helloWorldWS");

        return theService;
    }
}

I created a bean name as “helloWorldWSClient,” as you see. HelloWorldWS.class is the service class included in the client jar file. WSDL location is the path of the WSDL file in the jar file. serviceName consists of namespace and port name. You can put some configuration parameters into the properties map (like connection and socket timeout values). And the last thing to do is to set the endpoint of the service.

The LoggingFeature is required to log outgoing requests and incoming responses. If you want to log them you just have to put the below line into the application.properties file.

logging.level.org.apache.cxf.services = INFO

This will cause all CXF clients to log requests and responses. If you want to log only a specific service, then you need to have log configs like below. 

logging.level.org.apache.cxf.services.HelloWorldWS.REQ_OUT = INFO
logging.level.org.apache.cxf.services.HelloWorldWS.RESP_IN = INFO

As it is obvious, you can use the service class name to log a specific service.

Consume Web Service

As the configuration is done, I am ready to call and consume our soap service. First of all, I am going to create a consumer service like below. 

@Service
public class HelloWorldWSConsumerService {
    private final HelloWorldWS helloWorldWSClient;

    public HelloWorldWSConsumerService(HelloWorldWS helloWorldWS){
        this.helloWorldWSClient = helloWorldWS;
    }

    public String callHelloWorld(String name){
        return helloWorldWSClient.createMessage(name);
    }
}

Now, I need to test this consumer service. I am going to write a simple test class with a simple assertion. 

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloWorldWSConsumerServiceIT {
    @Autowired
    private HelloWorldWSConsumerService helloWorldWSConsumerService;

    @Test
    void testCallHelloWorld() {
        Assertions.assertEquals("Hello General Kenobi",
                helloWorldWSConsumerService.callHelloWorld("General Kenobi"));
    }
}

After running this test, let’s look at the console output. 

Code screenshot.

That’s all.

Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this