JSON Serialization
Although RESTful services that produce XML are common, it is perhaps even more common for the service to produce JSON, or the JavaScript Object Notation. JSON is a simple notation based on name/value pairs and ordered lists that are both easy to produce in many languages and extremely easy (in fact, part of the language) for JavaScript to parse and create. It’s actually nothing more than a proper subset of the JavaScript object literal notation.3
When it comes to Java, especially inside the WebSphere Liberty Profile, you have several ways to produce JSON, just as you have different ways of producing XML. You can, of course, manually hand-code it, although that is not recommended. For more complex situations requiring a great deal of flexibility, a dynamic method of producing JSON might be needed, just as a dynamic approach to producing XML is sometimes helpful. However, the most common approach for producing JSON is the same as that for XML—using static annotations with JAXB.
A Simple Transaction Example with JAX-RS
To show how annotations for JSON work, we going to introduce another service from the list earlier in the chapter. The Transaction service enables you to view a transaction with GET, view a list of transactions with GET, and also create a new transaction by POSTing to the appropriate URL.
Let’s start by introducing our BankingTransaction class (see Listing 4.7).
Listing 4.7 BankingTransaction Class
package com.ibm.mwdbook.restexamples; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class BankingTransaction { @XmlElement protected String id; @XmlElement protected Date; @XmlElement protected double amount; @XmlElement protected String currency; @XmlElement protected String merchant; @XmlElement(name="memo") protected String description; @XmlElement protected String tranType; public BankingTransaction() { } public BankingTransaction(String id, long date,String currency, String memo, double amount, String tranType, String merchant) { setId(id); setDescription(memo); setAmount(amount); setCurrency(currency); setTranType(tranType); setMerchant(merchant); setDate(new Date(date)); } public String getDescription() { return description; } public void setDescription(String aDescription) { description = aDescription; } public double getAmount() { return amount; } public void setAmount(double anAmount) { amount = anAmount; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTranType() { return tranType; } public void setTranType(String tranType) { this.tranType = tranType; } public String getMerchant() { return merchant; } public void setMerchant(String merchant) { this.merchant = merchant; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
At this point, you might be thinking that this looks exactly like the annotations in the previous example. That’s the point. If you use JAXB annotations, you have to annotate the class only once; you don’t have to put in separate annotations for JSON and XML. Also, it’s not entirely the same. Note that, in this case, we annotated the fields and not the properties—in practice, there is little difference between the two, and you can use either.
Handling Entity Parameters with POST and the Consumes Annotation
Now that you’ve seen how you can create a class with annotations that work for both XML and JSON, you can explore how to add methods to a service to take advantage of that. We’re only introducing a couple new concepts in this part of the example—take a look at the following new method from the AccountResource class:
@Path("{account}/transaction") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @POST public int putTransaction(@PathParam(value="account") int account, BankingTransaction aTrans){ return txnDao.putTransaction(account, aTrans); }
The first new annotation is the @Consumes annotation. None of the previous services we’ve written have taken in any message bodies, so this is the first time we’ve needed to use it. As you can see, it’s essentially similar to the @Produces annotation. The interesting part is how the browser interacts with the server based on these annotations. In this case, we’re being very restrictive—we insist that the format of the message body be in JSON, but we also provide the response back in JSON. This information about what format is acceptable to the server and the client is communicated in specific HTTP headers. Figure 4.11 shows the interaction.
Figure 4.11 Header and annotation interaction
For a resource method to process a request, the Content-Type header of the request must be compatible with the supported type of the @Consumes annotation (if one is provided). Likewise, the Accept header of the request must be compatible with the supported type of the @Produces annotation. The Content-type header of the response will be set to a type listed in the @Produces annotation. This case is very simple—we’re allowing only a single content type (application/json) into our service and a single content type (also application/json) out of the service; more complex cases might require content negotiation, which we discuss in more detail in the later section “More on Content Negotiation.”
Looking back at the code for our BankingTransaction class, you see one more interesting fact about the putTransaction() method. Not only does it take a @PathParam, as have several of our preceding examples, but another method parameter is not attached to a @PathParam annotation: an instance of a BankingTransaction named aTrans. Where does this parameter come from? The JAX-RS specification is very clear on this: A resource method may have only one nonannotated parameter; that special parameter is called the entity parameter and is mapped from the request body. It is possible to handle that mapping yourself, but in our case (and in most cases), that mapping will be handled by a mapping framework such as JAXB.
The Use of Singletons in Application Classes
Before you can test your simple transaction-posting method, you need to understand a couple more concepts. The first is how we’re implementing the DAO for this example. All the previous DAOs we implemented were just for prepopulating a collection with examples that we could retrieve with a GET. However, if we are now enabling POST, we want to be able to check that the information that we POST to the resource will be available on the next GET to that resource. In a “real” implementation of a DAO, that would be fine—we’d just fetch the values from a relational database on a GET and create the new rows on a POST. However, in our simplified example, we don’t yet have that option (we show that in Chapter 6). Our solution for this case is very simple—we add a static variable that is an instance of our DAO to the DAO class. That way, we implement what in Design Patterns parlance is often called a singleton, a class that has a single instance. You can see this in the source code (see Listing 4.8) of our very simple BankingTransactionDao, which holds on to a single static variable that is an instance of the class that we name instance.
Listing 4.8 BankingTransactionDao Class
package com.ibm.mwdbook.restexamples; import java.util.HashMap; public class BankingTransactionDao { static BankingTransactionDao instance = new BankingTransactionDao(); public static BankingTransactionDao getInstance() { return instance; } HashMap<String, BankingTransaction> accounts = new HashMap<String, BankingTransaction>(); int lastId=123; public BankingTransactionDao() { String key=deriveKey(123,123); BankingTransaction aTrans = new BankingTransaction("123", 1388249396976L,"USD", "paycheck", 110.0, "DEPOSIT", "DIRECT"); accounts.put(key, aTrans); } private String deriveKey(int account, int id) { StringBuffer buf = new StringBuffer(); buf.append(account); buf.append("-"); buf.append(id); String key = buf.toString(); return key; } public BankingTransaction getTransaction(int account, int id){ String key = deriveKey(account, id); return (BankingTransaction)accounts.get(key); } public int putTransaction(int account, BankingTransaction aTrans) { int id=getNextID(); String key = deriveKey(account,id); aTrans.setId(Integer.toString(id)); accounts.put(key, aTrans); return id; } private int getNextID() { return ++lastId; } }
Now the variable declaration of txnDao within our AccountResource class simply needs to obtain the instance of the Dao by invoking the getInstance() method, as follows:
BankingTransactionDao txnDao = BankingTransactionDao.getInstance();
However, although this is simple, it’s not the best solution for most cases. A better approach is to consider that JAX-RS provides you with the capability to produce singleton instances of resource classes. In JAX-RS, the normal process is that a new instance of the resource class is created for every request. However, this might not always be the best choice. Even though it is a best practice that resources be stateless (as are the REST services themselves), sometimes a singleton instance can be useful—notably, when it needs to contain cached information to improve performance. Our simple service has another reason for this—to provide a stateful test service that mimics a service implemented on a backing store such as a relational database. You achieve this through the use of the @Singleton annotation. When your resource class contains this annotation, the resource class itself is considered to be a singleton and will live through the lifetime of the server. We show you many examples of @Singleton-annotated resource classes in our more fully fleshed-out example in Chapter 7.
To complete this example, simply create a new class for your BankingTransactionDao and enter the previous code and then modify the AccountResource class to add the variable declaration for the txnDao and the new putTransaction() method we earlier described. You then need to let Eclipse patch up your import list using Source > Organize Imports so that the example compiles cleanly.
Testing POST and Other Actions with RESTClient
Now it’s time to test adding a banking transaction to our newly defined POST resource method in our AccountResource class. However, that brings up a problem: In all the previous examples, we’ve been testing only GETting a response from a resource, which can be tested in any browser. How can we test POSTing to a resource? That requires you to provide a message body and also (as you’ve already seen) a special Content-Type HTTP header. Essentially, a basic browser won’t do for this case. You can look into several testing options:
- Curl (http://curl.haxx.se/) is a commonly used command-line client tool for transferring data with a URL syntax that can be used over a variety of protocols, including HTTP. Curl is especially useful for scripting if you need to write reusable test scripts.
- rest-client (http://code.google.com/p/rest-client/) is a simple Java GUI application from Google (although it also comes in a command-line version) that can be used for testing REST resources.
The solution we demonstrate in this chapter fits better with our methodology of testing resource methods within the browser: We use RESTClient, a free Mozilla add-on written by Chao Zhou that is available on the Mozilla add-ons site (see https://addons.mozilla.org/en-US/firefox/addon/restclient/). Chapter 9 discusses similar plug-ins for Chrome.
Obtaining RESTClient and installing it into Firefox is easy; just visit the site and follow the instructions. To start a RESTClient session, click the red RESTClient icon in the upper-right corner of your screen that is added during the installation process. You will see a new tab that looks something like the one in Figure 4.12.
Figure 4.12 RESTClient for POST testing
When you are ready to test your new service, first select POST from the Method drop-down list. Then type the following URL on the URL line:
http://localhost:9080/RestServicesSamples/banking/accounts/123/ transaction
You need to add an appropriate Content-Type header. Click the Headers menu and choose Custom Header; then in the Request Header dialog box, type Content-Type as the Name and application/json as the value before clicking OK to dismiss the dialog box. Finally, type this into the body text area and click Send:
{"currency":"USD","memo":"books","amount":10,"tranType":"PURCHASE", "merchant":"Amazon" }
If you look at either of the Response Body tabs, they should show the new ID number of your transaction (124 if you’ve added only one BankingTransaction). Likewise, the Response Header tab should show a status code of 200 OK and a Content-Type of application/json, as explained in our earlier diagram.