package geniusweb.profilesserver.websocket; import java.io.IOException; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import com.fasterxml.jackson.databind.ObjectMapper; import geniusweb.profile.Profile; import geniusweb.profilesserver.ProfilesFactory; import geniusweb.profilesserver.events.ChangeEvent; import tudelft.utilities.listener.Listener; /** * Returns a websocket that communicates the list of currently available domains * and profiles. Every time something changes, a new list of domains and * profiles is sent. For each new websocket the server will create one of this * but they all share one {@link ProfilesFactory}. */ @ServerEndpoint("/websocket/get/{domain}/{profile}") public class GetProfileSocket { private final static ObjectMapper jackson = new ObjectMapper(); private Profile prof = null; // the latest that we sent to client. // should all be final, except that we can only set them when start is // called... private String profilename; private Listener changeListener; private Session session; @OnOpen public void start(Session session, @PathParam("domain") final String domain, @PathParam("profile") final String profile) throws IOException { this.session = session; this.profilename = domain + "/" + profile; changeListener = new Listener() { @Override public void notifyChange(ChangeEvent data) { sendupdatedProfile(); } }; sendupdatedProfile(); Profiles.factory.addListener(changeListener); } private void sendupdatedProfile() { Profile newprof = Profiles.factory.getProfile(profilename); // notice, may be null if profile does not exist/was removed. if (newprof == null ? prof != null : !newprof.equals(prof)) { prof = newprof; try { session.getBasicRemote() .sendText(jackson.writeValueAsString(prof)); } catch (Exception e) { e.printStackTrace(); } } } @OnClose public void end() throws IOException { Profiles.factory.removeListener(changeListener); } @OnError public void onError(Throwable t) throws Throwable { t.printStackTrace(); } }