Apache CXF: JAX-RS Restful web service using both (JSON + XML) example

In this article, we will learn and implement a JAX-RS Restful Web Service which consumes & produces in both XML/JSON format

The trick is to set method/class annotated with @Produces & @Consumes with multiple formats in the form of an array-of-string. See example to understand

Here, the rest web service client needs to make sure in setting up required format in the header. Otherwise, first of the multiple formats annotated on top of method/class will be returned. Similarly, if the clients intended to send the request body in the JSON format or XML format, then it’s the responsibility of the client to set those values in the header.

Header for,
request body –> Content-Type
response –> accept

Note: Extending/combining the last two applications to support multiple formats APPLICATION_XML and APPLICATION_JSON, etc

Annotation Used

  • @Path (javax.ws.rs.Path)
  • @GET (javax.ws.rs.GET)
  • @POST (javax.ws.rs.POST)
  • @PUT (javax.ws.rs.PUT)
  • @DELETE (javax.ws.rs.DELETE)
  • @PathParam (javax.ws.rs.PathParam)
  • @Consumes (javax.ws.rs.Consumes)
  • @Produces (javax.ws.rs.Produces)
  • @Service (org.springframework.stereotype.Service)
  • MediaType (javax.ws.rs.core.MediaType)

Technology Used

  • Java 1.7
  • Eclipse Luna IDE
  • Spring-4.0.0-RELEASE
  • Apache-CXF-3.0.0
  • Apache Maven 3.2.1
  • Apache Tomcat 7.0.54

Mavenize or download required jars

Add Apache-CXF-3.0.0 and Spring-4.0.0-RELEASE dependencies to pom.xml

<dependencies>
		<!-- Apache CXF -->
		<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-transports-http</artifactId>
			<version>${cxf.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http-jetty</artifactId>
			<version>${cxf.version}</version>
		</dependency>

		<!-- for JSON support in Apache-CXF Restful web service -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-jaxrs</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<!-- Spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
</dependencies>

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site or maven repository and include them in the classpath

JAXB – Generating java source files from XSD

Steps to generate java-sources from XML Schema Definition (XSD)

  • configure JAXB Maven plugin in pom.xml
  • write well-defined XSD for your service
  • use maven command “mvn generate-sources” to generate java source files

Configure JAXB Maven plugin

<!-- JAXB plugin to generate-sources from XSD -->
<plugin>
	<groupId>org.codehaus.mojo</groupId>
	<artifactId>jaxb2-maven-plugin</artifactId>
	<version>1.5</version>
	<executions>
		<execution>
			<goals>
				<goal>xjc</goal><!-- xjc/generate -->
			</goals>
			<configuration>
				<outputDirectory>${basedir}/generated/java/source</outputDirectory>
				<schemaDirectory>${basedir}/src/main/resources/com/apache/cxf/xml/json/service/entities</schemaDirectory>
				<schemaFiles>*.xsd</schemaFiles>
				<schemaLanguage>XMLSCHEMA</schemaLanguage>
				<extension>true</extension>
				<args>
					<arg>-XtoString</arg>
				</args>
				<plugins>
					<plugin>
						<groupId>org.jvnet.jaxb2_commons</groupId>
						<artifactId>jaxb2-basics</artifactId>
						<version>0.6.4</version>
					</plugin>
				</plugins>
			</configuration>
		</execution>
	</executions>
</plugin>

Player.xsd

Below XSD contains two elements with name “PlayerType” and “PlayerListType”

  • PlayerType contains four attributes namely playerId, name, age and matches
  • PlayerListType which returns list of PlayerType
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://benchresources.in/cdm/Player" xmlns:tns="http://benchresources.in/cdm/Player" elementFormDefault="qualified">

	<!-- player object with four attributes -->
	<xsd:element name="PlayerType">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element name="playerId" type="xsd:int" />
				<xsd:element name="name" type="xsd:string" />
				<xsd:element name="age" type="xsd:int" />
				<xsd:element name="matches" type="xsd:int" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>

	<!-- an object to contain lists of players referencing above player object -->
	<xsd:element name="PlayerListType">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="tns:PlayerType" minOccurs="0" maxOccurs="unbounded" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>
</xsd:schema>

Run mvn generate-sources

Look at the generated java source files in the generated folder

PlayerType.java

package in.benchresources.cdm.player;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "playerId",
    "name",
    "age",
    "matches"
})
@XmlRootElement(name = "PlayerType")
public class PlayerType {

