Saturday, December 26, 2009

Building XML Document Consumable RESTful Webservice.

Usecase:
In Enterprise Integration it is very common that Exchange of Messages will happen in XML format between Service components. Here the use case is very simple. Webservice has to consume input XML document,parse and populate Database.

Evaluations:
  • Open source REST API Implementation : I am very impressed with Jersy API from Sun MicroSystems. Active community with fast support. Nice feature set also.
  • HTTP method (Post or Put) : as per REST best practices, we have to use POST method in this case. PUT method used when we want to create resource. in this case we are not going to create any resource.

Approach:
 
1. REST Client: Write a HTML Form which accepts XML document.The user will upload an XML file.
 Please refer to index.jsp page in the sample.
<form action="/REST-POST-Demo/resources/filepost/form-data"
method="POST" enctype="multipart/form-data">
<table align="center">
<td> Please Select the XML file you want to Post to REST Webservice</td>
<tr>
<td><input type="file" name="file" id="file" /><input type="submit" name="submit" value="POST" /> </td>
</tr>
</table>
</form> 

2.  Design REST webservice:

@Path("form-data")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@POST
public Viewable uploadUrlFormData(@FormDataParam("file") List<FormDataBodyPart> parts,
                        @FormDataParam("submit") FormDataBodyPart submit)
                         throws IOException, ParseException {
for (FormDataBodyPart bp : parts) {
System.out.println("XML file content " + bp.getEntityAs(String.class));
// Here is the XML parse code will be handled.}
return new Viewable("/success", null);
}
Jersey has support to convert the consumed data to any type like String,Stream, etc....

Note: In this sample XML parsing and Populate Database code is not available.

3) Once The XML file is processed forward success.jsp page.
Here is the sample code to download.
 
How to Test Sample : Its very simple !!!!. Just open the downloaded Netbeans Project,Buld and Deploy the Project.

Software/Artifacts used:
- Netbeans 6.7
- Jersey 0.8
- Glassfishv2

Please try the sample and Let me know if you find any Issues.


Thank You !!!!!!!!!!!!