Debian Codegraph @

src/java/org/astrogrid/samp/client/ClientTracker.java

raw
1 package org.astrogrid.samp.client;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.Iterator;
6 import java.util.List;
7 import java.util.Map;
8 import java.util.Timer;
9 import java.util.TimerTask;
10 import java.util.logging.Logger;
11 import org.astrogrid.samp.Client;
12 import org.astrogrid.samp.Message;
13 import org.astrogrid.samp.Metadata;
14 import org.astrogrid.samp.SampUtils;
15 import org.astrogrid.samp.Subscriptions;
16
17 /**
18 * Message handler which watches hub event messages to keep track of
19 * what clients are currently registered and what their attributes are
20 * on behalf of the hub.
21 * The results are stored in an externally supplied {@link TrackedClientSet}
22 * object. This class tries its best to handle complications arising
23 * from the fact that calls concerning a client may arrive out of order
24 * (for instance declareMetadata before registration or after unregistration).
25 *
26 * @author Mark Taylor
27 * @author Laurent Bourges
28 * @since 16 Jul 2008
29 */
30 class ClientTracker extends AbstractMessageHandler {
31
32 private final TrackedClientSet clientSet_;
33 private final Map clientMap_;
34 private final OperationQueue opQueue_;
35 private final static Logger logger_ =
36 Logger.getLogger( ClientTracker.class.getName() );
37
38 private static final int QUEUE_TIME = 10000;
39 private static final String REGISTER_MTYPE;
40 private static final String UNREGISTER_MTYPE;
41 private static final String METADATA_MTYPE;
42 private static final String SUBSCRIPTIONS_MTYPE;
43 private static final String[] TRACKED_MTYPES = new String[] {
44 REGISTER_MTYPE = "samp.hub.event.register",
45 UNREGISTER_MTYPE = "samp.hub.event.unregister",
46 METADATA_MTYPE = "samp.hub.event.metadata",
47 SUBSCRIPTIONS_MTYPE = "samp.hub.event.subscriptions",
48 };
49
50 /**
51 * Constructor.
52 *
53 * @param clientSet object used to record registered clients and their
54 * attributes
55 */
56 public ClientTracker( TrackedClientSet clientSet ) {
57 super( TRACKED_MTYPES );
58 clientSet_ = clientSet;
59 clientMap_ = clientSet.getClientMap();
60 opQueue_ = new OperationQueue();
61 }
62
63 /**
64 * Removes all clients from the list.
65 */
66 public void clear() {
67 try {
68 initialise( null );
69 }
70 catch ( SampException e ) {
71 assert false;
72 }
73 }
74
75 /**
76 * Initialises this tracker from a hub connection.
77 * It is interrogated to find the current list of registered clients
78 * and their attributes.
79 *
80 * @param connection hub connection; may be null for no connection
81 */
82 public void initialise( HubConnection connection ) throws SampException {
83 String[] clientIds;
84
85 // If connection is null, there are no registered clients.
86 if ( connection == null ) {
87 clientIds = new String[ 0 ];
88 }
89
90 // If connection is live, get the list of other registered clients,
91 // and don't forget to add an entry for self, which
92 // getRegisteredClients() excludes.
93 else {
94 String[] otherIds = connection.getRegisteredClients();
95 clientIds = new String[ otherIds.length + 1 ];
96 System.arraycopy( otherIds, 0, clientIds, 0, otherIds.length );
97 clientIds[ otherIds.length ] = connection.getRegInfo().getSelfId();
98 }
99
100 // Prepare an array of client objects, populating their characteristics
101 // by interrogating the connection.
102 int nc = clientIds.length;
103 TrackedClient[] clients = new TrackedClient[ nc ];
104 for ( int ic = 0; ic < nc; ic++ ) {
105 String id = clientIds[ ic ];
106 TrackedClient client = new TrackedClient( id );
107 client.setMetadata( connection.getMetadata( id ) );
108 client.setSubscriptions( connection.getSubscriptions( id ) );
109 clients[ ic ] = client;
110 }
111
112 // Populate the client set. Discard any queued operations first.
113 // This doesn't guarantee that we've got the most up to date
114 // information ... but in absence of guaranteed delivery order for
115 // messages that's more or less impossible.
116 synchronized ( opQueue_ ) {
117 ClientOperation[] pendingOps = opQueue_.getOperations();
118 opQueue_.clear();
119 clientSet_.setClients( clients );
120 }
121 }
122
123 public Map processCall( HubConnection connection, String senderId,
124 Message message ) {
125 String mtype = message.getMType();
126 if ( ! senderId.equals( connection.getRegInfo().getHubId() ) ) {
127 logger_.warning( "Hub admin message " + mtype + " received from "
128 + "non-hub client. Acting on it anyhow" );
129 }
130 String id = (String) message.getParams().get( "id" );
131 if ( id == null ) {
132 throw new IllegalArgumentException( "id parameter missing in "
133 + mtype );
134 }
135 String selfId = connection.getRegInfo().getSelfId();
136 if ( REGISTER_MTYPE.equals( mtype ) ) {
137 TrackedClient client = new TrackedClient( id );
138 opQueue_.apply( client );
139 clientSet_.addClient( client );
140 }
141 else if ( UNREGISTER_MTYPE.equals( mtype ) ) {
142 performClientOperation( new ClientOperation( id, mtype ) {
143 public void perform( TrackedClient client ) {
144 opQueue_.discard( client );
145 clientSet_.removeClient( client );
146 }
147 }, connection );
148 }
149 else if ( METADATA_MTYPE.equals( mtype ) ) {
150 final Map meta = (Map) message.getParams().get( "metadata" );
151 performClientOperation( new ClientOperation( id, mtype ) {
152 public void perform( TrackedClient client ) {
153 client.setMetadata( meta );
154 clientSet_.updateClient( client, true, false );
155 }
156 }, connection );
157 }
158 else if ( SUBSCRIPTIONS_MTYPE.equals( mtype ) ) {
159 final Map subs = (Map) message.getParams().get( "subscriptions" );
160 performClientOperation( new ClientOperation( id, mtype ) {
161 public void perform( TrackedClient client ) {
162 client.setSubscriptions( subs );
163 clientSet_.updateClient( client, false, true );
164 }
165 }, connection );
166 }
167 else {
168 throw new IllegalArgumentException( "Shouldn't have received MType"
169 + mtype );
170 }
171 return null;
172 }
173
174 /**
175 * Performs an operation on a ClientOperation object.
176 *
177 * @param op client operation
178 * @param connection hub connection
179 */
180 private void performClientOperation( ClientOperation op,
181 HubConnection connection ) {
182 String id = op.getId();
183
184 // If the client is currently part of this tracker's data model,
185 // we can peform the operation directly.
186 TrackedClient client = (TrackedClient) clientMap_.get( id );
187 if ( client != null ) {
188 op.perform( client );
189 }
190
191 // If it's not, but it applies to this client itself, it's just
192 // because we haven't added ourself to the client list yet.
193 // Queue it.
194 else if ( id.equals( connection.getRegInfo().getSelfId() ) ) {
195 opQueue_.add( op );
196 }
197
198 // Otherwise, the client is not yet known. This is most likely
199 // because, in absence of any guarantee about message delivery order
200 // within SAMP, a message which was sent between its registration
201 // and its unregistration might still arrive either before its
202 // registration event has arrived or after its unregistration event
203 // has arrived. In the hope that it is the former, we hang on to
204 // this operation so that it can be peformed at some future date
205 // when we actually have a client object we can apply it to.
206 else {
207
208 // If it's for this client, this is just because it hasn't added
209 // itself to the client list yet. Should get resolved very soon.
210 if ( id.equals( connection.getRegInfo().getSelfId() ) ) {
211 logger_.info( "Message " + op.getMType() + " arrived for self"
212 + " - holding till later" );
213 }
214
215 // Otherwise less certain, but we still hope.
216 else {
217 logger_.info( "No known client " + id + " for message "
218 + op.getMType() + " - holding till later" );
219 }
220
221 // Either way, queue it.
222 opQueue_.add( op );
223 }
224 }
225
226 /**
227 * Client implementation used to populate internal data structures.
228 * It just implements the Client interface as well as adding mutators
229 * for metadata and subscriptions, and providing an equals method based
230 * on public id.
231 */
232 private static class TrackedClient implements Client {
233
234 private final String id_;
235 private Metadata metadata_;
236 private Subscriptions subscriptions_;
237
238 /**
239 * Constructor.
240 *
241 * @param id client public id
242 */
243 public TrackedClient( String id ) {
244 id_ = id;
245 }
246
247 public String getId() {
248 return id_;
249 }
250
251 public Metadata getMetadata() {
252 return metadata_;
253 }
254
255 public Subscriptions getSubscriptions() {
256 return subscriptions_;
257 }
258
259 /**
260 * Sets this client's metadata.
261 *
262 * @param metadata new metadata
263 */
264 void setMetadata( Map metadata ) {
265 metadata_ = Metadata.asMetadata( metadata );
266 }
267
268 /**
269 * Sets this client's subscriptions.
270 *
271 * @param subscriptions new subscriptions
272 */
273 void setSubscriptions( Map subscriptions ) {
274 subscriptions_ = Subscriptions.asSubscriptions( subscriptions );
275 }
276
277 public boolean equals( Object o ) {
278 if ( o instanceof TrackedClient ) {
279 TrackedClient other = (TrackedClient) o;
280 return other.id_.equals( this.id_ );
281 }
282 else {
283 return false;
284 }
285 }
286
287 public int hashCode() {
288 return id_.hashCode();
289 }
290
291 public String toString() {
292 return SampUtils.toString( this );
293 }
294 }
295
296 /**
297 * Describes an operation to be performed on a TrackedClient object
298 * which is already part of this tracker's model.
299 */
300 private static abstract class ClientOperation {
301 private final String id_;
302 private final String mtype_;
303 private final long birthday_;
304
305 /**
306 * Constructor.
307 *
308 * @param id client public ID
309 * @param mtype MType of the message which triggered this operation
310 */
311 ClientOperation( String id, String mtype ) {
312 id_ = id;
313 mtype_ = mtype;
314 birthday_ = System.currentTimeMillis();
315 }
316
317 /**
318 * Performs the instance-specific operation on a given client.
319 *
320 * @param client client
321 */
322 public abstract void perform( TrackedClient client );
323
324 /**
325 * Returns the client ID for the client this operation applies to.
326 *
327 * @return client public ID
328 */
329 public String getId() {
330 return id_;
331 }
332
333 /**
334 * Returns the MType of the message which triggered this operation.
335 *
336 * @return message MType
337 */
338 public String getMType() {
339 return mtype_;
340 }
341
342 /**
343 * Returns the creation time of this object.
344 *
345 * @return <code>System.currentTimeMillis()</code> at construction
346 */
347 public long getBirthday() {
348 return birthday_;
349 }
350
351 public String toString() {
352 return "message " + mtype_ + " for client " + id_;
353 }
354 }
355
356 /**
357 * Data structure for holding ClientOperation objects which (may) need
358 * to be applied in the future.
359 * Operations are dumped here if they cannot be performed immediately
360 * because the client in question is not (yet) known by this tracker.
361 * The hope is that the client will register at some point in the future
362 * and the pending operations can be applied then. However, this may
363 * never happen, so the queue maintains its own expiry system to throw
364 * out old events.
365 */
366 private static class OperationQueue {
367 private final Collection opList_;
368 private Timer tidyTimer_;
369
370 /**
371 * Constructor.
372 */
373 OperationQueue() {
374 opList_ = new ArrayList();
375 }
376
377 /**
378 * Add a new client operation which may get the opportunity to be
379 * performed some time in the future.
380 *
381 * @param op oeration to add
382 */
383 public synchronized void add( ClientOperation op ) {
384 if ( tidyTimer_ == null ) {
385 TimerTask tidy = new TimerTask() {
386 public void run() {
387 discardOld( QUEUE_TIME );
388 }
389 };
390 tidyTimer_ = new Timer( true );
391 tidyTimer_.schedule( tidy, QUEUE_TIME, QUEUE_TIME );
392 }
393 opList_.add( op );
394 }
395
396 /**
397 * Apply any pending operations to given client.
398 * This client was presumably unavailable at the time such operations
399 * were queued.
400 *
401 * @param client client to apply pending operations to
402 */
403 public synchronized void apply( TrackedClient client ) {
404 String id = client.getId();
405 for ( Iterator it = opList_.iterator(); it.hasNext(); ) {
406 ClientOperation op = (ClientOperation) it.next();
407 if ( op.getId().equals( id ) ) {
408 logger_.info( "Performing queued " + op );
409 op.perform( client );
410 it.remove();
411 }
412 }
413 }
414
415 /**
416 * Discards any operations corresponding to a given client,
417 * presumably because the client is about to disappear.
418 *
419 * @param client client to forget about
420 */
421 public synchronized void discard( TrackedClient client ) {
422 String id = client.getId();
423 for ( Iterator it = opList_.iterator(); it.hasNext(); ) {
424 ClientOperation op = (ClientOperation) it.next();
425 if ( op.getId().equals( id ) ) {
426 logger_.warning( "Discarding queued " + op );
427 it.remove();
428 }
429 }
430 }
431
432 /**
433 * Throws away any pending operations which are older than a certain
434 * age, presumably in the expectation that their client will never
435 * register.
436 *
437 * @param maxAge oldest operations (in milliseconds) permitted to
438 * remain in the queue
439 */
440 public synchronized void discardOld( long maxAge ) {
441 long now = System.currentTimeMillis();
442 for ( Iterator it = opList_.iterator(); it.hasNext(); ) {
443 ClientOperation op = (ClientOperation) it.next();
444 if ( now - op.getBirthday() > maxAge ) {
445 logger_.warning( "Discarding queued " + op
446 + " - client never showed up" );
447 it.remove();
448 }
449 }
450 }
451
452 /**
453 * Removes all entries from this queue.
454 */
455 public synchronized void clear() {
456 opList_.clear();
457 if ( tidyTimer_ != null ) {
458 tidyTimer_.cancel();
459 tidyTimer_ = null;
460 }
461 }
462
463 /**
464 * Returns an array containing all the operations currently pending.
465 *
466 * @return operation list
467 */
468 public synchronized ClientOperation[] getOperations() {
469 return (ClientOperation[])
470 opList_.toArray( new ClientOperation[ 0 ] );
471 }
472 }
473 }