    protected int playerId;
    @XmlElement(required = true)
    protected String name;
    protected int age;
    protected int matches;

    public int getPlayerId() {
        return playerId;
    }
    public void setPlayerId(int value) {
        this.playerId = value;
    }
    public String getName() {
        return name;
    }
    public void setName(String value) {
        this.name = value;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int value) {
        this.age = value;
    }
    public int getMatches() {
        return matches;
    }
    public void setMatches(int value) {
        this.matches = value;
    }
}

PlayerListType.java

package in.benchresources.cdm.player;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "playerType"
})
@XmlRootElement(name = "PlayerListType")
public class PlayerListType {

    @XmlElement(name = "PlayerType")
    protected List<PlayerType> playerType;
    public List<PlayerType> getPlayerType() {
        if (playerType == null) {
            playerType = new ArrayList<PlayerType>();
        }
        return this.playerType;
    }
}

Directory Structure

Before moving on, let us understand the directory/package structure once you create project in Eclipse IDE
Maven has to follow certain directory structure

  • src/test/java –> test related files, mostly JUnit test cases
  • src/main/java –> create java source files under this folder
  • src/main/resources –> all configuration files placed here
  • generated/java/source –> generated java source files are placed here
  • Maven Dependencies or Referenced Libraries –> includes jars in the classpath
  • WEB-INF under webapp –> stores web.xml & other configuration files related to web application

Project Structure (Package Explorer view in Eclipse)

1_ApacheCXF-XML-JSON-IO_Project_Structure_In_Eclipse

Jars Libraries Used in the Project (Maven Dependencies)

2_ApacheCXF-XML-JSON-IO_Jars_In_Classpath

Web application

For any web application, entry point is web.xml which describes how the incoming http requests are served / processed. Further, it describes about the global-context and local-context param (i.e.; <context-param> & <init-param>) for loading files particular to project requirements & contains respective listener

With this introduction, we will understand how we configured web.xml for Apache CXF JAX-RS Restful web service

web.xml (the entry point –> under WEB-INF)

