XML Example With RESTEasy+ JAXB

In this example we are going to see how you can integrateRESTEasy with JAXB (Java Architecture for XML Binding) to create RESTful services that consume and produce XML streams. As you probably know JAXB is used to marshal a Java Object to XML, and ummarshal an XML file (or stream in general) to Java Object.

In this example we are not going to focus on how to create the JAX-RS application from top to bottom. So make sure you read carefully RESTEasy Hello World Example  and pay attention to the sections concerning the creation of the project with Eclipse IDE as well as the deployment of the project in Tomcat.

You can create your own project following the instructions on RESTEasy Hello World Example. But you can also download the Eclipse project of this tutorial here : JAXRS-RESTEasy-CustomApplication.zip, and build your code on top of that.

1. Project structure

For this example, I’ve created a new Project called “RESTEasyXMLExample“. You can see the final structure of the project in the image below:

project-structure

At this point you can also take a look at the web.xml file to see how the project is configured:

web.xml:

01 <?xml version="1.0" encoding="UTF-8"?>
03   <display-name>RESTEasyXMLExample</display-name>
04   <servlet-mapping>
05     <servlet-name>resteasy-servlet</servlet-name>
06     <url-pattern>/rest/*</url-pattern>
07   </servlet-mapping>
08  
09   <context-param>
10     <param-name>resteasy.scan</param-name>
11     <param-value>true</param-value>
12   </context-param>
13  
14   <context-param>
15     <param-name>resteasy.servlet.mapping.prefix</param-name>
16     <param-value>/rest</param-value>
17   </context-param>
18  
19   <listener>
20     <listener-class>
21             org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
22             </listener-class>
23   </listener>
24  
25   <servlet>
26     <servlet-name>resteasy-servlet</servlet-name>
27     <servlet-class>
28             org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
29         </servlet-class>
30   </servlet>
31 </web-app>

As you can see our servlet is mapped to /rest/ URI pattern. So the basic structure of the URIs to reach the REST Services used in this example will have the form :

1. JAXB Dependency

You have to add the following lines to your pom.xml to obtain the JAXB library:

JAXB Dependency:

1 <dependency>
2     <groupId>org.jboss.resteasy</groupId>
3     <artifactId>resteasy-jaxb-provider</artifactId>
4     <version>3.0.4.Final</version>
5 </dependency>

2. Java Object with JAXB Annotations

This is the Object that is going to be represented in XML.

Student.java:

01 package com.javacodegeeks.enterprise.rest.resteasy;
02  
03 import javax.xml.bind.annotation.XmlAttribute;
04 import javax.xml.bind.annotation.XmlElement;
05 import javax.xml.bind.annotation.XmlRootElement;
06  
07 @XmlRootElement(name = "student")
08 public class Student {
09  
10     private int id;
11     private String firstName;
12     private String lastName;
13     private int age;
14  
15     // Must have no-argument constructor
16     public Student() {
17  
18     }
19  
20     public Student(String fname, String lname, int age, int id) {
21         this.firstName = fname;
22         this.lastName = lname;
23         this.age = age;
24         this.id = id;
25     }
26  
27     @XmlElement
28     public void setFirstName(String fname) {
29         this.firstName = fname;
30     }
31  
32     public String getFirstName() {
33         return this.firstName;
34     }
35  
36     @XmlElement
37     public void setLastName(String lname) {
38         this.lastName = lname;
39     }
40  
41     public String getLastName() {
42         return this.lastName;
43     }
44  
45     @XmlElement
46     public void setAge(int age) {
47         this.age = age;
48     }
49  
50     public int getAge() {
51         return this.age;
52     }
53  
54     @XmlAttribute
55     public void setId(int id) {
56         this.id = id;
57     }
58  
59     public int getId() {
60         return this.id;
61     }
62  
63     @Override
64     public String toString() {
65         return new StringBuffer(" First Name : ").append(this.firstName)
66                 .append(" Last Name : ").append(this.lastName)
67                 .append(" Age : ").append(this.age).append(" ID : ")
68                 .append(this.id).toString();
69     }
70  
71 }

In the above code:

  • @XmlRootElement: defines the root element of XML.
  • @XmlElement: is used to define element in XML file.
  • @XmlAttribute: is used to define an attribute of the root element.

3. REST Service to produce XML output

Let’s see how easy it is with RESTEasyto produce XML output using a simple Student instance.

JerseyRestService.java:

01 package com.javacodegeeks.enterprise.rest.resteasy;
02  
03 import javax.ws.rs.Produces;
04 import javax.ws.rs.GET;
05 import javax.ws.rs.Path;
06 import javax.ws.rs.PathParam;
07  
08 @Path("/xmlServices")
09 public class RESTEasyXMLServices {
10  
11     @GET
12     @Path("/print/{name}")
13     @Produces("application/xml")
14     public Student uploadFile(@PathParam("name") String name) {
15  
16         Student st = new Student(name, "Diaz",16,5);
17  
18         return st;
19     }
20  
21 }

After deploying the application, open your browser and go to:

Here is the response:

browser

Here is the raw HTTP Response:

HTTP Response:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/xml
Content-Length: 147
Date: Mon, 25 Nov 2013 17:51:40 GMT

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="5">
	<age>16</age>
	<firstName>Ramone</firstName>
	<lastName>Diaz</lastName>
</student>

3. REST Service to consume XML

Here is a REST Service that consumes a simple Student XML element.

JerseyRestService.java:

01 package com.javacodegeeks.enterprise.rest.resteasy;
02  
03 import javax.ws.rs.Consumes;
04 import javax.ws.rs.POST;
05 import javax.ws.rs.Path;
06 import javax.ws.rs.core.Response;
07  
08 @Path("/xmlServices")
09 public class RESTEasyXMLServices {
10  
11     @POST
12     @Path("/send")
13     @Consumes("application/xml")
14     public Response comsumeXML(Student student) {
15  
16         String output = student.toString();
17  
18         return Response.status(200).entity(output).build();
19     }
20  
21 }

Now in order to consume that service we have to create a POST request and append an XML file to it. For that we are going to use RESTEasy Client API. To use RESTEasy Client API you have to add an additional library in your pom.xml, as it is not included in the core RESTEasy library.

RESTEasy Client Dependency:

1 <dependency>
2     <groupId>org.jboss.resteasy</groupId>
3     <artifactId>resteasy-client</artifactId>
4     <version>3.0.4.Final</version>
5 </dependency>

For the client code, I’ve created a new class, called RESTEasyClient.java in a new Package calledcom.javacodegeeks.enterprise.rest.resteasy.resteasyclient. So the final Project Structure would be like so:

final-structure

Here is the client:

RESTEasyClient.java:

01 package com.javacodegeeks.enterprise.rest.resteasy.resteasyclient;
02  
03 import javax.ws.rs.client.Entity;
04 import javax.ws.rs.core.Response;
05  
06 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
07 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
08 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
09  
10 import com.javacodegeeks.enterprise.rest.resteasy.Student;
11  
12 public class RESTEasyClient {
13  
14     public static void main(String[] args) {
15  
16         Student st = new Student("Captain""Hook"1012);
17  
18         try {
19             ResteasyClient client = new ResteasyClientBuilder().build();
20  
21             ResteasyWebTarget target = client
22                     .target("http://localhost:9090/RESTEasyXMLExample/rest/xmlServices/send");
23  
24             Response response = target.request().post(
25                     Entity.entity(st, "application/xml"));
26  
27             if (response.getStatus() != 200) {
28                 throw new RuntimeException("Failed : HTTP error code : "
29                         + response.getStatus());
30             }
31  
32             System.out.println("Server response : \n");
33             System.out.println(response.readEntity(String.class));
34  
35             response.close();
36  
37         catch (Exception e) {
38  
39             e.printStackTrace();
40  
41         }
42  
43     }
44 }

As you can see, we create a simple Student instance and send it to the service via a POST Request. This is the output of the above client:

Outptut:

Server response : 

First Name : Captain Last Name : Hook Age : 10 ID : 12

Here is the raw POST request:

POST Request:

POST /RESTEasyXMLExample/rest/xmlServices/send HTTP/1.1
Content-Type: application/xml
Accept-Encoding: gzip, deflate
Content-Length: 150
Host: localhost:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.2.1 (java 1.5)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="12">
	<age>12</age>
	<firstName>Captain</firstName>
	<lastName>Hook</lastName>
</student>

Note: Of course you can produce your POST request using any other tool that does the job. The example will work as long as you append the appropriate code in the POST Request body, like you see in the above request. For instance, you could simply read an XML file as a String and append it to the request.

Download Eclipse Project

This was an XML Example With RESTEasy + JAXB. Download the Eclipse Project of this example: RESTEasyXMLExample.zip

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章