Friday, March 22, 2019

RESTful Web Services

In this blog, I would like to talk about the available  RESTful Web Services that we see today and how they are being utilized in our day to day applications.

                                                                                




Message-oriented communication

 Message-oriented communication is a way of communicating between processes. Messages, which correspond to events, are the basic units of data delivered. Tanenbaum and Steen classified message-oriented communication according to two factors-synchronous or asynchronous communication, and transient or persistent communication. The sender blocks waiting for the receiver in synchronous communication.

Asynchronous communication does not require simultaneous execution of both the sender and the receiver. So the sender is loosely coupled with the recipient. Whether the communication is transient or persistent is determined by the amount of time messages stored. Transient communication only stores the message when both partners are executing the communication. If the next router or receiver is not available, then the message is discarded. Persistent communication, on the other hand, stores the message until the recipient receives it.

A resource-oriented architecture (ROA) is the structural design supporting the internet working of resources. A resource, in this context, is any entity that can be identified and assigned a uniform resource identifier (URI).In information technology, architecture refers to the overall structure of an information system and the interrelationships of entities that make up that system. ROA is considered a RESTful architecture. REST (representational state transfer) is defined by Roy Fielding, co-author of the HTTP specification and co-founder of the Apache HTTP server project, as an architectural style that exploits the existing technology and protocols of the Web, including HTTP and XML.
   
Four essential concepts
        Resources
        Their names (URIs)
        Their representations
         The links between them
 Four properties:
            Address-ability
            Statelessness
            Connectedness
            A uniform interface

            The idea behind REST is that applications, i.e., clients, interact with APIs by retrieving and manipulating exposed representations of resources. A resource can be a real world object or a data object on the web. The representation of a resource details the current state of the resource. The characteristic of a dynamic data source is a very high update rate of the resource states. To enable clients to capture the resulting velocity of the data, dynamic data sources often expose a stream of data, which provides the information about the occurring state updates.
REST architecture treats as a resource every content. These resources may be text files, html pages, images, videos or business data dynamics. REST Server provides resource access and REST client access and resource modification. URIs / Global IDs identify each resource here. REST uses different representations to represent a resource that includes Text, JSON, XML.



       A resource in REST is or is like an entity in a database, a similar object in object - oriented programming. Once a resource is identified, its representation must be decided using a standard format to enable the server to send the resource in the format mentioned above and the client can understand the same format.

Following are some important points to be considered while designing a representation format of a resource in RESTful Web Services.

    Understand-ability
- Both the Server and the Client should be able to understand and utilize the representation format of the resource.


                                                         

                                                                      
   


 Completeness - Format should be able to represent a resource completely. For example, a resource can contain another resource. Format should be able to represent simple as well as complex structures of resources.

    Linkablity - A resource can have a linkage to another resource, a format should be able to handle such situations.


most of the web services are representing resources using either XML or JSON format. There are plenty of libraries and tools available to understand, parse, and modify XML and JSON data.




REST Constraints

REST constraints are design rules that are applied to establish the distinct characteristics of the REST architectural style. If you follow all constraints designed by the REST architectural style your systems is considered RESTful.

These constraints don't dictate what kind of technology to use; they only define how data is transferred between components and what benefits we get following the guidelines. Therefore, a RESTful system can be implemented in any networking architecture available.

  •     Client-Server
  •     Stateless
  •     Cache able
  •     Uniform Interface
  •     Layered System
  •     Code On Demand (Optional)

                    The Representational State Transfer (REST) style is an abstraction of the architectural elements within a distributed hypermedia system. REST distinguishes three classes of architectural elements, they are:

  •     Connectors                                            
  •     Components
  •     Data Elements




Connectors

Connectors represent the activities involved in accessing resources and transferring representations. Roles provide an interface for components to implement. REST encapsulates different activities of accessing and transferring representations into different connector types.

Components

In REST, the various software that interacts with one another are called components

Data Elements

The key aspect of REST is the state of the data elements, its components communicate by transferring representations of the current or desired state of data elements. REST identifies six data elements: a resource, resource identifier, resource metadata, representation, representation metadata, and control data.

   RESTful API

A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data.
A RESTful API - also referred to as a RESTful web service - is based on technology for representational state transfer (REST), architectural style, and communication approaches that are often used in the development of web services.
REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP) technology because REST leverages less bandwidth, making it more suitable for internet usage. An API for a website is code that allows two software programs to communicate with each another . The API spells out the proper way for a developer to write a program requesting services from an operating system or other application.

How RESTful APIs work

