Thursday, 27 August 2015

Jersey REST client for employee application


In previous post I explained, simple Jersey client application, in this post I am going to show you complete client program that work with all URIs of employee application.

As you remember, in previous posts, we developed following URIs.
API URL
Method
Description
/employees
GET
Return all employees
/employees
POST
Add new employee
/employees/employeeID
GET
Get employee details for given id
/employees/employeeID
PUT
Update specific employee
/employees/employeeID
DELETE
Delete employee details for given id
/employees?city=Bangalore
GET
Get all employees staying at Bangalore
/employees?start=1&size=2
GET
Get all employees with ids 1, 2 and 3
/employees/1/address/permanentAddress
GET
Get Permanent address of employee 1.
/employees/1/address/temporaryAddress
GET
Get Temporary address of employee 1.

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>

Step 1: Create model classes Link.java, Address.java, Employee.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();
 }

}

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

}

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 2: Create package "jersey_client.employee". Create classes EmployeeRestClient.java, EmployeeRestClientTest.java.
package jersey_client.employee;

import java.util.List;

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

import jersey_client.model.Address;
import jersey_client.model.Employee;

public class EmployeeRestClient {
 private static String rootURI = "http://localhost:8080/jersey_tutorial";

 private static Client client = ClientBuilder.newClient();

 public static List<Employee> getAllEmployees() {
  WebTarget target = client.target(rootURI).path("employees");
  List<Employee> employees = target.request(MediaType.APPLICATION_JSON)
    .get(new GenericType<List<Employee>>() {
    });
  return employees;
 }

 public static Employee getEmployee(long empId) {
  WebTarget target = client.target(rootURI).path("employees")
    .path("" + empId);
  Employee employee = target.request(MediaType.APPLICATION_JSON).get(
    Employee.class);
  return employee;
 }

 public static Employee updateEmployee(int empId, Employee emp) {
  WebTarget target = client.target(rootURI).path("employees")
    .path("" + empId);

  Entity<Employee> entity = Entity
    .entity(emp, MediaType.APPLICATION_JSON);
  Response res = target.request(MediaType.APPLICATION_JSON).put(entity);
  return res.readEntity(Employee.class);
 }

 public static Employee addNewEmployee(Employee emp) {
  WebTarget target = client.target(rootURI).path("employees");

  Entity<Employee> entity = Entity
    .entity(emp, MediaType.APPLICATION_JSON);
  Response res = target.request(MediaType.APPLICATION_JSON).post(entity);
  return res.readEntity(Employee.class);
 }

 public static Employee deleteEmployee(long empId) {
  WebTarget target = client.target(rootURI).path("employees")
    .path("" + empId);
  Employee emp = target.request(MediaType.APPLICATION_JSON).delete(
    Employee.class);
  return emp;
 }

 public static List<Employee> getEmployeesStayingAtCity(String city) {
  WebTarget target = client.target(rootURI).path("employees")
    .queryParam("city", city);
  List<Employee> employees = target.request(MediaType.APPLICATION_JSON)
    .get(new GenericType<List<Employee>>() {
    });
  return employees;
 }

 public static List<Employee> getEmployees(long start, long size) {
  WebTarget target = client.target(rootURI).path("employees")
    .queryParam("start", start).queryParam("size", size);
  List<Employee> employees = target.request(MediaType.APPLICATION_JSON)
    .get(new GenericType<List<Employee>>() {
    });
  return employees;
 }

 public static Address getPermanentAddress(long empId) {
  WebTarget target = client.target(rootURI).path("employees")
    .path("" + empId).path("address").path("permanentAddress");
  Address address = target.request(MediaType.APPLICATION_JSON).get(
    Address.class);
  return address;
 }

 public static Address getTemporaryAddress(long empId) {
  WebTarget target = client.target(rootURI).path("employees")
    .path("" + empId).path("address").path("temporaryAddress");
  Address address = target.request(MediaType.APPLICATION_JSON).get(
    Address.class);
  return address;
 }

}

package jersey_client.employee;

import static jersey_client.employee.EmployeeRestClient.addNewEmployee;
import static jersey_client.employee.EmployeeRestClient.deleteEmployee;
import static jersey_client.employee.EmployeeRestClient.getAllEmployees;
import static jersey_client.employee.EmployeeRestClient.getEmployee;
import static jersey_client.employee.EmployeeRestClient.getEmployees;
import static jersey_client.employee.EmployeeRestClient.getEmployeesStayingAtCity;
import static jersey_client.employee.EmployeeRestClient.getPermanentAddress;
import static jersey_client.employee.EmployeeRestClient.getTemporaryAddress;
import static jersey_client.employee.EmployeeRestClient.updateEmployee;

import java.util.List;

import jersey_client.model.Address;
import jersey_client.model.Employee;

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

public class EmployeeRestClientTest {
 private static Gson gson = new GsonBuilder().setPrettyPrinting().create();

 private static void printStars() {
  System.out.println("****************************************");
 }

