Learn in Java
 


   

Restful WebService using CXF

 
Any service which follows the REST(REpresentational State Transfer) architectural pattern is said to be restful. Let us look at an example on how to create a simple restful webservice using CXF and Spring. The following software has been used for this tutorial :
    1. Apache Maven 3.0.4
    2. Spring 3.2.6
    3. Apache CXF 3.0.3
    4. Jetty 6.1.10 or Tomcat 7
    

First, we need to create a basic CXF web project structure. For this, use the below command :

mvn archetype:generate -DgroupId=com.learninjava -DartifactId=cxfjaxrsws -DarchetypeArtifactId=org.apache.cxf.archetype:cxf-jaxrs-service -DinteractiveMode=false

Remember:
1. With the new maven version, the above command might not work. In such case, you can simply use the below command :
      
      mvn archetype:generate
      
      then select the appropriate archetype serial number from the list provided. On our development environment, the serial number  
      for our tutorial is,
      
      514: remote -> org.apache.cxf.archetype:cxf-jaxrs-service (Simple CXF JAX-RS webapp service using Spring configuration)
      
2. If you are too busy ;) and in a hurry, you can actually create a restful webservice without even writing a single line of code. 
      
      See here :
      http://java-hub.blogspot.in/2015/01/restful-webservice-using-cxf-and-maven.html.Remember, you will just get an unpolished 
	  version of the project with out concepts being explained. So, we recommend you going through the below tutorial.

If the command is successful, your basic project structure should look similar to the below :

cxfjaxrsws
|   pom.xml
|
+---.settings
+---src
|   +---main
|   |   +---java
|   |   |   +---com
|   |   |       +---learninjava
|   |   |               HelloWorld.java
|   |   |               JsonBean.java
|   |   |
|   |   +---webapp
|   |       +---META-INF
|   |       |       MANIFEST.MF
|   |       |
|   |       +---WEB-INF
|   |               beans.xml
|   |               web.xml
|   |
|   +---test
|       +---java
|           +---com
|               +---learninjava
|                       HelloWorldIT.java

Remember:
You CANNOT use the Test case files provided by this archetype without modification because if you do so, you cannot run the unit 
test file(client). This is because the maven surefire plugin expects the test file names in the following patterns :

    **/Test*.java
    **/*Test.java
    **/*TestCase.java
    
but the archetype creates the Test case file as HelloWorldIT.java

Maven does not consider this file(HelloWorldIT.java) as a test case as there is no "Test" string in the file name. For this purpose, we have renamed the test file to HelloAngryWorldTest.java to make sure the junit tests are run properly and also there were many changes made to pom.xml. For instance, we have removed some unused configurations and refactored the configurations for easy and better understanding.

For your convenience, we have provided configurations for running the webservice on both Jetty and Tomcat servers.

First, let us take a look at tomcat configuration. Later we will see about jetty configuration. There is a cool feature in jetty that attracts many developers. we will see what is it later in this tutorial.

Using Tomcat :

1. Change the default pom.xml as below :

<?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 http://maven.apache.org/maven-v4_0_0.xsd">
    
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.learninjava</groupId>
    <artifactId>cxfjaxrsws</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Simple CXF JAX-RS webapp service using spring configuration</name>
    <description>Simple CXF JAX-RS webapp service using spring configuration</description>
    
    <organization>
        <name>Learn in Java</name>
        <url>http://www.learninjava.com/</url>
    </organization>
    <!-- Change the version numbers or other configurations here -->
    <properties>
        <cxf.version>3.0.3</cxf.version>
        <jackson.version>1.8.6</jackson.version>
        <spring.version>3.2.6.RELEASE</spring.version>
        <junit.version>4.11</junit.version>
        <surefire.version>2.10</surefire.version>
        <tomcat7.version>2.0</tomcat7.version>
        <compiler.srcversion>1.6</compiler.srcversion>
        <compiler.tgtversion>1.6</compiler.tgtversion>
        
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <port.number>9090</port.number>
        <service.url>http://localhost:${port.number}/jaxrs-service</service.url>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-client</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-jaxrs</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                
                <!-- Optional plugin, This is added to specify service.url in pom.xml itself -->
                <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-surefire-plugin</artifactId>
                  <version>${surefire.version}</version>
                  <configuration>
                    <argLine>-Dservice.url=${service.url}</argLine>
                  </configuration>
                </plugin>
                
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>${tomcat7.version}</version>
                    <executions>
                        <execution>
                            <id>default-cli</id>
                            <goals>
                                <goal>run</goal>
                            </goals>
                            <configuration>
                                <port>${port.number}</port>
                                <path>/jaxrs-service</path>
                                <useSeparateTomcatClassLoader>true</useSeparateTomcatClassLoader>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>${compiler.srcversion}</source>
                        <target>${compiler.tgtversion}</target>
                    </configuration>
                </plugin>
                
                <!-- Optional plugin, This is added to create an eclipse compatible project. To do it, use : mvn eclipse:eclipse -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-eclipse-plugin</artifactId>
                    <configuration>
                        <projectNameTemplate>[artifactId]-[version]</projectNameTemplate>
                        <wtpmanifest>true</wtpmanifest>
                        <wtpapplicationxml>true</wtpapplicationxml>
                        <wtpversion>2.0</wtpversion>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

You will notice that there are 4 important plugins in the pom.xml out of which 2 are optional. We will see each of them in detail :

maven-surefire-plugin -  [Optional] This plugin is added to specify the service.url in the pom.xml itself. We will see its 
usage while running the web service client.
tomcat7-maven-plugin - This is the tomcat plugin where will be deploy our angry world webservice.
maven-compiler-plugin - This plugin specifies the Java compiler source and target versions.
maven-eclipse-plugin - [Optional] This plugin is used to generate the .classpath and .project files which enables us to use 
this project in eclipse.

The other important sections includes dependencies and properties which are used to specify the jar file dependencies and properties respectively.


 

2. Renamed HelloWorld.java to HelloAngryWorld.java :

package com.learninjava;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

/**
 * @author learninjava.com
 * @see www.learninjava.com
 */
@Path("/helloAngryWorld")
public class HelloAngryWorld {

    @GET
    @Path("/echo/{input}")
    @Produces("text/plain")
    public String ping(@PathParam("input") String input) {
        return input;
    }

    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("/jsonBean")
    public Response modifyJson(JsonBean input) {
        input.setVal2(input.getVal1());
        return Response.ok().entity(input).build();
    }
}

This is the actual webservice source file, so lets take a look at it.

This webservice exposes two methods one of type plain text and other of type JsonBean. These methods uses some important annotations:

@Path annotation at class level specifies the context path to access this webservice.
@Path annotation at method level specifies the path to access the actual method in the webservice.
@PathParam annotation is used to accept input from the request URL path specified by @Path.
@Produces annotation is used to specify the return type of the method.
@Consumes annotation is used to specify the return type accepted as input to a method.

For a complete listing of annotations refer : http://java-hub.blogspot.in/2015/01/jax-rs-annotations.html

3. JsonBean.java :

package com.learninjava;

/**
 * @author learninjava.com
 * @see www.learninjava.com
 */
public class JsonBean {
    private String val1;
    private String val2;

    public String getVal1() {
        return val1;
    }

    public void setVal1(String val1) {
        this.val1 = val1;
    }

    public String getVal2() {
        return val2;
    }

    public void setVal2(String val2) {
        this.val2 = val2;
    }

}

4. beans.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:jaxrs="http://cxf.apache.org/jaxrs" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
    
    <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <context:property-placeholder/>
    <context:annotation-config/>
    <bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer"/>
    <bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"/>

    <jaxrs:server id="services" address="/">
        <jaxrs:serviceBeans>
            <bean class="com.learninjava.HelloAngryWorld"/>
        </jaxrs:serviceBeans>
        <jaxrs:providers>
            <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
        </jaxrs:providers>
    </jaxrs:server>

</beans>

PreferencesPlaceholderConfigurer and ServletContextPropertyPlaceholderConfigurer are used to handle properties files. See references section at the bottom of this tutorial for more information.

The beans.xml has 2 important tags under <jaxrs:server> tag which is the most important tag in this xml.

<jaxrs:serviceBeans> - This lists all the service beans which are nothing but the services we want to make as a webservice

<jaxrs:providers> - This is to specify the provider which are used to extend the JAX-RS runtime. There are 3 types of providers: Entity providers, Context providers and Exception providers. Here Jackson is an alternative provider is used. Refer to the JAX-RS specification link provided in references section for more info. Please note that this is an optional configuration as there is already a default Json provider included with JAX-RS called Jettison(org.apache.cxf.jaxrs.provider.json.JSONProvider).

Observe that names of the entities like service, server etc. These are in conjunction with REST architecture. You will find these names to be different when dealing with JAX-WS.

5. web.xml :

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
    
    <display-name>JAX-RS Simple Service</display-name>
    <description>JAX-RS Simple Service</description>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/beans.xml</param-value>
    </context-param>
    <listener>
        <listener-class>
              org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    
    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>
              org.apache.cxf.transport.servlet.CXFServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

The configurations in web.xml are straighforward. CXFServlet is the actual servlet that reads the xml configurations and makes the service beans as webservices and handles the requests and responses to the exposed services.

ContextLoaderListener is the ROOT web application context that is used by spring.

Once the above files are ready, type the below command to start the tomcat container :

mvn clean package -DskipTests=true tomcat7:run

This command cleans the target directory, compiles, builds war and deploys it to tomcat. Notice that we used skipTests = true switch. This is to make sure that the test case are not run before the server starts.

Navigate to the URL :

