A REST Service Framework
Although web services tend to be more complex than REST services, there are web-service tools and libraries to help you avoid duplicating code and test effort. However, there aren't many available for REST; at least not for Java developers. To remedy this, I've built a REST service framework (available electronically; see "Resource Center," page 5) that helps avoid writing duplicate code for each service I need. This Java-based framework lets me focus on the interface and functionality I need to implement instead of the skeleton code required to implement a Java Servlet, and map URL query parameters to data.
There are two main components in the REST framework:
- The REST Server, which is the Java Servlet that maps HTTP URL queries to application code.
- The REST Worker, which is the Java class that is dynamically invoked by the framework when a request is made, and subsequently generates a response.
The REST worker objects are what you develop to provide service functionality. Every worker must implement the RestWorker interface as in Example 2.
public interface RestWorker { public String onRequest(Map paramMap); public boolean cacheReference(); }
The RestWorker interface defines the following methods:
- onRequest is called when an HTTP request arrives for the worker object, which is determined by the object's class name.
- cacheReference is called by the REST Server to determine if the reference to this worker object should be cached. If so, the object reference is stored and used in all subsequent HTTP requests for this object's URL key; otherwise, a new object is instantiated for each request.
The REST Server defines a common HTTP URL query parameter, request, which is used to determine which REST worker object should be called. The value of this parameter is matched to the name of the class to invoke. For instance, when this request arrives:
http://<rest_server_name> /restserver?request=EmpBenefits
the REST Server attempts to load a class with the name EmpBenefits, which implements the RestWorker interface, and calls its onRequest method. All of the additional URL query parameters, if there are any, are passed as a java.util.Map of named-value pairs.
Listing Two shows the doPost method for the Rest Server Java Servlet, where this work is done. After the request parameter is retrieved, the entire set of URL query parameters is retrieved via the call to HTTPServletRequest.getParameterMap. The request parameter is removed from this map because it's meaningful to the REST Server only, and not the worker object. Next, a call is made to getWorker, which first attempts to locate a reference to this request's worker object within a cache. If a precached reference is not found, a call is made to createWorker (see Listing Three).
protected void doPost( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletOutputStream out = resp.getOutputStream(); String response; // Determine which worker this request is for String urlKey = req.getParameter("request"); if ( urlKey == null ) { out.println("REST Server Ready"); return; } // Get the URL query parameters (remove param "request") Map paramMap = req.getParameterMap(); HashMap params = new HashMap(paramMap); params.remove("request"); // Lookup the correct worker for this request and call it RestWorker worker = getWorker(urlKey); if ( worker != null ) response = worker.onRequest(params); else response = "No REST worker for " + urlKey; // Output the response from the worker out.println(response); }
public RestWorker createWorker(String className) { try { Class compClass = Class.forName( className ); if ( compClass != null ) { Object obj = compClass.newInstance(); return (RestWorker)obj; } } catch ( Exception e ) { log(e.getMessage(), e); } return null; }
The method createWorker uses the Class.forName library call to load a reference to the specified class name's java.lang.Class object, using Java Reflection. With a standard Java Servlet container, such as Apache Tomcat, only classes within the WEB-INF/classes directory of the web application will be located by default. Therefore, for this algorithm to work, you must place your RestWorker objects within this directory. Once the class is located, and its java.lang.Class object is loaded, the actual RestWorker object is instantiated via a call to Class.newInstance.
Next, a call is made to the worker object's cacheReference method. If True is returned, a reference to this object is stored in an in-memory cache to make subsequent requests perform a bit faster (the Java reflection code just described will no longer need to be invoked). If this method returns False, then the object reference is used for this call only. This lets you dynamically update your worker object on a running server by simply copying a new class object to the WEB-INF/classes directory. Subsequent requests should use this new class.
Finally, the worker object's onRequest method is called with the Map of parameters from the original HTTP request. The return value from this method (a String) is used as the response, and is returned to the web client. Therefore, your object can return HTML, comma-delimited data, XML, or a human-readable sentence. For instance, the output of a simple "echo" worker object (see Listing Four), as seen from a web browser, is in Figure 2. HTTP Requests made to this RestWorker object are sent back in the form of a paragraph that includes all of the request parameters and values.
public String onRequest(Map params) { String resp = "Thank you for calling EchoWorker. "; if ( params.size() == 0 ) return resp; resp += "\n\nHere are the parameters you passed: "; Set keys = params.keySet(); Iterator keyIter = keys.iterator(); while ( keyIter.hasNext() ) { String key = (String)keyIter.next(); String[] val = (String[])params.get(key); resp += "\n " + key + "=" + val[0]; } return resp; }
Conclusion
I've built many RESTful services, as well as web services, in different production systems with great success. In my experience, it's quicker and easier to build, deploy, and consume a REST service than a full-blown web service. If you haven't jumped into the world of SOA-based development because of the complexities of web-service development, give REST and this framework a try.