source: src/main/java/geniusweb/profilesserver/websocket/GetProfileSocket.java@ 2

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

Initial Release

File size: 2.2 KB
Line 
1package geniusweb.profilesserver.websocket;
2
3import java.io.IOException;
4
5import javax.websocket.OnClose;
6import javax.websocket.OnError;
7import javax.websocket.OnOpen;
8import javax.websocket.Session;
9import javax.websocket.server.PathParam;
10import javax.websocket.server.ServerEndpoint;
11
12import com.fasterxml.jackson.databind.ObjectMapper;
13
14import geniusweb.profile.Profile;
15import geniusweb.profilesserver.ProfilesFactory;
16import geniusweb.profilesserver.events.ChangeEvent;
17import tudelft.utilities.listener.Listener;
18
19/**
20 * Returns a websocket that communicates the list of currently available domains
21 * and profiles. Every time something changes, a new list of domains and
22 * profiles is sent. For each new websocket the server will create one of this
23 * but they all share one {@link ProfilesFactory}.
24 */
25@ServerEndpoint("/websocket/get/{domain}/{profile}")
26public class GetProfileSocket {
27 private final static ObjectMapper jackson = new ObjectMapper();
28 private Profile prof = null; // the latest that we sent to client.
29
30 // should all be final, except that we can only set them when start is
31 // called...
32 private String profilename;
33 private Listener<ChangeEvent> changeListener;
34 private Session session;
35
36 @OnOpen
37 public void start(Session session, @PathParam("domain") final String domain,
38 @PathParam("profile") final String profile) throws IOException {
39 this.session = session;
40 this.profilename = domain + "/" + profile;
41
42 changeListener = new Listener<ChangeEvent>() {
43 @Override
44 public void notifyChange(ChangeEvent data) {
45 sendupdatedProfile();
46 }
47 };
48 sendupdatedProfile();
49 Profiles.factory.addListener(changeListener);
50 }
51
52 private void sendupdatedProfile() {
53 Profile newprof = Profiles.factory.getProfile(profilename);
54 // notice, may be null if profile does not exist/was removed.
55 if (newprof == null ? prof != null : !newprof.equals(prof)) {
56 prof = newprof;
57 try {
58 session.getBasicRemote()
59 .sendText(jackson.writeValueAsString(prof));
60 } catch (Exception e) {
61 e.printStackTrace();
62 }
63 }
64 }
65
66 @OnClose
67 public void end() throws IOException {
68 Profiles.factory.removeListener(changeListener);
69 }
70
71 @OnError
72 public void onError(Throwable t) throws Throwable {
73 t.printStackTrace();
74 }
75
76}
Note: See TracBrowser for help on using the repository browser.