In the previous article, we learnt and implemented an example on how to use JAX-RS Restful web service to send & receive XML data as request/response. Here, we will re-use and modify the same example to send & receive JSON data as web service request/response
JAX-RS specification supports the conversion of Java objects to JSON & vice-versa using Jackson library
Still we need Java objects to send/receive data in JSON format so start designing your XML Schema Definition (XSD), as we can use JAXB Maven plugin to generate Java classes. Later this generated POJO used to exchange JSON data on the fly with the help of Jackson
NOTE: an extra dependency “Jackson – high performance JSON parser” has been added to pom.xml to support exchange of JSON data with JAX-RS Restful web service
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
- jackson-jaxrs
- cxf-rt-frontend-jaxrs
- cxf-rt-transports-http
- cxf-rt-transports-http-jetty
- spring-core-4.0.0-RELEASE
- spring-context-4.0.0-RELEASE
- spring-beans-4.0.0-RELEASE
- spring-aop-4.0.0-RELEASE
- spring-expression-4.0.0-RELEASE
- spring-web-4.0.0-RELEASE
- spring-webmvc-4.0.0-RELEASE
- commons-logging-1.1.1
- aopalliance-1.0
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/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)
Jars Libraries Used in the Project (Maven Dependencies)
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"?> <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-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 the application context
- <context:component-scan base-package=”” /> tag scans all classes & sub-classes under the value of base-package attribute and register them with the 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
- 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.json.service" /> <!-- to support Java-to-JSON and vice-versa conversion --> <bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" /> <!-- CXFServlet configured in web.xml sends requests here --> <jaxrs:server id="restContainer" address="/"> <jaxrs:serviceBeans> <ref bean="playerService" /> </jaxrs:serviceBeans> <jaxrs:providers> <ref bean="jsonProvider" /> </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-JSON-IO. Initial path for this application is http://localhost:8080/ApacheCXF-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 are restricted to consume only JSON data and it is annotated with @Consumes(MediaType.APPLICATION_JSON)
@Produces
Define which MIME type it will produce. For this example, exposed methods are restricted to produce only JSON data and it is annotated with @Produces(MediaType.APPLICATION_JSON)
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.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-JSON-IO/services/playerservice/addplayer @POST @Path("addplayer") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_FORM_URLENCODED) public String createOrSaveNewPLayerInfo(PlayerType playerType); // http://localhost:8080/ApacheCXF-JSON-IO/services/playerservice/getplayer/564 @GET @Path("getplayer/{id}") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public PlayerType getPlayerInfo(@PathParam("id") int playerId); // http://localhost:8080/ApacheCXF-JSON-IO/services/playerservice/updateplayer @PUT @Path("updateplayer") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_FORM_URLENCODED) public String updatePlayerInfo(PlayerType playerType); // http://localhost:8080/ApacheCXF-JSON-IO/services/playerservice/deleteplayer @DELETE @Path("deleteplayer") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_FORM_URLENCODED) public String deletePlayerInfo(PlayerType playerType); // http://localhost:8080/ApacheCXF-JSON-IO/services/playerservice/getallplayer @GET @Path("getallplayer") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public PlayerListType getAllPlayerInfo(); }
Player Service implementation
Implements above interface. Self explanatory !!
PlayerServiceImpl.java
package com.apache.cxf.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 " + 564; } /** * 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("Graham Thorpe"); getplayer.setAge(45); getplayer.setMatches(100); 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(543); playerOne.setName("Alec Stewart"); playerOne.setAge(51); playerOne.setMatches(133); playerListType.getPlayerType().add(playerOne); // add to playerListType // player 2 info PlayerType playerTwo = new PlayerType(); playerTwo.setPlayerId(542); playerTwo.setName("Nasser Hussain"); playerTwo.setAge(46); playerTwo.setMatches(96); 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
First service: @POST (createOrSaveNewPLayerInfo())
URL: http://localhost:8080/ApacheCXF-JSON-IO/services/playerservice/addplayer
Request:
{ "playerId": 564, "name": "Graham Thorpe", "age": 45, "matches": 100 }
Response:
Player information saved successfully with PLAYER_ID 564
Second service: @GET (getPlayerInfo())
URL: http://localhost:8080/ApacheCXF-JSON-IO/services/playerservice/getplayer/564
Request: None
Response:
{ "playerId": 564, "name": "Graham Thorpe", "age": 45, "matches": 100 }
Third service: @PUT (updatePlayerInfo())
URL: http://localhost:8080/ApacheCXF-JSON-IO/services/playerservice/updateplayer
Request:
{ "playerId": 564, "name": "Graham Thorpe", "age": 45, "matches": 100 }
Response:
Player information updated successfully
Fourth service: @DELETE (deletePlayerInfo())
URL: http://localhost:8080/ApacheCXF-JSON-IO/services/playerservice/deleteplayer
Request:
{ "playerId": 564, "name": "Graham Thorpe", "age": 45, "matches": 100 }
Response:
Player information deleted successfully
Fifth service: @GET (getAllPlayerInfo())
URL: http://localhost:8080/ApacheCXF-JSON-IO/services/playerservice/getallplayer
Request: None
Response:
{ "playerType": [ { "playerId": 543, "name": "Alec Stewart", "age": 51, "matches": 133 }, { "playerId": 542, "name": "Nasser Hussain", "age": 46, "matches": 96 } ] }
2. Java Client
Uses HttpURLConnection and its support classes which comes in 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.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-JSON-IO/services/playerservice/getplayer/564"; 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 = 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":564,"name":"Graham Thorpe","age":45,"matches":100}
Conclusion: Thus, JSON format can be used to send/receive data where performance is a big consideration as it is light-weight. Especially, in mobile development client prefer to use JSON data for web service interaction
Download project
ApacheCXF-JSON-IO (9kB)
Happy Coding !!
Happy Learning !!