1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Quản trị mạng >

Chapter 22. Examples for Chapter 7

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.32 MB, 392 trang )


public void updateCustomer(@PathParam("id") int id,

Customer update)

{

Customer current = customerDB.get(id);

if (current == null)

throw new CustomerNotFoundException("Could not find customer " + id);

current.setFirstName(update.getFirstName());

current.setLastName(update.getLastName());

current.setStreet(update.getStreet());

current.setState(update.getState());

current.setZip(update.getZip());

current.setCountry(update.getCountry());

}

}



In ex06_1, our getCustomer() and updateCustomer() methods threw a

javax.ws.rs.WebApplicationException. We’ve replaced this exception with our own

custom class, CustomerNotFoundException:

src/main/java/com/restfully/shop/services/CustomerNotFoundException.java

public class CustomerNotFoundException extends RuntimeException

{

public NotFoundException(String s)

{

super(s);

}

}



There’s nothing really special about this exception class other than it inherits from

java.lang.RuntimeException. What we are going to do, though, is map this thrown

exception to a Response object using an ExceptionMapper:

src/main/java/com/restfully/shop/services/CustomerNotFoundExceptionMapper.java

@Provider

public class NotFoundExceptionMapper

implements ExceptionMapper

{

public Response toResponse(NotFoundException exception)

{

return Response.status(Response.Status.NOT_FOUND)

.entity(exception.getMessage())

.type("text/plain").build();

}

}



288



|



Chapter 22: Examples for Chapter 7



www.it-ebooks.info



When a client makes a GET request to a customer URL that does not exist, the Custom

erResource.getCustomer() method throws a CustomerNotFoundException. This ex‐

ception is caught by the JAX-RS runtime, and the NotFoundExceptionMapper.toRes

ponse() method is called. This method creates a Response object that returns a 404

status code and a plain-text error message.

The last thing we have to do is modify our Application class to register the Exception

Mapper:

src/main/java/com/restfully/shop/services/ShoppingApplication.java

public class ShoppingApplication extends Application {

private Set singletons = new HashSet();

private Set> classes = new HashSet>();

public ShoppingApplication()

{

singletons.add(new CustomerResource());

classes.add(CustomerNotFoundExceptionMapper.class);

}

@Override

public Set> getClasses()

{

return classes;

}

@Override

public Set getSingletons()

{

return singletons;

}

}



The Client Code

The client code for this example is very simple. We make a GET request to a customer

resource that doesn’t exist:

src/test/java/com/restfully/shop/test/CustomerResourceTest.java

package com.restfully.shop.test;

import javax.ws.rs.NotFoundException;

...

@Test

public void testCustomerResource() throws Exception

{

try



Example ex07_1: ExceptionMapper



www.it-ebooks.info



|



289



{

Customer customer = client.target

("http://localhost:8080/services/customers/1")

.request().get(Customer.class);

System.out.println("Should never get here!");

}

catch (NotFoundException e)

{

System.out.println("Caught error!");

String error = e.getResponse().readEntity(String.class);

System.out.println(error);

}

}



When this client code runs, the server will throw a CustomerNotFoundException, which

is converted into a 404 response back to the client. The client code handles the error as

discussed in “Exception Handling” on page 122 and throws a javax.ws.rs.NotFoun

dException, which is handled in the catch block. The error message is extracted from

the HTTP error response and displayed to the console.



Build and Run the Example Program

Perform the following steps:

1. Open a command prompt or shell terminal and change to the ex07_1 directory of

the workbook example code.

2. Make sure your PATH is set up to include both the JDK and Maven, as described

in Chapter 17.

3. Perform the build and run the example by typing maven install.



290



|



Chapter 22: Examples for Chapter 7



www.it-ebooks.info



CHAPTER 23



Examples for Chapter 9



In Chapter 9, you learned that clients can use HTTP Content Negotiation to request

different data formats from the same URL using the Accept header. You also learned

that JAX-RS takes the Accept header into account when deciding how to dispatch an

HTTP request to a Java method. In this chapter, you’ll see two different examples that

show how JAX-RS and HTTP conneg can work together.



Example ex09_1: Conneg with JAX-RS

This example is a slight modification from ex06_1 and shows two different concepts.

First, the same JAX-RS resource method can process two different media types. Chap‐

ter 9 gives the example of a method that returns a JAXB annotated class instance that

can be returned as either JSON or XML. We’ve implemented this in ex09_1 by slightly

changing the CustomerResource.getCustomer() method:

src/main/java/com/restfully/shop/services/CustomerResource.java

@Path("/customers")

public class CustomerResource {

...

@GET

@Path("{id}")

@Produces({"application/xml", "application/json"})

public Customer getCustomer(@PathParam("id") int id)

{

...

}



The JAXB provider that comes with RESTEasy can convert JAXB objects to JSON or

XML. In this example, we have added the media type application/json to getCusto

mer()’s @Produces annotation. The JAX-RS runtime will process the Accept header and

pick the appropriate media type of the response for getCustomer(). If the Accept header



291



www.it-ebooks.info



is application/xml, XML will be produced. If the Accept header is JSON, the Custom

er object will be outputted as JSON.

The second concept being highlighted here is that you can use the @Produces annotation

to dispatch to different Java methods. To illustrate this, we’ve added the getCustomer

String() method, which processes the same URL as getCustomer() but for a different

media type:

@GET

@Path("{id}")

@Produces("text/plain")

public Customer getCustomerString(@PathParam("id") int id)

{

return getCustomer(id).toString();

}



The Client Code

The client code for this example executes various HTTP GET requests to retrieve dif‐

ferent representations of a Customer. Each request sets the Accept header a little dif‐

ferently so that it can obtain a different representation. For example:

src/test/java/com/restfully/shop/test/CustomerResourceTest.java

public class CustomerResourceTest

{

@Test

public void testCustomerResource() throws Exception

{

... initialization code ...

System.out.println("*** GET XML Created Customer **");

String xml = client.target(location).request()

.accept(MediaType.APPLICATION_XML_TYPE)

.get(String.class);

System.out.println(xml);

System.out.println("*** GET JSON Created Customer **");

String json = client.target(location).request()

.accept(MediaType.APPLICATION_JSON_TYPE)

.get(String.class);

System.out.println(json);

}

}



The SyncInvoker.accept() method is used to initialize the Accept header. The client

extracts a String from the HTTP response so it can show you the request XML or JSON.



292



|



Chapter 23: Examples for Chapter 9



www.it-ebooks.info



Xem Thêm