Home > Articles > Web Development

This chapter is from the book

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

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020