source: src/main/java/geniusweb/partiesserver/websocket/PartySocket.java@ 8

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

Release 1.1.0

File size: 7.8 KB
Line 
1package geniusweb.partiesserver.websocket;
2
3import java.io.EOFException;
4import java.io.IOException;
5import java.net.URI;
6import java.util.Date;
7import java.util.List;
8import java.util.concurrent.CopyOnWriteArrayList;
9import java.util.logging.Level;
10
11import javax.websocket.CloseReason;
12import javax.websocket.CloseReason.CloseCodes;
13import javax.websocket.OnClose;
14import javax.websocket.OnError;
15import javax.websocket.OnMessage;
16import javax.websocket.OnOpen;
17import javax.websocket.Session;
18import javax.websocket.server.PathParam;
19import javax.websocket.server.ServerEndpoint;
20
21import com.fasterxml.jackson.core.JsonParseException;
22import com.fasterxml.jackson.databind.JsonMappingException;
23import com.fasterxml.jackson.databind.ObjectMapper;
24
25import geniusweb.actions.Action;
26import geniusweb.actions.PartyId;
27import geniusweb.connection.ConnectionEnd;
28import geniusweb.partiesserver.repository.RunningPartiesRepo;
29import geniusweb.partiesserver.repository.RunningParty;
30import geniusweb.party.Party;
31import geniusweb.party.inform.Inform;
32import geniusweb.party.inform.Settings;
33import geniusweb.references.Reference;
34import tudelft.utilities.listener.Listener;
35import tudelft.utilities.logging.ReportToLogger;
36import tudelft.utilities.logging.Reporter;
37
38/**
39 * Returns a websocket that communicates with the {@link RunningParty}. We close
40 * the socket when we detect the party is gone (eg, due to a bug in the party or
41 * a time-out). If the socket breaks, we close the party as it becomes isolated.
42 */
43@ServerEndpoint("/party/{party}")
44public class PartySocket implements ConnectionEnd<Inform, Action> {
45 private final static ObjectMapper jackson = new ObjectMapper();
46 private final Reporter log;
47 private final RunningPartiesRepo runningparties;
48 private final List<Listener<Inform>> listeners = new CopyOnWriteArrayList<Listener<Inform>>();
49
50 // should all be final, except that we can only set them when start is
51 // called...
52 private Session session;
53
54 private PartyId partyID;
55
56 private SendBuffer outstream;
57 private Throwable error = null;
58
59 public PartySocket() {
60 this(RunningPartiesRepo.instance(),
61 new ReportToLogger("partiesserver"));
62 }
63
64 public PartySocket(RunningPartiesRepo parties, Reporter reporter) {
65 this.runningparties = parties;
66 this.log = reporter;
67 }
68
69 @OnOpen
70 public void start(Session session,
71 @PathParam("party") final String partyidname) throws IOException {
72 if (partyidname == null) {
73 throw new IllegalArgumentException("party can't be null");
74 }
75 this.session = session;
76 this.partyID = new PartyId(partyidname);
77 this.outstream = new SendBuffer(session.getBasicRemote(), log);
78
79 // listen to parties repo, so that we can act if party is terminated
80 runningparties.addListener(new Listener<PartyId>() {
81 @Override
82 public void notifyChange(PartyId data) {
83 if (runningparties.get(partyID) == null) {
84 // party was removed, probably due to time out.
85 try {
86 log.log(Level.INFO,
87 "Party " + partyID + " was terminated ");
88 runningparties.removeListener(this);
89 session.close(new CloseReason(CloseCodes.GOING_AWAY,
90 "detected that party vanished"));
91 } catch (IOException e) {
92 log.log(Level.WARNING,
93 "failed to close the socket for " + partyID, e);
94 }
95 }
96 }
97 });
98 RunningParty runningparty = runningparties.get(partyID);
99
100 if (runningparty == null) {
101 session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT,
102 "No such party: " + partyID));
103 } else {
104 runningparties.replace(runningparty.withConnection(this));
105 }
106
107 // we do not listen for changes on the Parties factory as we can't
108 // replace the running party anyway
109 }
110
111 /**
112 * Called when a message comes in on the server socket that needs to be
113 * passed into the {@link Party}. We also sniff the message for termination
114 * indicators.
115 *
116 * @param informmessage the incoming string, supposedly a JSON-fornatted
117 * {@link Inform}
118 * @param session the session. We already have this info.
119 */
120 @OnMessage
121 public void onMessage(String informmessage, Session session)
122 throws JsonParseException, JsonMappingException, IOException {
123 if (this.session != session) {
124 throw new IllegalStateException("Unexpected change of session ID");
125 }
126 Inform info = jackson.readValue(informmessage, Inform.class);
127 RunningParty party = runningparties.get(partyID);
128 if (party != null) {
129 // first sniff, to ensure the deadlines are updated first.
130 sniff(info, party);
131 log.log(Level.FINE, "Inform " + partyID + ": " + info);
132 try {
133 party.inform(info);
134 } catch (Throwable e) {
135 log.log(Level.WARNING, "Party failed on inform.", e);
136 // we don't use jackson.writeValueAsString(e) here because
137 // CloseReason has 123 char limit.
138 // The error will be too large to fit and will be truncated
139 // therefore we send a plain string and hope that enough
140 // will arrive at the other side (the protocol)
141 session.close(new CloseReason(
142 CloseReason.CloseCodes.CLOSED_ABNORMALLY,
143 "party threw exception: " + collectReasons(e)));
144 }
145 } // else party is dead but that's handled in the listener above
146 }
147
148 /**
149 *
150 * @param e an exception
151 * @return collect all reasons and sub-reasons
152 */
153 private String collectReasons(Throwable e) {
154 String reason = "";
155 do {
156 reason = reason + " : " + e.getClass().getSimpleName() + ":"
157 + e.getMessage();
158 e = e.getCause();
159 } while (e != null);
160 return reason;
161 }
162
163 /**
164 * Sniffs the Inform for termination-related information
165 *
166 * @param info
167 * @param party the party we're handling
168 * @throws IOException
169 */
170 private void sniff(Inform info, RunningParty party) throws IOException {
171 // do NOT sniff Finished messages and close sockets. Parties and their
172 // sockets need to stay running till all messages are handled
173 if (info instanceof Settings) {
174 Date end = ((Settings) info).getProgress().getTerminationTime();
175 runningparties.replace(party.withEndTime(end));
176 }
177 }
178
179 @OnClose
180 public void onClose() throws IOException {
181 log.log(Level.INFO, "socket closed to " + partyID);
182 /*
183 * for now just kill the party. Maybe we can do something with reconnect
184 * but that will be complex.
185 */
186 runningparties.remove(partyID);
187 outstream.stop();
188 }
189
190 @OnError
191 public void onError(Throwable t) throws Throwable {
192 if (t instanceof EOFException) {
193 // This is a standard exception from Apache when a socket closes.
194 // Just ignore
195 // it...
196 log.log(Level.FINEST,
197 "apache reported EOF from (probably closed) socket, ignoring");
198 return;
199 }
200 log.log(Level.WARNING, "Unhandled exception was reported by Tomcat", t);
201 }
202
203 @Override
204 public void send(Action action) throws IOException {
205 log.log(Level.FINE, "Action " + partyID + ": " + action);
206 outstream.send(jackson.writeValueAsString(action));
207 }
208
209 @Override
210 public Reference getReference() {
211 return null;
212 }
213
214 @Override
215 public URI getRemoteURI() {
216 // In serverendpoints we apparently can't see who was contacting us.
217 throw new UnsupportedOperationException();
218 }
219
220 @Override
221 public void close() {
222 try {
223 session.close();
224 } catch (IOException e) {
225 log.log(Level.SEVERE, "failed to close " + partyID, e);
226 }
227 }
228
229 @Override
230 public Throwable getError() {
231 return error;
232 }
233
234 @Override
235 public void addListener(Listener<Inform> l) {
236 listeners.add(l);
237 }
238
239 @Override
240 public void removeListener(Listener<Inform> l) {
241 listeners.remove(l);
242 }
243
244 /**
245 * This should only be called by the owner of the listenable, not by
246 * listeners or others. Avoid calling this from synchronized blocks as a
247 * notified listener might immediately make more calls to you.
248 * <p>
249 * Any listeners that throw an exception will be intercepted and their
250 * stacktrace is printed.
251 *
252 * @param data information about the change.
253 */
254 public void notifyListeners(Inform data) {
255 for (Listener<Inform> l : listeners) {
256 l.notifyChange(data);
257 }
258 }
259
260}
Note: See TracBrowser for help on using the repository browser.