A RESTful API breaks down a transaction to create a series of small modules. Each module addresses a particular underlying part of the transaction. This modularity provides developers with a lot of flexibility, but it can be challenging for developers to design from scratch. Currently, the models provided by Amazon Simple Storage Service, Cloud Data Management Interface and Open Stack Swift are the most popular.



Pros
  •     Strong URL Routing support to create clean URLs using familiar MVC - style semantics routing Support for a variety of output formats supported including JSON, XML, ATOM
  • Strong standard REST semantics support but optional
  •  Easily extended support for For matter to add new types of input / output
  •  Very extensible, based on MVC, like For matters and Filters extensibility model
  • Self host able in non-Web applications
  •  Deep support for more advanced HTTP features through HAPT Response Message and HAPT Request Message classes and Enums strongly typed to describe many HTTP operations
  • Testable using testing concepts similar to MVC


cons
    1.Web API is MVC - like, but not the same
       
    2.Code Duplication

    3.Conclusion

 

 The JAX-RS API and its implementations 
   *JAX - RS stands for RESTful Web Services JAVA API. JAX - RS is a JAVA programming language API and specification to support the RESTful Web Services that have been created.

*Its 2.0 release was released on May 24, 2013. JAX - RS uses Java SE 5 annotations to simplify the development and deployment of JAVA - based web services.

*It also supports the creation of RESTful Web Services customers.

    *There are two main implementation of JAX-RS API
        1.Jersey
        2.RESTEasy


 JAX-RS
*The JAX - RS API uses annotations to supply meta - data around the web resource.

        1.The @Path Annotation (again) and @PathParam
        *The @Path annotation can be used to further refine the location of a resource using the resource method.
        *import javax.ws.rs.Path

    2.The @QueryParamter Annotation
        *A query parameter is the value associated with the key/value pair appended to a URL after the ? symbol.
        *import javax.ws.rs.QueryParam
       
    3.The @Produces Annotation
        *The @Produces annotations specify the type of media or types returned to the caller by the method.
        **import javax.ws.rs.Produces


    4.The @Consumes Annotation
        *You can specify the media type that a method can consume with the @Consumes annotation.

    5.@DELETE
        *@DELETE annotation corresponds to HTTP DELETE method.
    6.@GET, @POST
        *To map the HTTP methods to methods in the resource representing class. For example, @GET can be placed on getBook method.


“Media type” in JAX-RS

All methods of resource can consume and produce content of almost any kind. If you submit a POST request to a URI, such as api/books, the REST API expects that the HTTP body will have a payload that is the resource it should create

*This resource can be represented using any media type.



Read More

Friday, March 15, 2019

Web services and SOAP

  This article is about the Web services and SOAP 
What is web services and what is SOAP?

              Lets discus these topics...








                                                      Web services       Web services are a standardized means of propagating communication on the World Wide Web between client and server applications. This course will provide a detailed insight into the different components of web services such as SOAP, WSDL , REST, and how they work.
 Web services leads to many advantages for various software testing companies mentioned below:

    Re-usability of any code
    Reduced the Complexity
    Enhanced the features of any product
    Impact on cost
                                                          Speed




 A web application is a software application that a user runs in the web browser. It have the following features.
  •     It has a User Interface
  •     Runs in Client - Server environment
  •     Client runs it with the help of a web browser
  •     Server process the data based on client request and provide response
 WSDL
              WSDL is an XML format designed to describe network services as a set of endpoints that operate on messages that contain either document - oriented or procedural information. To define an endpoint, the operations and messages are described abstractly and then linked to a concrete network protocol and message format. Combining related concrete endpoints into abstract endpoints (services).



A WSDL document defines services as network endpoint or port collections.  In WSDL, endpoints and messages are separated from their concrete network deployment or data format bindings by the abstract definition. This enables abstract definitions to be reused: messages that are abstract descriptions of the data being exchanged, and types of port that are abstract operations collections. Hence, a WSDL document uses the following elements in the definition of network services:


    Types– a container for data type definitions using some type system (such as XSD).
    Message– an abstract, typed definition of the data being communicated.
    Operation– an abstract description of an action supported by the service.
    Port Type–an abstract set of operations supported by one or more endpoints.
    Binding– a concrete protocol and data format specification for a particular port type.
    Port– a single endpoint defined as a combination of a binding and a network address.
    Service– a collection of related endpoints.

