Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous


Web Services Interview Question

Q. What is SOAP?
Ans. SOAP is a simple XML-based protocol to let applications exchange information over HTTP.Soap, in its current form, is a method for RPC (Remote Procedure Calls) over a network. (Yes, it is also used a way to transfer documents around as XML:

  • SOAP allows you to get around firewalls 
  • SOAP stands for Simple Object Access Protocol 
  • SOAP is a communication protocol 
  • SOAP is for communication between applications 
  • SOAP is a format for sending messages  
  • SOAP is designed to communicate via Internet  
  • SOAP is platform independent  
  • SOAP is language independent  
  • SOAP is based on XML  
  • SOAP is simple and extensible  

Q. Where is SOAP used?
Ans. One of the most important uses of SOAP is to help enable XML Web Services. A web Service is an application provided as a service on the web. They are functional software components that can be accessed over the Internet. Web Services combines the best of component-based development and are based on Internet Standards that supports communication over the net.

Q. What is SOAP Envelope?
Ans. The HTTP request body contains the SOAP request itself. This is wrapped in a SOAP envelope, which contains metadata important for understanding the request. The structure is as follows:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.www.org/soap/envelope/"
SOAP-ENV:encodingStyle="http://www.www.org/soap/encoding/">
<!-- SOAP body goes here -->
</SOAP-ENV:Envelope>
The SOAP envelope is in the XML namespace prescribed by the specification: http://www.www.org/soap/envelope/. The envelope must specify how to interpret the SOAP body. This is accomplished with the SOAP-ENV:encodingStyle attribute. The value is a URI indicating a specification for the structure of the body.

Q. What does SOAP Namespace defines ?
Ans.The namespace defines the Envelope as a SOAP Envelope. If a different namespace is used, the application generates an error and discards the message.

Q. What is the SOAP encodings ?
Ans. The envelope specified the encoding for the body as http://www.wwww.org/soap/encoding/. This is a method for structuring the request that is suggested within the SOAP spec itself, known as the SOAP serialization.
It's worth noting that one of the biggest technical complaints against SOAP is that it mixes a specification for message transport with a specification for message structure. You needn't feel constrained to use the SOAP serialization encoding style.
Other possible encoding styles include Web Distributed Data Exchange (WDDX), XML Remote Procedure Call (XML-RPC), Resource Description Framework (RDF), or just a custom XML structure. The latter is probably good enough if you're not worried about whether an attribute value of "1" is supposed to be interpreted as a string or an integer, for example. See Resources for information on these encoding styles.


Q. What does SOAP encodingStyle Attribute defines ?
Ans. The encodingStyle attribute is used to define the data types used in the document. This attribute may appear on any SOAP element, and applies to the element's contents and all child elements.
A SOAP message has no default encoding
Syntax
soap:encodingStyle="URI"
Example
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.www.org/2010/12/soap-envelope"
soap:encodingStyle="http://www.www.org/2010/12/2001/12/soap-encoding">
...
Message information goes here
...
</soap:Envelope>

Q. Which Protocol is used by Web service and Web service consumer to communicate with each other ?
Ans. SOAP is a XML based 'message' that a web service client can send to an actual web service (& vice versa). The reason why this message is termed as a 'protocol' is because the XML semantics inside this message is based on a well know standard understood by both the actualweb service & all its clients.
Having said this, note that this XML based 'message' does not have any capability on its own whatsoever to physically travel from the so-calledweb service client (which may be on your desktop PC) to the actual web service (which may be on the server). Because after all, this messages is nothing but a set of XML tags sitting conceptually in a virtual world.
And this is where an underlying 'network technology' is required to physically take this XML based 'message' from the web service client to the actual web service. This underlying network technology can be anything eg: HTTP, raw TCP sockets, SMTP, JMS etc. Note that this network technology is also referred to as a 'protocol'.
So dont get confused between the 'message' which is a 'Communication Protocol' between a web service & its clients, & the actual network technology used to physically move it across the network which is actually referred to as a 'Transport Protocol'.

Q. What are the advantages of SOAP over standard http ?
Ans. SOAP is a firewallsfriendly way to make remote procedures call.. SOAP may also be used over HTTPS (since it is the same protocol as HTTP at the application level) It can leap through firewalls in a single bound(XML document can b e easily be transported via HTTP through firewalls without security risk.)
SOAP provides a shared language for mapping structured data transmitted over the wire. This enables processes of different platforms and architectures to decode the the serialized data structures of which they understand.

Q. Describe the SOAP actor attribute?
Ans. The actor Attribute
A SOAP message may travel from a sender to a receiver by passing different endpoints along the message path. However, not all parts of a SOAP message may be intended for the ultimate endpoint, instead, it may be intended for one or more of the endpoints on the message path.
The SOAP actor attribute is used to address the Header element to a specific endpoint.

Syntax
soap:actor="URI"
Example
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.www.org/2010/12/soap-envelope"
soap:encodingStyle="http://www.www.org/2010/12//soap-encoding">

<soap:Header>
<m:Trans xmlns:m="http://www.www.org/2010/12/transaction/"
soap:actor="http://www.www.org/2010/12/appml/">
</m:Trans>
</soap:Header>
...
...
</soap:Envelope>

Q. Explain about the role of XML in SOAP?
Ans. XML is chosen as a standard format because it was already in use by many large companies and immensely due to its open source nature. A wide variety of tools are available on shelves which ease the process of transition to SOAP. XML can significantly reduce the speed and efficiency but binary XML is being considered as a format for future.

Q. What are the elements which should be contained in SOAP message?
Ans. Following elements are contained in the SOAP message. 1) An envelope element which identifies and translates the XML document into a SOAP message. 2) A header element is a must as it should contain header message. 3) A body is required which should contain call and response message. 4) Fault element is required which can communicate about the errors occurred during the process.

