Java Reference
In-Depth Information
{
order
.
setId
(
idCounter
.
incrementAndGet
());
orderDB
.
put
(
order
.
getId
(),
order
);
System
.
out
.
println
(
"Created order "
+
order
.
getId
());
UriBuilder builder
=
uriInfo
.
getAbsolutePathBuilder
();
builder
.
path
(
Integer
.
toString
(
order
.
getId
()));
return
return
Response
.
created
(
builder
.
build
()).
build
();
}
The
createOrder()
method handles
POST /orders
requests. It generates new
Order
IDs
and adds the posted
Order
instance into the order database (the map). The
UriInfo.getAbsolutePathBuilder()
method generates the URL used to initialize the
Location
header returned by the
Response.created()
method. You'll see later that the cli-
ent uses this URL to further manipulate the created order.
@GET
@Path
(
"{id}"
)
@Produces
(
"application/xml"
)
public
public
Response
getOrder
(
@PathParam
(
"id"
)
int
int
id
,
@Context
UriInfo uriInfo
)
{
Order order
=
orderDB
.
get
(
id
);
iif
(
order
==
null
null
)
{
throw
throw new
new
WebApplicationException
(
Response
.
Status
.
NOT_FOUND
);
}
Response
.
ResponseBuilder
builder
=
Response
.
ok
(
order
);
iif
(!
order
.
isCancelled
())
addCancelHeader
(
uriInfo
,
builder
);
return
return
builder
.
build
();
}
The
getOrder()
method processes
GET /orders/{id}
requests and retrieves individual or-
ders from the database (the map). If the order has not been cancelled already, a
cancel Link
header is added to the
Response
so the client knows if an order can be cancelled and which
URL to post a cancel request to:
protected
protected
void
void
addCancelHeader
(
UriInfo uriInfo
,
Response
.
ResponseBuilder
builder
)
{
UriBuilder absolute
=
uriInfo
.
getAbsolutePathBuilder
();
URI cancelUrl
=
absolute
.
clone
().
path
(
"cancel"
).
build
();
builder
.
links
(
Link
.
fromUri
(
cancelUrl
).
rel
(
"cancel"
).
build
());
}