In addition to the core service definition framework, this specification introduces specific binding extensions for the following protocols and message formats:

    SOAP 1.1 (see Section 3)
    HTTP GET / POST (see Section 4)
    MIME (see Section 5)

  A WSDL document contains the following elements -

    Definition - It is the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here.

    Data types - The data types to be used in the messages are in the form of XML schemas.

    Message - It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation.

    Operation - It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message.

    Port type - It is an abstract set of operations mapped to one or more end-points, defining the collection of operations for a binding; the collection of operations, as it is abstract, can be mapped to multiple transports through various bindings.

Binding - It is the concrete protocol and data formats for the operations and messages defined for a particular port type.

Port - It is a combination of a binding and a network address, providing the target address of the service communication.

Service - It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions.


The main structure of a WSDL document looks like this -

<definitions>
   <types>
      definition of types........
   </types>

   <message>
      definition of a message....
   </message>

   <portType>
      <operation>
         definition of a operation....... 
      </operation>
   </portType>

   <binding>
      definition of a binding....
   </binding>

   <service>
      definition of a service....
   </service>
</definitions>


 Port Type Definition Element

portType" is a top level element of a WSDL 1.1 document. "portType" is used to define a port type with one or multiple operations with "operation" sub elements. An operation is defined with a sequence of messages to form an input-output pattern with "input" and "output" sub elements.

WSDL supports 4 input-output patterns which defines 4 types of operations:

    One-way - input only: The endpoint receives a message.
    Request-response - input followed by output: The endpoint receives a message, and sends a correlated message. This type of operation may also output an optional fault message.
    Solicit-response - output followed by input: The endpoint sends a message, and receives a correlated message. This type of operation may also output an optional fault message.
    Notification - output only: The endpoint sends a message.

The syntax of "portType" looks like this:

<wsdl:portType ...>
    <-- One-way operation -->
    <wsdl:operation name="nmtoken1" parameterOrder="nmtokens">
      <wsdl:input name="nmtoken2" message="qname2"/>
    </wsdl:operation>

    <-- Request-response operation -->
    <wsdl:operation name="nmtoken1" parameterOrder="nmtokens">
      <wsdl:input name="nmtoken2" message="qname2"/>
      <wsdl:output name="nmtoken3" message="qname3"/>
      <wsdl:fault name="nmtoken4" message="qname4"/>
    </wsdl:operation>

    <-- Solicit-response operation -->
    <wsdl:operation name="nmtoken1" parameterOrder="nmtokens">
      <wsdl:output name="nmtoken3" message="qname3"/>
      <wsdl:input name="nmtoken2" message="qname2"/>
      <wsdl:fault name="nmtoken4" message="qname4"/>
    </wsdl:operation>

    <-- Notification operation -->
    <wsdl:operation name="nmtoken1" parameterOrder="nmtokens">
      <wsdl:output name="nmtoken3" message="qname3"/>
    </wsdl:operation>

    ...
  </wsdl:portType >



Patterns of Operation

WSDL supports four basic patterns of operation -
One-way

The service receives a message. The operation therefore has a single input element. The grammar for a one-way operation is -



<wsdl:definitions .... >
   <wsdl:portType .... > *
      <wsdl:operation name = "nmtoken">
         <wsdl:input name = "nmtoken"? message = "qname"/>
      </wsdl:operation>
   </wsdl:portType >
</wsdl:definitions>


 Request-response

The service receives a message and sends a response. The operation therefore has one input element, followed by one output element. To encapsulate errors, an optional fault element can also be specified. The grammar for a request-response operation is -


<wsdl:definitions .... >
   <wsdl:portType .... > *
      <wsdl:operation name = "nmtoken" parameterOrder = "nmtokens">
         <wsdl:input name = "nmtoken"? message = "qname"/>
         <wsdl:output name = "nmtoken"? message = "qname"/>
         <wsdl:fault name = "nmtoken" message = "qname"/>*
      </wsdl:operation>
   </wsdl:portType>
</wsdl:definitions>


Solicit-response

The service sends a message and receives a response. The operation therefore has one output element, followed by one input element. To encapsulate errors, an optional fault element can also be specified.The grammar for a solicit-response operation is -


<wsdl:definitions .... >
   <wsdl:portType .... > *
      <wsdl:operation name = "nmtoken" parameterOrder = "nmtokens">
         <wsdl:output name = "nmtoken"? message = "qname"/>
         <wsdl:input name = "nmtoken"? message = "qname"/>
         <wsdl:fault name = "nmtoken" message = "qname"/>*
      </wsdl:operation>
   </wsdl:portType >
</wsdl:definitions>



               The binding element of a WSDL file describes how the service is bound to the SOAP messaging protocol. There are two possible SOAP binding styles: RPC and Document.

 There may also be an encoded use or a literal use of a SOAP binding. The usage attribute is about the representation of types in XML messages. It indicates if the message parts are encoded using some encoding rules or if the parts define the message's concrete schema.

