Thursday 27 August 2015

Jersey REST client API tutorial


Throught this tutorial, I am going to use webserive application developed in previous post ‘Jersey Content Negotiation’.

Jersey REST client API provides number of APIS to consume RESTful Web services exposed over HTTP.

Lets start writing our first RestClient for employee application that developed at post ‘Jersey Content Negotiation’. In this post, I am going to access the URI http://localhost:8080/jersey_tutorial/employees/1 using Jersey REST client, Next post shows complete application to access all URIs of employee application.

Following are the maven dependencies, I used to work with Jersey REST client.

<dependencies>
         <dependency>
                  <groupId>org.glassfish.jersey.core</groupId>
                  <artifactId>jersey-client</artifactId>
                  <version>2.21</version>
                  <scope>provided</scope>
         </dependency>

         <dependency>
                  <groupId>org.glassfish.jersey.media</groupId>
                  <artifactId>jersey-media-moxy</artifactId>
                  <version>2.21</version>
         </dependency>

         <dependency>
                  <groupId>com.google.code.gson</groupId>
                  <artifactId>gson</artifactId>
                  <version>2.3.1</version>
         </dependency>

</dependencies>

To utilize the client API it is first necessary to build an instance of a Client using one of the static ClientBuilder factory methods

Client client = ClientBuilder.newClient();

Once you got client instance, create WebTarget to the resource URI.
WebTarget target = client.target("http://localhost:8080").path("jersey_tutorial").path("employees").path("1");

Above statement creates a target that points to URI, http://localhost:8080/jersey_tutorial/employees/1.

Start building a request to the targeted web resource and define the accepted response media types.

Employee employee = target.request(MediaType.APPLICATION_JSON).get(Employee.class);

I used gson package to print employee object in json format.

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(employee);
System.out.println(json);

Following is the step-by-step procedure to develop our first application.

Step 1: Create simple java maven project “jersey_client_tutorial”.

Step 2: Create package jersey_client.model, create model classes Link.java, Address.java, Employee.java.

Link.java
package jersey_client.model;

public class Link {
 private String link;
 private String rel;

 public String getLink() {
  return link;
 }

 public void setLink(String link) {
  this.link = link;
 }

 public String getRel() {
  return rel;
 }

 public void setRel(String rel) {
  this.rel = rel;
 }

 public Link(String link, String rel) {
  this.link = link;
  this.rel = rel;
 }

 public Link() {

 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Link [link=").append(link).append(", rel=").append(rel)
    .append("]");
  return builder.toString();
 }

}


Address.java
package jersey_client.model;

public class Address {
 private String street;
 private String city;
 private String state;
 private String country;

 public Address() {
  this("No Data", "No Data", "No Data", "No Data");
 }

 public Address(String area, String city, String state, String country) {
  super();
  this.street = area;
  this.city = city;
  this.state = state;
  this.country = country;
 }

 public String getArea() {
  return street;
 }

 public String getCity() {
  return city;
 }

 public String getCountry() {
  return country;
 }

 public String getState() {
  return state;
 }

 public void setArea(String area) {
  this.street = area;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 public void setState(String state) {
  this.state = state;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Address [street=").append(street).append(", city=")
    .append(city).append(", state=").append(state)
    .append(", country=").append(country).append("]");
  return builder.toString();
 }

}


Employee.java
package jersey_client.model;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlTransient;

public class Employee {
 private String firstName;
 private String lastName;
 private long id;
 private List<Link> links = new ArrayList<Link>();

 private transient Address permAddrees;

 private transient Address tempAddrees;

 public Employee() {
  this("No Data", "No Data", -1, new Address(), new Address());
 }

 public Employee(String firstName, String lastName, long id,
   Address permAddrees, Address tempAddrees) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
  this.id = id;
  this.permAddrees = permAddrees;
  this.tempAddrees = tempAddrees;
 }

 public String getFirstName() {
  return firstName;
 }

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

 public String getLastName() {
  return lastName;
 }

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

 public long getId() {
  return id;
 }

 public void setId(long id) {
  this.id = id;
 }

 public Address getPermAddrees() {
  return permAddrees;
 }

 public void setPermAddrees(Address permAddrees) {
  this.permAddrees = permAddrees;
 }

 @XmlTransient
 public Address getTempAddrees() {
  return tempAddrees;
 }

 public void setTempAddrees(Address tempAddrees) {
  this.tempAddrees = tempAddrees;
 }

 public List<Link> getLinks() {
  return links;
 }

 public void setLinks(List<Link> links) {
  this.links = links;
 }

 public void updateLinks(String tempAddressURL, String permAddressURL) {
  links = new ArrayList<>();
  Link link1 = new Link(tempAddressURL, "Temporary Address");
  Link link2 = new Link(permAddressURL, "Permanent Address");

  links.add(link1);
  links.add(link2);
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [firstName=").append(firstName)
    .append(", lastName=").append(lastName).append(", id=")
    .append(id).append(", links=").append(links)
    .append(", permAddrees=").append(permAddrees)
    .append(", tempAddrees=").append(tempAddrees).append("]");
  return builder.toString();
 }

}


Step 3: Create package “jersey_client.employee”. Create EmployeeRestClient.java.

EmployeeRestClient.java
package jersey_client.employee;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;

import jersey_client.model.Employee;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class EmployeeRestClient {

 public static void main(String args[]) {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target("http://localhost:8080")
    .path("jersey_tutorial").path("employees").path("1");
  Employee employee = target.request(MediaType.APPLICATION_JSON).get(
    Employee.class);

  Gson gson = new GsonBuilder().setPrettyPrinting().create();
  String json = gson.toJson(employee);
  System.out.println(json);
 }
}


Run EmployeeRestClient application, you will get following output.

{
  "firstName": "Hari Krishna",
  "lastName": "Gurram",
  "id": 1,
  "links": [
    {
      "link": "http://localhost:8080/jersey_tutorial/employees/1/address/temporaryAddress",
      "rel": "Temporary Address"
    },
    {
      "link": "http://localhost:8080/jersey_tutorial/employees/1/address/permanentAddress",
      "rel": "Permanent Address"
    }
  ]
}





 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment