resteasy

XML Example With RESTEasy+ JAXB

In this example we are going to see how you can integrate RESTEasy 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:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>RESTEasyXMLExample</display-name>
  <servlet-mapping>
    <servlet-name>resteasy-servlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>

  <context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>true</param-value>
  </context-param>

  <context-param>
    <param-name>resteasy.servlet.mapping.prefix</param-name>
    <param-value>/rest</param-value>
  </context-param>

  <listener>
    <listener-class>
			org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
			</listener-class>
  </listener>

  <servlet>
    <servlet-name>resteasy-servlet</servlet-name>
    <servlet-class>
			org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
		</servlet-class>
  </servlet>
</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 :

http://localhost:8080/RESTEasyXMLExample/rest/...

1. JAXB Dependency

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

JAXB Dependency:

<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-jaxb-provider</artifactId>
	<version>3.0.4.Final</version>
</dependency>

2. Java Object with JAXB Annotations

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

Student.java:

package com.javacodegeeks.enterprise.rest.resteasy;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "student")
public class Student {

	private int id;
	private String firstName;
	private String lastName;
	private int age;

	// Must have no-argument constructor
	public Student() {

	}

	public Student(String fname, String lname, int age, int id) {
		this.firstName = fname;
		this.lastName = lname;
		this.age = age;
		this.id = id;
	}

	@XmlElement
	public void setFirstName(String fname) {
		this.firstName = fname;
	}

	public String getFirstName() {
		return this.firstName;
	}

	@XmlElement
	public void setLastName(String lname) {
		this.lastName = lname;
	}

	public String getLastName() {
		return this.lastName;
	}

	@XmlElement
	public void setAge(int age) {
		this.age = age;
	}

	public int getAge() {
		return this.age;
	}

	@XmlAttribute
	public void setId(int id) {
		this.id = id;
	}

	public int getId() {
		return this.id;
	}

	@Override
	public String toString() {
		return new StringBuffer(" First Name : ").append(this.firstName)
				.append(" Last Name : ").append(this.lastName)
				.append(" Age : ").append(this.age).append(" ID : ")
				.append(this.id).toString();
	}

}

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:

package com.javacodegeeks.enterprise.rest.resteasy;

import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

@Path("/xmlServices")
public class RESTEasyXMLServices {

	@GET
	@Path("/print/{name}")
	@Produces("application/xml")
	public Student uploadFile(@PathParam("name") String name) {

		Student st = new Student(name, "Diaz",16,5);

		return st;
	}

}

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

http://localhost:8080/RESTEasyXMLExample/rest/xmlServices/print/Ramone

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:

package com.javacodegeeks.enterprise.rest.resteasy;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/xmlServices")
public class RESTEasyXMLServices {

	@POST
	@Path("/send")
	@Consumes("application/xml")
	public Response comsumeXML(Student student) {

		String output = student.toString();

		return Response.status(200).entity(output).build();
	}

}

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:

<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-client</artifactId>
	<version>3.0.4.Final</version>
</dependency>

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

final-structure

Here is the client:

RESTEasyClient.java:

package com.javacodegeeks.enterprise.rest.resteasy.resteasyclient;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import com.javacodegeeks.enterprise.rest.resteasy.Student;

public class RESTEasyClient {

	public static void main(String[] args) {

		Student st = new Student("Captain", "Hook", 10, 12);

		try {
			ResteasyClient client = new ResteasyClientBuilder().build();

			ResteasyWebTarget target = client
					.target("http://localhost:9090/RESTEasyXMLExample/rest/xmlServices/send");

			Response response = target.request().post(
					Entity.entity(st, "application/xml"));

			if (response.getStatus() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ response.getStatus());
			}

			System.out.println("Server response : \n");
			System.out.println(response.readEntity(String.class));

			response.close();

		} catch (Exception e) {

			e.printStackTrace();

		}

	}
}

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

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button