Monday, 14 July 2014

Web Services

Java Web Services Interview Questions and Answers: Overview

Q. What are the different application integration styles?
A. There are a number of different integration styles like

1. Shared database
2. batch file transfer
3. Invoking remote procedures (RPC)
4. Exchanging asynchronous messages over a message oriented middle-ware (MOM).


Q. How does a Java EE application integrates with other systems?
A. Using various protocols like HTTP(S), SOAP, RMI, FTP, proprietary, etc.



Q. What are the different styles of Web Services used for application integration?
A. SOAP WS and RESTful Web Service

Q. What are the differences between both SOAP WS and RESTful WS?
A.  
  • The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
  • The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S),  Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
  • The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations.

             GET - read()
             POST - create()
             PUT - update()
             DELETE - delete() 
  • SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better.
  • SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not.
  • The SOAP has comprehensive support for both ACID based  transaction management  for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it  is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
  • The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.


  • Q. How would you decide what style of Web Service to use? SOAP WS or REST?
    A. In general, a REST based Web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security and transactional reliability.

    The answer really depends on the functional and non-functional requirements. Asking the questions listed below will help you choose.

    • Does the service expose data or business logic? (REST is a better choice for exposing data, SOAP WS might be a better choice for logic).
    • Do the consumers and the service providers require a formal contract? (SOAP has a formal contract via WSDL)
    • Do we need to support multiple data formats?
    • Do we need to make AJAX calls? (REST can use the XMLHttpRequest)
    • Is the call synchronous or  asynchronous?
    • Is the call stateful or stateless? (REST is suited for statless CRUD operations)
    • What level of security is required? (SOAP WS has better support for security)
    • What level of transaction support is required? (SOAP WS has better support for transaction management)
    • Do we have limited band width? (SOAP is more verbose)
    • What’s best for the developers who will build clients for the service? (REST is easier to implement, test, and maintain)


    Q. What tools do you use to test your Web Services?
    A. SoapUI tool for SOAP WS and the Firefox "poster" plugin for RESTFul services.


    Q. What is the difference between SOA and a Web service?
    A. 

    SOA is a software design principle and an architectural pattern for implementing loosely coupled, reusable and coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs).

    Web service is an implementation technology and one of the ways to implement SOA. You can build SOA based applications without using Web services – for example by using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web services offer is the standards based  and platform-independent service via HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies such as J2EE and .NET.



    Q. Why not favor traditional style middle-ware such as RPC, CORBA, RMI and DCOM as opposed to Web services?
    A. 

    The traditional middle-wares tightly couple connections to the applications and it can break if you make any modification to your application. Tightly coupled applications are hard to maintain and less reusable. Generally do not support heterogeneity. Do not work across Internet. Can be more expensive and hard to use.

    Web Services support loosely coupled connections. The interface of the Web service provides a layer of abstraction between the client and the server. The loosely coupled applications reduce the cost of maintenance and increases re-usability. Web Services present a new form of middle-ware based on XML and Web. Web services are language and platform independent. You can develop a Web service using any language and deploy it on to any platform, from small device to the largest supercomputer. Web service uses language neutral protocols such as HTTP and communicates between disparate applications by passing XML messages to each other via a Web API. Do work across internet, less expensive and easier to use.

    Q. What are the different approaches to developing a SOAP based Web service? A. 2 approaches.

    • The contract-first approach, where you define the contract first with XSD and WSDL and the generate the Java classes from the contract.
    • The contract-last approach where you  define the Java classes first and then generate the contract, which is the  WSDL file from the Java classes.

    Note: The WSDL describes all operations that the service provides, locations of the endpoints (i.e.e where the services can be invoked), and simple and complex elements that can be passed in requests and responses.

    Q. What are the pros and cons of each approach, and which approach would you prefer?

    A.

    Contract-first Web service


    PROS:

    • Clients are decoupled from the server, hence the implementation logic can be revised on the server without affecting the clients.
    • Developers can work simultaneously on client and server side based on the contract both agreed on.
    • You have full control over how the request and response messages are constructed -- for example, should "status" go as an element or as an attribute? The contract clearly defines it. You can change OXM (i.e. Object to XML Mapping) libraries without having to worry if the "status" would be generated as "attribute" instead of an element. Potentially, even Web service frameworks and tool kits can be changed as well from say Apache Axis to Apache CXF, etc

    CONS:

    • More upfront work is involved in setting up the XSDs and WSDLs. There are tools like XML Spy, Oxygen XML, etc to make things easier. The object models need to be written as well.
       
    • Developers need to learn XSDs and WSDLs in addition to just knowing Java.


    Contract-last Web service

    PROS:
    • Developers don't have to learn anything related to XSDs, WSDLs, and SOAP. The services are created quickly by exposing the existing service logic with frameworks/tool sets. For example, via IDE based wizards, etc.
        
    • The learning curve and development time can be smaller compared to the Contract-first Web service.

    CONS: 
    •  The development time can be shorter to initially develop it, but what about the on going maintenance and extension time if the contract changes or new elements need to be added? In this approach, since the clients and servers are more tightly coupled, the future changes may break the client contract and affect all clients or require the services to be properly versioned and managed.
    •  In this approach, The XML payloads cannot be controlled. This means changing your OXM libraries could cause something that used to be an element to become an attribute with the change of the OXM.


    So, which approach will you choose?

    The best practice is to use "contract-first", and here is the link that explains this much better with examples -->  contract-first versus contract-last web services In a nutshell, the contract-last is more fragile than the "contract-first".  You will have to decide what is most appropriate based on your requirements, tool sets you use, etc.

