Wednesday, November 29, 2017

RESTful with JAX-RS


Interview Question on Webservices







REST Web Services  - Handling Exceptions









RESTful Web Service - JAX-RS Annotations - Contents:

Annotation
Package Detail/Import statement
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;

@GET

Annotate your Get request methods with @GET.
1
2
3
4
@GET
public String getHTML() {
  ...
}

@Produces

@Produces annotation specifies the type of output this method (or web service) will produce.
1
2
3
4
5
@GET
@Produces("application/xml")
public Contact getXML() {
  ...
}
1
2
3
4
5
@GET
@Produces("application/json")
public Contact getJSON() {
  ...
}

@Path

@Path annotation specify the URL path on which this method will be invoked.
1
2
3
4
5
6
@GET
@Produces("application/xml")
@Path("xml/{firstName}")
public Contact getXML() {
  ...
}

@PathParam

We can bind REST-style URL parameters to method arguments using @PathParam annotation as shown below.
1
2
3
4
5
6
7
@GET
@Produces("application/xml")
@Path("xml/{firstName}")
public Contact getXML(@PathParam("firstName") String firstName) {
  Contact contact = contactService.findByFirstName(firstName);
  return contact;
}


1
2
3
4
5
6
7
@GET
@Produces("application/json")
@Path("json/{firstName}")
public Contact getJSON(@PathParam("firstName") String firstName) {
  Contact contact = contactService.findByFirstName(firstName);
  return contact;
}

@QueryParam

Request parameters in query string can be accessed using @QueryParam annotation as shown below.
1
2
3
4
5
6
7
@GET
@Produces("application/json")
@Path("json/companyList")
public CompanyList getJSON(@QueryParam("start") int start, @QueryParam("limit") int limit) {
  CompanyList list = new CompanyList(companyService.listCompanies(start, limit));
  return list;
}
The example above returns a list of companies (with server side pagination) which can be displayed with rich clients implemented using Ext-js or jQuery. You can read more more about setting up ExtJS grid panel with remote sorting and pagination using Hibernate.

@POST

Annotate POST request methods with @POST.
1
2
3
4
5
6
@POST
@Consumes("application/json")
@Produces("application/json")
public RestResponse<Contact> create(Contact contact) {
...
}

@Consumes

The @Consumes annotation is used to specify the MIME media types a REST resource can consume.
1
2
3
4
5
6
7
@PUT
@Consumes("application/json")
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Contact> update(Contact contact) {
...
}

@FormParam

The REST resources will usually consume XML/JSON for the complete Entity Bean. Sometimes, you may want to read parameters sent in POST requests directly and you can do that using @FormParam annotation. GET Request query parameters can be accessed using @QueryParam annotation.
1
2
3
4
5
@POST
public String save(@FormParam("firstName") String firstName,
    @FormParam("lastName") String lastName) {
      ...
  }

@PUT

Annotate PUT request methods with @PUT.
1
2
3
4
5
6
7
@PUT
@Consumes("application/json")
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Contact> update(Contact contact) {
...
}

@DELETE

Annotate DELETE request methods with @DELETE.
1
2
3
4
5
6
@DELETE
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Contact> delete(@PathParam("contactId") int contactId) {
...
}


Consuming Restful web services in Java




















1.1                     HTTP Request


An HTTP Request has five major parts −
·        Verb − Indicates the HTTP methods such as GET, POST, DELETE, PUT, etc.
·        URI − Uniform Resource Identifier (URI) to identify the resource on the server.
·        HTTP Version − Indicates the HTTP version. For example, HTTP v1.1.
·        Request Header − Contains metadata for the HTTP Request message as key-value pairs. For example, client (or browser) type, format supported by the client, format of the message body, cache settings, etc.
·        Request Body − Message content or Resource representation.

1.2                     HTTP Response