Q. How you explain Fault Element of SOAP?
Ans. The SOAP Fault element hold errors and status information for a SOAP message.
The optional SOAP Fault element is used to indicate error messages.
If a Fault element is present, it must appear as a child element of the Body element. A Fault element can only appear once in a SOAP message.
The SOAP Fault element has the following sub elements:
<faultcode> A code for identifying the fault
<faultstring> A human readable explanation of the fault
<faultactor> Information about who caused the fault to happen
<detail> Holds application specific error information related to the Body element
SOAP Fault Codes
The faultcode values defined below must be used in the faultcode element when describing faults:
VersionMismatch Found an invalid namespace for the SOAP Envelope element
MustUnderstand An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood
Client The message was incorrectly formed or contained incorrect information
Server There was a problem with the server so the message could not proceed

Q. How to explain Body Element in SOAP?
Ans. We use Body element in SOAP to contains the actual SOAP message specify the ultimate endpoint of the message.
Example:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.www.org/2010/12/soap-envelope"
soap:encodingStyle="http://www.www.org/2010/12/soap-encoding">
<soap:Body>
<m:GetPrice xmlns:m="http://www.www.org/2010/12/prices">
<m:Item>Mangos</m:Item>
</m:GetPrice>
</soap:Body>
</soap:Envelope>
Above example has write to requests the price of Mangos.In this m:GetPrice and Item elements botha re called as application specific elements. I want to confirm you both elements are not a part of SOAP namespace.
I have given you a SOAP response code according to above SOAP request.
Example:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.www.org/2010/12/soap-envelope"
soap:encodingStyle="http://www.www.org/2010/12/soap-encoding">
<soap:Body>
<m:GetPriceResponse xmlns:m="http://www.www.org/2010/12/prices">
<m:Price>1.90</m:Price>
</m:GetPriceResponse>
</soap:Body>
</soap:Envelope>

Q. How to explain The HTTP Protocol?
Ans. HTTP communicates over TCP/IP. An HTTP client connects to an HTTP server using TCP. After establishing a connection, the client can send an HTTP request message to the server:

POST /item HTTP/1.1
Host: 189.123.345.239
Content-Type: text/plain
Content-Length: 200

The server then processes the request and sends an HTTP response back to the client. The response contains a status code that indicates the status of the request:

