Java Reference
In-Depth Information
er service. If the absolute base URI of our server is http://shop.restfully.com , methods ex-
posed by our CustomerResource class would be available under http://shop.restfully.com/
customers .
In our class, we define a simple map in the customerDB field that will store created Cus-
tomer objects in memory. We use a java.util.concurrent.ConcurrentHashMap for cus-
tomerDB because CustomerResource is a singleton and will have concurrent requests ac-
cessing the map. Using a java.util.HashMap would trigger concurrent access exceptions in
a multithreaded environment. Using a java.util.Hashtable creates a synchronization bot-
tleneck. ConcurrentHashMap is our best bet. The idCounter field will be used to generate
IDs for newly created Customer objects. For concurrency reasons, we use a
java.util.concurrent.atomic.AtomicInteger , as we want to always have a unique
number generated. Of course, these two lines of code have nothing to do with JAX-RS and
are solely artifacts required by our simple example.
Creating customers
Let's now take a look at how to create customers in our CustomerResource class:
@POST
@Consumes ( "application/xml" )
public
public Response createCustomer ( InputStream is ) {
Customer customer = readCustomer ( is );
customer . setId ( idCounter . incrementAndGet ());
customerDB . put ( customer . getId (), customer );
System . out . println ( "Created customer " + customer . getId ());
return
return Response . created ( URI . create ( "/customers/"
+ customer . getId ())). build ();
}
We will implement customer creation using the same model as that used in Chapter 2 . An
HTTP POST request sends an XML document representing the customer we want to create.
The createCustomer() method receives the request, parses the document, creates a Cus-
tomer object from the document, and adds it to our customerDB map. The createCus-
tomer() method returns a response code of 201, “Created,” along with a Location header
pointing to the absolute URI of the customer we just created. So how does the createCus-
tomer() method do all this? Let's examine further.
To bind HTTP POST requests to the createCustomer() method, we annotate it with the
@javax.ws.rs.POST annotation. The @Path annotation we put on the CustomerResource
class, combined with this @POST annotation, binds all POST requests going to the relative
URI /customers to the Java method createCustomer() .
Search WWH ::




Custom Search