Debian Codegraph @

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

raw
1 package org.astrogrid.samp.client;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.HashMap;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.SortedMap;
10 import java.util.Timer;
11 import java.util.TimerTask;
12 import java.util.TreeMap;
13 import java.util.logging.Level;
14 import java.util.logging.Logger;
15 import org.astrogrid.samp.Client;
16 import org.astrogrid.samp.ErrInfo;
17 import org.astrogrid.samp.Message;
18 import org.astrogrid.samp.Metadata;
19 import org.astrogrid.samp.Platform;
20 import org.astrogrid.samp.Response;
21 import org.astrogrid.samp.SampUtils;
22 import org.astrogrid.samp.Subscriptions;
23
24 /**
25 * Manages a client's connection to SAMP hubs.
26 * Normally SAMP client applications will use one instance of this class
27 * for as long as they are running.
28 * It provides the following services:
29 * <ul>
30 * <li>Keeps track of other registered clients
31 * <li>Keeps track of hubs shutting down and starting up
32 * <li>Manages client metadata and subscription information across
33 * hub reconnections
34 * <li>Facilitates provision of callback services by the client
35 * <li>Implements simple MTypes such as <code>samp.app.ping</code>.
36 * <li>Optionally looks out for hubs starting up and connects automatically
37 * when they do
38 * </ul>
39 *
40 * <p>This object provides a {@link #getConnection} method which provides
41 * the currently active {@link HubConnection} object if one exists or can be
42 * acquired. The <code>HubConnection</code> can be used for direct calls
43 * on the running hub, but in some cases similar methods with additional
44 * functionality exist in this class:
45 * <dl>
46 * <dt>{@link #declareMetadata declareMetadata}
47 * <dt>{@link #declareSubscriptions declareSubscriptions}
48 * <dd>These methods not only make the relevant declarations to the
49 * existing hub connection, if one exists, but will retain the
50 * metadata and subscriptions information and declare them to
51 * other connections if the hub connection is terminated and
52 * restarted (with either the same or a different hub)
53 * over the lifetime of this object.
54 * </dd>
55 * <dt>{@link #callAndWait callAndWait}
56 * <dd>Provides identical semantics to the similarly named
57 * <code>HubConnection</code> method, but communicates with the hub
58 * asynchronously and fakes the synchrony at the client end.
59 * This is more robust and almost certainly a better idea.
60 * </dd>
61 * <dt>{@link #call call}
62 * <dt>{@link #callAll callAll}
63 * <dd>Convenience methods to make asynchronous calls without having to
64 * worry about registering handlers which match up message tags.
65 * </dd>
66 *
67 * </dl>
68 *
69 * <p>It is good practice to call {@link #setActive setActive(false)}
70 * when this object is finished with; however if it is not called
71 * explicitly, any open connection will unregister itself on
72 * object finalisation or JVM termination, as long as the JVM shuts
73 * down cleanly.
74 *
75 * <h3>Examples</h3>
76 * Here is an example of what use of this class might look like:
77 * <pre>
78 * // Construct a connector
79 * ClientProfile profile = DefaultClientProfile.getProfile();
80 * HubConnector conn = new HubConnector(profile)
81 *
82 * // Configure it with metadata about this application
83 * Metadata meta = new Metadata();
84 * meta.setName("Foo");
85 * meta.setDescriptionText("Application that does stuff");
86 * conn.declareMetadata(meta);
87 *
88 * // Prepare to receive messages with specific MType(s)
89 * conn.addMessageHandler(new AbstractMessageHandler("stuff.do") {
90 * public Map processCall(HubConnection c, String senderId, Message msg) {
91 * // do stuff
92 * }
93 * });
94 *
95 * // This step required even if no custom message handlers added.
96 * conn.declareSubscriptions(conn.computeSubscriptions());
97 *
98 * // Keep a look out for hubs if initial one shuts down
99 * conn.setAutoconnect(10);
100 *
101 * // Broadcast a message
102 * conn.getConnection().notifyAll(new Message("stuff.event.doing"));
103 * </pre>
104 *
105 * <p>A real example, including use of the GUI hooks, can be found in the
106 * {@link org.astrogrid.samp.gui.HubMonitor} client source code.
107 *
108 * <h3>Backwards Compatibility Note</h3>
109 * This class does less than it did in earlier versions;
110 * the functionality which is no longer here can now be found in the
111 * {@link org.astrogrid.samp.gui.GuiHubConnector} class instead.
112 *
113 * @author Mark Taylor
114 * @since 15 Jul 2008
115 */
116 public class HubConnector {
117
118 private final ClientProfile profile_;
119 private final TrackedClientSet clientSet_;
120 private final List messageHandlerList_;
121 private final List responseHandlerList_;
122 private final ConnectorCallableClient callable_;
123 private final Map responseMap_;
124 private final ClientTracker clientTracker_;
125 private final CallHandler callHandler_;
126 private volatile boolean isActive_;
127 private volatile HubConnection connection_;
128 private volatile Metadata metadata_;
129 private volatile Subscriptions subscriptions_;
130 private volatile int autoSec_;
131 private volatile Timer regTimer_;
132 private volatile int iCall_;
133 private final Logger logger_ =
134 Logger.getLogger( HubConnector.class.getName() );
135
136 private static final String SHUTDOWN_MTYPE = "samp.hub.event.shutdown";
137 private static final String DISCONNECT_MTYPE = "samp.hub.disconnect";
138 private static final String PING_MTYPE = "samp.app.ping";
139 private static final String GETENV_MTYPE = "client.env.get";
140
141 /**
142 * Constructs a HubConnector based on a given profile instance.
143 * A default client set implementation is used.
144 *
145 * @param profile profile implementation
146 */
147 public HubConnector( ClientProfile profile ) {
148 this( profile, new TrackedClientSet() );
149 }
150
151 /**
152 * Constructs a HubConnector based on a given profile instance
153 * using a custom client set implementation.
154 *
155 * @param profile profile implementation
156 * @param clientSet object to keep track of registered clients
157 */
158 public HubConnector( ClientProfile profile, TrackedClientSet clientSet ) {
159 profile_ = profile;
160 clientSet_ = clientSet;
161 isActive_ = true;
162
163 // Set up data structures.
164 messageHandlerList_ = Collections.synchronizedList( new ArrayList() );
165 responseHandlerList_ = Collections.synchronizedList( new ArrayList() );
166 callable_ = new ConnectorCallableClient();
167 responseMap_ = Collections.synchronizedMap( new HashMap() );
168
169 // Listen out for events describing changes to registered clients.
170 clientTracker_ = new ClientTracker( clientSet_ );
171 addMessageHandler( clientTracker_ );
172
173 // Listen out for hub shutdown events.
174 addMessageHandler( new AbstractMessageHandler( SHUTDOWN_MTYPE ) {
175 public Map processCall( HubConnection connection,
176 String senderId, Message message ) {
177 String mtype = message.getMType();
178 assert SHUTDOWN_MTYPE.equals( mtype );
179 checkHubMessage( connection, senderId, mtype );
180 disconnect();
181 return null;
182 }
183 } );
184
185 // Listen out for forcible disconnection events.
186 addMessageHandler( new AbstractMessageHandler( DISCONNECT_MTYPE ) {
187 public Map processCall( HubConnection connection,
188 String senderId, Message message ) {
189 String mtype = message.getMType();
190 assert DISCONNECT_MTYPE.equals( mtype );
191 if ( senderId.equals( connection.getRegInfo().getHubId() ) ) {
192 Object reason = message.getParam( "reason" );
193 logger_.warning( "Forcible disconnect from hub"
194 + ( reason == null ? " [no reason given]"
195 : " (" + reason + ")" ) );
196 disconnect();
197 isActive_ = false;
198 return null;
199 }
200 else {
201 throw new IllegalArgumentException( "Ignoring " + mtype
202 + " message from non-hub"
203 + " client " + senderId );
204 }
205 }
206 } );
207
208 // Implement samp.app.ping MType.
209 addMessageHandler( new AbstractMessageHandler( PING_MTYPE ) {
210 public Map processCall( HubConnection connection,
211 String senderId, Message message )
212 throws InterruptedException {
213 String waitMillis = (String) message.getParam( "waitMillis" );
214 if ( waitMillis != null ) {
215 Object lock = new Object();
216 synchronized ( lock ) {
217 lock.wait( SampUtils.decodeInt( waitMillis ) );
218 }
219 }
220 return null;
221 }
222 } );
223
224 // Implement client.env.get MType.
225 addMessageHandler( new AbstractMessageHandler( GETENV_MTYPE ) {
226 public Map processCall( HubConnection connection,
227 String senderId, Message message ) {
228 String name = (String) message.getParam( "name" );
229 String value = Platform.getPlatform().getEnv( name );
230 Map result = new HashMap();
231 result.put( "value", value == null ? "" : value );
232 return result;
233 };
234 } );
235
236 // Listen out for responses to calls for which we are providing
237 // faked synchronous call behaviour.
238 addResponseHandler( new ResponseHandler() {
239 public boolean ownsTag( String msgTag ) {
240 return responseMap_.containsKey( msgTag );
241 }
242 public void receiveResponse( HubConnection connection,
243 String responderId, String msgTag,
244 Response response ) {
245 synchronized ( responseMap_ ) {
246 if ( responseMap_.containsKey( msgTag ) &&
247 responseMap_.get( msgTag ) == null ) {
248 responseMap_.put( msgTag, response );
249 responseMap_.notifyAll();
250 }
251 }
252 }
253 } );
254
255 // Listen out for responses to calls for which we have agreed to
256 // pass results to user-supplied ResultHandler objects.
257 callHandler_ = new CallHandler();
258 addResponseHandler( callHandler_ );
259 }
260
261 /**
262 * Sets the interval at which this connector attempts to connect to a
263 * hub if no connection currently exists.
264 * Otherwise, a connection will be attempted whenever
265 * {@link #getConnection} is called.
266 *
267 * @param autoSec number of seconds between attempts;
268 * &lt;=0 means no automatic connections are attempted
269 */
270 public synchronized void setAutoconnect( int autoSec ) {
271 autoSec_ = autoSec;
272 configureRegisterTimer( autoSec_ );
273 }
274
275 /**
276 * Configures a timer thread to attempt registration periodically.
277 *
278 * @param autoSec number of seconds between attempts;
279 * &lt;=0 means no automatic connections are attempted
280 */
281 private synchronized void configureRegisterTimer( int autoSec ) {
282
283 // Cancel and remove any existing auto-connection timer.
284 if ( regTimer_ != null ) {
285 regTimer_.cancel();
286 regTimer_ = null;
287 }
288
289 // If required, install a new one.
290 if ( autoSec > 0 ) {
291 TimerTask regTask = new TimerTask() {
292 public void run() {
293 if ( ! isConnected() ) {
294 try {
295 HubConnection conn = getConnection();
296 if ( conn == null ) {
297 logger_.config( "SAMP autoconnection attempt "
298 + "failed" );
299 }
300 else {
301 logger_.info( "SAMP autoconnection attempt "
302 + "succeeded" );
303 }
304 }
305 catch ( SampException e ) {
306 logger_.config( "SAMP Autoconnection attempt "
307 + " failed: " + e );
308 }
309 }
310 }
311 };
312 regTimer_ = new Timer( true );
313 regTimer_.schedule( regTask, 0, autoSec_ * 1000 );
314 }
315 }
316
317 /**
318 * Declares the metadata for this client.
319 * This declaration affects the current connection and any future ones.
320 *
321 * @param meta {@link org.astrogrid.samp.Metadata}-like map
322 */
323 public void declareMetadata( Map meta ) {
324 Metadata md = Metadata.asMetadata( meta );
325 md.check();
326 metadata_ = md;
327 if ( isConnected() ) {
328 try {
329 connection_.declareMetadata( md );
330 }
331 catch ( SampException e ) {
332 logger_.log( Level.WARNING,
333 "SAMP metadata declaration failed", e );
334 }
335 }
336 }
337
338 /**
339 * Returns this client's own metadata.
340 *
341 * @return metadata
342 */
343 public Metadata getMetadata() {
344 return metadata_;
345 }
346
347 /**
348 * Declares the MType subscriptions for this client.
349 * This declaration affects the current connection and any future ones.
350 *
351 * <p>Note that this call must be made, with a subscription list
352 * which includes the various hub administrative messages, in order
353 * for this connector to act on those messages (for instance to
354 * update its client map and so on). For this reason, it is usual
355 * to call it with the <code>subs</code> argument given by
356 * the result of calling {@link #computeSubscriptions}.
357 *
358 * @param subscriptions {@link org.astrogrid.samp.Subscriptions}-like map
359 */
360 public void declareSubscriptions( Map subscriptions ) {
361 Subscriptions subs = Subscriptions.asSubscriptions( subscriptions );
362 subs.check();
363 subscriptions_ = subs;
364 if ( isConnected() ) {
365 try {
366 connection_.declareSubscriptions( subs );
367 }
368 catch ( SampException e ) {
369 logger_.log( Level.WARNING, "Subscriptions declaration failed",
370 e );
371 }
372 }
373 }
374
375 /**
376 * Returns this client's own subscriptions.
377 *
378 * @return subscriptions
379 */
380 public Subscriptions getSubscriptions() {
381 return subscriptions_;
382 }
383
384 /**
385 * Works out the subscriptions map for this connector.
386 * This is based on the subscriptions declared by for any
387 * {@link MessageHandler}s installed in this connector as well as
388 * any MTypes which this connector implements internally.
389 * The result of this method is usually a suitable value to pass
390 * to {@link #declareSubscriptions}. However you might wish to
391 * remove some entries from the result if there are temporarily
392 * unsubscribed services.
393 *
394 * @return subscription list for MTypes apparently implemented by this
395 * connector
396 */
397 public Subscriptions computeSubscriptions() {
398 MessageHandler[] mhandlers =
399 (MessageHandler[])
400 messageHandlerList_.toArray( new MessageHandler[ 0 ] );
401 Map subs = new HashMap();
402 for ( int ih = mhandlers.length - 1; ih >= 0; ih-- ) {
403 subs.putAll( mhandlers[ ih ].getSubscriptions() );
404 }
405 return Subscriptions.asSubscriptions( subs );
406 }
407
408 /**
409 * Adds a MessageHandler to this connector, which allows it to respond
410 * to incoming messages.
411 * Note that this does not in itself update the list of subscriptions
412 * for this connector; you may want to follow it with a call to
413 * <pre>
414 * declareSubscriptions(computeSubscriptions());
415 * </pre>
416 *
417 * @param handler handler to add
418 */
419 public void addMessageHandler( MessageHandler handler ) {
420 messageHandlerList_.add( handler );
421 }
422
423 /**
424 * Removes a previously-added MessageHandler to this connector.
425 * Note that this does not in itself update the list of subscriptions
426 * for this connector; you may want to follow it with a call to
427 * <pre>
428 * declareSubscriptions(computeSubscriptions());
429 * </pre>
430 *
431 * @param handler handler to remove
432 */
433 public void removeMessageHandler( MessageHandler handler ) {
434 messageHandlerList_.remove( handler );
435 }
436
437 /**
438 * Adds a ResponseHandler to this connector, which allows it to receive
439 * replies from messages sent asynchronously.
440 *
441 * <p>Note however that this class's {@link #callAndWait callAndWait} method
442 * can provide a synchronous facade for fully asynchronous messaging,
443 * which in many cases will be more convenient than installing your
444 * own response handlers to deal with asynchronous replies.
445 *
446 * @param handler handler to add
447 */
448 public void addResponseHandler( ResponseHandler handler ) {
449 responseHandlerList_.add( handler );
450 }
451
452 /**
453 * Removes a ResponseHandler from this connector.
454 *
455 * @param handler handler to remove
456 */
457 public void removeResponseHandler( ResponseHandler handler ) {
458 responseHandlerList_.remove( handler );
459 }
460
461 /**
462 * Sets whether this connector is active or not.
463 * If set false, any existing connection will be terminated (the client
464 * will unregister) and autoconnection attempts will be suspended.
465 * If set true, if there is no existing connection an attempt will be
466 * made to register, and autoconnection attempts will begin if applicable.
467 *
468 * @param active whether this connector should be active
469 * @see #setAutoconnect
470 */
471 public void setActive( boolean active ) {
472 isActive_ = active;
473 if ( active ) {
474 if ( connection_ == null ) {
475 try {
476 getConnection();
477 }
478 catch ( SampException e ) {
479 logger_.log( Level.WARNING,
480 "Hub connection attempt failed", e );
481 }
482 }
483 configureRegisterTimer( autoSec_ );
484 }
485 else {
486 HubConnection connection = connection_;
487 if ( connection != null ) {
488 disconnect();
489 try {
490 connection.unregister();
491 }
492 catch ( SampException e ) {
493 logger_.log( Level.INFO, "Unregister attempt failed", e );
494 }
495 }
496 configureRegisterTimer( 0 );
497 }
498 }
499
500 /**
501 * Indicates whether this connector is active or not.
502 *
503 * @return true if this connector is willing to connect
504 */
505 public boolean isActive() {
506 return isActive_;
507 }
508
509 /**
510 * Sends a message synchronously to a client, waiting for the response.
511 * If more seconds elapse than the value of the <code>timeout</code>
512 * parameter, an exception will result.
513 *
514 * <p>The semantics of this call are, as far as the caller is concerned,
515 * identical to that of the similarly named {@link HubConnection} method.
516 * However, in this case the client communicates with the hub
517 * asynchronously and internally simulates the synchrony for the caller,
518 * rather than letting the hub do that.
519 * This is more robust and almost certainly a better idea.
520 *
521 * @param recipientId public-id of client to receive message
522 * @param msg {@link org.astrogrid.samp.Message}-like map
523 * @param timeout timeout in seconds, or &lt;=0 for no timeout
524 * @return response
525 */
526 public Response callAndWait( String recipientId, Map msg, int timeout )
527 throws SampException {
528 long finish = timeout > 0
529 ? System.currentTimeMillis() + timeout * 1000
530 : Long.MAX_VALUE; // 3e8 years
531 HubConnection connection = getConnection();
532 String msgTag = createTag( this );
533 responseMap_.put( msgTag, null );
534 connection.call( recipientId, msgTag, msg );
535 synchronized ( responseMap_ ) {
536 while ( responseMap_.containsKey( msgTag ) &&
537 responseMap_.get( msgTag ) == null &&
538 System.currentTimeMillis() < finish ) {
539 long millis = finish - System.currentTimeMillis();
540 if ( millis > 0 ) {
541 try {
542 responseMap_.wait( millis );
543 }
544 catch ( InterruptedException e ) {
545 throw new SampException( "Wait interrupted", e );
546 }
547 }
548 }
549 if ( responseMap_.containsKey( msgTag ) ) {
550 Response response = (Response) responseMap_.remove( msgTag );
551 if ( response != null ) {
552 return response;
553 }
554 else {
555 assert System.currentTimeMillis() >= finish;
556 throw new SampException( "Synchronous call timeout" );
557 }
558 }
559 else {
560 if ( connection != connection_ ) {
561 throw new SampException( "Hub connection lost" );
562 }
563 else {
564 throw new AssertionError();
565 }
566 }
567 }
568 }
569
570 /**
571 * Sends a message asynchronously to a single client, making a callback
572 * on a supplied ResultHandler object when the result arrives.
573 * The {@link org.astrogrid.samp.client.ResultHandler#done} method will
574 * be called after the result has arrived or the timeout elapses,
575 * whichever happens first.
576 *
577 * <p>This convenience method allows the user to make an asynchronous
578 * call without having to worry registering message handlers and
579 * matching message tags.
580 *
581 * @param recipientId public-id of client to receive message
582 * @param msg {@link org.astrogrid.samp.Message}-like map
583 * @param resultHandler object called back when response arrives or
584 * timeout is exceeded
585 * @param timeout timeout in seconds, or &lt;=0 for no timeout
586 */
587 public void call( String recipientId, Map msg, ResultHandler resultHandler,
588 int timeout ) throws SampException {
589 HubConnection connection = getConnection();
590 if ( connection == null ) {
591 throw new SampException( "Not connected" );
592 }
593 String tag = createTag( this );
594 callHandler_.registerHandler( tag, resultHandler, timeout );
595 try {
596 connection.call( recipientId, tag, msg );
597 callHandler_.setRecipients( tag, new String[] { recipientId, } );
598 }
599 catch ( SampException e ) {
600 callHandler_.unregisterHandler( tag );
601 throw e;
602 }
603 }
604
605 /**
606 * Sends a message asynchronously to all subscribed clients,
607 * making callbacks on a supplied ResultHandler object when the
608 * results arrive.
609 * The {@link org.astrogrid.samp.client.ResultHandler#done} method will
610 * be called after all the results have arrived or the timeout elapses,
611 * whichever happens first.
612 *
613 * <p>This convenience method allows the user to make an asynchronous
614 * call without having to worry registering message handlers and
615 * matching message tags.
616 *
617 * @param msg {@link org.astrogrid.samp.Message}-like map
618 * @param resultHandler object called back when response arrives or
619 * timeout is exceeded
620 * @param timeout timeout in seconds, or &lt;=0 for no timeout
621 */
622 public void callAll( Map msg, ResultHandler resultHandler, int timeout )
623 throws SampException {
624 HubConnection connection = getConnection();
625 if ( connection == null ) {
626 throw new SampException( "Not connected" );
627 }
628 String tag = createTag( this );
629 callHandler_.registerHandler( tag, resultHandler, timeout );
630 try {
631 Map callMap = connection.callAll( tag, msg );
632 callHandler_.setRecipients( tag,
633 (String[])
634 callMap.keySet()
635 .toArray( new String[ 0 ] ) );
636 }
637 catch ( SampException e ) {
638 callHandler_.unregisterHandler( tag );
639 throw e;
640 }
641 }
642
643 /**
644 * Indicates whether this connector is currently registered with a
645 * running hub.
646 * If true, the result of {@link #getConnection} will be non-null.
647 *
648 * @return true if currently connected to a hub
649 */
650 public boolean isConnected() {
651 return connection_ != null;
652 }
653
654 /**
655 * If necessary attempts to acquire, and returns, a connection to a
656 * running hub.
657 * If there is an existing connection representing a registration
658 * with a hub, it is returned. If not, and this connector is active,
659 * an attempt is made to connect and register, followed by a call to
660 * {@link #configureConnection configureConnection}, is made.
661 *
662 * <p>Note that if {@link #setActive setActive(false)} has been called,
663 * null will be returned.
664 *
665 * @return hub connection representing configured registration with a hub
666 * if a hub is running; if not, null
667 * @throws SampException in the case of some unexpected error
668 */
669 public HubConnection getConnection() throws SampException {
670 HubConnection connection = connection_;
671 if ( connection == null && isActive_ ) {
672 connection = createConnection();
673 if ( connection != null ) {
674 connection_ = connection;
675 configureConnection( connection );
676 clientTracker_.initialise( connection );
677 connectionChanged( true );
678 }
679 }
680 return connection;
681 }
682
683 /**
684 * Configures a connection with a hub in accordance with the state of
685 * this object.
686 * The hub is made aware of how to perform callbacks on the registered
687 * client, and any current metadata and subscriptions are declared.
688 *
689 * @param connection connection representing registration with a hub
690 */
691 public void configureConnection( HubConnection connection )
692 throws SampException {
693 if ( metadata_ != null ) {
694 connection.declareMetadata( metadata_ );
695 }
696 if ( callable_ != null ) {
697 connection.setCallable( callable_ );
698 callable_.setConnection( connection );
699 if ( subscriptions_ != null ) {
700 connection.declareSubscriptions( subscriptions_ );
701 }
702 }
703 }
704
705 /**
706 * Returns a map which keeps track of other clients currently registered
707 * with the hub to which this object is connected, including their
708 * currently declared metadata and subscriptions.
709 * Map keys are public IDs and values are
710 * {@link org.astrogrid.samp.Client}s.
711 *
712 * <p>This map is {@link java.util.Collections#synchronizedMap synchronized}
713 * which means that to iterate over any of its views
714 * you must synchronize on it.
715 * When the map or any of its contents changes, it will receive a
716 * {@link java.lang.Object#notifyAll}.
717 *
718 * <p>To keep itself up to date, the client map reads hub status messages.
719 * These will only be received if
720 * <code>declareSubscriptions(computeSubscriptions())</code> has been
721 * called.
722 * Hence, this method should only be called after
723 * {@link #declareSubscriptions} has been called.
724 * If this order is not observed, a warning will be emitted through
725 * the logging system.
726 *
727 * @return id->Client map
728 */
729 public Map getClientMap() {
730 if ( subscriptions_ == null ) {
731 logger_.warning( "Danger: you should call declareSubscriptions "
732 + "before using client map" );
733 }
734 return getClientSet().getClientMap();
735 }
736
737 /**
738 * Returns the tracked client set implementation which is used to keep
739 * track of the currently registered clients.
740 *
741 * @return client set implementation
742 */
743 protected TrackedClientSet getClientSet() {
744 return clientSet_;
745 }
746
747 /**
748 * Invoked by this class to create a hub connection.
749 * The default implementation just calls <code>profile.register()</code>.
750 *
751 * @return new hub connection
752 */
753 protected HubConnection createConnection() throws SampException {
754 return profile_.register();
755 }
756
757 /**
758 * Unregisters from the currently connected hub, if any.
759 * Performs any associated required cleanup.
760 */
761 protected void disconnect() {
762 boolean wasConnected = connection_ != null;
763 connection_ = null;
764 clientTracker_.clear();
765 callHandler_.stopTimeouter();
766 synchronized ( responseMap_ ) {
767 responseMap_.clear();
768 responseMap_.notifyAll();
769 }
770 if ( wasConnected ) {
771 connectionChanged( false );
772 }
773 }
774
775 /**
776 * Method which is called every time this connector changes its connection
777 * status (from disconnected to connected, or vice versa).
778 * The default implementation does nothing, but it may be overridden
779 * by subclasses wishing to be informed of these events.
780 *
781 * @param isConnected true if we've just registered;
782 * false if we've just unregistered
783 */
784 protected void connectionChanged( boolean isConnected ) {
785 }
786
787 /**
788 * Performs sanity checking on a message which is normally expected to
789 * be sent only by the hub client itself.
790 *
791 * @param connection connection to the hub
792 * @param senderId public client id of sender
793 * @param mtype MType of sent message
794 */
795 private void checkHubMessage( HubConnection connection, String senderId,
796 String mtype ) {
797 if ( ! senderId.equals( connection.getRegInfo().getHubId() ) ) {
798 logger_.warning( "Hub admin message " + mtype + " received from "
799 + "non-hub client. Acting on it anyhow" );
800 }
801 }
802
803 /**
804 * Generates a new <code>msgTag</code> for use with this connector.
805 * It is guaranteed to return a different value on each invocation.
806 * It is advisable to use this method whenever a message tag is required
807 * to prevent clashes.
808 *
809 * @param owner object to identify caller
810 * (not really necessary - may be null)
811 * @return unique tag for this connector
812 */
813 public synchronized String createTag( Object owner ) {
814 return ( owner == null ? "tag"
815 : ( String.valueOf( owner ) + ":" ) )
816 + ++iCall_;
817 }
818
819 /**
820 * CallableClient implementation used by this class.
821 */
822 private class ConnectorCallableClient implements CallableClient {
823
824 private HubConnection conn_;
825
826 /**
827 * Sets the currently active hub connection.
828 *
829 * @param connection connection
830 */
831 private void setConnection( HubConnection connection ) {
832 conn_ = connection;
833 }
834
835 public void receiveNotification( String senderId, Message message ) {
836
837 // Offer the notification to each registered MessageHandler in turn.
838 // It may in principle get processed by more than one.
839 // This is almost certainly harmless.
840 MessageHandler[] mhandlers =
841 (MessageHandler[])
842 messageHandlerList_.toArray( new MessageHandler[ 0 ] );
843 for ( int ih = 0; ih < mhandlers.length; ih++ ) {
844 MessageHandler handler = mhandlers[ ih ];
845 Subscriptions subs =
846 Subscriptions.asSubscriptions( handler.getSubscriptions() );
847 String mtype = message.getMType();
848 if ( subs.isSubscribed( mtype ) ) {
849 try {
850 handler.receiveNotification( conn_, senderId, message );
851 }
852 catch ( Throwable e ) {
853 logger_.log( Level.WARNING,
854 "Notify handler failed " + mtype, e );
855 }
856 }
857 }
858 }
859
860 public void receiveCall( String senderId, String msgId,
861 Message message ) {
862
863 // Offer the call to each registered MessageHandler in turn.
864 // Since only one should be allowed to respond to it, only
865 // the first one which bites is allowed to process it.
866 String mtype = message.getMType();
867 ErrInfo errInfo = null;
868 MessageHandler[] mhandlers =
869 (MessageHandler[])
870 messageHandlerList_.toArray( new MessageHandler[ 0 ] );
871 for ( int ih = 0; ih < mhandlers.length; ih++ ) {
872 MessageHandler handler = mhandlers[ ih ];
873 Subscriptions subs =
874 Subscriptions.asSubscriptions( handler.getSubscriptions() );
875 if ( subs.isSubscribed( mtype ) ) {
876 try {
877 handler.receiveCall( conn_, senderId, msgId, message );
878 return;
879 }
880 catch ( Throwable e ) {
881 errInfo = new ErrInfo( e );
882 logger_.log( Level.WARNING,
883 "Call handler failed " + mtype, e );
884 }
885 }
886 }
887 if ( errInfo == null ) {
888 logger_.warning( "No handler for subscribed MType " + mtype );
889 errInfo = new ErrInfo( "No handler found" );
890 errInfo.setUsertxt( "No handler was found for the supplied"
891 + " MType. "
892 + "Looks like a programming error "
893 + "at the recipient end. Sorry." );
894 }
895 Response response = Response.createErrorResponse( errInfo );
896 response.check();
897 try {
898 conn_.reply( msgId, response );
899 }
900 catch ( SampException e ) {
901 logger_.warning( "Failed to reply to " + msgId );
902 }
903 }
904
905 public void receiveResponse( String responderId, String msgTag,
906 Response response ) {
907
908 // Offer the response to each registered ResponseHandler in turn.
909 // It shouldn't be processed by more than one, but if it is,
910 // warn about it.
911 int handleCount = 0;
912 ResponseHandler[] rhandlers =
913 (ResponseHandler[])
914 responseHandlerList_.toArray( new ResponseHandler[ 0 ] );
915 for ( int ih = 0; ih < rhandlers.length; ih++ ) {
916 ResponseHandler handler = rhandlers[ ih ];
917 if ( handler.ownsTag( msgTag ) ) {
918 handleCount++;
919 try {
920 handler.receiveResponse( conn_, responderId, msgTag,
921 response );
922 }
923 catch ( Exception e ) {
924 logger_.log( Level.WARNING, "Response handler failed",
925 e );
926 }
927 }
928 }
929 if ( handleCount == 0 ) {
930 logger_.warning( "No handler for message "
931 + msgTag + " response" );
932 }
933 else if ( handleCount > 1 ) {
934 logger_.warning( "Multiple (" + handleCount + ")"
935 + " handlers handled message "
936 + msgTag + " respose" );
937 }
938 }
939 }
940
941 /**
942 * ResponseHandler which looks after responses made by calls using the
943 * call() and callAll() convenience methods.
944 */
945 private class CallHandler implements ResponseHandler {
946 private final SortedMap tagMap_;
947 private Thread timeouter_;
948
949 /**
950 * Constructor.
951 */
952 CallHandler() {
953
954 // Set up a structure to contain tag->CallItem entries for
955 // responses we are expecting. They are arranged in order of
956 // which is going to time out soonest.
957 tagMap_ = new TreeMap();
958 }
959
960 /**
961 * Ensures that a thread is running to wake up when the next timeout
962 * has (or at least might have) happened.
963 */
964 private void readyTimeouter() {
965 synchronized ( tagMap_ ) {
966 if ( timeouter_ == null ) {
967 timeouter_ = new Thread( "ResultHandler timeout watcher" ) {
968 public void run() {
969 watchTimeouts();
970 }
971 };
972 timeouter_.setDaemon( true );
973 timeouter_.start();
974 }
975 }
976 }
977
978 /**
979 * Stops any current timeout watcher operating on behalf of this
980 * handler and tidies up associated resources.
981 */
982 private void stopTimeouter() {
983 synchronized ( tagMap_ ) {
984 if ( timeouter_ != null ) {
985 timeouter_.interrupt();
986 }
987 timeouter_ = null;
988 tagMap_.clear();
989 }
990 }
991
992 /**
993 * Runs in a daemon thread to watch out for timeouts that might
994 * have occurred.
995 */
996 private void watchTimeouts() {
997 while ( ! Thread.currentThread().isInterrupted() ) {
998 synchronized ( tagMap_ ) {
999
1000 // Wait until the next scheduled timeout is expected.
1001 long nextFinish =
1002 tagMap_.isEmpty() ? Long.MAX_VALUE
1003 : ((CallItem)
1004 tagMap_.get( tagMap_.firstKey() ))
1005 .finish_;
1006 final long delay = nextFinish - System.currentTimeMillis();
1007 if ( delay > 0 ) {
1008 try {
1009 tagMap_.wait( delay );
1010 }
1011 catch ( InterruptedException e ) {
1012 Thread.currentThread().interrupt();
1013 }
1014 }
1015
1016 // Then process any timeouts that are pending.
1017 long now = System.currentTimeMillis();
1018 for ( Iterator it = tagMap_.entrySet().iterator();
1019 it.hasNext(); ) {
1020 Map.Entry entry = (Map.Entry) it.next();
1021 CallItem item = (CallItem) entry.getValue();
1022 if ( now >= item.finish_ ) {
1023 item.handler_.done();
1024 it.remove();
1025 }
1026 }
1027 }
1028 }
1029 }
1030
1031 /**
1032 * Stores a ResultHandler object which will take delivery of the
1033 * responses tagged with a given tag.
1034 *
1035 * @param tag message tag identifying send/response
1036 * @param handler callback object
1037 * @param timeout milliseconds before forcing completion
1038 */
1039 public void registerHandler( String tag, ResultHandler handler,
1040 int timeout ) {
1041 long finish = timeout > 0
1042 ? System.currentTimeMillis() + timeout * 1000
1043 : Long.MAX_VALUE; // 3e8 years
1044 CallItem item = new CallItem( handler, finish );
1045 if ( ! item.isDone() ) {
1046 synchronized ( tagMap_ ) {
1047 readyTimeouter();
1048 tagMap_.put( tag, item );
1049 tagMap_.notifyAll();
1050 }
1051 }
1052 else {
1053 handler.done();
1054 }
1055 }
1056
1057 /**
1058 * Set the recipients from which we are expecting responses.
1059 * Once all are in, the handler can be disposed of.
1060 *
1061 * @param tag message tag identifying send/response
1062 * @param recipients clients expected to reply
1063 */
1064 public void setRecipients( String tag, String[] recipients ) {
1065 CallItem item;
1066 synchronized ( tagMap_ ) {
1067 item = (CallItem) tagMap_.get( tag );
1068 }
1069 item.setRecipients( recipients );
1070 retireIfDone( tag, item );
1071 }
1072
1073 /**
1074 * Unregister a handler for which no responses are expected.
1075 *
1076 * @param tag message tag identifying send/response
1077 */
1078 public void unregisterHandler( String tag ) {
1079 synchronized ( tagMap_ ) {
1080 tagMap_.remove( tag );
1081 }
1082 }
1083
1084 public boolean ownsTag( String tag ) {
1085 synchronized ( tagMap_ ) {
1086 return tagMap_.containsKey( tag );
1087 }
1088 }
1089
1090 public void receiveResponse( HubConnection connection,
1091 String responderId, String msgTag,
1092 Response response ) {
1093 final CallItem item;
1094 synchronized ( tagMap_ ) {
1095 item = (CallItem) tagMap_.get( msgTag );
1096 }
1097 if ( item != null ) {
1098 item.addResponse( responderId, response );
1099 retireIfDone( msgTag, item );
1100 }
1101 }
1102
1103 /**
1104 * Called when a tag/handler entry might be ready to finish with.
1105 */
1106 private void retireIfDone( String tag, CallItem item ) {
1107 if ( item.isDone() ) {
1108 synchronized ( tagMap_ ) {
1109 item.handler_.done();
1110 tagMap_.remove( tag );
1111 }
1112 }
1113 }
1114 }
1115
1116 /**
1117 * Stores state about a particular set of responses expected by the
1118 * CallHandler class.
1119 */
1120 private class CallItem implements Comparable {
1121 final ResultHandler handler_;
1122 final long finish_;
1123 volatile Map responseMap_; // responderId -> Response
1124 volatile Map recipientMap_; // responderId -> Client
1125
1126 /**
1127 * Constructor.
1128 *
1129 * @param handler callback object
1130 * @param finish epoch at which timeout should be called
1131 */
1132 CallItem( ResultHandler handler, long finish ) {
1133 handler_ = handler;
1134 finish_ = finish;
1135 }
1136
1137 /**
1138 * Sets the recipient Ids for which responses are expected.
1139 *
1140 * @param recipientIds recipient client ids
1141 */
1142 public synchronized void setRecipients( String[] recipientIds ) {
1143 recipientMap_ = new HashMap();
1144
1145 // Store client objects for each recipient ID. Note however
1146 // because of various synchrony issues we can't guarantee that
1147 // all these client objects can be determined - some may be null.
1148 // Store the ids as keys in any case.
1149 Map clientMap = getClientMap();
1150 for ( int ir = 0; ir < recipientIds.length; ir++ ) {
1151 String id = recipientIds[ ir ];
1152 Client client = (Client) clientMap.get( id );
1153 recipientMap_.put( id, client );
1154 }
1155
1156 // If we have pending responses (couldn't be processed earlier
1157 // because no recipients), take care of them now.
1158 if ( responseMap_ != null ) {
1159 for ( Iterator it = responseMap_.entrySet().iterator();
1160 it.hasNext(); ) {
1161 Map.Entry entry = (Map.Entry) it.next();
1162 String responderId = (String) entry.getKey();
1163 Response response = (Response) entry.getValue();
1164 processResponse( responderId, response );
1165 }
1166 responseMap_ = null;
1167 }
1168 }
1169
1170 /**
1171 * Take delivery of a response object.
1172 *
1173 * @param responderId client ID of responder
1174 * @param response response object
1175 */
1176 public synchronized void addResponse( String responderId,
1177 Response response ) {
1178
1179 // If we know the recipients, deal with it now.
1180 if ( recipientMap_ != null ) {
1181 processResponse( responderId, response );
1182 }
1183
1184 // Otherwise, defer until we do know the recipients.
1185 else {
1186 if ( responseMap_ == null ) {
1187 responseMap_ = new HashMap();
1188 }
1189 responseMap_.put( responderId, response );
1190 }
1191 }
1192
1193 /**
1194 * Process a response when we have both the list of recipients
1195 * and the response itself.
1196 *
1197 * @param responderId client ID of responder
1198 * @param response response object
1199 */
1200 private synchronized void processResponse( final String responderId,
1201 Response response ) {
1202 if ( recipientMap_.containsKey( responderId ) ) {
1203
1204 // Get a client object. We have to try belt and braces.
1205 Client client = (Client) recipientMap_.get( responderId );
1206 if ( client == null ) {
1207 client = (Client) getClientMap().get( responderId );
1208 }
1209 if ( client == null ) {
1210 client = new Client() {
1211 public String getId() {
1212 return responderId;
1213 }
1214 public Metadata getMetadata() {
1215 return null;
1216 }
1217 public Subscriptions getSubscriptions() {
1218 return null;
1219 }
1220 };
1221 }
1222
1223 // Make the callback to the supplied handler.
1224 handler_.result( client, response );
1225
1226 // Note that we've done this one.
1227 recipientMap_.remove( responderId );
1228 }
1229 }
1230
1231 /**
1232 * Indicate whether this call item has received all the responses it's
1233 * going to.
1234 *
1235 * @return iff no further activity is expected
1236 */
1237 public synchronized boolean isDone() {
1238 return ( recipientMap_ != null && recipientMap_.isEmpty() )
1239 || System.currentTimeMillis() >= finish_;
1240 }
1241
1242 /**
1243 * Compares on timeout epochs.
1244 * Implementation is <em>consistent with equals</em>,
1245 * which means it's OK to use them in a SortedMap.
1246 */
1247 public int compareTo( Object o ) {
1248 CallItem other = (CallItem) o;
1249 if ( this.finish_ < other.finish_ ) {
1250 return -1;
1251 }
1252 else if ( this.finish_ > other.finish_ ) {
1253 return +1;
1254 }
1255 else {
1256 return System.identityHashCode( this )
1257 - System.identityHashCode( other );
1258 }
1259 }
1260 }
1261 }