Tuesday 29 August 2017

Return http status code for exceptions in rest services

By extending/using the class 'javax.ws.rs. WebApplicationException’, you can return exceptions with http status code (or) customize error handling.

For example,
public class RestException extends WebApplicationException {

         private static final long serialVersionUID = 1L;

         public RestException(String message, Status status) {
         super(Response.status(status).entity(message).type(MediaType.TEXT_PLAIN).build());
         }
}

You can throw this kind of exception on wrong inputs, validation failures, server errors etc.,

For example, getEmployee method tries to get an employee by id, if employee not exists, it throws RestException with status code 404 (Status.NOT_FOUND) and with some message.
public static Employee getEmployee(int id) {

         Employee emp = employees.get(id);

         if (emp == null) {
                 throw new RestException("Employee with id " + id + " not exist", Status.NOT_FOUND);
         }
         return emp;
}

Below step-by-step procedure explains complete project setup.

Step 1: Create new dynamic web project ‘app’ in eclipse.

Right click on ‘Project Explorer’ -> New -> Dynamic Web Project

Give the project name as ‘app’ and press Next.

In Java window, press Next.

In Web Module window, select the check box ‘Generate web.xml deployment descriptor’, press Finish.

Step 2: Mavenize the project.

Right click on the project ‘app’ -> Configure -> Convert To Maven Project.
It opens ‘Maven POM’ window, use the defaults and press the button Finish.

I am using below maven dependencies.
 <dependencies>
  <dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-servlet-core</artifactId>
   <version>2.25.1</version>
  </dependency>

  <dependency>
   <groupId>org.glassfish.jersey.core</groupId>
   <artifactId>jersey-server</artifactId>
   <version>2.25.1</version>
  </dependency>

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

Step 3: Create a package ‘com.sample.model’ and define the class Employee like below.

Employee.java
package com.sample.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {

 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

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

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

}

Step 4: Create a package ‘com.sample.services’ and define class EmployeeService like below.


EmployeeService.java
package com.sample.service;

import java.util.*;

import javax.ws.rs.core.Response.Status;

import com.sample.exceptions.RestException;
import com.sample.model.Employee;

public class EmployeeService {
 private static Map<Integer, Employee> employees = new HashMap<>();
 private static int id = 1;

 static {
  initializeEmployees();
 }

 private static void initializeEmployees() {
  Employee emp1 = new Employee();

  emp1.setFirstName("Chamu");
  emp1.setLastName("Majety");
  emp1.setId(id);
  id++;

  Employee emp2 = new Employee();
  emp2.setFirstName("Siva");
  emp2.setLastName("Ponnam");
  emp2.setId(id);
  id++;

  employees.put(emp1.getId(), emp1);
  employees.put(emp2.getId(), emp2);
 }

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

 public static Employee getEmployee(int id) {

  Employee emp = employees.get(id);

  if (emp == null) {
   throw new RestException("Employee with id " + id + " not exist", Status.NOT_FOUND);
  }
  return emp;
 }

 public static Employee createEmployee(Employee employee) {
  Employee emp = new Employee();

  if (isEmpty(employee.getFirstName())) {
   throw new RestException("first name should not be empty", Status.BAD_REQUEST);
  }

  if (isEmpty(employee.getLastName())) {
   throw new RestException("last name should not be empty", Status.BAD_REQUEST);
  }

  emp.setFirstName(employee.getFirstName());
  emp.setLastName(employee.getLastName());
  emp.setId(id);
  id++;
  return emp;
 }

 private static boolean isEmpty(String name) {
  if (name == null || name.isEmpty()) {
   return true;
  }

  return false;

 }
}

Step 5: Create a package ‘com.sample.resources’ and define EmployeeResource like below.


EmployeeResource.java
package com.sample.resources;

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

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

import com.sample.model.Employee;
import com.sample.service.EmployeeService;

@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") int empId) {
  Employee emp = EmployeeService.getEmployee(empId);
  return emp;
 }

 @POST
 @Produces(MediaType.APPLICATION_JSON)
 public Employee createEmployee(Employee emp) {
  Employee employee = EmployeeService.createEmployee(emp);
  return employee;
 }
}

Step 6: Create new package ‘com.sample.exceptions’ and define RestException like below.


RestException.java
package com.sample.exceptions;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

public class RestException extends WebApplicationException {

 private static final long serialVersionUID = 1L;

 public RestException(String message, Status status) {
  super(Response.status(status).entity(message).type(MediaType.TEXT_PLAIN).build());
 }
}

Step 7: Define web.xml like below.


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
 <display-name>jersey_tutorial</display-name>
 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>

 <servlet>
  <servlet-name>Jersey REST Service</servlet-name>
  <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  <init-param>
   <param-name>jersey.config.server.provider.packages</param-name>
   <param-value>com.sample.resources</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>Jersey REST Service</servlet-name>
  <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>


My complete project structure looks like below.
Run the application on server. Right click on the project -> Run As -> Run On Server.

If you do not know, hot to configure server in eclipse, you can go through my below post.

I am going to use, rest client plugin to demo this application.

Hit the url ‘http://localhost:8080/app/employees/’ by setting the content type to application/json, you can able to get all the employees information as json.
Now hit the url ‘http://localhost:8080/app/employees/5’, you will get response code as 404 with message ‘Employee with id 5 not exist’.
You can also use the below exceptions directly.
·       BadRequestException
·       ClientErrorException
·       ForbiddenException
·       InternalServerErrorException
·       NotAcceptableException
·       NotAllowedException
·       NotAuthorizedException
·       NotFoundException
·       NotSupportedException
·       ProcessingException
·       RedirectionException
·       ServerErrorException
·       ServiceUnavailableException







Previous                                                 Next                                                 Home

No comments:

Post a Comment