RESTEasy Tutorial Part 3 – Exception Handling

 

RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 – Exception Handling

Exception Handling is an obvious requirement while developing software application. If any error occured while processing user request we should show the user an error page with details like brief exception message, error code(optional), hints to correct the input and retry(optional) and actual root cause(optional). This is applicable to RESTful web services also.

But putting try-catch-finally blocks all around the code is not a good practice. We should design/code in such a way that if there is any unrecoverable error occured then the code should throw that exception and there should an exception handler to catch those exceptions and extract the error details and give a proper error response to the client with all the error details.

RESTEasy provides such ExceptionHandler mechanism which simplifies the ExceptionHandling process.

In this part I will show you how we can use RESTEasy’s ExceptionHandlers to handle Exceptions.

Step#1: Create Application Specific Exceptions.

Step#2: Create ExceptionHandlers by implementing ExceptionMapper interface.

Step#3: Update UserResource.getUserXMLById() method to validate user input and throw respective exceptions.

Step#4: Test the UserResource.getUserXMLById() service method by issueing following requests.


Important things to note:
As Spring is creating the necessary objects we should let Spring know about @Provider classes to get them registered with RESTEasy. We can do this in two ways.

a)Annotate Provider classes with @Component

b)Using component-scan’s include-filter.

<context:component-scan base-package=”com.sivalabs.springdemo”>
         <context:include-filter expression=”javax.ws.rs.ext.Provider” type=”annotation”/>
</context:component-scan>

RESTEasy Tutorial Part-2: Spring Integration

 

RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 – Exception Handling
RESTEasy provides support for Spring integration which enables us to expose Spring beans as RESTful WebServices.

Step#1: Configure RESTEasy+Spring dependencies using Maven.

Step#2: Configure RESTEasy+Spring in web.xml


		
   
    org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
  
  
    org.jboss.resteasy.plugins.spring.SpringContextLoaderListener
  
  
    Resteasy
    org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
  
  
    Resteasy
    /rest/*
  
  
    contextConfigLocation
    classpath:applicationContext.xml
  
  
    resteasy.servlet.mapping.prefix
    /rest
  

  
        resteasy.scan
        false
    

Step#3: Create a Spring Service class UserService and update UserResource to use UserService bean.

Step#4: Same JUnit TestCase to test the REST Webservice described in Part-1.

Important Things to Keep in mind:
1. org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap Listener should be registered before any other listener.
2. You should configure resteasy.servlet.mapping.prefix <context-param> if the HttpServletDispatcher servlet url-pattern is anything other than /*
3. While using Spring integration set resteasy.scan to false or don’t configure resteasy.scan parameter at all.
Otherwise you may get REST Resource instances(UserResource) from RestEasy instead of Spring container. While running JUnit Tests I observed this random behavior.

4. You should register REST Resource as Spring bean by annotating with @Component or @Service.

RESTEasy Tutorial Part-1: Basics

 

RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 – Exception Handling
RESTEasy is a JAX-RS implementation from JBoss/RedHat and is in-built in JBoss 6 onwards.
Here I am going to show you how to develop a Simple RESTful Web Services application using RESTEasy and JBossAS7.1.1.FINAL.

Step#1: Configure RESTEasy dependencies using Maven.

Step#2: Configure RESTEasy in web.xml

Step#3: Create User domain class, MockUserTable class to store User objects in-memory for testing purpose and UserResource class to expose CRUD operations on User as RESTful webservices.

Step#6: JUnit TestCase to test the REST Webservice.

Step#7: To test the REST service we can use the REST Client Tool. 
You can download REST Client Tool at http://code.google.com/a/eclipselabs.org/p/restclient-tool/

Important Things to Keep in mind:
1. org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap Listener should be registered before any other listener.

2. You should configure resteasy.servlet.mapping.prefix <context-param> if the HttpServletDispatcher servlet url-pattern is anything other than /*


3. Keep visiting my blog 🙂

JAX-WS WSI Authentication using UserName & Password Security Headers

Developing WebServices using JDK6/JAX-WS is simple. Is it true?

In many articles, blogs we can see how to develop WebServices using with JDK6’s JAX-WS in-built support in just 5 minutes.

We can simply write a POJO and annotate it with @WebService, publish it with Endpoint.publish(…) and you can see the generated wsdl by pointing your browser to http://localhost:8080/JAXWS/helloService?wsdl.

Immediately we can write a client and call helloPort.sayHello(“siva”) and you will get “Hello Siva!!!” response from your HelloWebService.

In the first look it feels like developing web services is very simple using JDK6’s in-built JAX-WS support.

With that confidence immediately I thought of writing a bit more complex WebService and deploy it on Tomcat.

As we can find number of articles on how to develop/deploy JAX-WS webservices on Tomcat Server, I started writing my next ABitComplexService and deployed on Tomcat and saw the generated WSDL file.

Then I generated client stubs using wsimport and invoked webservice methods and it worked fine… 🙂

Then I though of invoking the webservice from a simple web project and put the client code in a new Web web project and and call the web service.

Now the show begins 🙂

Then I got an opportunity to know what is JDK’s endorsed directory, how App Servers have their specific endorsed directories etc etc.

I got weird errors like:

Exception in thread “main” javax.xml.ws.soap.SOAPFaultException: javax.xml.ws.WebFault.messageName()Ljava/lang/String;

java.lang.ClassCastException: com.sun.xml.bind.v2.runtime.JAXBContextImpl cannot be cast to com.sun.xml.bind.api.JAXBRIContext

After struggling for sometime I copied jaxws-api.jar/jaxb-api.jar to endorsed directories and finally get it worked.

Now I wanted to make it a bit more complicated and thought of creating another WebService and deploy on JBoss Server and call it from the first WebService deployed on Tomcat.

Now I have:

1. MySecondWS webservice deployed on JBoss.
2. MyFirstWS webservice deployed on Tomcat. It is a Service Provider and Consumer(for MySecondWS) as well.
3. MyWebClient a Dynamic Web Project. Its a client for MyFirstWS.

Here as MyFirstWS webservice is a Service provider I have all the JAX-WS RI jars in WEB-INF/lib directory.

All set and I deployed all the Apps on their servers and hit the Submit button triggering MyFirstWS webservice call().

I got weird errors like NullPointerExceptions, MetadataModelExceptions etc.

After some trials I have identified the pattern that if I invoke the client from a project which has JAXWS-RI jars in its classpath I am getting this error.

But I need to develop a WebService which is both Service Provider and Consumer…
For the Service Producer I need to have those Jars in my classpath and at the same time to be Service Consumer I shouldn’t have those jars in my WEB-INF/lib.

So what to do? Yes, I know I need some more time to Google and I can find a way how to do this as this is very common requirement. But I feel like Developing Web Services using JDK6’s JAX-WS in-build support is not as easy as Advertised(My opinion only).

Anyway this weekend I understood two things:
1. Developing (Real)WebServices with JAX-WS is not that simple as advertised in the Articles/Blogs.
2. You can easily waste your week-ends by entering into Java-Jar-Hell 🙂