An HTTP Response has four major parts −
·        Status/Response Code − Indicates the Server status for the requested resource. For example, 404 means resource not found and 200 means response is ok.
·        HTTP Version − Indicates the HTTP version. For example HTTP v1.1.
·        Response Header − Contains metadata for the HTTP Response message as keyvalue pairs. For example, content length, content type, response date, server type, etc.
·        Response Body − Response message content or Resource representation.
·         Addressing refers to locating a resource or multiple resources lying on the server. It is analogous to locate a postal address of a person.
·         Each resource in REST architecture is identified by its URI (Uniform Resource Identifier). A URI is of the following format −
·         <protocol>://<service-name>/<ResourceType>/<ResourceID>
·         Purpose of an URI is to locate a resource(s) on the server hosting the web service. Another important attribute of a request is VERB which identifies the operation to be performed on the resource. For example, in RESTful Web Services - First Application chapter, the URI is http://localhost:8080/UserManagement/rest/UserService/users and the VERB is GET.
---------------------------------------------------------------------------------------------------------------------------

 

JAXB – Marshalling and Unmarshalling List or Set of Objects


JAXB stands for Java Architecture for XML Binding. It provides a 
mechanism to write Java objects into XML and read XML as 
objects. Simply put, you can say it is used to convert Java 
objects into XML and vice-versa.
JAXB provides a fast and convenient way to bind XML schemas
 and Java representations, making it easy for Java developers 
to incorporate XML data and processing functions in Java 
applications. As part of this process, JAXB provides methods
 for unmarshalling (reading) XML instance documents into Java 
content, and then marshalling (writing) Java content back into 
XML instance documents. JAXB also provides a way to generate
 XML schemas from Java objects.

Features of JAXB 2.0

·         Support for all W3C XML Schema features.
·         Annotation support with the addition of the javax.xml.bind.annotation package to control this binding.
·         Additional validation capabilities through the JAXP 1.3 validation APIs.
·         Smaller runtime libraries.

1.3         Marshalling: Converting Objects to XML

In this example, we need to convert Java objects to an XML document. First, we need to create a POJO class.
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Student {
    private String name;
    private int id;
    private String subject;
    Student(){
    }
    Student(String name,int id,String subject){
        this.name=name;
        this.id=id;
        this.subject=subject;
    }
    @XmlElement
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @XmlAttribute
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @XmlElement
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
}

In the above class:
·         @XmlRootElement specifies the root element for the XML document.
·         @XmlAttribute specifies the attribute for the root element.
·         @XmlElement specifies the sub-element for the root element.
Now, we will call the marshaller method
try{
    //creating the JAXB context
    JAXBContext jContext = JAXBContext.newInstance(Student.class);
    //creating the marshaller object
    Marshaller marshallObj = jContext.createMarshaller();
    //setting the property to show xml format output
    marshallObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    //setting the values in POJO class
    Student student = new Student(“abhishek”, 1163, “hadoop”);
    //calling the marshall method
    marshallObj.marshal(student, new FileOutputStream(/home/knoldus/Desktop/student.xml”));
} catch(Exception e) {
    e.printStackTrace();
}

1.4         Unmarshalling: Converting XML to Objects

try{
    //getting the xml file to read
    File file = new File(/home/knoldus/Desktop/student.xml”);
    //creating the JAXB context
    JAXBContext jContext = JAXBContext.newInstance(Student.class);
    //creating the unmarshall object
    Unmarshaller unmarshallerObj = jContext.createUnmarshaller();
    //calling the unmarshall method
    Student student=(Student) unmarshallerObj.unmarshal(file);
    System.out.println(student.getName()+ +student.getId()+ +student.getSubject());
}catch(Exception e){
    e.printStackTrace();
}

An example of marshalling and unmarshalling of collection of objects. These collections in java can be of type : List and Set implementations e.g. ArrayList or HashSet.

JAXB – Marshalling and Unmarshalling List or Set of Objects


We know that JAXB(Java Architecture for XML Binding) allows Java developers to map
 Java classes to XML representations. JAXB provides two main features: the ability to marshal
 Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. JAXB 
mostly is used while implementing webservices or any other such client interface for an 
application where data needs to be transferred in XML format instead of HTML format 
which is default in case of visual client like web browsers.
A good example is facebook APIs. Facebook has exposed its services through some
 open endpoints in form of RESTful webservices where you hit a URL and post some 