200 OK
Content-Type: text/plain
Content-Length: 200

In the example above, the server returned a status code of 200. This is the standard success code for HTTP. If the server could not decode the request, it could have returned something like this: 400 Bad Request Content-Length: 0

Q. How you explain the WSDL Standard Format ?
Ans. The Web Services Description Language (WSDL) is a standardized XML format for describing network services. The description includes the name of the service, the location of the service, and ways to communicate with the service. WSDL service descriptions can be stored in registries or published on the web (or both). The Sun Java System Application Server Platform Edition 8 provides a tool for generating the WSDL specification of a web service that uses remote procedure calls to communicate with clients.

Q. What is the Web service protocol stack?
Ans. The Web service protocol stack is an evolving set of protocols used to define, discover, and implement Web services. The core protocol stack consists of four layers: Service Transport: This layer is responsible for transporting messages between applications. Currently, this includes HTTP, SMTP, FTP, and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP). XML Messaging: This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this includes XML-RPC and SOAP.
Service Description: This layer is responsible for describing the public interface to a specific Web service. Currently, service description is handled via the WSDL. Service Discovery: This layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via the UDDI. Beyond the essentials of XML-RPC, SOAP, WSDL, and UDDI, the Web service protocol stack includes a whole zoo of newer, evolving protocols. These include WSFL (Web Services Flow Language), SOAP-DSIG (SOAP Security Extensions: Digital Signature), and USML (UDDI Search Markup Language).
For an overview of these protocols, check out Pavel Kulchenko's article, Web Services Acronyms, Demystified, on XML.com. Fortunately, you do not need to understand the full protocol stack to get started with Web services. Assuming you already know the basics of HTTP, it is best to start at the XML Messaging layer and work your way up.

Q. What is WSDL?
Ans. The Web Services Description Language (WSDL) currently represents the service description layer within the Web service protocol stack. In a nutshell, WSDL is an XML grammar for specifying a public interface for a Web service. This public interface can include the following:
Information on all publicly available functions. Data type information for all XML messages. Binding information about the specific transport protocol to be used. Address information for locating the specified service.
WSDL is not necessarily tied to a specific XML messaging system, but it does include built-in extensions for describing SOAP services.
Below is a sample WSDL file. This file describes the public interface for the weather service used in the SOAP example above. Obviously, there are many details to understanding the example. For now, just consider two points. First, the elements specify the individual XML messages that are transferred between computers. In this case, we have a getWeatherRequest and a getWeatherResponse. Second, the element specifies that the service is available via SOAP and is available at a specific URL.

Q. What is UDDI?
Ans. UDDI (Universal Description, Discovery, and Integration) currently represents the discovery layer within the Web services protocol stack. UDDI was originally created by Microsoft, IBM, and Ariba, and represents a technical specification for publishing and finding businesses and Web services.
At its core, UDDI consists of two parts. First, UDDI is a technical specification for building a distributed directory of businesses and Web services. Data is stored within a specific XML format, and the UDDI specification includes API details for searching existing data and publishing new data.
Second, the UDDI Business Registry is a fully operational implementation of the UDDI specification. Launched in May 2001 by Microsoft and IBM, the UDDI registry now enables anyone to search existing UDDI data. It also enables any company to register themselves and their services. The data captured within UDDI is divided into three main categories: White Pages: This includes general information about a specific company. For example, business name, business description, and address.

Q. What is XML-RPC?
Ans. XML-RPC is a protocol that uses XML messages to perform Remote Procedure Calls. Requests are encoded in XML and sent via HTTP POST; XML responses are embedded in the body of the HTTP response. More succinctly, XML-RPC = HTTP + XML + Remote Procedure Calls. Because XML-RPC is platform independent, diverse applications can communicate with one another. For example, a Java client can speak XML-RPC to a Perl server. To get a quick sense of XML-RPC, here is a sample XML-RPC request to a weather service (with the HTTP Headers omitted): weather.getWeather

