Java Reference
In-Depth Information
By default, RESTEasy allows only one connection per
Client
to be open at one time. So we
use the proprietary
ClientBuilder
implementation of RESTEasy to set a connection pool
size of 3. We also initialize a
WebTarget
with the URL of the chat service.
Next, we use the JAX-RS client asynchronous callback API to set up a loop to pull chat mes-
sages from the server:
target
.
request
().
async
().
get
(
new
new
InvocationCallback
<
Response
>()
{
@Override
public
public
void
void
completed
(
Response response
)
{
Link next
=
response
.
getLink
(
"next"
);
String message
=
response
.
readEntity
(
String
.
class
);
System
.
out
.
println
();
System
.
out
.
print
(
message
);
// + "\r");
System
.
out
.
println
();
System
.
out
.
print
(
"> "
);
client
.
target
(
next
).
request
().
async
().
get
(
this
this
);
}
@Override
public
public
void
void
failed
(
Throwable throwable
)
{
System
.
err
.
println
(
"FAILURE!"
);
}
});
The code starts off by making an async request to the base chat URI. This invocation re-
gisters an
InvocationCallback
interface that we've implemented as a Java inner class.
When the initial GET request is complete, the
InvocationCallback.complete()
method is
invoked, passing in the
Response
from the server. We first extract the
next Link
header and
the chat message from the
Response
. We then print the message to the console. Finally, we
make a new asynchronous GET request using the URI contained in the
next Link
header.
We register the current
InvocationCallback
instance with this new request. This will set up
a continuous pull request with the chat service.
After we've set up our receive loop, we set up another loop that allows us to send chat mes-
sages:
while
while
(
true
true
)
{
System
.
out
.
print
(
"> "
);
BufferedReader br
=
new
new
BufferedReader
(