Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Web Services work on client-server model where client applications can access
web services over the network. Web services provide endpoint URLs and expose
methods that can be accessed over network through client programs written in
java, shell script or any other different technologies.
Web services are stateless and doesnt maintain user session like web
applications.
o SOAP Web Services: Runs on SOAP protocol and uses XML technology
for sending data.
What is SOAP?
SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry
standard protocol for designing and developing web services. Since its XML
based, its platform and language independent. So our server can be based on
JAVA and client can be on .NET, PHP etc. and vice versa.
o SOAP uses XML data for payload as well as contract, so it can be easily
read by any technology.
o Only XML can be used, JSON and other lightweight formats are not
supported.
o SOAP is slow because payload is large for a simple string message, since
it uses XML format.
o Anytime there is change in the server side contract, client stub classes
need to be generated again.
What is WSDL?
WSDL stands for Web Service Description Language. WSDL is an XML based
document that provides technical details about the web service. Some of the
useful information in WSDL document are: method name, port types, service end
point, binding, method parameters etc.
What is UDDI?
UDDI is acronym for Universal Description, Discovery and Integration. UDDI is a
directory of web services where client applications can lookup for web services.
Web Services can register to the UDDI server and make them available to client
applications.
In Bottom Up approach, first web service code is written and then WSDL is
generated. Its also termed as contract last approach. This approach is easy to
implement because WSDL is generated based on code. In this approach client
code have to wait for WSDL from server side to start their work.
o Supports multiple technologies for data transfer such as text, xml, json,
image etc.
SOAP is a standard protocol for creating web services. REST is an architectural style to create web service
SOAP is acronym for Simple Object Access Protocol. REST is acronym for REpresentational State Trans
SOAP uses WSDL to expose supported methods and REST exposes methods through URIs, there are n
SOAP web services and client programs are bind with REST doesnt have any contract defined between s
contract.
SOAP learning curve is hard, requires us to learn about REST learning curve is simple, POJO classes can
WSDL generation, client stubs creation etc. generated easily and works on simple HTTP metho
SOAP supports XML data format only REST supports any data type such as XML, JSON
etc.
SOAP web services are hard to maintain, any change in REST web services are easy to maintain when com
WSDL contract requires us to create client stubs again SOAP, a new method can be added without any ch
and then make changes to client code. client side for existing resources.
SOAP web services can be tested through programs or REST can be easily tested through CURL comman
software such as Soap UI. Browsers and extensions such as Chrome Postma
REST web services can be tested easily with program, curl commands and
through browser extensions. Resources supporting GET method can be tested
with browser itself, without any program.
Content-Type header is used to tell server what is the format of data being sent in
the request. If Content-Type header is application/xml then server will try to
parse it as XML data. This header is useful in HTTP Post and Put requests.
o Do you know your web service clients beforehand? If Yes, then you can
define a contract before implementation and SOAP seems better choice. But
if you dont then REST seems better choice because you can provide
sample request/response and test cases easily for client applications to use
later on.
o How much time you have? For quick implementation REST is the best
choice. You can create web service easily, test it through browser/curl and
get ready for your clients.
o What kind of data format are supported? If only XML then you can go with
SOAP but if you think about supporting JSON also in future then go with
REST.
o @WebService
o @SOAPBinding
o @WebMethod
What is use
of javax.xml.ws.Endpoint class?
Endpoint class provides useful methods to create endpoint and publish existing
implementation as web service. This comes handy in testing web services before
making further changes to deploy it on actual server.
What is the difference between RPC Style and
Document Style SOAP web Services?
RPC style generate WSDL document based on the method name and its
parameters. No type definitions are present in WSDL document.
Document style contains type and can be validated against predefined schema.
Lets look at these with a simple program. Below is a simple test program where I
am using Endpoint to publish my simple SOAP web service.
TestService.java
package com.journaldev.jaxws.service;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Endpoint;
@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
@WebMethod
Endpoint.publish("http://localhost:8888/testWS",
new TestService());
}
When I run above program and then access the WSDL, it gives me below XML.
rpc.xml
<definitions xmlns:wsu="http://docs.oasis-
open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-
1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy"
xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://service.jaxws.journaldev.com/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://service.jaxws.journaldev.com/"
name="TestServiceService">
<types/>
<message name="sayHello">
</message>
<message name="sayHelloResponse">
</message>
<portType name="TestService">
<operation name="sayHello">
<input
wsam:Action="http://service.jaxws.journaldev.com/TestServic
e/sayHelloRequest" message="tns:sayHello"/>
<output
wsam:Action="http://service.jaxws.journaldev.com/TestServic
e/sayHelloResponse" message="tns:sayHelloResponse"/>
</operation>
</portType>
<binding name="TestServicePortBinding"
type="tns:TestService">
<soap:binding
transport="http://schemas.xmlsoap.org/soap/http"
style="rpc"/>
<operation name="sayHello">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"
namespace="http://service.jaxws.journaldev.com/"/>
</input>
<output>
<soap:body use="literal"
namespace="http://service.jaxws.journaldev.com/"/>
</output>
</operation>
</binding>
<service name="TestServiceService">
<port name="TestServicePort"
binding="tns:TestServicePortBinding">
<soap:address location="http://localhost:8888/testWS"/>
</port>
</service>
</definitions>
Notice that types element is empty and we cant validate it against any schema.
Now just change the SOAPBinding.Style.RPC to SOAPBinding.Style.DOCUMENT and
you will get below WSDL.
document.xml
<definitions xmlns:wsu="http://docs.oasis-
open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-
1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy"
xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://service.jaxws.journaldev.com/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://service.jaxws.journaldev.com/"
name="TestServiceService">
<types>
<xsd:schema>
<xsd:import
namespace="http://service.jaxws.journaldev.com/"
schemaLocation="http://localhost:8888/testWS?xsd=1"/>
</xsd:schema>
</types>
<message name="sayHello">
<message name="sayHelloResponse">
</message>
<portType name="TestService">
<operation name="sayHello">
<input
wsam:Action="http://service.jaxws.journaldev.com/TestServic
e/sayHelloRequest" message="tns:sayHello"/>
<output
wsam:Action="http://service.jaxws.journaldev.com/TestServic
e/sayHelloResponse" message="tns:sayHelloResponse"/>
</operation>
</portType>
<binding name="TestServicePortBinding"
type="tns:TestService">
<soap:binding
transport="http://schemas.xmlsoap.org/soap/http"
style="document"/>
<operation name="sayHello">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="TestServiceService">
<port name="TestServicePort"
binding="tns:TestServicePortBinding">
<soap:address location="http://localhost:8888/testWS"/>
</port>
</service>
</definitions>
Open schemaLocation URL in browser and you will get below XML.
schemaLocation.xml
<xs:schema xmlns:tns="http://service.jaxws.journaldev.com/"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0"
targetNamespace="http://service.jaxws.journaldev.com/">
<xs:element name="sayHelloResponse"
type="tns:sayHelloResponse"/>
<xs:complexType name="sayHello">
<xs:sequence>
</xs:sequence>
</xs:complexType>
<xs:complexType name="sayHelloResponse">
<xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:schema>
sun-jaxws.xml
<endpoints xmlns="http://java.sun.com/xml/ns/jax-
ws/ri/runtime" version="2.0">
<endpoint
name="PersonServiceImpl"
implementation="com.journaldev.jaxws.service.PersonServiceI
mpl"
url-pattern="/personWS"/>
</endpoints>
o @Path:
used to specify the relative path of class and methods. We can get
the URI of a webservice by scanning the Path annotation value.
o @GET, @PUT, @POST, @DELETE and @HEAD: used to specify the HTTP request
type for a method.
return Response.status(422).entity(exception).build();
1. What is REST?
REST is an architectural style which was brought in by Roy Fielding in 2000 in his
doctoral thesis.
4. What are HTTP methods that can be used in Restful web services?
RESTful web services use HTTP protocol methods for the operations they perform.
Some important Methods are:
GET : It defines a reading access of the resource without side-effects.This operation
is idempotent i.e.they can be applied multiple times without changing the result
PUT : It is generally used for updating resource. It must also be idempotent.
DELETE : It removes the resources. The operations are idempotent i.e. they can get
repeated without leading to different results.
POST : It is used for creating a new resource. It is not idempotent.
5. What do you mean by Idempotent and which HTTP methods are idempotent?
Idempotent means result of multiple successful request will not change state of
resource after initial application
For example : Delete is idempotent method because when you first time use delete,
it will delete the resource (initial application) but after that, all other request will
have no result because resource is already deleted. Get, put and delete are HTTP
Idempotent methods.
7. What happens if resources are shared by multiple clients? Do you need to make
it thread safe explicitly?
New resource instance is created for each request, so you don't need to implement
thread safety or synchronization aid. It is by default thread safe.
8. What is JAX-RS?
Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST
service. JAX-RS is part of the Java EE6, and make developers to develop REST web
application easily.
9. What are REST frameworks that you are aware of and which can be used to
create Restful webservices?
There are multiple Rest framework that can be used to create Restful web services
such as
Jersey
RestEasy
Restlet
CFX
10. What are some important annotations which you use to create Restful web
services?
Some of important annotations which are used for creating web services are:
@Path : This is used to set path for URI at class level or method level
@GET,@POST,@PUT,@DELETE : There are annotations corresponds to HTTP
methods
@Produces(MediaType.TEXT_XML [, more-types ]): @Produces defines which
MIME type is delivered by a method
@PathParam: Used to inject values from the URL into a method parameter.
@Consumes(MediaType.TEXT_XML) : @Cosumes defines which MIME type will be
consumed by the method .
11. Can you use get method to create Resources rather than post?
No, Get should be used only for resource retrieval and not for resource creation.
Constraints. Any service which satisfies these constraints is called RESTful Web Service.
There are a lot of misconceptions about REST Web Services : They are over HTTP , based on
JSON etc. Yes : More than 90% of RESTful Web Services are JSON over HTTP. But these are not
necessary constraints. We can have RESTful Web Services which are not using JSON and which
Important Annotations:
@ApplicationPath("/"). @Path("users") : used on class and methods to define the url
path.
@GET @POST : Used to define the HTTP method that invokes the method.
@Produces(MediaType.APPLICATION_JSON) : Defines the output format of Restful
service.
@Path("/{id}") on method (and) @PathParam("id") on method parameter : This helps in
defining a dynamic parameter in Rest URL. @Path("{user_id}/followers/{follower_id}") is a
more complicated example.
@QueryParam("page") : To define a method parameter ex: /users?page=10.
Useful methods:
Response.OK(jsonBuilder.build()).build() returns json response with status code.
Json.createObjectBuilder(). add("id",user.getId()); creates a user object.
What are the advantages of Restful web services?
Lightweight : Easy to consume from mobile devices also.
Easy to expose : Little or no restrictions on output format and communication protocol.
Most Restful services use HTTP protocol : Entire web is based on HTTP and is built for
efficiency of HTTP. Things like HTTP caching enable Restful services to be effective.
High Performance : Less xml & soap overhead and More caching enable Restful services
to be highly performant.
REST Interview Question 1:
What is the Caching mechanism that a RESTful service would provide?
This is how I would answer this question
As RESTful service uses HTTP as transport protocol, it can leverage caching
features from HTTP specification as well.
HTTP 1.0 specification has Expires header that can be used to indicate ways
to client side for the appropriate caching intentions of server.
HTTP 1.1 specification however has more caching related features to choose
from.
These are in form of various directives used along with header such as Cache-
Control.
---------------------------------------------------------------------------------------
REST interview question 2:
What are those comma separated directives of Cache-Control header?
This is how I would answer this question
The comma separated directives of Cache-Control headers are
private, public, no-cache, no-store, no-transform, max-age, s-maxage.
---------------------------------------------------------------------------------------
REST interview question 3:
What are the differences between no-cache, and no-store directives used
along with
Cache-Control header?
This is how I would answer this question
no-cache can be set in response in order to inform client/browser that this
response
should not be used for caching content and any of the cache data should not
be sent to
server without revalidation from server.
In case of no-cache, one can use data with revalidation, but in no-store that is
no ways
any data can be retrieved locally from the hard disk and data won't be
available when machine
if restarted.
---------------------------------------------------------------------------------------
REST interview question 4:
---------------------------------------------------------------------------------------
REST interview question 5:
What is the difference in usage for the s-maxage and max-age directives?
---------------------------------------------------------------------------------------
REST interview question 6:
What are the various annotations available from JAX-RS api specification,
for sending data from client-side to service endpoint?
---------------------------------------------------------------------------------------
REST interview question 7:
How to inject Web container related values and configurations to the JAX-
RS service
implementation instance
---------------------------------------------------------------------------------------
REST interview question 8:
/employees/name=Ishtek;age=34
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
What are the major differences you can state while using SOAP or REST,
in terms of
applicability as concern?
---------------------------------------------------------------------------------------
Some of the options available to use for securing a RESTful service, for now,
are
1. Basic Authentication
This type of Authentication will require transport level encryption(SSL), as
user
credentials are to be sent via wire in plain text.
---------------------------------------------------------------------------------------
What is the main factor to consider while choosing OAuth version to use,
whether to use
OAuth 1.0a or OAuth 2.0?
The main reson is the sensitivity of the data that is exchanged, and transport
level
security related considerations. If the application data is less sensitive,
the OAuth 1.0a could be well enough for use, and OAuth 1.0a specification
can be applied
without much of encryptions on transport. But OAuth 2.0 would rely on HTTPS
transport
level security/encryption for communication.
---------------------------------------------------------------------------------------
What are the various credential types used along with OAuth 2.0?
There are three types of credentials available to use along with OAuth 2.0,
such as
Bearer Token, MAC token, SAML.
---------------------------------------------------------------------------------------
POST - Create
GET - Read
PUT - Update
DELETE - Delete
are the corresponding HTTP method used for CRUD operations with
resource(s).
---------------------------------------------------------------------------------------
Can you write a very simple code showing resource being exposed as
RESTful service?
@Path("/book")
public class Book {
@GET
@Path("{id}")
public Book getBookInfo(@PathParam("id") String bookId) {
//return Book Instance by using value bookId.
return new Book();
}
}
---------------------------------------------------------------------------------------
What are the annotations that can be used for specifying content-type that
is supported
by any RESTful service?
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
Answer :
Jersey Framework can be used along with web container that is having support
for JAX-RS
or not. Where as any web container that has support for JAX-RS specification,
can be used
to provide a resource as RESTful web service.
---------------------------------------------------------------------------------------
Answer :
Yes, by using @Context as argument type for the method that is exposed as
REST uri.
import javax.ws.rs.core.HttpHeaders;
...
...
@GET
@Path("abc")
public void getValue(@Context HttpHeaders headers) {
...
...
}
---------------------------------------------------------------------------------------
Have you used Maven to generate Jersey based RESTful services? if yes,
how?
Answer :
I have used a archetype from Maven repository, called as 'jersey-quickstart-
webapp',
for generating a web application, just to start head's up on using Jersey for
creating
RESTful services.
---------------------------------------------------------------------------------------
Answer :
One can define context parameter in web.xml file and corresponding value of
the parameter
in the resource method, by using @Context annotations with instance level
variable of
ServletContext type.
---------------------------------------------------------------------------------------
What are the headers types from HTTP request, those can be used for
mapping same URI
but different resource methods?
Answer :
One can use Accept, Accept-Language, Accept-Encoding, Content-Type with
appropriate values
for mapping same URI but different methods. Appropriate method would be
called that is
receiving corresponding values in form of those headers, in the HTTP
REQUEST.
Please keep visiting this page... as more questions will be added here,
as and when available.
---------------------------------------------------------------------------------------
Answer :
One can explore javax.ws.rs.core.MultivaluedMap<Object, Object> and its
implementations
for providing ways to pass form-level POST parameters and corresponding
values. This way
additions and deletions won't effect method signature to some level.
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
As per JAX-RS specification, what are the corresponding annotations
used for various HTTP operations,
such as GET, PUT, POST, DELETE, HEAD etc.?
Answer :
Various annotations for these operations are
@javax.ws.rs.GET for HTTP GET Operation
@javax.ws.rs.PUT for HTTP PUT Operation
@javax.ws.rs.POST for HTTP POST Operation
@javax.ws.rs.DELETE for HTTP DELETE Operation
@javax.ws.rs.HEAD for HTTP HEAD Operation
---------------------------------------------------------------------------------------
@GET
@Path("books")
@Produces("application/xml")
public String retrieveAllBookInLibrary() {
return "<books><book></book><books/>"; //or any other ways of forming
the actual return result
}
}
---------------------------------------------------------------------------------------
In the code that you have just written, can you add a separate method for
retrieving a selected book with a ISBN code?
Answer
Sure, we can add another method with a path for book and a parameter for
ISBN code, may be something like as shown below,
@GET
@Path("books/book/{isbnCode}")
@Produces("text/xml")
public String retriveBook(@PathParam("isbnCode") String isbnCode) {
return "<book></book>"; //or any other ways of forming the actual return
result
}
---------------------------------------------------------------------------------------