Sunday, May 24, 2009

Rest in Spring 3.0 Sample Application in the form of Web Module(OSGi bundle)

Sample Hello World Program to Expose a RESTfull service using Spring 3.0 and REST Support of Spring 3.0. or this I am Using SpringDm Server 2.0 m2 and STS2.x
Things to do before starting this example: Spring Framewoek 2.5 annotations, OSGi bundle development.
1)Go to File->New Project->Spring Sourcedm Server -> Bundle Project
2)Provide a Name as HelloWorld
then create a class as HelloWorld

package hello.world;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;
@Controller@RequestMapping("/test/**")
public class HelloWorld {
@RequestMapping("/test")
public ModelAndView sayMessage()
{
ModelMap modelMap = new ModelMap();
String response = "HelloWorld";
modelMap.addAttribute("message", response);
return new ModelAndView("hello", modelMap); }
@RequestMapping(value = "test/{message}", method = RequestMethod.GET)
public ModelAndView sayMessage(@PathVariable("message") String message, ModelMap modelMap,HttpServletRequest request,HttpServletResponse response) throws Exception{
System.out.println("Hai in HelloWorld");
modelMap.addAttribute("message", message);
HelloData helloData = new HelloData();
helloData.setMessage(message);
XMLTreeBuilder xmlBuilder = new XMLTreeBuilder();
xmlBuilder.createXMLTree(helloData, response);
return new ModelAndView();
}
}

The above calss is acts like a controller with the Request mapping as /test/** means if any request comes up with the URL /test/ that should come to this controller , we can also provide option for Method as Post,Get,Put and Delete.

The corresponding Manifest file should looks like

Manifest-Version: 1.0Bundle-Version: 1.0.0Bundle-Name: RestBundle BundleBundle-ManifestVersion: 2Bundle-SymbolicName: RestBundleModule-Type: WebImport-Library: org.springframework.spring;version="[3.0.0.CI-217,3.0.0.CI-217]"Web-ContextPath: helloWeb-DispatcherServletUrlPatterns: /Import-Package: javax.servlet;version="[2.5.0,2.5.0]", javax.xml;version="[1.0.1,1.0.1]"Import-Bundle: com.springsource.javax.servlet;version="[2.5.0,2.5.0]"

and the Module-Context.xml looks like
http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> dataAccessFailure uncaughtException


and the OSGi-Context.xml should looks like

http://www.springframework.org/schema/osgi" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


Util class is
package hello.world;
import java.io.PrintWriter;import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;import org.w3c.dom.Element;
public class XMLTreeBuilder {
public void createXMLTree(HelloData helloData,HttpServletResponse response)throws Exception{ PrintWriter pw = null; response.setContentType("text/xml"); pw = response.getWriter(); try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = builderFactory.newDocumentBuilder(); //creating a new instance of a DOM to build a DOM tree. Document doc = docBuilder.newDocument(); createXmlTree(doc,helloData,pw); } catch(Exception e) { System.out.println(e); }
}
public void createXmlTree(Document document,HelloData helloData,PrintWriter pw) throws Exception { Element treeElement = document.createElement("tree");
document.appendChild(treeElement);
Element itemID = null;
itemID = document.createElement("message"); itemID.setAttribute("text",helloData.getMessage()); treeElement.appendChild(itemID);
//TransformerFactory instance is used to create Transformer objects. TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// create string from xml tree StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(document); transformer.transform(source, result); String xmlString = sw.toString(); System.out.println("XMLString "+xmlString); pw.write(xmlString); pw.flush(); pw.close();
}}


add this particular HelloWorld project to Spring Dm Server and start deploy it.
Once it is successfully deploying application go to http://localhost:8080/hello/test/{message you want get there}

You will get the message that you want to display in the form of xml which is to used by the client to read using RESTTemplate.