JAX pack technologies


<<Previous Next>> 
Java web service - Feb 08, 2009, 17:00 pm by Vidya Sagar 

Explain the technologies included within JAX pack, i.e. JAXP, JAXB, JAXM, JAX-RPC, JAXR.

JAXP: Java API for xml processing. It provides the validation capability and parsing XML documents. There are three basic parsing interfaces in JAXP are DOM, SAX and Straming API for XML STAX.
JAXB: Java Architecture for XML Binding: The java classes are mapped to XML representations. The two main features of JAXB are the ability to marshal Java objects into XML and unmarshal XML back to Java objects.
The Java API for XML Messaging (JAXM) enables distributed software applications to communicate using XML (and SOAP). JAXM supports both asynchronous and synchronous messaging.
JAX-RPC: Java API for XML based RPC. Allows a java based web service that is to be invoked by a Java application provided the description, still being consistent with WSDL description. This can resemble as Java RMI over web services.
Allowing a web service to be implemented at server side as a servlet/jsp or EJB container is the advantage of JAX-RPC.
Java web service - Aug 09, 2009, 13:00 pm by Amit Satpute

Explain the technologies included within JAX pack, i.e. JAXP, JAXB, JAXM, JAX-RPC, JAXR.

Included in the bundle are
Java API for XML Processing (JAXP)
JAXP enables applications to parse, transform, validate and query XML documents. It uses an API that is independent of a particular XML processor implementation.
JAXP enables vendors to provide their own implementations without introducing dependencies in application code.
Java Architecture for XML Binding (JAXB)XML is a standard for exchanging data across heterogeneous systems.
Java provides a platform for building portable applications.
A combination of these two enables users and application developers to program Web based functionality on an platform.
Java API for XML Messaging (JAXM)JAXM is a SOAP 1.1 based standard to send XML documents over the Internet from the Java platform.
JAXM can be extended to work with higher level messaging protocols by adding the protocol's functionality on top of SOAP.
Java API for XML-based RPC (JAX-RPC)JAX-RPC project provides the code base for the Reference Implementation of JAX-RPC, the Java APIs for XML based RPC. JAX-RPC RI is a production-quality implementation that is used directly in a number of products by Sun and other vendors.
Java API for XML Registries (JAXR). JAXR gives you a uniform way to use business registries that are based on open standards (ebXML) or industry consortium-led specifications (UDDI).

Explain the web services architecture.

The operations between different software applications, which are running on a variety of platforms and frameworks are supported by a standard called Web services. The web services architecture provides the concepts, model and understanding web services and relationships among the components.
The WSA specifies the minimal characteristics that are very common for all web services and a number of characteristics to the needed web services. WSA is called interoperability architecture that means the global elements of a global web service network are identified by this architecture in order to perform the interoperability between the web services.
Explain the web services architecture.
Web Services are based on three operations: publish, find, and bind.
Service providers publish services to a service broker.
Service requesters find required services using a service broker and bind to them.

http://www.w3schools.com/Webservices/ws_wsdl_intro.asp


Usage of document/literal wrapped pattern in WSDL design

A WSDL (Web Services Description Language) binding style can be either RPC or document, but the wrapped-document/literal pattern is the one, which blends the best out of both these styles.
Vivek Gupta (vivek20.g@tcs.com), Technical Architect, Tata Consultancy Services
21 April 2011
Also available in Chinese Japanese

Introduction

While defining a highly interoperable Web Service in a WSDL using document/literal style of messaging, a “pattern” which is known as wrapped-document/literal, is followed across service providers. This pattern takes the advantage of best features of both the RPC/Literal as well as Document/Literal messaging in WSDL by:
  1. Inserting the SEI (Service Endpoint Interface) Operation name in SOAP Message – Feature of RPC/literal.
  2. Complete definition of the SOAP Message in the W3C XML Schema – Feature of Document/Literal.