This means there are four potential style/use models. It is generally accepted that it is best practice to avoid using RPC/Literal or Document/Encoded. Therefore, the following are supported:

    RPC/Encoded
    Document/Literal
Each style has particular features that dictate how to create a WSDL file, and how to translate a WSDL binding to a SOAP message. Essentially these result in different formatting of the SOAP messages.

 SOAP (Simple Object Access Protocol abbreviation)

         SOAP  is a specification of the messaging protocol for the exchange of structured information in computer network implementation of web services. Its purpose is to provide extensible, independence and neutrality.
It uses XML Information Set for its message format and relies on HTTP (Hypertext Transfer Protocol) application layer protocols.
Hypertext Transfer Protocol (HTTP) or Simple Mail Transfer Protocol (SMTP) is most commonly used for negotiating and transmitting messages. Using Extensible Markup Language (XML), SOAP enables processes running on different operating systems (such as Windows and Linux) to communicate. Because web protocols such as HTTP are installed and running on all operating systems, SOAP enables clients to rely on web services and receive responses independent of language and platforms.

POST /In Stock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 299
SOAP Action: "http://www.w3.org/2003/05/soap-envelope"




<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:m="http://www.example.org">
  <soap:Header>
  </soap:Header>
  <soap:Body>
    <m:GetStockPrice>
      <m:StockName>GOOG</m:StockName>
    </m:GetStockPrice>
  </soap:Body>
</soap:Envelope>


Advantages
SOAP's neutrality characteristic explicitly makes it suitable for use with any transport protocol. Implementations often use HTTP as a transport protocol, but other popular transport protocols can be used. For example, SOAP can also be used over SMTP, JMS and message queues.
SOAP, when combined with HTTP post/response exchanges, tunnels easily through existing firewalls and proxies, and consequently doesn't require modifying the widespread computing and communication infrastructures that exist for processing HTTP post/response exchanges.

Disadvantages
When using standard implementations and the default SOAP/HTTP binding, the XML infoset is serialized as XML. To improve performance for the special case of XML with embedded binary objects, the Message Transmission Optimization Mechanism was introduced.
When relying on HTTP as a transport protocol and not using Web Services Addressing or an Enterprise Service Bus, the roles of the interacting parties are fixed. Only one party (the client) can use the services of the other.


                   SOAP is an XML message format (of an envelope, message headers, and a message body) and a standard encoding mechanism that allows messages to be sent over a variety of transports, including HTTP and JMS. ... Due to the frequent use of SOAP-over-HTTP, SOAP is often understood to be a request-response (RPC-like) protocol.

                   Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format of email to support:

    Text in character sets other than ASCII
    Non-text attachments: audio, video, images, application programs etc.
    Message bodies with multiple parts
    Header information in non-ASCII character sets

Although MIME was primarily designed for SMTP, the content types defined by MIME standards are also important in non - e - mail communication protocols, such as HTTP for the World Wide Web. At the beginning of any Web transmission, servers insert the MIME header. Clients use this type of content or media type header to select a suitable viewer application for the data type indicated by the header. Some of these viewers are integrated into the Web client or browser (for example, nearly all browsers have GIF and JPEG viewers as well as the ability to handle HTML files).

 SOAP Framework

The Dell Boomi SOAP Framework is a collection of third-party libraries and custom code that enables easy integration with any SOAP web service.     




The syntax of SOAP is standardized, but the semantics to interact with a given SOAP web service is not. Implementation details such as authentication, resource protection, and object representation are handled in a different ways so that almost every web service is unique in some aspect. The Dell Boomi SOAP Framework provides building blocks/templates to handle many common web service implementation features. When assembled, they provide a fully-featured Dell Boomi SDK Connector implementation.

 JAX-WS annotations

This JAX-WS annotation can be used in 2 ways. If we are annotating this over a class, it means that we are trying to mark the class as the implementing the Web Service, in other words Service Implementation Bean (SIB). Or we are marking this over an interface, it means that we are defining a Web Service Interface (SEI), in other words Service Endpoint Interface.

Now lets see the java program demonstrating both of the mentioned ways:

WSAnnotationWebServiceI.java
   
package com.javacodegeeks.examples.jaxWsAnnotations.webservice;


import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style=Style.RPC)
public interface WSAnnotationWebServiceI {
    @WebMethod
    float celsiusToFarhenheit(float celsius);
}




















































































Read More