http://localhost:9090/jaxrs-service/helloAngryWorld/echo/tweet

Output:
tweet

This is an echo service so whatever you input in the URL should be echoed to your browser.

If you are unware of your endpoint address, you can use the below url to find out,

http://localhost:9090/jaxrs-service/cxf/services

This lists all the REST and SOAP services running on your server.

Using Jetty :

1. pom.xml :

The pom.xml is pretty much similar to the one we have used for tomcat configuration except that the tomcat plugin is replaced with the jetty equivalent. Also the port number is changed 8080 just to distinguish between tomcat and jetty.

<?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 http://maven.apache.org/maven-v4_0_0.xsd">
    
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.learninjava</groupId>
    <artifactId>cxfjaxrsws</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Simple CXF JAX-RS webapp service using spring configuration</name>
    <description>Simple CXF JAX-RS webapp service using spring configuration</description>
    
    <organization>
        <name>Learn in Java</name>
        <url>http://www.learninjava.com/</url>
    </organization>
    <!-- Change the version numbers or other configurations here -->
    <properties>
        <cxf.version>3.0.3</cxf.version>
        <jackson.version>1.8.6</jackson.version>
        <spring.version>3.2.6.RELEASE</spring.version>
        <junit.version>4.11</junit.version>
        <surefire.version>2.10</surefire.version>
        <jetty.version>6.1.10</jetty.version>
        <compiler.srcversion>1.6</compiler.srcversion>
        <compiler.tgtversion>1.6</compiler.tgtversion>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <port.number>8080</port.number>
        <service.url>http://localhost:${port.number}/jaxrs-service</service.url>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-client</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-jaxrs</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                
                <!-- Optional plugin, This is added to specify service.url in pom.xml itself -->
                <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-surefire-plugin</artifactId>
                  <version>${surefire.version}</version>
                  <configuration>
                    <argLine>-Dservice.url=${service.url}</argLine>
                  </configuration>
                </plugin>
                
                <plugin>
					<groupId>org.mortbay.jetty</groupId>
					<artifactId>maven-jetty-plugin</artifactId>
					<version>${jetty.version}</version>
					<configuration>
						<scanIntervalSeconds>10</scanIntervalSeconds>
						<connectors>
							<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
								<port>${port.number}</port>
								<maxIdleTime>60000</maxIdleTime>
							</connector>
						</connectors>
						<webAppConfig>
							<contextPath>/jaxrs-service</contextPath>
						</webAppConfig>
                  </configuration>
                </plugin>
                
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>${compiler.srcversion}</source>
                        <target>${compiler.tgtversion}</target>
                    </configuration>
                </plugin>
                
                <!-- Optional plugin, This is added to create an eclipse compatible project. To do it, use : mvn eclipse:eclipse -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-eclipse-plugin</artifactId>
                    <configuration>
                        <projectNameTemplate>[artifactId]-[version]</projectNameTemplate>
                        <wtpmanifest>true</wtpmanifest>
                        <wtpapplicationxml>true</wtpapplicationxml>
                        <wtpversion>2.0</wtpversion>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

All other steps are same as above.

To start the jetty container and the webservice use the below command :

mvn clean package -DskipTests=true jetty:run

Navigate to the URL :

http://localhost:8080/jaxrs-service/helloAngryWorld/echo/tweet

Output:
tweet

Advantage of using Jetty - Hot code deployment :

By default, Jetty scans the following directories :

  target/classes  -  for changes to Java sources and 
  src/main/webapp -  for changes to web sources. 

If any source file is modified, the changes are autodeployed to the jetty container without manually restarting for the changes to take effect.

To test this hot code deployment, try to change any source file. We have changed the Path param of ping method from echo to ping. Now, recompiled the source using mvn compile command.

The moment the source file is compiled, notice the server console. You will observe that jetty hot deploys the code automatically and you can access the changes via browser instantly.

Navigate to the URL :

http://localhost:8080/jaxrs-service/helloAngryWorld/ping/tweet

Output:
tweet


References :

PreferencesPlaceholderConfigurer

ServletContextPropertyPlaceholderConfigurer

Providers

 
   

Related Articles

Restful Client using CXF
SOAP WebService using CXF
SOAP Client using CXF
Restful WebService using Jersey
Restful Client using Jersey
 
   

Recommended Articles

User and Daemon Threads
Thread States
Java 8 Stream
Java 8 Functional Interfaces
Java 8 Lambda Expressions
Top 10 Free Tutorials




LIKE/SHARE
 
 
 
Download Source:

Comments:


 

Top Picks

1. Top 5 websites offering free e-books

2. Top 10 websites for free Java Articles and Tutorials

3. Top 5 websites for Java Certifications

4. Top 5 Softwares for Java developers




   
   
   
 
 
© Copyright 2017. All rights reserved. All trademarks and logos belongs to their owners.         Website Counter