Q. What is a payload in SOAP?
Ans. The payload is the actual message content that you want to send to the other application. For example, here's a typical "hello world" SOAP message (using document/literal encoding):
<e:Envelope xmlns:e="http://schemas.xmlsoap.org/soap/envelope/">
<e:Body xmlns:t="http://my.example.com/xsd/types/"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns:d="http://www.w3.org/2001/XMLSchema">
<t:In i:type="d:string">
Hello world!
</t:In>
</e:Body>
</e:Envelope>
This data is the message payload.

Q. What is difference between Contract First and Contract Last Web Services?
Ans. Web service design seems to come in two flavours contract-first and contract-last. Contract-first starts with designing the XML schema / WSDL and then creating the Java interface based upon the schema.
Contract-last takes an existing Java interface and from that, creates your web service. On reflection, you'd think that this meant create a schema contract, but generally it seems to mean getting hold of some tool that will take a Java interface as an input and deliver a WSDL as an output.
Research seems to show that, at the time of writing, contract-first is preferred over contract-last and various reasons are given:

  • Object to XML impedance mismatch, which generally means that with contract-last, some Java types don't readily convert to XML and if they did then there could be a certain loss of information as defined by an XSD's <restriction> element. I.e, Java isn't really expressive enough to produce a rugged contract. 
  • Contract-last could suffer from performance issues as you, the developer, have no control of what's sent over the wire. 
  • Using contract-first means that you have your XML types defined in a set of separate schema files, which could be re-used effectively. 
  • Contract-first has looser coupling between definition and implementation making version management easier. 
  • One of the positive things about web services is that they allow services written in different languages to work together. Contract-first reinforces this approach as the WDSL / XML Schema provides a programming language independent, centralised method of specifying a contract. Contract-last, on the other hand, means that your contract is defined in your implementation code, which may differ from your client's implementation code and who's to say which is the master copy of the code? 
  • Which brings us on the next benefit of using contract-first: the management of change. There is usually a version 2 of an interface adding in something that was forgotten in version 1. Using a schema makes that change management easier. 
  • Finally, a plus point for contract-last is that it should be easier, there's no messing about with XSDs, meaning there are no extra skills for your team to learn. 

This is not a complete list, but should underline the reasons why contract first seems to be the preferred choice.

Q. What is a REST Web Service?
Ans. REST stands for Representational State Transfer, which is an architectural style for networked hypermedia applications, it is primarily used to build Web services that are lightweight, maintainable, and scalable. A service based on REST is called a RESTful service. REST is not dependent on any protocol, but almost every RESTful service uses HTTP as its underlying protocol. In this article, I examine the creation of RESTful services with HTTP.
Features of a RESTful Services
Every system uses resources. These resources can be pictures, video files, Web pages, business information, or anything that can be represented in a computer-based system. The purpose of a service is to provide a window to its clients so that they can access these resources. Service architects and developers want this service to be easy to implement, maintainable, extensible, and scalable. A RESTful design promises that and more. In general, RESTful services should have following properties and features, which I'll describe in detail:

  • Representations  
  • Messages  
  • URIs  
  • Uniform interface  
  • Stateless  
  • Links between resources  
  • Caching  

The focus of a RESTful service is on resources and how to provide access to these resources. A resource can easily be thought of as an object as in OOP. A resource can consist of other resources. While designing a system, the first thing to do is identify the resources and determine how they are related to each other.

Q. What are important constraints for a RESTful Web Service?
Ans. REST constraints are design rules that are applied to establish the distinct characteristics of the REST architectural style. The formal REST constraints are:

  • Client-Server  
  • Stateless  
  • Cache  
  • Interface / Uniform Contract  
  • Layered System  
  • Code-On-Demand  

Each constraint is a pre-determined design decision that can have both positive and negative impacts. The intent is for the positives of each constraint to balance out the negatives to produce an overall architecture that resembles the Web.
An architecture that weakens or eliminates a required REST constraint is generally considered to no longer conform to REST. This requires that educated decisions be made to understand the potential trade-offs when deliberately deviating from the application of REST constraints.

