Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts
Saturday, December 20, 2014
Marshalling Java to JSON in JAX-RS
1 comment:
Posted by
Unknown
at
3:09 PM
Labels:
Java,
jax-rs,
Jersey,
Marshaller,
REST,
RESTful,
Serialization
In this article, I am going to explain about the purpose and the process of writing custom marshaller for web services. First we have to be clear on what is marshaller. Marshalling is the nothing but the process of converting in-memory object into persisting or transportable format.
Now a days most of the web services are returning the response as JSON object. Some people are still using XML as their preferred transport medium.
JAX-RS api has introduced a generic and pluggable interface called MessageBodyWriter for doing the marshalling.
In the above REST method, we have just returned Java object itself to the client as response. If you notice the @Produces, we are returning the JSON contents back to the client.
Stumbled! The magic happens at the marshalling layer. Now we will see how the marshalling code will look like.
We have to look 'writeTo' method just to understand the process. The first arguments is coming from the injection layer so the current Java object will be available to this processor. Now we have process the Java object and should generate JSON object. In this example I have used the 'javax.json.jar' for generating the JSON content. Finally the JSON content should be written into output stream.
Finally we have register the provider (BookJsonMarshaller) into our application like other resources...
Before we conclude this article, you may have one question. Why we need to write the custom marshaller for processing the Java object. Is it not possible by default? You question is valid. This is still possible. But if you want to have a full control over the generated JSON content, we have to write our own @Providers...
I hope you have enjoyed reading this article. If you have any questions or comments please reply to this thread... We will meet again with another discussion.
For code reference, don't forget to visit Github
Advance Christmas wishes to my readers!
Now a days most of the web services are returning the response as JSON object. Some people are still using XML as their preferred transport medium.
JAX-RS api has introduced a generic and pluggable interface called MessageBodyWriter for doing the marshalling.
Use-case:
We will take an use-case in-order to understand the situation little better. We have a Java bean called Book. Now we have to write a REST service which will fetch the Java object from the given ID and return JSON response back to the client.Book.java:
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
}
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
}
BookResource.java:
public class BookResource {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Book getBook(@PathParam("id") String id) {
//DataProvider is simple data holder
DataProvider dataProvider = DataProvider.getInstance();
return dataProvider.getBook(id);
}
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Book getBook(@PathParam("id") String id) {
//DataProvider is simple data holder
DataProvider dataProvider = DataProvider.getInstance();
return dataProvider.getBook(id);
}
}
In the above REST method, we have just returned Java object itself to the client as response. If you notice the @Produces, we are returning the JSON contents back to the client.
Stumbled! The magic happens at the marshalling layer. Now we will see how the marshalling code will look like.
BookJsonMarshaller.java:
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class BookJsonMarshaller implements MessageBodyWriter<Book> {
@Override
public long getSize(Book book, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return clazz == Book.class;
}
@Override
public void writeTo(Book book, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> valueMap, OutputStream stream) throws IOException, WebApplicationException {
JsonObject jsonObject = Json.createObjectBuilder()
.add("title", book.getTitle())
.add("author", book.getAuthor()).build();
DataOutputStream outputStream = new DataOutputStream(stream);
outputStream.writeBytes(jsonObject.toString());
}
}
@Produces(MediaType.APPLICATION_JSON)
public class BookJsonMarshaller implements MessageBodyWriter<Book> {
@Override
public long getSize(Book book, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return clazz == Book.class;
}
@Override
public void writeTo(Book book, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> valueMap, OutputStream stream) throws IOException, WebApplicationException {
JsonObject jsonObject = Json.createObjectBuilder()
.add("title", book.getTitle())
.add("author", book.getAuthor()).build();
DataOutputStream outputStream = new DataOutputStream(stream);
outputStream.writeBytes(jsonObject.toString());
}
}
We have to look 'writeTo' method just to understand the process. The first arguments is coming from the injection layer so the current Java object will be available to this processor. Now we have process the Java object and should generate JSON object. In this example I have used the 'javax.json.jar' for generating the JSON content. Finally the JSON content should be written into output stream.
Finally we have register the provider (BookJsonMarshaller) into our application like other resources...
Before we conclude this article, you may have one question. Why we need to write the custom marshaller for processing the Java object. Is it not possible by default? You question is valid. This is still possible. But if you want to have a full control over the generated JSON content, we have to write our own @Providers...
I hope you have enjoyed reading this article. If you have any questions or comments please reply to this thread... We will meet again with another discussion.
For code reference, don't forget to visit Github
Advance Christmas wishes to my readers!
Monday, November 24, 2014
REST service client with JAX-RS API
Background:
Are you still using Apache HTTP client or Java URL connection to speak with REST service? Then this article is for you. JAX-RS specification has released with new client API to communicate with RESTful services. Here you can see how you can use JAX-RS client API for your communication.As a first step, we have to create a web target in-order to talk to our web services. Using the ClientBuilder, we should create a Client object.
From the client object we can create WebTarget object like below,
WebTarget api will accept base path and resource path separately. But we can also give the combined url as a whole to the target method.
Once we get the webTarget object, we are ready to communicate with the REST service. From the webTarget object we can invoke the respective REST methods...
In the above image we have called the get method. This will return the response object. From the response object we can validate the response status and read the entity from the response.
Just to get the JSON string from the response, we have passed the object type (String.class) to the readEntity method. If we get any complex object type, we can still use them.
I hope you will enjoy this article. Please give your comments or feedback if you have any... We will meet shortly with another article.
Sunday, September 21, 2014
How to write REST client with proxy configurations?
Proxy?
Most of the enterprises have the proxy settings in-order to hide the actual endpoint from the client. Client will interact with the proxy, but the proxy will forward the request to the actual endpoint and return the response back to the client.So what?
Till now we have seen code, how to communicate directly to the REST end-point. So the approach is straight forward. We don't need to have any special handling for the communication. Where-as if the REST service is hosted behind the proxy how to communicate?Still thinking how? Don't worry it is very easy with Jersey client API.
client = ClientBuilder.newClient();
client.property(ClientProperties.PROXY_URI, "<proxy_host>:<proxy_port");
client.property(ClientProperties.PROXY_URI, "<proxy_host>:<proxy_port");
In some cases, our network proxy has been restricted with user name and password. In such a situation we need to set the user name and password configuration into the client object as below,
client.property(ClientProperties.PROXY_USERNAME, "<username>");
client.property(ClientProperties.PROXY_PASSWORD, "<password>");
This is how we have to communicate with the REST end-point if our services are available behind proxy.client.property(ClientProperties.PROXY_PASSWORD, "<password>");
I hope this has clarified your doubts on REST client with proxy configuration. If you have any comments or questions please add your comments below...
Friday, September 19, 2014
How to write POST method in RESTful Java using Jersey?
Introduction:
In our previous articles, we have seen how to write basic REST services using Jersey framework. And also we saw how to write REST client using Jersey client API. In this article we are going to see, how to write POST method and how to consume the API.Implementation:
POST method is a special method and it being used interchangeably based on the situation. Meaning some will use POST method for updating an object and some people are using POST method for creating an object. It is up to the user who can decide the situation based on their need.As you guessed so, the POST method is annotated with @POST annotation. In the below example there are 2 variables are passed from the client.
title
author
Both these parameters are annotated with @FormParam annotation.
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public String createBook(@FormParam(value = "title") String title, @FormParam(value = "author") String author) {
Book book = new Book(title, author);
Gson gson = new Gson(); //Gson is used to simplify the JSON generation process
return gson.toJson(book); //Just send back the JSON to the client. But user can do anything...
}
@Produces(MediaType.APPLICATION_JSON)
public String createBook(@FormParam(value = "title") String title, @FormParam(value = "author") String author) {
Book book = new Book(title, author);
Gson gson = new Gson(); //Gson is used to simplify the JSON generation process
return gson.toJson(book); //Just send back the JSON to the client. But user can do anything...
}
Client code:
JAX-RS and Jersey have provided lot of useful API's to write REST client code.
//Setting the post method url to the client
WebTarget webTarget = client.target("http://localhost:8080/restfullab/api").path("book");
//Add key-value pair into the form object
Form form = new Form();
form.param("title", "RESTful Java with JAX-RS 2.0 ");
form.param("author", "Bill Burke");
//Send the form object along with the post call
Response response = webTarget.request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));
System.out.println("Respose code: " + response.getStatus());
System.out.println("Respose value: " + response.readEntity(String.class));
The parameters will be passed through 'Form' values as key-value pair. 'Key' should match with the @FormParam annotation value.
I hope you have enjoyed reading this post. Please give your valuable feedback or comments if you have any...
We will meet again in few days in another article. Until then enjoy hacking RESTful Java and Jersey framework!
We will meet again in few days in another article. Until then enjoy hacking RESTful Java and Jersey framework!
Source references:
Working source code is available under the following location in Github. Fork and enjoy...https://github.com/LiquidLab/restfullab/blob/master/src/com/liquidlab/restfullab/resources/BookResource.java
https://github.com/LiquidLab/restfullab/blob/master/test/com/liquidlab/restfullab/resources/test/BookResourceTest.java
Refer Jersey Javadoc for further details...
Tuesday, September 9, 2014
How to write REST service client with JAX-RS API?
Introduction:
The purpose of the article is how to write REST service client code JAX-RS api. I hope you have understood the basic concepts of RESTful web services and how to write services with Jersey framework. Now we will write some code to consume the REST service using the JAX-RS client API.Possible ways of REST client:
There are many possible ways through which we can communicate with the available rest services. Here our main focus is to communicate with rest services using JAX-RS code. The other possible ways are the following,- CURL
- Advanced REST client (browser plugin)
- Post Man (browser plugin)
In one of the previous example, I have explained how to write rest services. Based on the above article I assume, there is a service running in Tomcat in the following url,
http://localhost:8080/restfullab/apiAnd we have defined one resource with GET method in "hello"
So the complete url to access the rest end-point is http://localhost:8080/restfullab/api/hello
Client code:
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("http://localhost:8080/restfullab/api").path("hello");
Response response = webTarget.request(MediaType.TEXT_PLAIN).get();
System.out.println(response.getStatus()); //Prints the response code. 200 if OK
System.out.println(response.readEntity(String.class)); // Prints the response text
WebTarget webTarget = client.target("http://localhost:8080/restfullab/api").path("hello");
Response response = webTarget.request(MediaType.TEXT_PLAIN).get();
System.out.println(response.getStatus()); //Prints the response code. 200 if OK
System.out.println(response.readEntity(String.class)); // Prints the response text
I hope this article have given an overview on how to call REST service using JAX-RS api. In the next article we will see how to call other types of methods like POST, PUT and DELETE.
Give your valuable feedback if you have any... See you next time...
Monday, August 25, 2014
RESTful Java Part2: How to setup the environment for REST service development
In the below video, you can watch the step by step information on how to setup the development environment for RESTful web services with Jersey.
This video is mainly for non Maven developers...
Keep watching this space for more information on RESTful Java and related technologies. For basic introduction on RESTful Java, Read the earlier article
This video is mainly for non Maven developers...
Keep watching this space for more information on RESTful Java and related technologies. For basic introduction on RESTful Java, Read the earlier article
RESTful Java Part3: Basic terminologies on RESTful Java
Introduction:
The purpose of this article is to explain about the basic terminologies on JAX-RS / RESTful Java. Here we can understand how all the small pieces are playing its role
High Level Diagram:

Next we will go through the details about each component and its role in the whole REST world...

Resource:
- Base resources and sub-resources can be annotated with @Path.
- @Path represents the actual end-point for REST resources.
- Only public methods can be exposed as resource end-points.

HTTP Methods:
- GET
- POST
- PUT
- DELETE
- HEAD and OPTIONS (special cases)
Parameters:
- PathParam
Extracts the values from the resource path. For example when a resource path is mentioned like, @Path("users/{id}"), the value of id will be passed along with the path. This will be accessed using @PathParam inside the method.
- QueryParam
Extracts the values passed along with the query string.
Example: http://<host_name>:<port>/users?response=json. Here "response" will be treated as a query parameter and will be accessed like @QueryParam inside the method
- FormParam
Kind of special parameters. When a html form is submitted to the resource, all the form values will be available through @FormParam
- MatrixParam
Just a key-value pair of parameters available through the resource end-point. This will extracts the path parameters
- HeaderParam
The values passed through the HTTP headers will be available through @HeaderParam
- Context
This indicates about the values available from client to server. For example UriInfo and HttpHeaders and some of the servlet information can be accessible through @Context annotations
- CookieParam
Client cookie related variables can be accessed through @CookieParam annotations
Consumes:
Mentioned by the client what kind of data the server will accept (Exact match of the request content-type will be decided at the run-time based on the priority. We will see this in detail in the coming series)
Produces:
Based on the @produces value, the server will send the output packets to the client.
I hope this article has given you high level understanding on each terminologies mentioned by JAX-RS specification. HTTP Methods will be covered in details in separate article.
Thanks for your valuable time. We will meet again in few days... Don't forget to put your comments below if any...
Hello RESTful Java
Background:
The purpose of the article is to give some background information on, what is RESTful webservices and how this can be possible using Java language. You will understand the following when you finish reading this article.
What you will learn:
- What is RESTful web services?
- How to write RESTful web service using Java
Let us first see some of the definitions about RESTful web services.
As per wiki,
REST is an architectural style consisting of a coordinated set of architectural constraints applied to components, connectors, and data elements, within a distributed hypermedia system and REST stands for Representational state transfer (REST).
So REST is not a technology but it is architectural style for programming. In a highly distributed system, everything can be seen as a resource.
In the background the communication is happening through the plain old HTTP protocol. So REST is completely stateless.
As a programmer we are bored reading lot of contents. So we quickly see some of live coding for writing our first RESTful web services in Java.
The following picture will explain what are the various framework / specification has been used in our demo...

Service code:
@Path("/hello")
public class HelloWorldResource {
@GET
@Produces(MediaType.TEXT_PLAIN_TYPE)
public String sayHello() {
return "Welcome RESTful Java";
}
}
Looks so simple know... Now you have written your first REST service in Java. All the annotations are used from Jersey library. So download the Jersey library and put in inside your web application path (WEB-INF/lib).
After you deploy your applicable (rest.war) into any web server, open a browser and hit http://localhost:8080/rest/hello, then you will see "Welcome RESTful Java" in your browser window.
In order to generate JSON string from the given bean object, you can use Gson library.
User user = new User();
user.setId("123");
user.setName("John");
Gson gson = new Gson();
return gson.toJson(user);
The above code will return,
{
"id": "123",
"name": "John"
}
Thanks for reading... Next article we will see how we can set up our environment to start coding with Java and RESTful web services...
All the related source codes are available under https://github.com/LiquidLab/restfullab
Subscribe to:
Posts (Atom)



