Showing posts with label JAX-RS. Show all posts
Showing posts with label JAX-RS. Show all posts

Saturday 23 September 2017

Working with Statelessness in JAX-RS

Before Pitching in to the "How the Stateless works with the JAX-RS" , I want to discuss here about the basics of the stateless and how it can be created and what are the configurations required .


So What is Statelessness ? It is said that , while processing the request , the server does not maintain any state or the Information that is required , If it is not maintaining it, how can be proceed yes the client sends the information that is required to process the request this behavior is called as the statelessness .

JAX-RS implementation With ATG Commerce has support for this statelessness and we can see how we are going to enable it .

We all know that, we are generating the Ear for the ATG Application from the RunAssembler , and we are passing all the arguments while executing the RunAssembler.So to enable the Statelessness we have to pass the stateless argument for the RunAssembler . Once it if passed then the Required Modules are built along with it . I am just pasting the Snippet you can use the same for the ant build .For other Maven you see their manuals before using it .

               <arg line="stateless"/>

Now you have enabled the stateless mode .So the Beauty of the Statelessnessis that, all the session scope components in ATG will be converted in to the Request Scope Components .

So now its our time to See more about the functional aspects .

So what is x-ocstatedata ? I was mentioning about the required data must be passed as part of the Request from the client , this will be carried by this x-ocstatedata .

Did I need to create this x-ocstatedata every time? . No you need to create it OOTB takes care of creating it , but it is your responsiblity to put the data in the way OOTB expects then the x-ocstatedata is created automatically, So How to put it ? let see in the below .

Create a class extends GenericService implements MapLoadableService . When you create like this
there should be two methods that needs to implemented .

1))@Override
public void loadService(Map<String, Object> paramMap) {
}

//This method is the place where we have to read the previous state from the x-ocstatedata and used for the current request .

2)@Override
public Map<String,Object>getProperties() {
}
// This is the method where we need to write a logic so that it returns the request data that has to be put as part of the X-ocstatedata . Which is of type Map<String,Object>. This method will be called after each endpoint finishes . 


For More Information on the Implementation details you can refer the ProfileLoadableService OOTB class  . Where they have used the Profile component from the x-ocstatedata .

You can inject the created component in the RequestStateManager as below 

loadableServicePaths=\
                                       /atg/userprofiling/ProfileLoadableService


Once it is declared in the component path it will be called before it hits any service and end of the service calls .

By Following the above way you can Handle the stateless data in the JAX-RS.


Exception Handling in JAX-RS

In JAX-RS Implementation of REST, Each and every Exception should be handled as the Rest Exception as the OOTB Handles it , We can utilize the OOTB features to the Fullest by consuming this Classes and throwing the way it does , we can Briefly see how to handle it .

ATG 11.3 JAX-RS Implementation has inbuilt class RestException for handling this .  RestException  is the class that has different constructors for Providing the required inputs to be passed while Throwing it .

RestException error = RestUtils.getRestUtils().createException(400, "500", "Internal Server Error", null, null);

throw error;

Same like this above will have many constructors 

From the above example A RestException class can be instantiated
through utility methods in RestUtils , hence we are injecting in this way and supplying the parameters.

If you add error conditions to your endpoint, you should build a RestException, setting HTTP response codes,error messages, debug information and, optionally, error codes that are returned from your endpoint method.

400 is the status codes .

500 is the "internalserver" ie error codes

"Internal Server Error" is the message 

The RestExceptionMapper instance of the Jersey ExceptionMapper builds a response from the RestException that is returned to the client.If you want to handle any custom unhandled exceptions you can write the code here for handling it .


Additinally Every REST method should be constructed with an error message,which should be stored as resource strings in a property file residing in your custom module. Once you have constructed an error message, you can create string constants that refer to the error string keys within your endpoint class.


I am gives some of the status codes which you can use it while developing it .


ACCEPTED 202 Accepted
BAD_REQUEST 400 Bad Request
CONFLICT 409 Conflict
CREATED 201 Created
FORBIDDEN 403 Forbidden
GONE 410 Gone
INTERNAL_SERVER_ERROR 500 Internal Server Error
MOVED_PERMANENTLY 301 Moved Permanently
NO_CONTENT 204 No Content
NOT_ACCEPTABLE 406 Not Acceptable
NOT_FOUND 404 Not Found
NOT_MODIFIED 304 Not Modified
OK 200 OK
PRECONDITION_FAILED 412 Precondition Failed
SEE_OTHER 303 See Other
SERVICE_UNAVAILABLE 503 Service Unavailable
TEMPORARY_REDIRECT 307 Temporary Redirect
UNAUTHORIZED 401 Unauthorized
UNSUPPORTED_MEDIA_TYPE 415 Unsupported Media Type

It is our duty to set the correct status codes and error codes while throwing it .

Happy Handling !!!!


Friday 22 September 2017

JAX-RS Basics - Getting Started : Sample Program

Hi All,
     
        Hope all are doing well, Today we are going to see some Interesting Basics of the JAX-RS .

JAX-RS Implementation was Introduced in the Oracle Commerce Platform 11.3 , with this Standard Oracle was able to competate the Industrial Standards,   in the REST Services . So Lets Deep in to .

