Java Reference
In-Depth Information
"
+
wae
.
getResponse
().
getStatus
());
}
else
else iif
(
throwable
instanceof
instanceof
ResponseProcessingException
) {
ResponseProcessingException rpe
= (
ResponseProcessingException
)
cause
;
System
.
err
.
println
(
"Failed with status:
"
+
rpe
.
getResponse
().
getStatus
());
}
else
else
{
throwable
.
printStackTrace
();
}
}
}
This case is a little bit different than when we implement
InvocationCallback
with a
Re-
sponse
. If there is a successful HTTP response from the server (like 200, “OK”), JAX-RS
will attempt to unmarshal the response into an
Order
object. If there were an HTTP error re-
sponse, or the JAX-RS runtime failed to unmarshal the response body into an
Order
object,
then the
failed()
method is invoked with the appropriate exception. Basically, we see the
same kind of exceptions thrown by similar synchronous invocations or the
Future
example
we discussed earlier. You do not have to close the underlying
Response
object; JAX-RS will
do this after
completed()
or
failed()
is invoked.
Now that our callback classes have been implemented, let's finish our example by invoking
on some services:
Client client
=
ClientBuilder
.
newClient
();
Future
<
Response
>
future1
=
client
.
target
(
"http://example.com/customers/123"
)
.
request
()
.
async
().
get
(
new
new
CustomerCallback
());
Future
<
Order
>
future2
=
client
.
target
(
"http://foobar.com/orders/456"
)
.
request
()
.
async
().
get
(
new
new
OrderCallback
());
That's all we have to do. Notice that the
get()
methods return a
Future
object. You can ig-
nore this
Future
, or interact with it as we did previously. I suggest that you only use the
Fu-
ture.cancel()
and
Future.isDone()
methods, though, as you may have concurrency is-
sues with
InvocationCallback
.
Futures Versus Callbacks
Given that we have two different ways to do asynchronous client invocations, which style
should you use? Futures or callbacks? In general, use futures if you need to
join
a set of re-
quests you've invoked asynchronously. By
join
, I mean you need to know when each of the