Q. How do I send complex objects as parameters?
Ans. There are three typical options available to you.

  • Pass object variables into request  
  • Using a common data interchange format  
  • Custom message convertor  

Q. What are the best practices in designing RESTful APIs?
Ans. Good restful API design is hard! An API represents a contract between you and those who Consume your data. Breaking this contract will result in many angry emails, and a slew of sad users with mobile apps which no longer work. Documentation is half the battle, and it is very difficult to find programmer who also likes to write.
Building an API is one of the most important things you can do to increase the value of your service. By having an API, your service / core application has the potential to become a platform from which other services grow. Look at the current huge tech companies: Facebook, Twitter, Google, GitHub, Amazon, Netflix.. None of them would be nearly as big as they are today if they hadn't opened up their data via API. In fact, an entire industry exists with the sole purpose of consuming data provided by said platforms.
These are 10 best practices to design a clean RESTful API:
1. Use nouns but no verbs
Do not use verbs:

/getAllCars
/createNewCar
/deleteAllRedCars

2. GET method and query parameters should not alter the state
Use PUT, POST and DELETE methods instead of the GET method to alter the state.
Do not use GET for state changes:

GET /users/711?activate or
GET /users/711/activate

3. Use plural nouns

Do not mix up singular and plural nouns. Keep it simple and use only plural nouns for all resources.

/cars instead of /car
/users instead of /user
/products instead of /product
/settings instead of /setting


4. Use sub-resources for relations
If a resource is related to another resource use subresources.

GET /cars/711/drivers/ Returns a list of drivers for car 711
GET /cars/711/drivers/4 Returns driver #4 for car 711

5. Use HTTP headers for serialization formats
Both, client and server, need to know which format is used for the communication. The format has to be specified in the HTTP-Header.

Content-Type defines the request format.
Accept defines a list of acceptable response formats.

6. Use HATEOAS
Hypermedia as the Engine of Application State is a principle that hypertext links should be used to create a better navigation through the API. for more infomation click here

7. Provide filtering, sorting, field selection and paging for collections
Use a unique query parameter for all fields or a query language for filtering.
Allow ascending and descending sorting over multiple fields.
Give the API consumer the ability to choose returned fields.
Use limit and offset. It is flexible for the user and common in leading databases.

GET /cars?color=red Returns a list of red cars
GET /cars?sort=-manufactorer,+model
GET /cars?fields=manufacturer,model,id,color
GET /cars?offset=10&limit=5


8. Version your API
Make the API Version mandatory and do not release an unversioned API. Use a simple ordinal number and avoid dot notation such as 2.5.
We are using the url for the API versioning starting with the letter "v"

/blog/api/v1

9. Handle Errors with HTTP status codes
It is hard to work with an API that ignores error handling. Pure returning of a HTTP 500 with a stacktrace is not very helpful.
Use HTTP status codes
The HTTP standard provides over 70 status codes to describe the return values. We don't need them all, but there should be used at least a mount of 10.
200 - OK - Eyerything is working
201 - OK - New resource has been created
204 - OK - The resource was successfully deleted
304 - Not Modified - The client can use cached data
400 - Bad Request - The request was invalid or cannot be served. The exact error should be explained in the error payload. E.g. "The JSON is not valid"
401 - Unauthorized - The request requires an user authentication
403 - Forbidden - The server understood the request, but is refusing it or the access is not allowed.
404 - Not found - There is no resource behind the URI.
500 - Internal Server Error - API developers should avoid this error.

10. Allow overriding HTTP method
Some proxies support only POST and GET methods. To support a RESTful API with these limitations, the API needs a way to override the HTTP method.

Q. What are the best practices in using HTTP methods with Restful Web Services?
Ans. A browser uses a HTTP method whenever it sends a request to the server. There are different types of HTTP methods. The most popular and widely used HTTP methods are GET and POST. The HTTP protocol not only contains these two methods but it also contains other methods like PUT, DELETE, HEAD and OPTIONS. On creating any REST service the way these request methods are being used is very crucial and that is one of the main discipline in REST that separates it from the traditional web services.