 public static void main(String args[]) {
  Employee emp1 = getEmployee(3);
  List<Employee> employees = getAllEmployees();

  /* Adding new employee */
  Address tempAddr = new Address();
  Address permAddr = new Address();

  tempAddr.setArea("Domlur");
  tempAddr.setCity("Bangalore");
  tempAddr.setCountry("India");
  tempAddr.setState("Karnataka");

  permAddr.setArea("MGRoad");
  permAddr.setCity("Jaipur");
  permAddr.setCountry("India");
  permAddr.setState("Rajasthan");

  Employee emp2 = new Employee();
  emp2.setFirstName("Sankalp");
  emp2.setLastName("Dubey");
  emp2.setTempAddrees(tempAddr);
  emp2.setPermAddrees(permAddr);

  Employee emp3 = addNewEmployee(emp2);

  /* Update employee 1 */
  Employee emp4 = updateEmployee(1, emp2);

  /* Delete employee 2 */
  Employee emp5 = deleteEmployee(2);

  /* Get employees staying at Hyderabad */
  List<Employee> employees2 = getEmployeesStayingAtCity("Hyderabad");

  /* Get Employees from ids 1, 2, 3, 4, 5 */
  List<Employee> employees3 = getEmployees(1, 5);

  /* Get Permanent address of employee 3 */
  Address permAddr1 = getPermanentAddress(3);

  /* Get Temporary address of employee 3 */
  Address tempAddr1 = getTemporaryAddress(3);

  System.out.println("Employee 3 details");
  printStars();
  System.out.println(gson.toJson(emp1));

  System.out.println("All employee details");
  printStars();
  System.out.println(gson.toJson(employees));

  System.out.println("New employee added");
  printStars();
  System.out.println(gson.toJson(emp3));

  System.out.println("Updated employee 1");
  printStars();
  System.out.println(gson.toJson(emp4));

  System.out.println("Employee deleted with id 2");
  printStars();
  System.out.println(gson.toJson(emp5));

  System.out.println("Employees staying at Hyderabad");
  printStars();
  System.out.println(gson.toJson(employees2));

  System.out.println("First five employees are");
  printStars();
  System.out.println(gson.toJson(employees3));

  System.out.println("Permanenet Address of employee 3 is");
  printStars();
  System.out.println(gson.toJson(permAddr1));

  System.out.println("Temporary Address of employee 3 is");
  printStars();
  System.out.println(gson.toJson(tempAddr1));

 }
}


Run EmployeeRestClientTest, you will get following output.
Employee 3 details
****************************************
{
  "firstName": "Rama Krishna",
  "lastName": "Gurram",
  "id": 3,
  "links": [
    {
      "link": "http://localhost:8080/jersey_tutorial/employees/3/address/temporaryAddress",
      "rel": "Temporary Address"
    },
    {
      "link": "http://localhost:8080/jersey_tutorial/employees/3/address/permanentAddress",
      "rel": "Permanent Address"
    }
  ]
}
All employee details
****************************************
[
  {
    "firstName": "Hari Krishna",
    "lastName": "Gurram",
    "id": 1,
    "links": []
  },
  {
    "firstName": "PTR",
    "lastName": "PTR",
    "id": 2,
    "links": []
  },
  {
    "firstName": "Rama Krishna",
    "lastName": "Gurram",
    "id": 3,
    "links": [
      {
        "link": "http://localhost:8080/jersey_tutorial/employees/3/address/temporaryAddress",
        "rel": "Temporary Address"
      },
      {
        "link": "http://localhost:8080/jersey_tutorial/employees/3/address/permanentAddress",
        "rel": "Permanent Address"
      }
    ]
  }
]
New employee added
****************************************
{
  "firstName": "Sankalp",
  "lastName": "Dubey",
  "id": 4,
  "links": []
}
Updated employee 1
****************************************
{
  "firstName": "Sankalp",
  "lastName": "Dubey",
  "id": 1,
  "links": []
}
Employee deleted with id 2
****************************************
{
  "firstName": "PTR",
  "lastName": "PTR",
  "id": 2,
  "links": []
}
Employees staying at Hyderabad
****************************************
[
  {
    "firstName": "Rama Krishna",
    "lastName": "Gurram",
    "id": 3,
    "links": [
      {
        "link": "http://localhost:8080/jersey_tutorial/employees/3/address/temporaryAddress",
        "rel": "Temporary Address"
      },
      {
        "link": "http://localhost:8080/jersey_tutorial/employees/3/address/permanentAddress",
        "rel": "Permanent Address"
      }
    ]
  }
]
First five employees are
****************************************
[
  {
    "firstName": "Sankalp",
    "lastName": "Dubey",
    "id": 1,
    "links": []
  },
  {
    "firstName": "Rama Krishna",
    "lastName": "Gurram",
    "id": 3,
    "links": [
      {
        "link": "http://localhost:8080/jersey_tutorial/employees/3/address/temporaryAddress",
        "rel": "Temporary Address"
      },
      {
        "link": "http://localhost:8080/jersey_tutorial/employees/3/address/permanentAddress",
        "rel": "Permanent Address"
      }
    ]
  },
  {
    "firstName": "Sankalp",
    "lastName": "Dubey",
    "id": 4,
    "links": []
  }
]
Permanenet Address of employee 3 is
****************************************
{
  "street": "Bharath Nagar",
  "city": "Hyderabad",
  "state": "Andhra Pradesh",
  "country": "India"
}
Temporary Address of employee 3 is
****************************************
{
  "street": "SR Nagar",
  "city": "Hyderabad",
  "state": "Andhra Pradesh",
  "country": "India"
}


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment