Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 7 of 7
Once components, connectors, and resource representation classes and interfaces are implemented, a FrontController servlet is provided to receive incoming client requests and respond to clients with the representation state of the resources
that it manages.
Listing 8 shows a sample implementation of the standard doGet method of the HttpServlet class. In this example, doGet handles a REST-based HTTP GET method.
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException
{
HTTPConnector connector =
(HTTPConnector)Connectors.getConnector(Protocol.HTTP);
HTTPServerComponent serverComponent =
(HTTPServerComponent)connector.addServer(request.getServerPort());
String contextRootPath = this.getServletContext().getRealPath("/");
String contextPath = request.getContextPath() + "/" + this.getServletName();
serverComponent.addContext(contextRootPath, contextPath);
Representation representation = null;
try
{
representation =
serverComponent.getContext(request,
this).handleGet(new HTTPRequest(request));
}
catch (Exception e)
{
e.printStackTrace();
throw new ServletException("Error: " + e);
}
new HTTPResponse(response).write(representation.getContentType(),
representation.getInputStream());
}
A BusinessService class can be employed to encapsulate resource representations for specific-domain business logic. The BusinessService classes should embody the implementations for each resource representation using an implementation of the javax.activation.DataHandler class and the javax.activation.DataSource interface that is appropriate for the content of the model generated from the service's business logic.
An example of a simple business service that encapsulates file resources is shown in Listing 9.
public class SimpleBusinessService
implements BusinessService
{
// todo: read RESOURCES_DIR from config or system property
//
private static final String RESOURCES_DIR = "resources";
private String contextRootPath = "";
private String contextPath = "";
public SimpleBusinessService(String contextRootPath,
String contextPath)
{
this.contextRootPath = contextRootPath;
this.contextPath = contextPath;
}
protected String filePathFromRequest(Request httpReq)
{
return contextRootPath + RESOURCES_DIR
+ ((HTTPRequest)httpReq).getRequest().getPathInfo();
}
protected void writeToFile(Request request, File file, boolean append)
throws IOException,
FileNotFoundException
{
System.out.println("writeToFile called");
InputStream inStream = ((HTTPRequest)request).getInputStream();
byte[] dataBuf = new byte[4096];
FileOutputStream outStream = new FileOutputStream(file, append);
int bytesRead = 0;
while ((bytesRead = inStream.read(dataBuf)) > 0)
{
System.out.println("Writing [" + bytesRead + " bytes]");
outStream.write(dataBuf, 0, bytesRead);
}
outStream.flush();
outStream.close();
}
public Representation create(Request request)
throws ServiceExecutionException
{
System.out.println("SimpleBusinessService.create()");
String filePath = filePathFromRequest(request);
File file = new File(filePath);
try
{
boolean append = false;
writeToFile(request, file, append);
}
catch (Exception e)
{
e.printStackTrace();
throw new ServiceExecutionException(e);
}
FileRepresentation representation = new FileRepresentation(file);
return representation;
}
public Representation read(Request request)
throws ServiceExecutionException
{
System.out.println("SimpleBusinessService.read()");
String filePath = filePathFromRequest(request);
File file = new File(filePath);
if (file.exists() == false)
{
throw new ServiceExecutionException("File [" + filePath + "] does not exist.");
}
FileRepresentation representation = new FileRepresentation(file);
return representation;
}
public Representation update(Request request)
throws ServiceExecutionException
{
System.out.println("SimpleBusinessService.update()");
String filePath = filePathFromRequest(request);
File file = new File(filePath);
FileRepresentation representation = new FileRepresentation(file);
try
{
boolean append = (file.exists() ? true : false);
writeToFile(request, file, append);
}
catch (Exception e)
{
e.printStackTrace();
throw new ServiceExecutionException(e);
}
return representation;
}
public void delete(Request request)
throws ServiceExecutionException
{
System.out.println("SimpleBusinessService.delete()");
String filePath = filePathFromRequest(request);
System.out.println("SimpleBusinessService.delete() - resolving file ["
+ filePath
+ "]");
File file = new File(filePath);
System.out.println("SimpleBusinessService.delete() - file resolved");
if (file.exists())
{
System.out.println("SimpleBusinessService.delete() - deleting file");
if (file.delete() == false)
{
System.out.println("SimpleBusinessService.delete() - file deletion failed");
throw new ServiceExecutionException("Error deleting file ["
+ filePath + "]");
}
System.out.println("SimpleBusinessService.delete() - file deletion succeeded");
}
else
{
System.out.println("SimpleBusinessService.delete() - file ["
+ filePath
+ "] does not exist");
}
}
}
As previously mentioned, business services should represent the data models generated by their specific logic using implementations of the JAF classes and interfaces that are appropriate for the content of the models. This might entail database resources, dynamically generated resources, file system resources and others.
REST is a style of software architecture and a collection of architecture principles for distributed systems that stipulates mechanisms for defining and accessing resources. REST can be used to describe a framework that transmits data over a protocol, such as HTTP, without additional semantic layers or session management. REST defines a separation of concerns and stateless conversations that simplify the actors and communication semantics in a distributed system. Within REST, media types are exchanged using standard message verbs.
JAF is a standard extension to the Java platform that presents a framework of Java-based APIs and components in which resources represented by Java objects or beans are recognized and accessed. JAF defines APIs through which data is registered and discovered by content or MIME type. These mechanisms make JAF and the MIME-defined aspects of JAF great facilitators of a REST data-element implementation.
In this article I have introduced you to REST and JAF. Using a sample Web application that tracks requests and responses through a Java servlet-based system, I have shown how JAF facilitates the exchange of data in REST-based systems. See the Resources section to learn more about REST and JAF.
Read more about Enterprise Java in JavaWorld's Enterprise Java section.