Thursday, 20 November 2014

Websphere Commerce Rest Service Part 1 till WCS 7 Feature Pack6



Rest Services provides way of implementing client service communication model like SOAP services. SOAP usually makes use of action verbs to archive the same. But rest makes use of http verbs like GET, PUT, POST, and DELETE. The response format can be JSON, XML or HTML.

1. Everything in REST is considered as a resource.
2. Each resource is identified by an URI.
3. It is stateless, so every request is an independent request. Each request from client to server must contain all the information necessary to understand the request.
4. Communications are done via representations. E.g. XML, JSON
                                     
Java API for Restful Web Services (JAX-RS) is used to simplify the development of new Restful web services. JAX-RS runtime handles the processing of incoming client requests and responses from the WebSphere Commerce Server. WebsphereCommerce is using Apache wink (Library) implementation of JAX_RS.                        

Apache Wink Library
The Apache Wink run time architecture is a straightforward implementation of the JAX-RS specification. Apache Wink comprised of the following three components:

1.Rest Servlet
2.Request processor
3.Resource
 
1.Rest Servlet. The Rest Servlet is configured in the Java EE web.xml descriptor file of the Web application. This servlet serves as the primary entry point of all the HTTP Web service requests and delegates the request and response object instances to the request processor for further processing.
We can find the inclusion of org.apache.wink.server.internal.servlet.RestServlet in web.xml file inside workspace\Rest\WebContent\WEB-INF folder .

<?xml version="1.0" encoding="UTF-8"?>
<servlet>
<description />
<display-name />
<icon>
<small-icon />
<large-icon />
</icon>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>org.apache.wink.server.internal.servlet.RestServlet</servlet-class>
<init-param>
<param-name>propertiesLocation</param-name>
<param-value>/WEB-INF/config/rest-config.properties</param-value>
</init-param>
<init-param>
<param-name>applicationConfigLocation</param-name>
<param-value>/WEB-INF/config/providers-ext.properties;/WEB- 
INF/config/providers.properties;/WEB-INF/config/resources-ext.properties;/WEB-
INF/config/resources.properties</param-value>
</init-param>
init-param>
<param-name>deploymentConfiguration</param-name>
<param-value>com.ibm.commerce.foundation.rest.config.CommerceDeploymentConfiguration</param-value>
</init-param>
</servlet>

2.Request processor. The Request Processor is the core Apache Wink engine that is initialized by the Apache Wink Rest Servlet. The request processor uses the request URI to find, match, and invoke the corresponding resource class and method. Any exception that occurs during the request processing results in the Request Processor invoking the Error Handler Chain for processing the exception.

3.Resource. In REST, any component or object that represents the Web service is termed resource. A resource enables the retrieval and manipulation of data through one of its many representations. Any POJO that implements the resource is known as the resource class. Resource classes further implement the resource methods that actually handle the underlying business logic.

Each WCS Rest service contains below components.


1.Resource

2.Representation

3.Resource Handler

4.Data Object Mapper

5.Entity Provider

Rest Service Client-Server Request Flow in WCS .


Step1    : Client Gives HTTP request which can be either “GET”,”PUT”,”POST” or  “DELETE”. If the request requires authentication security tokens must be sent in the HTTP request Header. For Non secure requests only WCToken should be sent. But for secure requests both WCToken and WCTrustedToken should be sent.
Step2    :  Apache Wink JAX_RS library will invoke the request Handler.Request Handler creates the business context and call the security run time to verify the authentication tokens.
Step3    : Security run time verifies the authentication tokens.
Step 4   : Request Handler converts incoming REST request to websphere commerce OAGIS service request.
Step5    : Service returns the response in BOD format.
Step 6   :  Data  Object Mapper will convert the BOD response to JSON Format.
Step 7   : Entity Provider will read the JSON returned by data object mapper and convert the response into required format needed by the client and return the response.

More detailed explanation of the components of REST Service is mentioned below.

1. Resource 
A resource is a logical entity that client can interact with .It can be created, updated and deleted.
E.g.Shopping Cart
resources.properties(Rest\WebContent\WEB-INF\config\resources.properties)
# Resources
com.ibm.commerce.rest.order.handler.CartHandler
com.ibm.commerce.rest.order.handler.OrderHandler

resources-ext.properties (Rest\WebContent\WEB-INF\config\resources-ext.properties)
This file contains the custom resources.
wc-rest­resourceconfig.xml.(Rest\WebContent\WEB-INF\config\com.ibm.commerce.rest\wc-rest­resourceconfig.xml )
Resource URI to Access Profile mapping is found in wc-rest­resourceconfig.xml.
<?xml version="1.0" ?>
<ResourceConfig>
<Resource name="cart">
<GetUri uri="store/{storeId}/cart/@self" description="Get order items in current cart"
accessProfile="IBM_Details"/>
<GetUri uri="store/{storeId}/cart/@self/payment_instruction" description="Get payment
instruction for current cart"
accessProfile="IBM_Details"/>
</Resource>
</ResourceConfig>

2.Representation

This is a specific form of a resource in a specified format.
E.g.JSON
wc-rest-responseformat.xml(Rest\WebContent\WEB-INF\config\com.ibm.commerce.rest\wc-rest-responseformat.xml)

<?xml version="1.0" encoding="UTF-8"?>
<responseFormatMappings>
<!-- Define response format and Internet media type mapping. -->
<!-- Internet media type was originally called a MIME type. -->
<!-- When default attribute is defined to true, the response format is the default format -->
<formatMapping responseFormat="json" mediaType="application/json" default="true"/>
<formatMapping responseFormat="xml" mediaType="application/xml"/>
<formatMapping responseFormat="atom" mediaType="application/atom+xml"/>
<formatMapping responseFormat="xhtml" mediaType="application/xhtml+xml"/>
</responseFormatMappings>

3.Resource Handler

Resource Handler is a java class which provides method handlers for various types of resource requests such as create and update.It uses @Path  notation to indicate which URL the class  handles.

The resource handlers are responsible for coordinating the BOD request and response and converting the request and response to and from a form that is consumable by the client by using standard HTTP protocol elements. Resource handlers are also responsible for ensuring that related resources are correctly identified and specified in the representation.     

4.Data Object Mapper

This files converts between BOD representations of a request to JSON representation

E.g. Rest\WebContent\WEB-INF\config\bodMapping\rest-cart-clientobjects.xml

<?xml version="1.0" encoding="UTF-8"?>
<_config:URLtoOAGIS xmlns:_config="http://www.ibm.com/xmlns/prod/commerce/foundation/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ibm.com/xmlns/prod/commerce/foundation/config ../xsd/url-to-oagis.xsd ">
<_config:NounDefinitions>
<_config:Noun name="Order">
<_config:NounElement name="OrderItem" part="true" />
<_config:NounElement name="OrderPaymentInfo/PaymentInstruction" part="true" />
<_config:NounElement name="OrderItem/OrderItemShippingInfo" part="true" />
<_config:NounElement name="OrderShippingInfo" part="true" />
</_config:Noun>
</_config:NounDefinitions>
<_config:URLDefinitions>
<!--  All data in Order noun except for shipping_info and payment_instruction. -->
<_config:URLParameterGroup name="cart" noun="Order">
<_config:URLParameter  name="recordSetComplete" nounElement="/Show/@recordSetCompleteIndicator" key="false" return="true" />
<_config:URLParameter name="recordSetTotal" nounElement="/Show/@recordSetTotal" key="false" return="true" />
<_config:URLParameter name="recordSetCount" nounElement="/Show/@recordSetCount" key="false" return="true" />
<_config:URLParameter name="recordSetStartNumber" nounElement="/Show/@recordSetStartNumber" key="false" return="true" />
<!--  order level data -->
<!-- UserData Section -->
<_config:URLParameter name="x_" nounElement="/UserData/UserDataField" key="false" return="true" type="UserData" />
<_config:URLParameter name="xamou_" nounElement="/OrderAmount/UserData/UserDataField" key="false" return="true" type="UserData" />
<_config:URLParameter name="xstat_" nounElement="/OrderStatus/UserData/UserDataField" key="false" return="true" />
<_config:URLParameter name="adjustment/xadju_" nounElement="/OrderAmount/Adjustment/UserData/UserDataField" key="false" return="true" type="UserData" />
</_config:URLParameterGroup>
</_config:URLDefinitions>
</_config:URLtoOAGIS>
 
Explanation of the  different sections of this XML file is  as below.

 <_config:URLParameterGroup name="cart" noun="Order">
This   section of the file represents the logical name of the mapping
 name="x_"
In this  section   name stands for  Rest  representation of data
 nounElement="/UserData/UserDataField"
In this section   name stands for Rest representation of data
 return="true"
Return true means this value is included in the rest response.

5.Entity Provider

This java class transforms a resource from its server side representation to response format expected by calling service.

Rest\WebContent\WEB-INF\config\providers.properties

# Entity providers for DataObject
com.ibm.commerce.foundation.rest.providers.JSONSDOProvider
com.ibm.commerce.foundation.rest.providers.XMLSDOProvider

# Entity providers for Map
#See Javadoc of com.ibm.commerce.foundation.rest.providers.AbstractEntityProvider for the #content of Map
com.ibm.commerce.foundation.rest.providers.JSONEntityProvider
com.ibm.commerce.foundation.rest.providers.XMLEntityProvider

Rest\WebContent\WEB-INF\config\providers-ext.properties

This file is the provided for the  custom providers.

Available and default response formats
Rest.war\WebContent\WEB-INF\config\com.ibm.commerce.rest\wc-rest­responseformat.xml     

Caching Service Response

Two Types of Caching.

1. Server Side Cache: This method uses Dyna Cache and cache configuration is defined in cachespec.xml.
2. Client Side Cache: This caching improves performance by reduce calls to server.

Client side cacheable resources are configured in
Rest\WebContent\WEB-INF\config\com.ibm.commerce.rest\wc-rest-clientCaching.xml

Custom configurations are kept in
Rest\WebContent\WEB-INF\config\com.ibm.commerce.rest.ext\wc-rest-clientCaching.xml

Please read the post on Websphere Commerce Rest Service Part 2 : Make Rest Service Calls from java class for more details on REST Services.


2 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete
  2. I think you mistakenly gave the same explanation fro two different elements of the data object mapper:

    name="x_"
    In this section name stands for Rest representation of data
    nounElement="/UserData/UserDataField"
    In this section name stands for Rest representation of data

    I think nounElement should be defined some other way

    ReplyDelete