This web.xml file describes,

  • like any JEE web framework register org.apache.cxf.transport.servlet.CXFServletwith servlet container
  • all http requests with URL pattern “/services/*” will be sent to the registered servlet called “CXFServlet” (org.apache.cxf.transport.servlet.CXFServlet)
  • <context-param> with its attributes describes the location of the “apache-cxf-service.xml” file from where it has to be loaded. We will discuss briefly about this file
  • <welcome-file-list> files under this tag is the start-up page

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<display-name>ApacheCXF-XML-JSON-IO</display-name>

	<!-- Apache CXF -->
	<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>/services/*</url-pattern>
	</servlet-mapping>

	<!-- web context param -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>WEB-INF/apache-cxf-services.xml</param-value>
	</context-param>

	<!-- listener -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- welcome file list -->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Apache CXF services

Apache CXF comes with spring based configuration, so it is easy to register beans in the spring container much like we do any bean in spring application. CXFServlet receives the incoming http requests and invokes corresponding registered beans in according to http url path

NOTE: For this Restful JAX-RS application, we are using Spring annotations to define/register beans in the spring container thereby avoiding lot of boilerplate code to write

This apache-cxf-services.xml describes,

  • <context:annotation-config /> to activate annotation on the registered beans with application context
  • <context:component-scan base-package=”” /> tag scans all classes & sub-classes under value of base-package attribute and register them with Spring container
  • <jaxrs:server /> defines which service bean to be invoked for the incoming http requests. In this case, any wild card pattern “/” will invoke “playerService” which is registered as service bean using @Service(“playerService”) annotation (on top of the PlayerServiceImpl java class)
  • bean with id=”jsonProvider” defined to support JSON format
  • bean with id=”jaxbXmlProvider” defined to support XML format
  • <jaxrs:extensionMappings> with this element you can use dot notation to get result in the required format, instead of supplying the accept header parameter
  • NOTE: For two different beans we can have two different url-pattern(address) like
		<jaxrs:server id="restContainer" address="/">
			<jaxrs:serviceBeans>
				<ref bean="playerService" />
			</jaxrs:serviceBeans>
		</jaxrs:server>
		
		<jaxrs:server id="twotest" address="/two">
			<jaxrs:serviceBeans>
				<ref bean="testService" />
			</jaxrs:serviceBeans>
		</jaxrs:server>

apache-cxf-services.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" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">

	<!-- to turn on annotation wiring == turns on only the registered beans through ApplicationContext -->
	<context:annotation-config />

	<!-- scans and register beans using annotation-config (metadata) -->
	<context:component-scan base-package="com.apache.cxf.xml.json.service" />

	<!-- to support Java-to-JSON and vice-versa conversion -->
	<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />

	<!-- to support Java-to-XML and vice-versa conversion -->
	<bean id="jaxbXmlProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider" />

	<!-- CXFServlet configured in web.xml sends requests here -->
	<jaxrs:server id="restContainer" address="/">
		<jaxrs:serviceBeans>
			<ref bean="playerService" />
		</jaxrs:serviceBeans>

		<jaxrs:extensionMappings>
			<entry key="json" value="application/json" /> <!-- use .json to get data in JSON format -->
			<entry key="xml" value="application/xml" />   <!-- use .xml to get data in XML format -->
		</jaxrs:extensionMappings>

		<jaxrs:providers>
			<ref bean="jsonProvider" />
			<ref bean="jaxbXmlProvider" />
		</jaxrs:providers>
	</jaxrs:server>
</beans>




Let’s see coding in action

 

URL Pattern

Http URL for any common web application is http://<server>:<port>/<context-root>/<from_here_application_specific_path>

In our example, we are going to deploy the war into Tomcat 7.0 server so our server & port are localhost and 8080 respectively. Context root is the project name i.e.; ApacheCXF-XML-JSON-IO. Initial path for this application is http://localhost:8080/ApacheCXF-XML-JSON-IO

We have configured “/services/*” as url-pattern for the CXFServlet in web.xml and at interface-level (or say class-level) path configured is “/player” using @Path annotation. Next respective path for each method annotated with @Path (method-level)

Player Service interface

Defines simple CURD operations

  • @POST          – create/inserts a new resource (new player)
  • @GET           – read/selects internal resource representation based on the playerId
  • @PUT            – update/modifies an internal resource representation (modify player)
  • @DELETE       – delete/removes a resource (delete player)
  • @GET           – retrieves all players (get all players)

Let’s discuss @Produces, @Consumes and MediaType

@Consumes

Define which MIME type is consumed by this method. For this example, exposed methods supports both XML & JSON formats i.e.; methods are annotated with @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})

Note: When Content-Type is not specified in the header, then by default it expects request body in “application/x-www-form-urlencoded”. So, Content-Type needs to be set/sent in the header

@Produces

Define which MIME type it will produce. For this example, exposed methods produce response in both XML & JSON formats i.e.; methods are annotated with @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})

Note: By default, when invoked it returns the response in XML as it is the first string in the array. So, to get the response in the JSON format then set accept=”application/json” in the header

Most widely used Media Types are

  • MediaType.APPLICATION_XML,
  • MediaType.APPLICATION_JSON,
  • MediaType.TEXT_PLAIN,
  • MediaType.TEXT_XML,
  • MediaType.APPLICATION_FORM_URLENCODED,
  • etc

NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately

IPlayerService.java

package com.apache.cxf.xml.json.service;

import in.benchresources.cdm.player.PlayerListType;
import in.benchresources.cdm.player.PlayerType;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/playerservice")
public interface IPlayerService {

	// Basic CRUD operations for Player Service

	// http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/addplayer
	@POST
	@Path("addplayer")
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Produces({MediaType.APPLICATION_FORM_URLENCODED})
	public String createOrSaveNewPLayerInfo(PlayerType playerType);

	// http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/getplayer/238
	@GET
	@Path("getplayer/{id}")
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public PlayerType getPlayerInfo(@PathParam("id") int playerId);

	// http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/updateplayer
	@PUT
	@Path("updateplayer")
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	@Produces({MediaType.APPLICATION_FORM_URLENCODED})
	public String updatePlayerInfo(PlayerType playerType);

	// http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/deleteplayer
	@DELETE
	@Path("deleteplayer")
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON,})
	@Produces({MediaType.APPLICATION_FORM_URLENCODED})
	public String deletePlayerInfo(PlayerType playerType);

	// http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/getallplayer
	@GET
	@Path("getallplayer")
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public PlayerListType getAllPlayerInfo();
}

Player Service implementation

Implements above interface. Self explanatory !!

PlayerServiceImpl.java

package com.apache.cxf.xml.json.service;

import in.benchresources.cdm.player.PlayerListType;
import in.benchresources.cdm.player.PlayerType;

import org.springframework.stereotype.Service;

@Service("playerService")
public class PlayerServiceImpl implements IPlayerService {

	/**
	 * returns a String value with SUCCESS message after adding a player
	 */
	@Override
	public String createOrSaveNewPLayerInfo(PlayerType playerType) {

		// get the player information from formal arguments and inserts into database & return playerId (primary_key)
		return "Player information saved successfully with PLAYER_ID " + 238;
	}

	/**
	 * retrieves a player object based on the playerId supplied in the formal argument using @PathParam
	 */
	@Override
	public PlayerType getPlayerInfo(int playerId) {

		// retrieve player based on the id supplied in the formal argument
		PlayerType getplayer = new PlayerType	();
		getplayer.setPlayerId(playerId);
		getplayer.setName("Allan Donald");
		getplayer.setAge(47);
		getplayer.setMatches(72);
		return getplayer;
	}

	/**
	 * returns a String value with SUCCESS message after updating a player
	 */
	@Override
	public String updatePlayerInfo(PlayerType playerType) {

		// update player info & return SUCCESS message
		return "Player information updated successfully";
	}

	/**
	 * returns a String value with SUCCESS message after deleting a player
	 */
	@Override
	public String deletePlayerInfo(PlayerType playerType) {

		// delete player info & return SUCCESS message
		return "Player information deleted successfully";
	}

	/**
	 * retrieves all players stored
	 */
	@Override
	public PlayerListType getAllPlayerInfo() {

		// create a object of type PlayerType which takes player objects in its list
		PlayerListType playerListType = new PlayerListType();

		// player 1 info
		PlayerType playerOne = new PlayerType();
		playerOne.setPlayerId(237);
		playerOne.setName("Hansie Cronje");
		playerOne.setAge(33);
		playerOne.setMatches(68);
		playerListType.getPlayerType().add(playerOne); // add to playerListType

		// player 2 info
		PlayerType playerTwo = new PlayerType();
		playerTwo.setPlayerId(265);
		playerTwo.setName("Lance Klusener");
		playerTwo.setAge(42);
		playerTwo.setMatches(49);
		playerListType.getPlayerType().add(playerTwo); // add to playerListType

		return playerListType;
	}
}

 