parameters, and API return you the data in xml format. Now it is upto you, how you
 use that data.
In this post, I am giving an example of marshalling and unmarshalling of collection of 
objects. These collections in java can be of type : List and Set implementations
 e.g. ArrayList or HashSet.

Maven dependencies

To run JAXB examples, we need to add run time maven dependencies like below:
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.2.8-b01</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2-promoted-b65</version>
</dependency>

Model classes

I have created a model class “Employee.java” which has some common fields.
 I want to build code which could parse a set of employees. Please note that JAXB 
requires @XmlRootElement annotation on top most class which we are going to 
marshal or unmarshal. ArrayList class is part of collection framework and it does 
not have any JAXB annotations. So We need to have another class “Employees.java” 
which will represent the set of employees. Now in this class we can add any annotation
 we like.
Employee.java
@XmlRootElement(name = "employee")
@XmlAccessorType (XmlAccessType.FIELD)
public class Employee
{
    private Integer id;
    private String firstName;
    private String lastName;
    private double income;
     
    //Getters and Setters
}

Employees.java
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employees")
@XmlAccessorType (XmlAccessType.FIELD)
public class Employees
{
    @XmlElement(name = "employee")
    private List<Employee> employees = null;

    public List<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }
}

1.1  Marshalling example

Marshalling is “to convert the java object into xml representation”. 
In below example code, I am writing the list of employees first in console, and then in a file.
//Initialize the employees list
static Employees employees = new Employees();
static
{
    employees.setEmployees(new ArrayList<Employee>());
    //Create two employees
    Employee emp1 = new Employee();
    emp1.setId(1);
    emp1.setFirstName("Lokesh");
    emp1.setLastName("Gupta");
    emp1.setIncome(100.0);
     
    Employee emp2 = new Employee();
    emp2.setId(2);
    emp2.setFirstName("John");
    emp2.setLastName("Mclane");
    emp2.setIncome(200.0);
     
    //Add the employees in list
    employees.getEmployees().add(emp1);
    employees.getEmployees().add(emp2);
}
private static void marshalingExample() throws JAXBException
{
    JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
     
    //Marshal the employees list in console
    jaxbMarshaller.marshal(employees, System.out);


     
    //Marshal the employees list in file
    jaxbMarshaller.marshal(employees, new File("c:/temp/employees.xml"));
}


Output of above code is :
JAXB marshalling example output

1.1          Unmarshalling example

Unmarshalling is the process of converting the xml back to java object. Let’s see the 
example of our Employees class.
private static void unMarshalingExample() throws JAXBException
{
    JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
     
    //We had written this file in marshalling example
    Employees emps = (Employees) jaxbUnmarshaller.unmarshal( new File("c:/temp/employees.xml") );
     
    for(Employee emp : emps.getEmployees())
    {
        System.out.println(emp.getId());
        System.out.println(emp.getFirstName());
    }
}
     
Output:

1
Lokesh
2
John
----------------------------------------------------------------------------------------------------------------------------
1) What is Web Service?
Web Service is a software system for communicating two devices over the 
network. More details...
2) What are the advantages of web services?
o    Interoperability: By the help of web services, an application can communicate with other application developed in any language.
o    Reusability: We can expose the web service so that other applications can use it.
o    Modularity: By the help of web service, we can create a service for a specific task such as tax calculation etc.
3) What are the different types of web services?
There are two types of web services:
o    SOAP
o    RESTful
4) What is SOAP?
SOAP stands for Simple Object Access Protocol. It is a XML-based protocol for accessing web services. More details...
5) What are the advantages of SOAP web services?
o    WS Security
o    Language Independent
o    Platform Independent
6) What are the disadvantages of SOAP web services?
o    Slow
o    WSDL Dependent
7) What is WSDL?
WSDL stands for Web Services Description Language. It is a xml document containing information about web services such as method name, method parameter etc. 
8) What is UDDI?
UDDI stands for Universal Description, Discovery and Integration. It is a XML based framework for describing, discovering and integrating web services. It contains a list of available web services. WSDL is the part of UDDI. More details...
9) What is RESTful web services?
REST stands for Representational State Transfer. It is a architectural style. It is not a protocol like SOAP. More details...
10) What are the advantages of RESTful web services?
o    Fast
o    Language Independent
o    Platform Independent
o    Can use SOAP.
o    Allows different data format.

