My linux world » Java Spring – CXF

Java Spring - CXF


Contents

Prerequistes

Please read : Java spring – quickstart

Dependencies

If you use maven, please add this to your pom.xml:

<dependencies>
(...)
 
	<!-- apache cxf -->
	<dependency>
		<groupId>org.apache.cxf</groupId>
		<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
		<version>${cxf-spring-boot.version}</version>
	</dependency>
 
	<dependency>
		<groupId>org.apache.cxf</groupId>
		<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
		<version>${cxf-spring-boot.version}</version>
	</dependency>
 
	<dependency>
		<groupId>org.apache.cxf</groupId>
		<artifactId>cxf-rt-rs-service-description-swagger</artifactId>
		<version>${cxf-spring-boot.version}</version>
	</dependency>
 
	<!-- jackson rest providers -->
	<dependency>
		<groupId>com.fasterxml.jackson.jaxrs</groupId>
		<artifactId>jackson-jaxrs-json-provider</artifactId>
		<version>${jackson-jaxrs.version}</version>
	</dependency>
 
	<dependency>
		<groupId>com.fasterxml.jackson.jaxrs</groupId>
		<artifactId>jackson-jaxrs-xml-provider</artifactId>
		<version>${jackson-jaxrs.version}</version>
	</dependency>
 
	<dependency>
		<groupId>com.fasterxml.jackson.jaxrs</groupId>
		<artifactId>jackson-jaxrs-yaml-provider</artifactId>
		<version>${jackson-jaxrs.version}</version>
	</dependency>
 
(...)
</dependencies>

Server Part

Model

Let’s deal with the following model:

public class User {
 
	private String firstName;
	private String lastName;
 
	/**
	 * Default constructor.
	 */
	public User(){}
 
	/**
	 * @param firstName
	 * @param lastName
	 */
	public User(String firstName, String lastName) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
	}
 
// getters and setters.
}

WebServices

Let’s create two web services:

The interface :

import javax.jws.WebService;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
 
@WebService
public interface MyPrettyWebService {
	@GET
	@Path("/sayHelloByString/{message}") 
	@Consumes({"application/json", "application/xml", "application/yaml"}) 
	@Produces({"application/json", "application/xml", "application/yaml"})
        String sayHelloByString(@PathParam("message") String message);
 
	@GET
	@Path("/getDefaultUser")
	@Produces({"application/json", "application/xml", "application/yaml"})
	User getDefaultUser();	
}

The implementation :

@WebService(endpointInterface = "net.rabahi.java.jee.spring.service.HelloWorld")
@Service
public class MyPrettyWebServiceImpl implements MyPrettyWebService {
 
	public String sayHelloByString(String message) {
		return "Hello " + message;
	}
 
	@Override
	public User getDefaultUser() {
		User user = new User();
		user.setFirstName("John");
		user.setLastName("Doe");
		return user;
	}
}

Configuration

In WebConfig, add servlet CXFServlet and map it to “/services/*”:

public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
(..)
 
    /* (non-Javadoc)
     * @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#onStartup(javax.servlet.ServletContext)
     */
    @Override
    public void onStartup(ServletContext container) {
        // Method implementation
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MainConfig.class);
        container.addListener(new ContextLoaderListener(context));
 
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new CXFServlet());
        dispatcher.addMapping("/services/*");
    }
}

And declare your rest and soap endpoints :

@Configuration
@ImportResource({ "classpath:META-INF/cxf/cxf.xml", "classpath:META-INF/cxf/cxf-servlet.xml" })
 
public class WebServerConfig {
    @Autowired
    private Bus bus;
 
    @Bean
    public Endpoint soapEndPoint() {
	EndpointImpl endpoint = new EndpointImpl(bus, new HelloWorldImpl());
	endpoint.publish("/soap");
	return endpoint;
    }
 
    @Bean
    public Server restEndPoint() {
        JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
        endpoint.setBus(bus);
        endpoint.setAddress("/rest");
        endpoint.setServiceBeans(Arrays.<Object>asList(new MyPrettyWebServiceImpl()));
        endpoint.setFeatures(Arrays.asList(new Swagger2Feature()));
 
        List<Object> providers = new ArrayList<>();
        providers.add(new JacksonJaxbJsonProvider());
        providers.add(new JacksonJaxbXMLProvider());
        providers.add(new JacksonJaxbYAMLProvider());
        endpoint.setProviders(providers);
 
        return endpoint.create();
    }
}

Client Part

Configuration

Create the restClient and soapClient beans:

@Configuration
public class ClientConfiguration {
 
        @Bean(name = "soapClient")
	public MyPrettyWebService proxyFactoryBean() {
		JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean();
		proxyFactory.setServiceClass(HelloWorld.class);
		proxyFactory.setAddress("http://localhost:8080/services/soap");
		return proxyFactory.create();
	}
 
        @Bean(name = "restClient")
	public WebClient restClient() {
		return WebClient.create("http://localhost:8080/services/rest",
				Arrays.asList(
					jacksonJsonProvider(),
					jacksonXMLProvider(),
					jacksonYAMLProvider()
				));
	}
}

Use SOAP Client

public class MyImplentation {
 
  private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
  private MyPrettyWebService myPrettyWebService = (MyPrettyWebService) context.getBean("soapClient");
 
  public void method(){
     String response = myPrettyWebService.sayHelloByString("john");
     User user = myPrettyWebService.getDefaultUser();
  }
}

Use REST Client

public class MyImplentation {
 
  private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
  private WebClient webclient = (WebClient ) context.getBean("restClient");
 
  public void method(){
     // sayHelloByString
     String message="john";
     webclient.path("/sayHelloByString/"+message).accept(MediaType.APPLICATION_JSON_TYPE);
     String response = webclient.get(String.class);
 
     // getDefaultUser
     webclient.path("/getDefaultUser").accept(MediaType.APPLICATION_JSON_TYPE);
     User user= webclient.get(User.class);
  }
}

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.