Deployment

  • Run maven command to build the war : mvn clean install (use command prompt or integrated maven in eclipse IDE)
  • Copy the war file from the target folder
  • Paste it into apache tomcat (webapps folder)
  • Start the tomcat server

Test the service !!

 

Testing

There are many ways to do testing

  • Copy the URL of GET service into web browser
  • Advanced REST client from Google Chrome
  • Rest client from Mozilla Firefox Add On
  • Write your own client for example, Java client using httpcomponents from Apache
  • JDK’s in-built classes like HttpURLConnection

 

1. Using RestClient from Mozilla Firefox Add-On

Every service tested setting up header parameters “accept” & “Content-Type” in the request. First for JSON format and then XML format

1.1

First service: @POST (createOrSaveNewPLayerInfo())
URL:http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/addplayer
Request:

{
  "playerId": 238,
  "name": "Allan Donald",
  "age": 47,
  "matches": 72
}

Content-Type: application/json
accept: application/x-www-form-urlencoded
Response: Player information saved successfully with PLAYER_ID 238
MF_3_ApacheCXF-XML-JSON-IO_advanced_rest_client_addplayer_json

Request:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
	<playerId>238</playerId>
	<name>Allan Donald</name>
	<age>47</age>
	<matches>72</matches>
</PlayerType>

Content-Type: application/xml
accept: application/x-www-form-urlencoded
Response: Player information saved successfully with PLAYER_ID 238
MF_3_ApacheCXF-XML-JSON-IO_advanced_rest_client_addplayer_xml

1.2

Second service: @GET (getPlayerInfo())
URL: http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/getplayer/238
Request: None
Content-Type: application/x-www-form-urlencoded
accept: application/json
Response:

{
  "playerId": 238,
  "name": "Allan Donald",
  "age": 47,
  "matches": 72
}

MF_4_ApacheCXF-XML-JSON-IO_advanced_rest_client_getplayer_json

Request: None
Content-Type: application/x-www-form-urlencoded
accept: application/xml
Response:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
	<playerId>238</playerId>
	<name>Allan Donald</name>
	<age>47</age>
	<matches>72</matches>
</PlayerType>

MF_4_ApacheCXF-XML-JSON-IO_advanced_rest_client_getplayer_xml

1.3

Third service: @PUT (updatePlayerInfo())
URL: http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/updateplayer
Request:

{
  "playerId": 238,
  "name": "Allan Donald",
  "age": 47,
  "matches": 72
}

Content-Type: application/json
accept: application/x-www-form-urlencoded
Response: Player information updated successfully
MF_5_ApacheCXF-XML-JSON-IO_advanced_rest_client_updateplayer_json

Request:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
	<playerId>238</playerId>
	<name>Allan Donald</name>
	<age>47</age>
	<matches>72</matches>
</PlayerType>

Content-Type: application/xml
accept: application/x-www-form-urlencoded
Response: Player information updated successfully
MF_5_ApacheCXF-XML-JSON-IO_advanced_rest_client_updateplayer_xml

1.4

Fourth service: @DELETE (deletePlayerInfo())
URL: http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/deleteplayer
Request:

{
  "playerId": 238,
  "name": "Allan Donald",
  "age": 47,
  "matches": 72
}

Content-Type: application/json
accept: application/x-www-form-urlencoded
Response: Player information deleted successfully
MF_6_ApacheCXF-XML-JSON-IO_advanced_rest_client_deleteplayer_json

Request:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerType xmlns="http://benchresources.in/cdm/Player">
	<playerId>238</playerId>
	<name>Allan Donald</name>
	<age>47</age>
	<matches>72</matches>
</PlayerType>

Content-Type: application/xml
accept: application/x-www-form-urlencoded
Response: Player information deleted successfully
MF_6_ApacheCXF-XML-JSON-IO_advanced_rest_client_deleteplayer_xml

1.5

Fifth service: @GET (getAllPlayerInfo())
URL: http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/getallplayer
Request: None
Content-Type: application/x-www-form-urlencoded
accept: application/json
Response:

{
  "playerType": [
    {
      "playerId": 237,
      "name": "Hansie Cronje",
      "age": 33,
      "matches": 68
    },
    {
      "playerId": 265,
      "name": "Lance Klusener",
      "age": 42,
      "matches": 49
    }
  ]
}

MF_7_ApacheCXF-XML-JSON-IO_advanced_rest_client_getallplayer_json

Request: None
Content-Type: application/x-www-form-urlencoded
accept: application/xml
Response:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerListType xmlns="http://benchresources.in/cdm/Player">
	<PlayerType>
		<playerId>237</playerId>
		<name>Hansie Cronje</name>
		<age>33</age>
		<matches>68</matches>
	</PlayerType>
	<PlayerType>
		<playerId>265</playerId>
		<name>Lance Klusener</name>
		<age>42</age>
		<matches>49</matches>
	</PlayerType>
</PlayerListType>

MF_7_ApacheCXF-XML-JSON-IO_advanced_rest_client_getallplayer_xml

 

2. Java Client

Uses HttpURLConnection and its supporting classes which comes shipped with JDK

Tested one service i.e.; /getplayer/{id} using HttpURLConnection. Do test other services using this Java client making necessary changes to the requestParams[] array like requestURL, httpMethod, contentType, accept and include correct requestString

NOTE: Intentionally, commented out few lines of code. Make sure to un-comment while invoking services for POST, PUT requests

TestPlayerService.java

package com.apache.cxf.xml.json.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MediaType;

public class TestPlayerService {

	/**
	 * main method to invoke test method
	 * @param args
	 */
	public static void main(String[] args) {

		/*String requestURL = "http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/addplayer";
		String httpMethod = HttpMethod.POST;
		String contentType = MediaType.APPLICATION_XML;
		String accept = MediaType.APPLICATION_FORM_URLENCODED;
		String requestParam = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
				+				"<PlayerType xmlns=\"http://benchresources.in/cdm/Player\">"
				+					"<playerId>344</playerId>"
				+					"<name>Ian Healy</name>"
				+					"<age>50</age>"
				+					"<matches>119</matches>"
				+ 				"</PlayerType>";

		String[] requestParams = {requestURL, httpMethod, requestParam, contentType, accept};*/

		String requestURL = "http://localhost:8080/ApacheCXF-XML-JSON-IO/services/playerservice/getplayer/238";
		String httpMethod = HttpMethod.GET;
		String contentType = MediaType.APPLICATION_FORM_URLENCODED;
		String accept = MediaType.APPLICATION_JSON;
		String requestString =  "{"
				+  		"\"playerId\": 564,"
				+  		"\"name\": \"Graham Thorpe\","
				+  		"\"age\": 45,"
				+  		"\"matches\": 100 "
				+  	"}";

		String[] requestParams = null;
		requestParams = new String[]{requestURL, httpMethod, contentType, accept, requestString};

		String responseFromService = testPlayerService(requestParams);
		System.out.println("Response String: " + responseFromService);
	}

	/**
	 * This method uses HttpURLConnection to invoke exposed Restful web service and returns the response string to the calling client
	 * @param requestParams
	 * @return
	 */
	public static String testPlayerService(String[] requestParams) {

		// local variables
		URL url = null;
		HttpURLConnection httpURLConnection = null;
		OutputStreamWriter outputStreamWriter = null;
		String responseMessageFromServer = null;
		String responseXML = null; 

		try {
			url = new URL(requestParams[0]);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod(requestParams[1]);
			httpURLConnection.setRequestProperty("Content-Type", requestParams[2]);
			httpURLConnection.setRequestProperty("Accept", requestParams[3]);
			httpURLConnection.setDoOutput(true);

			/*outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
			outputStreamWriter.write(requestParams[4]);
			outputStreamWriter.flush();*/

			System.out.println("Response code: " + httpURLConnection.getResponseCode());

			if (httpURLConnection.getResponseCode() == 200) {

				responseMessageFromServer = httpURLConnection.getResponseMessage();
				System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);
				responseXML = getResponseXML(httpURLConnection);
			}
		}
		catch(Exception  ex){
			ex.printStackTrace();
		}
		finally{
			httpURLConnection.disconnect();
		}
		return responseXML;
	}

	/**
	 * This method is used to get response XML from the HTTP GET Request created for Authorization WireKey
	 * @param httpURLConnection
	 * @return stringBuffer.toString()
	 * @throws IOException
	 */
	private static String getResponseXML(HttpURLConnection httpURLConnection) throws IOException{

		StringBuffer stringBuffer = new StringBuffer();
		BufferedReader bufferedReader = null;
		InputStreamReader inputStreamReader = null;
		String readSingleLine = null;

		try{
			// read the response stream AND buffer the result into a StringBuffer
			inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
			bufferedReader = new BufferedReader(inputStreamReader);

			// reading the XML response content line BY line
			while ((readSingleLine = bufferedReader.readLine()) != null) {
				stringBuffer.append(readSingleLine);
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		finally{
			// finally close all operations
			bufferedReader.close();
			httpURLConnection.disconnect();
		}
		return stringBuffer.toString();
	}
}

Output in Console

Response code: 200
ResponseMessageFromServer: OK
Response String: {"playerId":238,"name":"Allan Donald","age":47,"matches":72}

Study java client and do necessary changes to test other exposed services

Conclusion: With this implementation, we can say that web service request/response can be exchanged in different formats depending upon the business requirements

Download project

ApacheCXF-XML-JSON-IO (10kB)

Happy Coding !!
Happy Learning !!

Apache CXF: JAX-RS Restful web service + Integrating with Spring & Hibernate
Apache CXF: JAX-RS Restful web service using JAXB + JSON example