A WSDL describes a web service by defining its interface, the operations on that interface, their binding to the transport protocol, and the network address they are available at. A WSDL binding describes how a web service is bound to a messaging protocol, that is, what is the format or structure of the Messages being exchanged with a Service, and the transport protocol over which this Message will be sent. The most popular messaging protocol in web services today, is the SOAP messaging protocol (The other option is to use the REST-based Messages). For a web service using SOAP messaging protocol, the binding "style" can be either RPC (remote-procedure-call) or document style. The binding style being chosen is important from the point of view of the WSDL definition of Input & Output messages for a Web Service Operation & the corresponding SOAP Request/Response message structure. Only "literal" (each element or type is schema defined and serialization follows definition from W3C XML Schema) way of representing the message is supported in WS-I (Web Service – interoperability organization) recommendation for these two binding styles.
In document/literal style of messaging, there exists a pattern which is known as wrapped-document/literal. This is just a pattern, and is not a part of WSDL specification. This pattern has a mention in JSR 224 (JAX-WS: Java API for XML based web services).
This article provides the rules for this pattern in WSDL and intends to stress on the usage of this pattern in WSDL Design. This style/pattern is discussed in the following sections.

Rules for document/literal – Wrapped pattern style of SOAP messaging

The rules for the "wrapped" convention to be followed during WSDL Design:
  1. Only "One" Part Definition in the Input & Output Messages in WSDL
    "Wrapped" is a form of document/literal. When defining a WS-I compliant document/literal service, there can be at most one body part in your input message and at most one body part in your output message. You do *not* define each method parameter as a separate part in the message definition. (The parameters are defined in the WSDL “types” section, instead).
  2. "Part" Definitions are wrapper elements
    Each part definition must reference an element (not a type, type is used in RPC) defined to make it document style of messaging. This element definition can be imported, or included in the types section of the WSDL document. These element definitions are "wrapper" elements (hence the name of this convention). Define the input and output parameters as element structures within these wrapper elements.
  3. Child Elements of "Part" Element Type will be SEI Method parameter
    An input wrapper element must be defined as a complex type that is a sequence of elements. Each child element-type in that sequence will be generated (while using code generation tool on WSDL) as a parameter of the operation in the service interface.
  4. Input Wrapper Element name should match with Operation name 
    The name of the input wrapper element must be the same as the web service operation name in WSDL.
  5. <Output Wrapper Element Name> = <Operation Name> + "Response" 
    The name of the output wrapper element could be (but doesn't have to be) the operation name appended with "Response" (e.g., if the operation name is "add", the output wrapper element should be called "addResponse").
  6. In the WSDL Binding section, soap:binding style = "document"
    Since, the style is document/literal for this wrapped pattern, hence in the binding definition, the soap:binding should specify style="document" (although this is the default value, so the attribute may be omitted), and the soap:body definitions must specify use="literal" and nothing else. You must not specify the namespace or encodingStyle attributes in the soap:body definition.
The illustration of this pattern is done through the diagrams from which style of WSDL should I use?
In listing 1 below you can see the wrapper element "myMethod" matches the operation name "myMethod" in portType section.
Listing 1. Document/literal wrapped WSDL for myMethod
<types>
    <schema>
        <element name="myMethod">
            <complexType>
                <sequence>
                    <element name="x" type="xsd:int"/>
                </sequence>
            </complexType>
        </element>
        <element name="myMethod Response">
            <complexType>
                <sequence>
                    <element name="z" type="xsd:int"/>
                </sequence>
            </complexType>
        </element>
    </schema>
</types>
<message name="myMethodRequest">
    <part name="parameters" element="myMethod"/>
</message>
<message name="myMethodResponse">
    <part name="parameters" element="myMethodResponse"/>
</message>
<portType name="PT">
    <operation name="myMethod">
        <input message="myMethodRequest"/>
        <output message="myMethodResponse"/>
    </operation>
</portType>
<binding.../>
The SOAP Request Message as shown below in listing 2.
Listing 2. Document/literal wrapped SOAP message for myMethod
<SOAP-ENV:Body>
    <myMethod>
        <x>-0</x>
        <y>3.14</y>
    </myMethod>
</SOAP-ENV:Body>
The following is a snapshot of Java SEI generated from the WSDL using "wsimport" facility from JWSDP 2.0. The WSDL used document/literal-wrapped pattern. As can be noticed, the method name will match the input element name.
Listing 3. Java SEI from wsimport run on document/literal wrapped WSDL for myMethod
/**
  *This class was generated by JAXWS SI.
  *JAX-WS RI 2.0-b62-ea3
  *Generated source version: 2.0
  *
  */
  @WebService(name ="PT", wsdlLocation = "PT.wsdl")
  public interface PT {

  /**
  *
  *@param y
  *@param x
  *@return
  *   returns int
  */
  @WebMethods
  @WebResult(name ="z")
  @RequestWrapper(localname = "myMethod", className = "myMethod")
  @ResponseWrapper(localname = "myMethodResponse", className = "MyMethodResponse")

  public int myMethod (
    @WebParam(name = "x", targetNameSpace = "")
    int x,
    @WebParam(name = "y", targetNameSpace = "")
    float y);
}

Advantages of document/literal – wrapped pattern

The following advantages can be considered by following this pattern -
  1. Wide-Acceptance of Document/Literal-Wrapped style amongst web service providers
    Wrapped Document/Literal pattern provides highly interoperable web service design and has been accepted in the service provider community as a de facto standard while defining the Web Services. The wrapped pattern has evolved from Microsoft® environments. Given the fact that
    1. Microsoft does not have explicit support for RPC-Literal and
    2. Microsoft tools by default generate the WSDL using this wrapped pattern,

      It inherently increases the popularity of this style/pattern when it comes to interoperability.

      Dual Advantage –
    1. The complete SOAP Message under soap:Body can be validated against schema and
    2. This pattern is "always" compliant with WS-I by allowing only one child element under soap:Body.
This high interoperability index of this pattern has resulted into a wider acceptance by the industry as compared to other styles of messaging in Web Service such as RPC/Literal or Document/Literal un-wrapped. Also, IBM WebSphere® tools generate the WSDL with this pattern while using Bottom-up approach in developing web services.
  1. Advantage for SOAP Engine to "Dispatch" SOAP Request to appropriate Web Service Provider
    The SOAP Engine has an advantage with this pattern since it has a clear and simple naming convention available during un-marshaling (XML to Java/C# etc) same as it is available in RPC style. This advantage may save the SOAP Engine from extra execution of matching the parameters in the input SOAP Request message (non WS-Address)
Figure 1. SOAP Message Dispatching to Endpoint Implementation
SOAP Message Dispatching to Endpoint Implementation
With this pattern, the SOAP Engine will use wsdl:portType to determine the Interface and the Method name to whom the SOAP Message should be dispatched. The industry SOAP Engine pioneers (for example Apache Axis2) dispatching process has a mapping of the first child element under soap:Body in the SOAP Message with the operation name.
The deployment descriptor for the Web Service contains the information on wrapped pattern. If two different methods in the Web Service have similar input parameter names, then it becomes increasingly difficult for the SOAP Engine to determine the exact operation name to which the SOAP message should be dispatched to. For wrapped pattern, the operation name is mapped so, there is no additional restriction on the input parameter names to be different in different methods for a given web service.
  1. Optimal Approach
    This style is generally regarded as an optimal approach that enhances maintainability, comprehension, portability, and, to a certain extent, performance. The performance is better in this pattern mainly due to the following reasons –
    1. No Encoding used (advantage of "literal" usage).
    2. Direct parsers & optimized validation of complex data structures of SOAP Messages (advantage of Document style of messaging).
    3. Certain tests have also claimed better performance over RPC/Literal.
  2. Better choice for web service operations with multiple Input Parameters
    If you have a method which takes in more than a parameter, and you wish to expose it as a web service then you are left with one of the following 2 choices together with being WS-I complaint –
    1. RPC/Literal
    2. Document/Literal – Wrapped.
You cannot use Document/Literal -unwrapped, since more than one child element is not allowed under soap:Body element in SOAP Message by WS-I. The advantage of document/literal-wrapped over RPC/Literal is that the complete message under soap:Body is schema-defined and can be validated with the help of Schema Parsers. In RPC/Literal, the web service operation name and part names are not part of the XML Schema.
  1. Advantage of Document/Literal-Wrapped over Document/Literal (Unwrapped)
    Although document/literal-wrapped is a form of document/literal style of messaging, but if the overall document/literal style of messaging is compared with restricted/wrapped document/literal, the disadvantage with a SOAP Message using document/literal (unwrapped) is that it does not contain details of which operation of the web service corresponds to the incoming XML document. So, if two distinct operations of a Web Service have the same type of method parameter, then dispatching will be difficult for SOAP Engine. The operation information is available with RPC style of messaging. The document literal wrapped design pattern resolves this shortcoming of document/literal style by adding a wrapper element around the document representing the input parameters of the operation.

Discussion: Overloaded Methods & Wrapped Document/Literal Pattern

Method Overloading

Listing 4. Overloaded Method "add"
public void add(int addReq){}
public void add(String addReq){}
  1. This pattern CANNOT be used in cases of method overloading. Method overloading using this pattern would require two elements with the same name in the WSDL-types/schema. However, this is possible through the XML Schema rules (different namespace), but in case of Web Service, method overloading is not encouraged.
  2. WS-I Basic Profile 1.0 (see R2304) requires operations within a wsdl:portType to be uniquely named. So, from a WS-I compliance perspective, there should be no case of operation overloading.
  3. WSDL 2.0 does not support operation overloading. Hence overloaded operations might not see the light in the future and should be avoided.

No comments:

Post a Comment