More on Content Negotiation
One of the most challenging parts of writing a resource is determining what Content-Type the resource for each method will accept and what Content-Type will be returned. The problem is that different Content-Types are better suited for different purposes, as we hinted at earlier. For instance, XML is extremely well suited to Enterprise-level SOA services because a number of languages can parse and generate XML. Likewise, XML has the benefit of a commonly accepted schema language (XML Schema) for defining valid XML documents. This enables you to associate a particular schema document representing the entire range of valid request or response bodies with each service that you write—this capability can be useful for creating an Enterprise registry of your services.
However, a great number of services will be mostly consumed by JavaScript code as part of the Modern Web Application architecture we’ve described. Thus, the simplicity and efficiency of JSON needs to be strongly considered also. So in practice, many of the actual services you write will have to handle the possibility of consuming and producing multiple Content-Types. People have suggested handling this content negotiation problem in a few ways.
You could accept different URI parameters for each content type and then implement different methods in your Resource class (each having a different @Path annotation) to differentiate between the two. The problem with this approach is that, although it’s simple, it’s not natural. Appending .xml or .json to the end of URI is not something most developers would think to do. Also, it has the problem that you now have two different methods that effectively do the same thing—so any changes thus have to be made in two places.
Another possibility is to use QueryParams. With this solution, you append a ?format=someformat query parameter to the end of each URI or for cases when you want to use a format other than the default (presuming that you remembered to test for the query parameter being null). Although this avoids the two-method problem of the previous solution, it’s still not natural. It makes the format request not part of the structure of the request URI itself, but something that hangs off the end. The problem with that kind of extension by query parameter is that when it’s begun, it’s hard to stop.4
The best way to avoid this kind of pain is simply not to follow any of these approaches. HTTP already gives you the right mechanism for negotiating the content type that should be returned, and JAX-RS provides easy support for this approach. To illustrate this, take a look at the following example, which is a new method in the AccountResource class:
@Path("{account}/transaction/{id}") @Produces(MediaType.APPLICATION_XML+ ","+MediaType.APPLICATION_JSON) @GET public BankingTransaction getTransaction(@PathParam(value="account") int account,@PathParam(value="id") int id){ BankingTransaction aTrans = txnDao.getTransaction(account, id); return aTrans; }
Note that, in this method, we’ve simply expanded on our earlier examples by adding two different MediaTypes into the @Produces method. Here, if the client states that it wants to receive back JSON, it needs to send along application/json in the Accept header. If the client wants to receive back XML, it sends application/xml instead. Likewise, this method interprets either XML or JSON correctly as its input; it uses the Content-Type header (looking for those same two values) to figure out which is which and determine how to interpret what is sent in.
Testing the new method is simple: After it has been added to the class, go back into the RESTClient in your browser and set the Accept header to application/json. Then perform a GET on the following URL:
http://localhost:9080/RestServicesSamples/banking/accounts/123/ transaction/123
The returned value in the body should be in JSON. However, you change the Accept header value to application/xml, you’ll receive the value in XML.
Introducing the JAX-RS Response
So far in our examples, the only thing we’ve ever returned from a Resource method is what corresponds to the value the client should receive in the best of all possible cases—the case in which the request works. However, in the real world, you often need some more sophisticated error-handling techniques to deal with more complex problems. The JAX-RS spec essentially says that you can return three things from a Resource method. If you return void, that gives you back an empty message body and an HTTP status code 204 (No Content). We’ve seen the second case several times: You return an entity of some type, and the status code sent back is HTTP status code 200 (OK). However, sometimes it’s important to be able to set your own status codes for more complicated error handling cases. That is where the JAX-RS spec defines one more thing you can return: an instance of javax.ws.rs.core.Response. Response contains methods for adding bodies that have other status codes—for instance, temporaryRedirect() for redirect (HTTP status code 307) and, the one we are interested in, status, which we use to send the correct response for a missing resource, HTTP status code 404 (Not Found). We demonstrate this in the following code snippet, which is a rewritten version of the getAccount() method from the AccountResource class:
@GET @Path("/{id}") @Produces(MediaType.APPLICATION_XML) public Response getAccount(@PathParam(value="id") int id){ Account value = dao.get(id); if (value != null) return Response.ok(value).build(); else return Response.status(404).build(); }
Note a couple important points about what we’ve done to this method. First, the return type of the method is no longer Account, but Response. We are using two helpful static methods in Response: The method ok(Object) simply indicates that the response should be built around the object that is passed in as a parameter, and that the HTTP return code should be status code 200. By contrast, the status(int) method indicates that you simply want to return an HTTP status code. Both of these methods actually return an instance of a ResponseBuilder object. You create a Response from the ResponseBuilder by sending it the message build(). You might want to investigate the many other useful methods on the Response class on your own.
Hints on Debugging: Tips and Techniques
So far, we’ve assumed that everything has gone well for you in writing and running these examples. However, that’s not always the case; sometimes you need to debug problems in the code. Eclipse itself provides a lot of helpful features. You can always examine the console log (which is STDOUT), and you can start the server in debug mode (using the bug icon to start it) to set breakpoints and step through your code. However, when the console doesn’t give you enough information to help you determine the cause of your problems, another helpful place to look for more detailed information that is unique to the WebSphere Liberty profile is in your server’s logs directory. We briefly passed by this directory in Chapter 2 when we examined the Liberty directory structure. Look under your WAS Liberty Profile installation directory for /wlp/usr/RESTServer/logs. In particular, if you encounter a problem that keeps a service from executing (for example, a mismatch between the @Produces Content-Type and the annotations that you provide in your entity classes), you can often find helpful information in the TRACEXXX logs that are created in this directory. The FFDC (First Failure Data Capture) logs are also good places to look for additional information in debugging problems.
Simple Testing with JUnit
One of the best approaches to software development that has emerged in the last 15 years is the notion of Test Driven Development, popularized by Kent Beck as a part of the Extreme Programming method. Many other agile methods have adopted this principle, and we’ve found it to be extremely useful in our own development as well. A helpful tool that has emerged from this movement is the JUnit testing tool. JUnit enables you to write simple test cases that you can use to validate your own code.
From what you’ve learned in this chapter, you’ve probably concluded that testing at the browser is helpful for fast little validation tests, but it quickly becomes tedious. What’s more, you’ve probably noticed that it is quite error prone and hardly repeatable, especially when you have to use a tool such as RESTClient to manually enter JSON or XML request bodies.
Let’s finish the code examples in this chapter with an example of how to write a JUnit test for one of the previous examples (see Listing 4.9).
Listing 4.9 JUnit Test for SimpleAccountResource
package com.ibm.mwdbook.restexamples.tests; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.junit.Test; public class SimpleAccountResourceTest { @Test public void testGetAccounts() { String address = "http://localhost:9080/RestServicesSamples/banking/simple/accounts"; StringBuffer result = new StringBuffer(); String expectedResult = "<accounts><account>123</account>"+ "<account>234</account></accounts>"; try { fetchResult(address,result); } catch (MalformedURLException e) { e.printStackTrace(); fail("MalformedURLException caught"); } catch (IOException e) { e.printStackTrace(); fail("IOException caught"); } assertEquals(expectedResult, result.toString()); } private void fetchResult(String address,StringBuffer result) throws MalformedURLException,IOException { URL; url = new URL(address); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) result.append(inputLine); in.close(); } }
JUnit tests are like most other classes in Java today—they are annotated POJOs. In this case, the annotation @Test (from org.junit.test) identifies a method as a JUnit test method. A single class can have many test methods, each individually identified. In this excerpt, we show only the test method for the getAccounts() method, which corresponds to a GET to the URL http://localhost:9080/RestServicesSamples/banking/simple/accounts. If you browse the full class definition as included in the sample code, you’ll see that we also include test methods that test retrieving an account that has an account number defined, as well as the error case of retrieving an account that does not have an account number defined. All these methods use a utility method named fetchResult() that uses a URLConnection to fetch the contents of a particular URL.
After fetching the results, we use JUnit assertions (from org.junit.Assert) to compare the value we receive against an expected value. So if you know the XML or JSON you want to compare against ahead of time, you can easily set up a test that can validate that your code still functions, even after multiple changes.
Running the JUnit Test is extremely easy. Just select the SimpleAccountResourceTest class in the Java EE explorer pane and then right-click and select Run As > JUnit Test from the menu. You should see a result in the bottom-right pane that looks like Figure 4.13.
Figure 4.13 JUnit test results
This is an improvement over using a browser for testing, but as you can tell from close inspection of the code, even this approach leaves much to be desired. In particular, the fetchResult() utility method is limited to GETs and does not provide a way to pass in header values or even a message body. You can address each of these issues, but the method becomes more complicated as a result (see the corresponding method in the class AccountResource-Test for an example of exactly how complicated). Thus, you’ll want a better mechanism for invoking the REST APIs than hand-coding it with a URLConnection. In Chapter 7, you examine using the Apache Wink client for just that purpose.