2) What is differences between RESTful web services and SOAP web services ?
Though both RESTful web series and SOAP web service can operate cross platform they are architecturally different to each other, here is some of differences between REST and SOAP:

1) REST is more simple and easy to use than SOAP
2) REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.
3) REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDA's.
4) REST supports different format like text, JSON and XML while SOAP only support XML.
5) REST web services call can be cached to improve performance.

11) What is the difference between SOAP and REST web services?
No.
SOAP
REST
1)
SOAP is a protocol.
REST is an architectural style.
2)
SOAP stands for Simple Object Access Protocol.
REST stands for 
REpresentational State
Transfer.
3)
SOAP can't use REST because it is a protocol.
REST can use SOAP 
web services because
 it is a concept and
 can use any protocol
 like HTTP, SOAP.
4)
SOAP uses services interfaces to expose the business logic.
REST uses URI to
expose business
logic.
5)
SOAP defines standards to be strictly followed.
REST does not define
 too much standards
 like SOAP.
6)
SOAP permits XML data format only.
REST permits
different data
 format such as Plain text,
 HTML, XML, JSON etc.

No.
SOAP
REST
1)
SOAP is a protocol.
REST is an architectural style.
2)
SOAP stands for Simple Object Access Protocol.
REST stands for REpresentational
State Transfer.
3)
SOAP can't use REST because it is a protocol.
REST can use SOAP web services
because it is a concept and can use
any protocol like HTTP, SOAP.
4)
SOAP uses services interfaces to expose the business logic.
REST uses URI to expose business
logic.
5)
JAX-WS is the java API for SOAP web services.
JAX-RS is the java API for RESTful
web services.
6)
SOAP defines standards to be strictly followed.
REST does not define too much
standards like SOAP.
7)
SOAP requires more bandwidth and resource than REST.
REST requires less bandwidth and
resource than SOAP.
8)
SOAP defines its own security.
RESTful web services inherits
 security measures from the
underlying transport.
9)
SOAP permits XML data format only.
REST permits different data format
such as Plain text, HTML, XML, JSON etc.
10)
SOAP is less preferred than REST.
REST more preferred than SOAP.

12) What is SOA?
SOA stands for Service Oriented Architecture. It is a design pattern to provide services to other application through protocol.More details...
13) What tools are used to test web services?
o    SoapUI tool for testing SOAP and RESTful web services
o    Poster for firefox browser
o    Postman extension for Chrome

1) What is REST and RESTful web services ?
this is the first REST interview question on most of interviews as not everybody familiar with REST and also
start discussion based on candidates response. Anyway REST stands for REpresentational State Transfer (REST) its a relatively new concept of writing web services which enforces a stateless client server design where web services are treated as resource and can be accessed and identified by there URL unlike SOAP web services which were defined by WSDL.

Web services written by apply REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol to a different clients written in different languages. In RESTful web services http methods like GET, PUT, POST and DELETE can be used to perform CRUD operations.


3) What is Restlet framework ?
Restlet is leading RESTful web framework for Java applications is used to build RESTFul web services it has two part Restlet API and a Restlet implementation much like Servlet specification. There are many implementation of Restlet framework available you just need to add there jar in your classpath to use them. By using Restlet web framework you can write client and server.

4) What is Resource in REST framework ?
it represent a "resource" in REST architecture. on RESTLET API it has life cycle methods like init(), handle() and release() and contains a Context, Request and Response corresponding to specific target resource. This is now deprecated over ServerResource class and you should use that. see Restlet documentation for more details.

5) Can you use Restlet without any web-container ?
Yes, Restlet framework provide default server which can be used to handle service request in web container is not available.

