source: src/main/java/geniusweb/runserver/websocket/RunningListSocket.java@ 13

Last change on this file since 13 was 1, checked in by bart, 5 years ago

Initial Release

File size: 2.5 KB
Line 
1package geniusweb.runserver.websocket;
2
3import java.io.IOException;
4import java.util.List;
5import java.util.logging.Level;
6import java.util.stream.Collectors;
7
8import javax.websocket.OnClose;
9import javax.websocket.OnError;
10import javax.websocket.OnOpen;
11import javax.websocket.Session;
12import javax.websocket.server.ServerEndpoint;
13
14import com.fasterxml.jackson.databind.ObjectMapper;
15
16import geniusweb.protocol.NegoProtocol;
17import geniusweb.runserver.RunningNego;
18import geniusweb.runserver.RunningNegotiationsRepo;
19import tudelft.utilities.listener.Listener;
20import tudelft.utilities.logging.ReportToLogger;
21import tudelft.utilities.logging.Reporter;
22
23/**
24 * Returns a websocket that communicates the list of currently running
25 * {@link NegoProtocol}s. Every time something changes, a new list of
26 * {@link RunningNego}s is sent.
27 */
28@ServerEndpoint("/websocket/running")
29public class RunningListSocket {
30
31 private Listener<String> changeListener; // final, but only initialized in
32 // startSession.
33 private Session session; // a web session, not a negotiatino session
34 private RunningNegotiationsRepo repo;
35 private final static ObjectMapper jackson = new ObjectMapper();
36 private final Reporter log;
37
38 public RunningListSocket() {
39 this(new ReportToLogger("runserver"));
40 }
41
42 public RunningListSocket(Reporter reporter) {
43 this.log = reporter;
44 }
45
46 @OnOpen
47 public void start(Session session) throws IOException {
48 this.session = session;
49
50 repo = getRepo();
51 changeListener = new Listener<String>() {
52 @Override
53 public void notifyChange(String data) {
54 sendUpdatedSessions();
55 }
56 };
57 repo.addListener(changeListener);
58
59 sendUpdatedSessions();
60 }
61
62 /**
63 * Send the currently running sessions to the client.
64 */
65 private void sendUpdatedSessions() {
66 List<String> list = repo.list().stream().map(session -> session.getID())
67 .collect(Collectors.toList());
68 try {
69 System.out.println("new running negotiations:" + list);
70 session.getBasicRemote().sendText(jackson.writeValueAsString(list));
71 } catch (IOException e) {
72 log.log(Level.SEVERE, "Internal problem converting json", e);
73 }
74 }
75
76 @OnClose
77 public void end() throws IOException {
78 repo.removeListener(changeListener);
79 }
80
81 @OnError
82 public void onError(Throwable t) throws Throwable {
83 log.log(Level.SEVERE, "Internal problem converting json", t);
84 }
85
86 /**
87 * FactoryMethod for testing
88 *
89 * @return RunningPartiesRepo
90 */
91 protected RunningNegotiationsRepo getRepo() {
92 return RunningNegotiationsRepo.instance();
93 }
94
95}
Note: See TracBrowser for help on using the repository browser.