1) The First Step to start with the JAX-RS Application is add the Following entry in the web.xml

<servlet>
    <servlet-name>Jersey</servlet-name>
    <servlet-class>atg.service.jaxrs.JerseyServletWrapper</servlet-class>
    <init-param>
        <param-name>atg.service.jaxrs.JerseyServletWrapper.servletClasses
</param-name>
        <param-value>org.glassfish.jersey.servlet.ServletContainer,
atg.service.swagger.SwaggerBootstrap</param-value>
    </init-param>
    <!-- Params for JerseyServletWrapper servlet -->
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>atg.service.jaxrs.JAXRSApplication</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>atg.service.swagger.SwaggerApiListingResource,
io.swagger.jaxrs.listing.SwaggerSerializers</param-value>
    </init-param>
    <init-param>
        <!-- Params for JAXRSApplication -->
        <param-name>atg.service.jaxrs.JAXRSApplication.resourceRegistryPath
</param-name>
        <param-value>/atg/dynamo/service/jaxrs/RestResourceRegistry</param-value>
    </init-param>
    <init-param>
        <param-name>atg.service.jaxrs.JAXRSApplication.validatorRegistryPath
</param-name>
        <param-value>/atg/dynamo/service/validator/ValidatorRegistry</param-value>
    </init-param>
    <init-param>
        <!-- Params for SwaggerBootstrap servlet -->
        <param-name>atg.service.swagger.SwaggerBootstrap.bootstrapService
</param-name>
        <param-value>/atg/dynamo/service/swagger/SwaggerBootstrapService
</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
    <async-supported>true</async-supported>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

Once if you add the Following entry then the JAX-RS is enabled in the application, we can go ahead and creating our Resource classes . 

From the above XML there is a path for defining the RestResourceRegistry,Validatory Registry and SwaggerBootStratService , if you are defining your Custom you can update to point yours. For SwaggerBootStratService and ValidatoryRegistry give the OOTB Component path this is required till you start diving in to more . 

2)You can add the mentioned classes  are avaliable in the DAS, Rest Modules you can add the Reference in the Build Path once it is done ,these will be available for your project  .Make Sure you Resolve the Dependency issue  of the Jars. 

3)Start Creating the Component in the path /atg/dynamo/service/jaxrs/RestResourceRegistry
this is the Component where we have register the Components created on behalf of the JAX-RS implementaiton.

nucleusRestResources : this property hold those components .

Those components can be created by the Following way 

4)Create a class extends GenericService

@RestResource(id=OrderRestConstants.CURRENT_ORDER_ID)
@Path("/cart")
@Api(value="/cart")
public class CurrentOrderRestResource extends GenericService {
}

Here@RestResource – must be present for all resource classes, as it specifies the ID of the
resource. The ID is a string that uniquely identifies the resource and does not change when the context and/or version change.Try to give the package name as well.

@Path . The annotation contains the URI path for the resource. For example, @path ("/cart"). Note: If you are creating a sub-resource,ensure that there is no @Path annotation.

Create like above example . Next Will Start Writing the methods 

@GET
@Endpoint(id="/cart#GET" filterId="cart-Default")
@ApiOperation(value="Gets the current order.")
public Object getOrder(JSONObject pJson) throws RestException, CommerceException {
}

@GET, @POST, @PUT, @PATCH, and, @DELETE – These annotations are used as necessary when working with the endpoint.

@Endpoint – This annotation identifies the endpoint with a unique string ID. The ID does not change if the context or version changes. If the endpoint is for a singular resource, the isSingular attribute must be true.

5)A resource’s schema is controlled using the ValidatorManager component and payloadSchema.xml files.These XML files configure multiple validators that contain the definitions for expected input fields, as well as required output fields. Endpoints can specify which validator definition to use for input, using the validatorId attribute, and for output, using the filterId attribute.Will Discuss Brief more about this in the upcoming Sessions .

6)Write the Logic here and return type should be the Object , this is required because we are returning the RepresentationModel . 


The RepresentationModel is a holder class that allows you to build a representation of a resource for aresponse. It contains properties that specify the resource state, embedded resources, collection members, links,headers, and other properties. If an endpoint needs to respond with a representation of the resource, create an instance of this class.

7)Register the Class which we have created in to the Component and declare that component to the RestResourceRegistry component  nucleusRestResources property. 

8)How End Point Works .

Resources are registered with a REST resource registry that has a context root defined in the web.xml file. This context root takes the following format:


 <context-param>
    <param-name>context-root</param-name>
    <param-value>/public/v1</param-value>
  </context-param>


For example, a URI may be /public/v1. The full URI would be http://localhost:8080/public/v1.

Then the corresponding end point we have to invoke . In our Scenario of above example it is like 
http://localhost:8080/public/v1/cart/ this will change as per our Requirement. 


Try to access your First Ever JAX-RS application .

We will  start looking in to the advance concepts in the upcoming Tutorials . You can also take a look at the OOTB Classes on the JAX-RS implementation for more technical Stuffs.

Happy Learning !!!!!