Java Reference
In-Depth Information
We could use Collections.synchronizedSet from standard Java libraries but it's
a great chance to remember what we described in Chapter 3 , Introducing Java EE 7 -
EJBs , about container-based concurrency. In SessionRegistry , we defined some ba-
sic methods to add, get, and remove sessions. For the sake of collection thread safety dur-
ing retrieval, we return an unmodifiable view.
We defined the registry, so now we can move to the endpoint definition. We will need a
POJO, which will use our newly defined registry as shown:
@ServerEndpoint("/tickets")
public class TicketEndpoint {
@Inject
private SessionRegistry sessionRegistry;
@OnOpen
public void open(Session session, EndpointConfig conf) {
sessionRegistry.add(session);
}
@OnClose
public void close(Session session, CloseReason reason) {
sessionRegistry.remove(session);
}
public void send (@Observes Seat seat) {
sessionRegistry.getAll().forEach(session ->
session.getAsyncRemote().sendText(toJson(seat)));
}
private String toJson(Seat seat) {
final JsonObject jsonObject =
Json.createObjectBuilder()
.add("id", seat.getId())
.add("booked", seat.isBooked())
.build();
return jsonObject.toString();
}
}
Search WWH ::




Custom Search