Showing posts with label Jersey. Show all posts
Showing posts with label Jersey. Show all posts

Saturday, December 20, 2014

Marshalling Java to JSON in JAX-RS

1 comment:
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.

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;
}
}

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);
}
}

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());
}
}

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!

Read More

Sunday, September 21, 2014

How to write REST client with proxy configurations?

3 comments:

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");
After created the client object, we have to add the property with specific with the proxy url configuration into the client.

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.

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...

Read More

Friday, September 19, 2014

How to write POST method in RESTful Java using Jersey?

7 comments:

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...
}

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! 

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...

Read More

Monday, August 25, 2014

RESTful Java Part2: How to setup the environment for REST service development

No comments:
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

Read More