6) What is difference between Restlets and Jersey ?
This REST web service interview questions is open for you all, post you answer in comment section.

7) What is RESTEasy ?
RESTEasy is another REST framework introduced in JBoss Application Server. This was rather easy REST interview questions. you can answer in detail only if you have used this or working in JBoss.

8) What are the tools used for creating RESTFull web services ?
You can use AJAX(Asynchronous JavaScript with XAML) and Direct Web Removing to consume web serives in web application. Both Eclipse and NetBeans also supported development of RESTFul services.

9) How to display custom error pages using RestFull web services ?
In order to customize error you need to extend StatusService and implement getRepresentation(Status, Request, Response) method with your custom code now assign instance of your CustomStatusService to appropriate "statusService property".

10) Which HTTP methods are supported by RestFull web services ?
Another common REST interview questioning RESTFul web service each Resource supports GET, POST, PUT and DELETE http methods.GET is mapped to represent(), POST - acceptRepresentation(), PUT- storeRepresentation and DELET for rmeoveRepresentation.

11) What is difference between top-down and bottom-up approach of developing web services ?
In top-down approach first WSDL document is created and than Java classes are developed based on WSDL contract, so if WSDL contract changes you got to change your Java classes while in case of bottom up approach of web service development you first create Java code and then use annotations like @WebService to specify contract or interface and WSDL field will be automatically generated from your build.

12) What happens if RestFull resources are accessed by multiple clients ? do you need to make it thread-safe?
Since a new Resource instance is created for every incoming Request there is no need to make it thread-safe or add synchronization. multiple client can safely access RestFull resources concurrently.

That’s all on REST interview questions , I will add couple of  more REST Interview questions whenever I got them from my friend circle.

HTTP Methods

Following five HTTP methods are commonly used in REST based architecture.
·        GET - Provides a read only access to a resource.
·        PUT - Used to create a new resource.
·        DELETE - Used to remove a resource.
·        POST - Used to update a existing resource or create a new resource.
·        OPTIONS - Used to get the supported operations on a resource.

Introduction to RESTFul Web Services

A web service is a collection of open protocols and 
standards used for exchanging data between 
applications or systems. Software applications written 
in various programming languages and running on 
various platforms can use web services to exchange 
data over computer networks like the Internet in a 
manner similar to inter-process communication 
on a single computer. This interoperability 
(e.g., between Java and Python, or Windows
 and Linux applications) is due to the use of open standards.
Web services based on REST Architecture are known as 
RESTful web services. These web services use HTTP 
methods to implement the concept of REST architecture. 
A RESTful web service usually defines a URI, Uniform 
Resource Identifier a service, provides resource 
representation such as JSON and set of HTTP Methods.

Creating RESTFul Web Service

