Tuesday 15 November 2016

Embedded Jetty & Jersey Example

In this post, I am going to explain how to integrate Jersey with Embedded jetty server.

If you want to know about REST in detail, you can go through the following tutorial.


If you want to know about Jetty server, you can go through following tutorial.


Following step-by-step procedure explains the implementation and deployment of complete application.

Step 1: Create new Maven project ‘jetty_tutorial’ in Eclipse.
File -> New -> Other. Select 'Maven Project'. Give the project name as 'jetty_tutorial'.

Step 2: Open pom.xml and update the maven dependencies. I am using following maven dependencies.
<dependencies>
  <dependency>
   <groupId>org.eclipse.jetty</groupId>
   <artifactId>jetty-server</artifactId>
   <version>9.4.0.RC1</version>
  </dependency>
  <dependency>
   <groupId>org.eclipse.jetty</groupId>
   <artifactId>jetty-servlet</artifactId>
   <version>9.4.0.RC1</version>
  </dependency>
  <dependency>
   <groupId>org.glassfish.jersey.core</groupId>
   <artifactId>jersey-server</artifactId>
   <version>2.15</version>
  </dependency>
  <dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-servlet-core</artifactId>
   <version>2.15</version>
  </dependency>
  <dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-jetty-http</artifactId>
   <version>2.15</version>
  </dependency>
  <dependency>
   <groupId>org.glassfish.jersey.media</groupId>
   <artifactId>jersey-media-moxy</artifactId>
   <version>2.15</version>
  </dependency>
 </dependencies>

Step 3: Create new package 'com.sample'. Add the class HelloWorld.java.

HelloWorld.java
package com.sample;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public class HelloWorld {
 @GET
 @Path("test")
 @Produces(MediaType.TEXT_PLAIN)
 public String test() {
  return "Test";
 }
}

Step 4: Define App.java like below.
App.java
package com.sample;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class App {
 public static void main(String[] args) throws Exception {
  ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath("/");

  Server jettyServer = new Server(8080);
  jettyServer.setHandler(context);

  ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
  jerseyServlet.setInitOrder(0);

  jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", HelloWorld.class.getCanonicalName());

  try {
   jettyServer.start();
   jettyServer.join();
  } catch (Exception e) {
   e.printStackTrace();
  } finally{
   jettyServer.destroy();
  }
 }
}

Run ‘App.java’, you can able to see following log messages in console.
2016-11-15 13:42:19.682:INFO::main: Logging initialized @245ms to org.eclipse.jetty.util.log.StdErrLog
2016-11-15 13:42:19.828:INFO:oejs.Server:main: jetty-9.4.0.RC1
2016-11-15 13:42:19.828:WARN:oejs.Server:main: THIS IS NOT A STABLE RELEASE! DO NOT USE IN PRODUCTION!
2016-11-15 13:42:19.828:WARN:oejs.Server:main: Download a stable release from http://download.eclipse.org/jetty/
2016-11-15 13:42:19.876:INFO:oejs.session:main: DefaultSessionIdManager workerName=node0
2016-11-15 13:42:19.876:WARN:oejs.session:main: No SessionScavenger set, using defaults
2016-11-15 13:42:19.879:INFO:oejs.session:main: Scavenging every 600000ms
2016-11-15 13:42:20.712:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler@1f9e9475{/,null,AVAILABLE}
2016-11-15 13:42:21.022:INFO:oejs.AbstractConnector:main: Started ServerConnector@2506fbde{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2016-11-15 13:42:21.023:INFO:oejs.Server:main: Started @1588ms

Open any browser and hit the url ‘http://localhost:8080/hello/test’, you can able to see the message ‘Test’ in browser body.

Returning a json response using embedded jetty. 
Following step-by-step procedure explains how to send json response.


Address.java
package com.sample;

import javax.xml.bind.annotation.XmlRootElement;

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

}

Employee.java
package com.sample;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {
 private String firstName;
 private String lastName;
 private long id;
 private Address permAddrees;
 private 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;
 }

 public Address getTempAddrees() {
  return tempAddrees;
 }

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

}

EmployeeService.java
package com.sample;

import java.util.HashMap;
import java.util.Map;

public class EmployeeService {
 private static Map<Long, Employee> employees = new HashMap<>();

 static {
  initializeEmployees();
 }

 private static void initializeEmployees() {
  Address tempAddr1 = new Address("Electronic City", "Bangalore", "Karnataka", "India");
  Address tempAddr2 = new Address("BTM Layout", "Bangalore", "Karnataka", "India");
  Address permAddr1 = new Address("Marthali", "Bangalore", "Karnataka", "India");
  Address permAddr2 = new Address("Bharath Nagar", "Hyderabad", "Andhra Pradesh", "India");

  Employee emp1 = new Employee("Hari Krishna", "Gurram", 1, permAddr1, tempAddr1);
  Employee emp2 = new Employee("PTR", "PTR", 2, permAddr2, tempAddr2);

  employees.put(1l, emp1);
  employees.put(2l, emp2);
 }

 public static Map<Long, Employee> getAllEmployees() {
  return employees;
 }

 public static Employee getEmployee(long id) {
  return employees.get(id);
 }
}

EmployeeResource.java
package com.sample;

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

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

@Path("employees")
public class EmployeeResource {

 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public List<Employee> getAllEmployees() {
  return new ArrayList<>(EmployeeService.getAllEmployees().values());
 }

 @GET
 @Path("/{employeeId}")
 @Produces(MediaType.APPLICATION_JSON)
 public Employee getEmployee(@PathParam("employeeId") long empId) {
  return EmployeeService.getEmployee(empId);
 }

}

App.java
package com.sample;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class App {
 public static void main(String[] args) throws Exception {
  ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath("/");

  Server jettyServer = new Server(8080);
  jettyServer.setHandler(context);

  ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
  jerseyServlet.setInitOrder(0);

  jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
    EmployeeResource.class.getCanonicalName());

  try {
   jettyServer.start();
   jettyServer.join();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   jettyServer.destroy();
  }
 }
}

Open any browser, hit the url 'http://localhost:8080/employees/2'. You can able to see following json response.
{"firstName":"PTR","id":2,"lastName":"PTR","permAddrees":{"area":"Bharath Nagar","city":"Hyderabad","country":"India","state":"Andhra Pradesh"},"tempAddrees":{"area":"BTM Layout","city":"Bangalore","country":"India","state":"Karnataka"}}








Previous                                                 Next                                                 Home

No comments:

Post a Comment