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