In next chapters, we'll create a web service say user 
management with following functionalities:
Sr. No.
HTTP Method
URI
Operation
Operation Type
1
GET
/UserService/users
Get list of users
Read Only
2
GET
/UserService/users/1
Get User of Id 1
Read Only
3
PUT
/UserService/users/2
Insert User with Id 2
Idempotent
4
POST
/UserService/users/2
Update User with Id 2
N/A
5
DELETE
/UserService/users/1
Delete User with Id 1
Idempotent
6
OPTIONS
/UserService/users
List the supported operations in web service
Read Only
Program in Webservices.
Web.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns: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>User Management</display-name>
            <servlet>
                        <servlet-name>Jersey RESTful Application</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.tutorialspoint</param-value>
                        </init-param>
            </servlet>
            <servlet-mapping>
                        <servlet-name>Jersey RESTful Application</servlet-name>
                        <url-pattern>/rest/*</url-pattern>
            </servlet-mapping>
</web-app>
User.java
package com.tutorialspoint;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public  class   User  implements  Serializable {

            private   static  final  longserialVersionUID = 1L;
            private   int  id;
            private   String   name;
            private   String   profession;

            public User() {
            }

            public User(intid, String name, String profession) {
                        this.id = id;
                        this.name = name;
                        this.profession = profession;
            }

            public  int  getId() {
                        returnid;
            }

            @XmlElement
            public  void   setId(intid) {
                        this.id = id;
            }

            public String getName() {
                        returnname;
            }

            @XmlElement
            publicvoid setName(String name) {
                        this.name = name;
            }

            public String getProfession() {
                        returnprofession;
            }

            @XmlElement
            publicvoid setProfession(String profession) {
                        this.profession = profession;
            }
}
UserDao.java
package com.tutorialspoint;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public  class   UserDao {
            public List<User> getAllUsers() {
                        List<User>userList = null;
                        try {
                                    File file = new File("Users.txt");
                                    if (!file.exists()) {
                                                User user = new User(1, "Mahesh", "Teacher");
                                                userList = new ArrayList<User>();
                                                userList.add(user);
                                                saveUserList(userList);
                                    } else {
                                                FileInputStream fis = new FileInputStream(file);
                                                ObjectInputStream ois = new ObjectInputStream(fis);
                                                userList = (List<User>) ois.readObject();
                                                ois.close();
                                    }
                        } catch (IOException e) {
                                    e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                                    e.printStackTrace();
                        }
                        returnuserList;
            }

            public List<User> getAllAnotherUsers() {
                        List<User>userList = null;
                        try {
                                    File file = new File("Users.txt");
                                    User user = new User(1, "Kunal", "Sr.Software Engineer");
                                    userList = new ArrayList<User>();
                                    userList.add(user);
                                    FileOutputStream fos = new FileOutputStream(file);
                                    ObjectOutputStream oos = new ObjectOutputStream(fos);

                                    oos.writeObject(userList);
                                    oos.close();

                        } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                        } catch (IOException e) {
                                    e.printStackTrace();
                        }
                        returnuserList;
            }

            private  void   saveUserList(List<User>userList) {
                        try {
                                    File file = new File("Users.txt");
                                    FileOutputStream fos;

                                    fos = new FileOutputStream(file);

                                    ObjectOutputStream oos = new ObjectOutputStream(fos);
                                    oos.writeObject(userList);
                                    oos.close();
                        } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                        } catch (IOException e) {
                                    e.printStackTrace();
                        }
            }
}


UserService.java
package com.tutorialspoint;

import java.util.List;

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

@Path("/UserService")
publicclassUserService {

   UserDao userDao = new UserDao();

@GET
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(){
returnuserDao.getAllUsers();
   }

@GET
@Path("/anotherUsers")
@Produces(MediaType.APPLICATION_XML)
public List<User> getAnotherUsers(){
            returnuserDao.getAllAnotherUsers();
               }       
}
http://localhost:8080/UserManagement/rest/UserService/anotherUsers
http://localhost:8080/UserManagement/rest/UserService/users

OUTPUT:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<users>
<user>
<id>1</id>
<name>Kunal</name>
<profession>Sr.Software Engineer</profession>
</user>
</users>

Exception Handling on Webservices

Errors can be reported to a client either by creating and 
returning the appropriate Response object or by throwing
 an exception. Application code is allowed to throw any 
checked (classes extending java.lang.Exception) or 
unchecked (classes extending java.lang.RuntimeException
exceptions they want. Thrown exceptions are handled by
 the JAX-RS runtime if you have registered an exception 
mapper. Exception mappers can convert an exception to 
an HTTP response. If the thrown exception is not handled 
by a mapper, it is propagated and handled by the container
 (i.e., servlet) JAX-RS is running within. JAX-RS also provides the javax.ws.rs.WebApplicationException. This can be 
thrown by application code and automatically processed
 by JAX-RS without having to write an explicit mapper. 
Let’s look at how to use the WebApplicationException first.
 We’ll then examine how to write your own specific 
exception mappers.
javax.ws.rs.WebApplicationException
JAX-RS has a built-in unchecked exception that applications 
can throw. This exception is preinitialized with either a 
Response or a particular status code:
public class WebApplicationException extends RuntimeException {
 
   public WebApplicationException() {...}
   public WebApplicationException(Response response) {...}
   public WebApplicationException(int status) {...}
   public WebApplicationException(Response.Status status) {...}
   public WebApplicationException(Throwable cause) {...}
   public WebApplicationException(Throwable cause,
                                       Response response) {...}
   public WebApplicationException(Throwable cause, int status) {...}
   public WebApplicationException(Throwable cause,
                                   Response.Status status) {...}
 
   public Response getResponse() {...]
}
When JAX-RS sees that a WebApplicationException has been thrown by application code, it catches the exception and
 calls its getResponse() method to obtain a Response to send back to the client.
 If the application has initialized the WebApplicationException with a status code or 
Response object, that code or Response will be used to create the actual HTTP response. 
Otherwise, the WebApplicationException will return a status code of 500, “Internal Server 
Error,” to the client.
For example, let’s say we have a web service that allows clients to query for customers
 represented in XML:
@Path("/customers")
public class CustomerResource {
 
   @GET
   @Path("{id}")
   @Produces("application/xml")
   public Customer getCustomer(@PathParam("id") int id) {
 
       Customer cust = findCustomer(id);
       if (cust == null) {
         throw new WebApplicationException(Response.Status.NOT_FOUND);
       }
       return cust;
   }
}
In this example, if we do not find a Customer instance with the given ID, 
we throw a WebApplicationException that causes a 404, 
“Not Found,” status code to be sent back to the client.
Exception Mapping
Many applications have to deal with a multitude of 
exceptions thrown from application code and third-party 
frameworks. Relying on the underlying servlet container to
handle the exception doesn’t give us much flexibility. 

Catching and then wrapping all these exceptions within 
WebApplicationExceptionwould become quite tedious. 
Alternatively, you can implement and register instances of javax.ws.rs.ext.ExceptionMapper. These objects know 
how to map a thrown application exception to a Response 
object:
public interface ExceptionMapper<E extends Throwable> {
{
   Response toResponse(E exception);
}
For example, one exception that is commonly thrown in Java Persistence API
 (JPA)–based database applications is 
javax.persistence.EntityNotFoundException. It is thrown
 when JPA cannot find a particular object in the database. 
Instead of writing code to handle this exception explicitly, 
you could write an ExceptionMapper to handle this 
exception for you. Let’s do that:
@Provider
public class EntityNotFoundMapper
     implements ExceptionMapper<EntityNotFoundException> {
 
   public Response toResponse(EntityNotFoundException e) {
      return Response.status(Response.Status.NOT_FOUND).build();
   }
}
Our ExceptionMapper implementation must be annotated with the @Provider annotation. This tells the JAX-RS runtime that it is a component. The class implementing the ExceptionMapper interface must provide the parameterized type of the ExceptionMapper. JAX-RS uses this generic type information to match up thrown exceptions to ExceptionMappers. Finally, the toResponse() method receives the thrown exception and creates a Response object that will be used to build the HTTP response.
JAX-RS supports exception inheritance as well. When an exception is thrown, JAX-RS will first try to find an ExceptionMapper for that exception’s type. If it cannot find one, it will look for a mapper that can handle the exception’s superclass. It will continue this process until there are no more superclasses to match against.
Finally, ExceptionMappers are registered with the JAX-RS runtime using the deployment APIs discussed in Chapter 14.
Exception Hierarchy
JAX-RS 2.0 has added a nice exception hierarchy for various HTTP error conditions. So, instead of creating an instance of WebApplicationException and initializing it with a specific status code, you can use one of these exceptions instead. We can change our previous example to use javax.ws.rs.NotFoundException:
@Path("/customers")
public class CustomerResource {
 
   @GET
   @Path("{id}")
   @Produces("application/xml")
   public Customer getCustomer(@PathParam("id") int id) {
 
       Customer cust = findCustomer(id);
       if (cust == null) {
         throw new NotFoundException());
       }
       return cust;
   }
}
Like the other exceptions in the exception hierarchy, 
NotFoundException inherits from WebApplicationException.
 If you looked at the code, you’d see that in its constructor 
it is initializing the status code to be 404. Table 7-1 lists some
 other exceptions you can use for error conditions that are 
under the javax.ws.rs package.
Table 7-1. JAX-RS exception hierarchy
Exception
Status code
Description
BadRequestException
400
Malformed message
NotAuthorizedException
401
Authentication failure
ForbiddenException
403
Not permitted to access
NotFoundException
404
Couldn’t find resource
NotAllowedException
405
HTTP method not supported
NotAcceptableException
406
Client media type requested not supported
NotSupportedException
415
Client posted media type not supported
InternalServerErrorException
500
General server error
ServiceUnavailableException
503
Server is temporarily unavailable or busy
BadRequestException is used when the client sends something to the server that the server cannot interpret. The JAX-RS runtime will actually throw this exception in certain scenarios. The most obvious is when a PUT or POST request has submitted malformed XML or JSON that the MessageBodyReaderfails to parse. JAX-RS will also throw this exception if it fails to convert a header or cookie value to the desired type. For example:
@HeaderParam("Custom-Header") int header;
@CookieParam("myCookie") int cookie;
If the HTTP request’s Custom-Header value or the myCookie value cannot be parsed into an integer, BadRequestException is thrown.
NotAuthorizedException is used when you want to write your own authentication protocols. The 401 HTTP response code this exception represents requires you to send back a challenge header called WWW-Authenticate. This header is used to tell the client how it should authenticate with the server. NotAuthorizedException has a few convenience constructors that make it easier to build this header automatically:
    public NotAuthorizedException(Object challenge, Object... moreChallenges) {}
For example, if I wanted to tell the client that OAuth Bearer tokens are required for authentication, I would throw this exception:
    throw new NotAuthorizedException("Bearer");
The client would receive this HTTP response:
HTTP/1.1 401 Not Authorized
WWW-Authenticate: Bearer
ForbiddenException is generally used when the client making the invocation does not have permission to access the resource it is invoking on. In Java EE land, this is usually because the authenticated client does not have the specific role mapping required.
NotFoundException is used when you want to tell the client that the resource it is requesting does not exist. There are also some error conditions where the JAX-RS runtime will throw this exception automatically. If the JAX-RS runtime fails to inject into an @PathParam@QueryParam, or @MatrixParam, it will throw this exception. Like in the conditions discussed for BadRequestException, this can happen if you are trying to convert to a type the parameter value isn’t meant for.
NotAllowedException is used when the HTTP method the client is trying to invoke isn’t supported by the resource the client is accessing. The JAX-RS runtime will automatically throw this exception if there isn’t a JAX-RS method that matches the invoked HTTP method.
NotAcceptableException is used when the client is requesting a specific format through the Acceptheader. The JAX-RS runtime will automatically throw this exception if there is not a JAX-RS method with an @Produces annotation that is compatible with the client’s Accept header.
NotSupportedException is used when a client is posting a representation that the server does not understand. The JAX-RS runtime will automatically throw this exception if there is no JAX-RS method with an @Consumes annotation that matches the Content-Type of the posted entity.
InternalServerErrorException is a general-purpose error that is thrown by the server. For applications, you would throw this exception if you’ve reached an error condition that doesn’t really fit with the other HTTP error codes. The JAX-RS runtime throws this exception if a MessageBodyWriterfails or if there is an exception thrown from an ExceptionMapper.
ServiceUnavailableException is used when the server is temporarily unavailable or busy. In most cases, it is OK for the client to retry the request at a later time. The HTTP 503 status code is often sent with a Retry-After header. This header is a suggestion to the client when it might be OK to retry the request. Its value is in seconds or a formatted date string.
ServiceUnavailableException has a few convenience constructors to help with initializing this header:
    public ServiceUnavailableException(Long retryAfter) {}
    public ServiceUnavailableException(Date retryAfter) {}

Mapping default exceptions

What’s interesting about the default error handling for JAX-RS is that you can write an ExceptionMapper for these scenarios. For example, if you want to send back a different response to the client when JAX-RS cannot find an @Produces match for an Accept header, you can write an ExceptionMapper for NotAcceptableException. This gives you complete control on how errors are handled by your application.


----------------------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment