Java Reference
In-Depth Information
Our endpoint is defined in the /tickets address. We injected a SessionReposit-
ory to our endpoint. During @OnOpen , we add Sessions to the registry, and during
@OnClose , we just remove them. Message sending is performed on the CDI event (the
@Observers annotation), which is already fired in our code during
TheatreBox.buyTicket(int) . In our send method, we retrieve all sessions from
SessionRepository , and for each of them, we asynchronously send information
about booked seats. We don't really need information about all the Seat fields to realize
this feature. That's the reason why we don't use the automatic JSON serialization we know
from the last chapter here. Instead, we decided to use a minimalistic JSON object, which
provides only the required data. To do this, we used the new Java API for JSON Process-
ing (JSR-353). Using a fluent-like API, we're able to create a JSON object and add two
fields to it. Then, we just convert JSON to the string, which is sent in a text message.
Because in our example we send messages in response to a CDI event, we don't have (in
the event handler) an out-of-the-box reference to any of the sessions. We have to use our
sessionRegistry object to access the active ones. However, if we would like to do
the same thing but, for example, in the @OnMessage method, then it is possible to get all
active sessions just by executing the session.getOpenSessions() method.
These are all the changes required to perform on the backend side. Now, we have to modi-
fy our AngularJS frontend to leverage the added feature. The good news is that JavaScript
already includes classes that can be used to perform WebSocket communication! There
are a few lines of code we have to add inside the module defined in the seat.js file,
which are as follows:
var ws = new WebSocket("ws://localhost:8080/
ws.onmessage = function (message) {
var receivedData =;
var bookedSeat = JSON.parse(receivedData);
$scope.$apply(function () {
for (var i = 0; i < $scope.seats.length; i++) {
if ($scope.seats[i].id === {
$scope.seats[i].booked = bookedSeat.booked;
Search WWH ::

Custom Search