package geniusweb.runserver.websocket; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.stream.Collectors; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import com.fasterxml.jackson.databind.ObjectMapper; import geniusweb.protocol.NegoProtocol; import geniusweb.runserver.RunningNego; import geniusweb.runserver.RunningNegotiationsRepo; import tudelft.utilities.listener.Listener; import tudelft.utilities.logging.ReportToLogger; import tudelft.utilities.logging.Reporter; /** * Returns a websocket that communicates the list of currently running * {@link NegoProtocol}s. Every time something changes, a new list of * {@link RunningNego}s is sent. */ @ServerEndpoint("/websocket/running") public class RunningListSocket { private Listener changeListener; // final, but only initialized in // startSession. private Session session; // a web session, not a negotiatino session private RunningNegotiationsRepo repo; private final static ObjectMapper jackson = new ObjectMapper(); private final Reporter log; public RunningListSocket() { this(new ReportToLogger("runserver")); } public RunningListSocket(Reporter reporter) { this.log = reporter; } @OnOpen public void start(Session session) throws IOException { this.session = session; repo = getRepo(); changeListener = new Listener() { @Override public void notifyChange(String data) { sendUpdatedSessions(); } }; repo.addListener(changeListener); sendUpdatedSessions(); } /** * Send the currently running sessions to the client. */ private void sendUpdatedSessions() { List list = repo.list().stream().map(session -> session.getID()) .collect(Collectors.toList()); try { System.out.println("new running negotiations:" + list); session.getBasicRemote().sendText(jackson.writeValueAsString(list)); } catch (IOException e) { log.log(Level.SEVERE, "Internal problem converting json", e); } } @OnClose public void end() throws IOException { repo.removeListener(changeListener); } @OnError public void onError(Throwable t) throws Throwable { log.log(Level.SEVERE, "Internal problem converting json", t); } /** * FactoryMethod for testing * * @return RunningPartiesRepo */ protected RunningNegotiationsRepo getRepo() { return RunningNegotiationsRepo.instance(); } }