HTTP Verb CRUD Specific Item/Code
POST Create 201 (Created), 404 (Not Found), 409 (Conflict) if resource already exists.
GET Read 200 (OK), list of customers. 404 (Not Found), if ID not found or invalid.
PUT Update/Replace 404 (Not Found), 200 (OK) or 204 (No Content).
PATCH Update/Modify 404 (Not Found),200 (OK) or 204 (No Content).
DELETE Delete 404 (Not Found),200 (OK). 404 (Not Found), if ID not found or invalid.

Q. Can you explain a little bit about JAX-RS?
Ans. JAX-RS is a Java programming language API designed to make it easy to develop applications that use the REST architecture. The JAX-RS API uses Java programming language annotations to simplify the development of RESTful web services. Developers decorate Java programming language class files with JAX-RS annotations to define resources and the actions that can be performed on those resources. JAX-RS annotations are runtime annotations; therefore, runtime reflection will generate the helper classes and artifacts for the resource. A Java EE application archive containing JAX-RS resource classes will have the resources configured, the helper classes and artifacts generated, and the resource exposed to clients by deploying the archive to a Java EE server. The JAX-RS Annotations are:

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

Q. What are the advantages of Restful web services?
Ans. Advantage of REST Web Service

  • RESTful web services are platform independent. 
  • RESTful web services are language independent. 
  • RESTful web services are fast. 
  • RESTful web services provide a level of simplicity which speeds things up, making integrations cost-effective. 
  • It requires lower learning curve to consumer. 
  • It supports caching of URI which improves performance. 
  • As compared to SOAP web services, it is light weighted which in turn improves performance. 

Q. What is the difference between REST and SOAP Based Services?
Ans. A SOAP client will be tightly coupled to the server and works like a custom desktop application. This is like a contract between client and server. If either side changes anything then it may break everything. We need constant updates following any change. In SOAP, the client needs previous knowledge on everything he will be using, or it won't even begin the interaction. A SOAP client cannot be extended by code-on-demand supplied by the server itself.
A REST client is more like a browser. It's a generic client that knows how to use a protocol and standardized methods, and an application has to fit inside that. We don't violate the protocol standards by creating extra methods. We leverage on the standard methods and create the actions with them on our media type. This result into less coupling. A client is supposed to enter a REST service with zero knowledge of the API, except for the entry point and the media type. A REST client can be extended by code-on-demand supplied by the server itself.

Q. What is a Web Service ?
Ans. The term Web services describes a standardized way of integrating Web-based applications using the XML, SOAP, WSDL and UDDI open standards over an Internet protocol backbone. XML is used to tag the data, SOAP is used to transfer the data, WSDL is used for describing the services available and UDDI is used for listing what services are available. Used primarily as a means for businesses to communicate with each other and with clients, Web services allow organizations to communicate data without intimate knowledge of each other's IT systems behind the firewall.

Q. What is DISCO(Discovery) ?
Ans. The Web Service Discovery Tool (DISCO) is used to discover the URLs of XML Web Services located on a Web server and saves documents related to each XML service on a local disk. The DISCO takes the URL and discovers and produce publishes discovery documents (.wsdl, .xsd, .disco and .dicomap files) as arguments. Some of the options available for use with this tool are:
/d[omain]:domain - Specifies the domain name to use when connecting to a proxy server that requires authentication
/nosave - Does not save the discovered document or results
/nologo - Suppresses the Microsoft startup banner display
/o[ut]:directoryName - Specifies the output directory in which to save the discovered documents. Current directory is the default one.
/p[assword]:password - Specifies the password to use when connecting to a proxy server
/proxy:url - Specifies the URL of the proxy server to use for HTTP requests.
DISCO is a tool, not a web service itself.

