Java Reference
In-Depth Information
package
package javax . rs . ws . client ;
public
public interface
interface InvocationCallback
InvocationCallback < RESPONSE > {
public
public void
void completed ( RESPONSE response );
public
public void
void failed ( Throwable throwable );
}
JAX-RS introspects the application class that implements InvocationCallback to determ-
ine whether your callback wants a Response object or if you want to unmarshal to a specific
type. Let's convert our Future example to use callbacks. First, we'll implement a callback
for our initial request:
public
public class
class CustomerCallback
CustomerCallback implements
implements InvocationCallback < Response > {
public
public void
void completed ( Response response ) {
iif ( response . getStatus () == 200 ) {
Customer cust = response . readEntity ( Customer . class );
} else
else {
System . err . println ( "Request error: " + response . getStatus ());
}
}
public
public void
void failed ( Throwable throwable ) {
throwable . printStackTrace ();
}
}
The CustomerCallback class implements InvocationCallback with a Response generic
parameter. This means JAX-RS will call the completed() method and pass in an untouched
Response object. If there is a problem sending the request to the server or the JAX-RS
runtime is unable to create a Response , the failed() method will be invoked with the ap-
propriate exception. Otherwise, if there is an HTTP response, then completed() will be
called.
Next, let's implement a different callback for our second parallel request. This time we want
our successful HTTP responses to be converted into Order objects:
public
public class
class OrderCallback
OrderCallback implements
implements InvocationCallback < Order > {
public
public void
void completed ( Order order ) {
System . out . println ( "We received an order." );
}
public
public void
void failed ( Throwable throwable ) {
iif ( throwable instanceof
instanceof WebApplicationException ) {
WebApplicationException wae = ( WebApplicationException ) throwable ;
System . err . println ( "Failed with status:
Search WWH ::




Custom Search