Q. What is difference between Contract First and Contract Last Web Services?
Ans. Web service design seems to come in two flavours contract-first and contract-last. Contract-first starts with designing the XML schema / WSDL and then creating the Java interface based upon the schema.
Contract-last takes an existing Java interface and from that, creates your web service. On reflection, you'd think that this meant create a schema contract, but generally it seems to mean getting hold of some tool that will take a Java interface as an input and deliver a WSDL as an output.
Research seems to show that, at the time of writing, contract-first is preferred over contract-last and various reasons are given:

  • Object to XML impedance mismatch, which generally means that with contract-last, some Java types don't readily convert to XML and if they did then there could be a certain loss of information as defined by an XSD's <restriction> element. I.e, Java isn't really expressive enough to produce a rugged contract. 
  • Contract-last could suffer from performance issues as you, the developer, have no control of what's sent over the wire. 
  • Using contract-first means that you have your XML types defined in a set of separate schema files, which could be re-used effectively. 
  • Contract-first has looser coupling between definition and implementation making version management easier. 
  • One of the positive things about web services is that they allow services written in different languages to work together. Contract-first reinforces this approach as the WDSL / XML Schema provides a programming language independent, centralised method of specifying a contract. Contract-last, on the other hand, means that your contract is defined in your implementation code, which may differ from your client's implementation code and who's to say which is the master copy of the code? 
  • Which brings us on the next benefit of using contract-first: the management of change. There is usually a version 2 of an interface adding in something that was forgotten in version 1. Using a schema makes that change management easier. 
  • Finally, a plus point for contract-last is that it should be easier, there's no messing about with XSDs, meaning there are no extra skills for your team to learn. 

This is not a complete list, but should underline the reasons why contract first seems to be the preferred choice.

Q. How do I handle authentication in REST?
Ans. There are a number of ways of supplying REST requests with authentication credentials.

HTTP basic auth over HTTPS

This first solution, based on the standard HTTPS protocol, is used by most web services. It's easy to implement, available by default on all browsers, but has some known draw-backs, like the awful authentication window displayed on the Browser, which will persist (there is no LogOut-like feature here), some server-side additional CPU consumption, and the fact that the user-name and password are transmitted (over HTTPS) into the Server.

Cookies Authentication

One possibility could be to maintain all data within the cookie content. And, by design, the cookie is handled on the Server side (Client in fact don't even try to interpret this cookie data: it just hands it back to the server on each successive request). But this cookie data is application state data, so the client should manage it, not the server, in a pure Stateless world.
The cookie technique itself is HTTP-linked, so it's not truly RESTful, which should be protocol-independent. In our framework, since we don't provide HTTP-like headers within each request, we can not handle cookies natively, for all transmission protocol used. So we tried not to use the Cookie technique.

Query Authentication

Query Authentication consists in signing each RESTful request via some additional parameters on the URI.
For instance, here is a generic URI sample, extracted from the link above:

GET /object?apiKey=Qwerty2010

should be transmitted as such:

GET /object?timestamp=1261496500&apiKey=Qwerty2010&signature=abcdef0123456789

The string being signed is "/object?apikey=Qwerty2010×tamp=1261496500" and the signature is the SHA256 hash of that string using the private component of the API key.
This technique is perhaps the more compatible with a Stateless architecture, and can also been implemented with a light session management.
Server-side data caching is always available. In our framework, we cache the responses at the SQL level, not at the URI level (thanks to our optimized implementation of GetJSONObjectAsSQL, the URI to SQL conversion is very fast). So adding this extra parameter doesn't break the cache mechanism.

Per-User authentication

On the Server side, a dedicated RESTful Service, accessible via the ModelRoot/Auth URI is to be called to register an User, and create a session. On the Server side, two tables, implemented by TSQLAuthGroup and TSQLAuthUser will handle respectively per-group access rights, and user authentication.
If both AuthGroup and AuthUser are not available on the Server TSQLModel (i.e. if the aHandleUserAuthentication parameter was set to false for the TSQLRestServer. Create constructor), no authentication is performed. All tables will be accessible by any client. For security reasons, the ability to execute INSERT / UPDATE / DELETE SQL statement via a RESTful POST command is never allowed with remote connections: only SELECT can be executed via this command.
If authentication is enabled for the Client-Server process (i.e. if both AuthGroup and AuthUser are available in the Server TSQLModel, i.e. aHandleUserAuthentication=true), each REST request will expect an additional parameter, named session_signature, to every URL. Using the URL instead of cookies allows the signature process to work with all communication protocols, not only HTTP.
This will implement both Query Authentication together with a group-oriented per-user right management.

Session handling

A dedicated RESTful service, available from the ModelRoot/Auth URI, is to be used for user authentication, handling so called sessions.
Here are the typical steps to be followed in order to create a new user session:
- Client sends a GET ModelRoot/auth?UserName=... request to the remote server;
- Server answers with an hexadecimal nonce contents (valid for about 5 minutes);
- Client sends a GET ModelRoot/auth?UserName=...&PassWord=...&ClientNonce=... request to the remote server, in which ClientNonce is a random value used as Client nonce, and PassWord is computed from the log-on and password entered by the User, using both Server and Client nonce as salt;
- Server checks that the transmitted password is valid, i.e. that its matches the hashed password stored in its database and a time-valid Server once - if the value is not correct, authentication failed;
- On success, Server will create a new in-memory session (sessions are not stored in the database, for lighter and safer process) and returns the session number and a private key to be used during the session;
- On any further access to the Server, a &session_signature= parameter is added to the URL, and will be checked against the valid sessions in order to validate the request;
- When the Client is about to close (typically in TSQLRestClientURI. Destroy), the GET ModelRoot/auth?UserName=...&Session=... request is sent to the remote server, in order to explicitly close the corresponding session in the server memory (avoiding most re-play attacks);
- Each opened session has an internal TimeOut parameter (retrieved from the associated TSQLAuthGroup table content): after some time of inactivity, sessions are closed on the Server Side.
Note that with this design, it's up to the Client to react to an authentication error during, and ask for the User pseudo and password at any time. For multiple reasons (server restart, session timeout...) the session can be closed at any time by the Server.

Q. What is Richardson Maturity Model?
Ans. The Richardson Maturity Model is a model developed by Leonard Richardson. It talks about the basics of REST in terms of resources, verbs, and hypermedia controls. The starting point for the maturity model is to use the HTTP layer as the transport. It is a scale for evaluating services and their RESTfulness. It consists of four levels:
- HTTP transport - Remote interaction through tunnel, no web mechanisms.
- Resources - Separate resources instead of a single endpoint.
- HTTP Verbs - Standardized use of HTTP verbs to perform actions.
- Hypermedia controls - HATEOAS is implemented.
For more information click here

Q. What are the pros and cons of each approach, and which approach would you prefer?
Ans. I've used both approaches. My suggestion is to use contract first schema, but code first WSDL.
Writing a WSDL file has a lot of weird nuances like bindings, ports and such. I'd rather have this done by tools rather than by hand. There are tools to help do this, but none of them are simpler than

@WebService
public ...

At the very least you can verify your deployment.
For the schema, I suggested contract first because the XML Schema language is far richer than what you can describe in Java. An example I usually give is showing that XML Schema can restrict the size of a string and apply a regular expression pattern. Doing that in Java and annotations looks a bit messier.

Another advantage of doing the schema as contract first is the presence of tools to convert your schema file into HTML documentation.
The XJC tool can generate the requisite class files. However, I would only recommend doing that at start.
In the end you should take the generated WSDL file and work with that instead. That way you can use wsimport and verify that the whole thing from WSDL to Schema is valid.
You can deploy with the WSDL file by using the wsdlLocation attribute in your @WebService implementation and the application server will fix the binding data for you when users request the WSDL from the server, but you still retain your annotations. Otherwise your annotations will not appear on the requested WSDL files.

Q. What is Idempotent Methods?
Ans. GET, HEAD, PUT and DELETE request methods are idempotent. Idempotent means how many times these requests are applied serially to the server the result is same as the intial request. If you are deleting a resource or data through DELETE request, when you issue the request at the first time the resource is removed from the server and if you again issue the same request nothing new should happen in the server i.e the state of the server should not be changed. The same rule applies for other requests also. When you are designing RESTful services idempotence should also be considered for these HTTP methods.


     << Previous