Debian Codegraph @

src/java/org/astrogrid/samp/hub/BasicHubService.java

raw
1 package org.astrogrid.samp.hub;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Comparator;
6 import java.util.HashMap;
7 import java.util.Iterator;
8 import java.util.List;
9 import java.util.Map;
10 import java.util.Random;
11 import java.util.TreeMap;
12 import java.util.logging.Level;
13 import java.util.logging.Logger;
14 import org.astrogrid.samp.Message;
15 import org.astrogrid.samp.Metadata;
16 import org.astrogrid.samp.RegInfo;
17 import org.astrogrid.samp.Response;
18 import org.astrogrid.samp.Subscriptions;
19 import org.astrogrid.samp.client.AbstractMessageHandler;
20 import org.astrogrid.samp.client.CallableClient;
21 import org.astrogrid.samp.client.HubConnection;
22 import org.astrogrid.samp.client.SampException;
23 import org.astrogrid.samp.httpd.UtilServer;
24
25 /**
26 * HubService implementation.
27 *
28 * @author Mark Taylor
29 * @since 15 Jul 2008
30 */
31 public class BasicHubService implements HubService {
32
33 private final KeyGenerator keyGen_;
34 private final ClientIdGenerator idGen_;
35 private final Map waiterMap_;
36 private ClientSet clientSet_;
37 private HubClient serviceClient_;
38 private HubConnection serviceClientConnection_;
39 private volatile boolean started_;
40 private volatile boolean shutdown_;
41 private static final char ID_DELIMITER = '_';
42 private final Logger logger_ =
43 Logger.getLogger( BasicHubService.class.getName() );
44 private final static ProfileToken INTERNAL_PROFILE = new ProfileToken() {
45 public String getProfileName() {
46 return "Internal";
47 }
48 public MessageRestriction getMessageRestriction() {
49 return null;
50 }
51 };
52
53 /** The maximum timeout for a synchronous call permitted in seconds.
54 * Default is 43200 = 12 hours. */
55 public static int MAX_TIMEOUT = 12 * 60 * 60;
56
57 /** The maximum number of concurrently pending synchronous calls.
58 * Default is 100. */
59 public static int MAX_WAITERS = 100;
60
61 /**
62 * Constructor.
63 *
64 * @param random random number generator used for message tags etc
65 */
66 public BasicHubService( Random random ) {
67
68 // Prepare ID generators.
69 keyGen_ = new KeyGenerator( "m:", 16, random );
70 idGen_ = new ClientIdGenerator( "c" );
71
72 // Prepare the data structure which keeps track of pending synchronous
73 // calls.
74 waiterMap_ = Collections.synchronizedMap( new HashMap() );
75 }
76
77 public void start() {
78
79 // Prepare the data structure which keeps track of registered clients.
80 clientSet_ = createClientSet();
81
82 // Prepare and store the client object which represents the hub itself
83 // (the one that apparently sends samp.hub.event.shutdown messages etc).
84 serviceClient_ = createClient( "hub", INTERNAL_PROFILE );
85 serviceClientConnection_ = createConnection( serviceClient_ );
86 Metadata meta = new Metadata();
87 meta.setName( "Hub" );
88 try {
89 meta.setIconUrl( UtilServer.getInstance()
90 .exportResource( "/org/astrogrid/samp/images/"
91 + "hub.png" )
92 .toString() );
93 }
94 catch ( Throwable e ) {
95 logger_.warning( "Can't set icon" );
96 }
97 meta.put( "author.name", "Mark Taylor" );
98 meta.put( "author.mail", "[email protected]" );
99 meta.setDescriptionText( getClass().getName() );
100 serviceClient_.setMetadata( meta );
101 HubCallableClient hubCallable =
102 new HubCallableClient( serviceClientConnection_,
103 createHubMessageHandlers() );
104 serviceClient_.setCallable( hubCallable );
105 serviceClient_.setSubscriptions( hubCallable.getSubscriptions() );
106 clientSet_.add( serviceClient_ );
107 started_ = true;
108 }
109
110 /**
111 * Factory method used to create the client set used by this hub service.
112 *
113 * @return client set
114 */
115 protected ClientSet createClientSet() {
116 return new BasicClientSet( getIdComparator() ) {
117 public void add( HubClient client ) {
118 assert client.getId().indexOf( ID_DELIMITER ) < 0;
119 super.add( client );
120 }
121 };
122 }
123
124 /**
125 * Factory method used to create all the client objects which will
126 * be used by this hub service.
127 *
128 * @param publicId client public ID
129 * @param ptoken connection source
130 * @return hub client
131 */
132 protected HubClient createClient( String publicId, ProfileToken ptoken ) {
133 return new HubClient( publicId, ptoken );
134 }
135
136 /**
137 * Constructs a list of MessageHandlers to use for the client
138 * provided by the Hub.
139 *
140 * @return hub message handler list
141 */
142 protected AbstractMessageHandler[] createHubMessageHandlers() {
143 return new AbstractMessageHandler[] {
144 new PingMessageHandler(),
145 new MetaQueryMessageHandler( getClientSet() ),
146 };
147 }
148
149 /**
150 * Returns a comparator which will order client IDs.
151 * The ordering is in creation sequence.
152 *
153 * @return public ID comparator
154 */
155 public Comparator getIdComparator() {
156 return idGen_.getComparator();
157 }
158
159 /**
160 * Returns the structure which keeps track of registered clients.
161 *
162 * @return client set
163 */
164 public ClientSet getClientSet() {
165 return clientSet_;
166 }
167
168 public HubConnection register( ProfileToken ptoken ) throws SampException {
169 if ( ! started_ ) {
170 throw new SampException( "Not started" );
171 }
172 HubClient client = createClient( idGen_.next(), ptoken );
173 assert client.getId().indexOf( ID_DELIMITER ) < 0;
174 clientSet_.add( client );
175 hubEvent( new Message( "samp.hub.event.register" )
176 .addParam( "id", client.getId() ) );
177 return createConnection( client );
178 }
179
180 public void disconnectAll( ProfileToken profileToken ) {
181 HubClient[] clients = clientSet_.getClients();
182 List profClientIdList = new ArrayList();
183 for ( int ic = 0; ic < clients.length; ic++ ) {
184 HubClient client = clients[ ic ];
185 if ( profileToken.equals( client.getProfileToken() ) ) {
186 profClientIdList.add( client.getId() );
187 }
188 }
189 disconnect( (String[]) profClientIdList.toArray( new String[ 0 ] ),
190 new Message( "samp.hub.event.shutdown" ) );
191 }
192
193 /**
194 * Returns a new HubConnection for use by a given hub client.
195 * The instance methods of the returned object delegate to similarly
196 * named protected methods of this BasicHubService object.
197 * These BasicHubService methods may therefore be overridden to
198 * modify the behaviour of such returned connections.
199 *
200 * @param caller client requiring a connection
201 * @return connection whose methods may be called by or on behalf of
202 * <code>caller</code>
203 */
204 protected HubConnection createConnection( final HubClient caller ) {
205 final BasicHubService service = this;
206 final RegInfo regInfo = new RegInfo();
207 regInfo.put( RegInfo.HUBID_KEY, serviceClient_.getId() );
208 regInfo.put( RegInfo.SELFID_KEY, caller.getId() );
209 return new HubConnection() {
210 public RegInfo getRegInfo() {
211 return regInfo;
212 }
213 public void ping() throws SampException {
214 if ( ! service.isHubRunning() ) {
215 throw new SampException( "Service is stopped" );
216 }
217 }
218 public void unregister() throws SampException {
219 checkCaller();
220 service.unregister( caller );
221 }
222 public void setCallable( CallableClient callable )
223 throws SampException {
224 checkCaller();
225 service.setCallable( caller, callable );
226 }
227 public void declareMetadata( Map meta ) throws SampException {
228 checkCaller();
229 service.declareMetadata( caller, meta );
230 }
231 public Metadata getMetadata( String clientId )
232 throws SampException {
233 checkCaller();
234 return service.getMetadata( caller, clientId );
235 }
236 public void declareSubscriptions( Map subs )
237 throws SampException {
238 checkCaller();
239 service.declareSubscriptions( caller, subs );
240 }
241 public Subscriptions getSubscriptions( String clientId )
242 throws SampException {
243 checkCaller();
244 return service.getSubscriptions( caller, clientId );
245 }
246 public String[] getRegisteredClients() throws SampException {
247 checkCaller();
248 return service.getRegisteredClients( caller );
249 }
250 public Map getSubscribedClients( String mtype )
251 throws SampException {
252 checkCaller();
253 return service.getSubscribedClients( caller, mtype );
254 }
255 public void notify( String recipientId, Map message )
256 throws SampException {
257 checkCaller();
258 service.notify( caller, recipientId, message );
259 }
260 public String call( String recipientId, String msgTag,
261 Map message ) throws SampException {
262 checkCaller();
263 return service.call( caller, recipientId, msgTag, message );
264 }
265 public List notifyAll( Map message ) throws SampException {
266 checkCaller();
267 return service.notifyAll( caller, message );
268 }
269 public Map callAll( String msgTag, Map message )
270 throws SampException {
271 checkCaller();
272 return service.callAll( caller, msgTag, message );
273 }
274 public void reply( String msgId, Map response )
275 throws SampException {
276 checkCaller();
277 service.reply( caller, msgId, response );
278 }
279 public Response callAndWait( String recipientId, Map message,
280 int timeout ) throws SampException {
281 checkCaller();
282 return service.callAndWait( caller, recipientId, message,
283 timeout );
284 }
285
286 /**
287 * Checks that this connection's client is able to make calls
288 * on this connection. If it is not, for instance if it has been
289 * unregistered, an exception will be thrown.
290 */
291 private void checkCaller() throws SampException {
292 if ( ! clientSet_.containsClient( caller ) ) {
293 throw new SampException( "Client not registered" );
294 }
295 }
296 };
297 }
298
299 /**
300 * Does the work for the <code>unregister</code> method of conections
301 * registered with this service.
302 *
303 * @param caller client to unregister
304 * @see org.astrogrid.samp.client.HubConnection#unregister
305 */
306 protected void unregister( HubClient caller ) throws SampException {
307 clientSet_.remove( caller );
308 hubEvent( new Message( "samp.hub.event.unregister" )
309 .addParam( "id", caller.getId() ) );
310 }
311
312 /**
313 * Does the work for the <code>setCallable</code> method of connections
314 * registered with this service.
315 *
316 * @param caller client
317 * @param callable callable object
318 * @see org.astrogrid.samp.client.HubConnection#setCallable
319 */
320 protected void setCallable( HubClient caller, CallableClient callable )
321 throws SampException {
322 caller.setCallable( callable );
323 }
324
325 /**
326 * Does the work for the <code>declareMetadata</code> method of connections
327 * registered with this service.
328 *
329 * @param caller client
330 * @param meta new metadata for client
331 * @see org.astrogrid.samp.client.HubConnection#declareMetadata
332 */
333 protected void declareMetadata( HubClient caller, Map meta )
334 throws SampException {
335 Metadata.asMetadata( meta ).check();
336 caller.setMetadata( meta );
337 hubEvent( new Message( "samp.hub.event.metadata" )
338 .addParam( "id", caller.getId() )
339 .addParam( "metadata", meta ) );
340 }
341
342 /**
343 * Does the work for the <code>getMetadata</code> method of connections
344 * registered with this service.
345 *
346 * @param caller calling client
347 * @param clientId id of client being queried
348 * @return metadata for client
349 * @see org.astrogrid.samp.client.HubConnection#getMetadata
350 */
351 protected Metadata getMetadata( HubClient caller, String clientId )
352 throws SampException {
353 return getClient( clientId ).getMetadata();
354 }
355
356 /**
357 * Does the work for the <code>declareSubscriptions</code> method of
358 * connections registered with this service.
359 *
360 * @param caller client
361 * @param subscriptions new subscriptions for client
362 * @see org.astrogrid.samp.client.HubConnection#declareSubscriptions
363 */
364 protected void declareSubscriptions( HubClient caller, Map subscriptions )
365 throws SampException {
366 if ( ! caller.isCallable() ) {
367 throw new SampException( "Client is not callable" );
368 }
369 Subscriptions subs = Subscriptions.asSubscriptions( subscriptions );
370 subs.check();
371 caller.setSubscriptions( subs );
372 String callerId = caller.getId();
373 String serviceId = serviceClient_.getId();
374 String mtype = "samp.hub.event.subscriptions";
375 HubClient[] recipients = clientSet_.getClients();
376 for ( int ic = 0; ic < recipients.length; ic++ ) {
377 HubClient recipient = recipients[ ic ];
378 if ( recipient != serviceClient_ &&
379 canSend( serviceClient_, recipient, mtype ) &&
380 clientSet_.containsClient( recipient ) ) {
381 Message msg = new Message( mtype );
382 msg.addParam( "id", callerId );
383 msg.addParam( "subscriptions",
384 getSubscriptionsFor( recipient, subs ) );
385 try {
386 recipient.getCallable()
387 .receiveNotification( serviceId, msg );
388 }
389 catch ( Exception e ) {
390 logger_.log( Level.WARNING,
391 "Notification " + caller + " -> " + recipient
392 + " failed: " + e, e );
393 }
394 }
395 }
396 }
397
398 /**
399 * Does the work for the <code>getSubscriptions</code> method of connections
400 * registered with this service.
401 *
402 * @param caller calling client
403 * @param clientId id of client being queried
404 * @return subscriptions for client
405 * @see org.astrogrid.samp.client.HubConnection#getSubscriptions
406 */
407 protected Subscriptions getSubscriptions( HubClient caller,
408 String clientId )
409 throws SampException {
410 return getSubscriptionsFor( caller,
411 getClient( clientId ).getSubscriptions() );
412 }
413
414 /**
415 * Does the work for the <code>getRegisteredClients</code> method of
416 * connections registered with this service.
417 *
418 * @param caller calling client
419 * @return array of registered client IDs excluding <code>caller</code>'s
420 * @see org.astrogrid.samp.client.HubConnection#getRegisteredClients
421 */
422 protected String[] getRegisteredClients( HubClient caller )
423 throws SampException {
424 HubClient[] clients = clientSet_.getClients();
425 List idList = new ArrayList( clients.length );
426 for ( int ic = 0; ic < clients.length; ic++ ) {
427 if ( ! clients[ ic ].equals( caller ) ) {
428 idList.add( clients[ ic ].getId() );
429 }
430 }
431 return (String[]) idList.toArray( new String[ 0 ] );
432 }
433
434 /**
435 * Does the work for the <code>getSubscribedClients</code> method of
436 * connections registered with this service.
437 *
438 * @param caller calling client
439 * @param mtype message type
440 * @return map in which the keys are the public IDs of clients
441 * subscribed to <code>mtype</code>
442 * @see org.astrogrid.samp.client.HubConnection#getSubscribedClients
443 */
444 protected Map getSubscribedClients( HubClient caller, String mtype )
445 throws SampException {
446 HubClient[] clients = clientSet_.getClients();
447 Map subMap = new TreeMap();
448 for ( int ic = 0; ic < clients.length; ic++ ) {
449 HubClient client = clients[ ic ];
450 if ( ! client.equals( caller ) ) {
451 Map sub = client.getSubscriptions().getSubscription( mtype );
452 if ( sub != null && canSend( caller, client, mtype ) ) {
453 subMap.put( client.getId(), sub );
454 }
455 }
456 }
457 return subMap;
458 }
459
460 /**
461 * Does the work for the <code>notify</code> method of connections
462 * registered with this service.
463 *
464 * @param caller calling client
465 * @param recipientId public ID of client to receive message
466 * @param message message
467 * @see org.astrogrid.samp.client.HubConnection#notify
468 */
469 protected void notify( HubClient caller, String recipientId, Map message )
470 throws SampException {
471 Message msg = Message.asMessage( message );
472 msg.check();
473 String mtype = msg.getMType();
474 HubClient recipient = getClient( recipientId );
475 checkSend( caller, recipient, mtype );
476 try {
477 recipient.getCallable().receiveNotification( caller.getId(), msg );
478 }
479 catch ( SampException e ) {
480 throw e;
481 }
482 catch ( Exception e ) {
483 throw new SampException( e.getMessage(), e );
484 }
485 }
486
487 /**
488 * Does the work for the <code>call</code> method of connections
489 * registered with this service.
490 *
491 * @param caller calling client
492 * @param recipientId client ID of recipient
493 * @param msgTag message tag
494 * @param message message
495 * @return message ID
496 * @see org.astrogrid.samp.client.HubConnection#call
497 */
498 protected String call( HubClient caller, String recipientId, String msgTag,
499 Map message )
500 throws SampException {
501 Message msg = Message.asMessage( message );
502 msg.check();
503 String mtype = msg.getMType();
504 HubClient recipient = getClient( recipientId );
505 String msgId = MessageId.encode( caller, msgTag, false );
506 checkSend( caller, recipient, mtype );
507 try {
508 recipient.getCallable().receiveCall( caller.getId(), msgId, msg );
509 }
510 catch ( SampException e ) {
511 throw e;
512 }
513 catch ( Exception e ) {
514 throw new SampException( e.getMessage(), e );
515 }
516 return msgId;
517 }
518
519 /**
520 * Does the work for the <code>notifyAll</code> method of connections
521 * registered with this service.
522 *
523 * @param caller calling client
524 * @param message message
525 * @return list of public IDs for clients to which the notify will be sent
526 * @see org.astrogrid.samp.client.HubConnection#notifyAll
527 */
528 protected List notifyAll( HubClient caller, Map message )
529 throws SampException {
530 Message msg = Message.asMessage( message );
531 msg.check();
532 String mtype = msg.getMType();
533 HubClient[] recipients = clientSet_.getClients();
534 List sentList = new ArrayList();
535 for ( int ic = 0; ic < recipients.length; ic++ ) {
536 HubClient recipient = recipients[ ic ];
537 if ( recipient != caller && canSend( caller, recipient, mtype ) &&
538 clientSet_.containsClient( recipient ) ) {
539 try {
540 recipient.getCallable()
541 .receiveNotification( caller.getId(), msg );
542 sentList.add( recipient.getId() );
543 }
544 catch ( Exception e ) {
545 logger_.log( Level.WARNING,
546 "Notification " + caller + " -> " + recipient
547 + " failed: " + e, e );
548 }
549 }
550 }
551 return sentList;
552 }
553
554 /**
555 * Does the work for the <code>call</code> method of connections
556 * registered with this service.
557 *
558 * @param caller calling client
559 * @param msgTag message tag
560 * @param message message
561 * @return publicId-&gt;msgId map for clients to which an attempt to
562 * send the call will be made
563 * @see org.astrogrid.samp.client.HubConnection#callAll
564 */
565 protected Map callAll( HubClient caller, String msgTag, Map message )
566 throws SampException {
567 Message msg = Message.asMessage( message );
568 msg.check();
569 String mtype = msg.getMType();
570 String msgId = MessageId.encode( caller, msgTag, false );
571 HubClient[] recipients = clientSet_.getClients();
572 Map sentMap = new HashMap();
573 for ( int ic = 0; ic < recipients.length; ic++ ) {
574 HubClient recipient = recipients[ ic ];
575 if ( recipient != caller && canSend( caller, recipient, mtype ) &&
576 clientSet_.containsClient( recipient ) ) {
577 try {
578 recipient.getCallable()
579 .receiveCall( caller.getId(), msgId, msg );
580 }
581 catch ( SampException e ) {
582 throw e;
583 }
584 catch ( Exception e ) {
585 throw new SampException( e.getMessage(), e );
586 }
587 sentMap.put( recipient.getId(), msgId );
588 }
589 }
590 return sentMap;
591 }
592
593 /**
594 * Does the work for the <code>reply</code> method of connections
595 * registered with this service.
596 *
597 * @param caller calling client
598 * @param msgIdStr message ID
599 * @param resp response to forward
600 * @see org.astrogrid.samp.client.HubConnection#reply
601 */
602 protected void reply( HubClient caller, String msgIdStr, Map resp )
603 throws SampException {
604 Response response = Response.asResponse( resp );
605 response.check();
606 MessageId msgId = MessageId.decode( msgIdStr );
607 HubClient sender = getClient( msgId.getSenderId() );
608 String senderTag = msgId.getSenderTag();
609
610 // If we can see from the message ID that it was originally sent
611 // synchronously, take steps to place the response in the map of
612 // waiting messages where it will get picked up and returned to
613 // the sender as a callAndWait return value.
614 if ( msgId.isSynch() ) {
615 synchronized ( waiterMap_ ) {
616 if ( waiterMap_.containsKey( msgId ) ) {
617 if ( waiterMap_.get( msgId ) == null ) {
618 waiterMap_.put( msgId, response );
619 waiterMap_.notifyAll();
620 }
621 else {
622 throw new SampException(
623 "Response ignored - you've already sent one" );
624 }
625 }
626 else {
627 throw new SampException(
628 "Response ignored - synchronous call timed out" );
629 }
630 }
631 }
632
633 // Otherwise, just pass it to the sender using a callback.
634 else {
635 try {
636 sender.getCallable()
637 .receiveResponse( caller.getId(), senderTag, response );
638 }
639 catch ( SampException e ) {
640 throw e;
641 }
642 catch ( Exception e ) {
643 throw new SampException( e.getMessage(), e );
644 }
645 }
646 }
647
648 /**
649 * Does the work for the <code>callAndWait</code> method of connections
650 * registered with this service.
651 *
652 * @param caller calling client
653 * @param recipientId client ID of recipient
654 * @param message message
655 * @param timeout timeout in seconds
656 * @return response response
657 * @see org.astrogrid.samp.client.HubConnection#callAndWait
658 */
659 protected Response callAndWait( HubClient caller, String recipientId,
660 Map message, int timeout )
661 throws SampException {
662 Message msg = Message.asMessage( message );
663 msg.check();
664 String mtype = msg.getMType();
665 HubClient recipient = getClient( recipientId );
666 MessageId hubMsgId =
667 new MessageId( caller.getId(), keyGen_.next(), true );
668 long start = System.currentTimeMillis();
669 checkSend( caller, recipient, mtype );
670 synchronized ( waiterMap_ ) {
671
672 // If the number of pending synchronous calls exceeds the
673 // permitted maximum, remove the oldest calls until there is
674 // space for the new one.
675 if ( MAX_WAITERS > 0 && waiterMap_.size() >= MAX_WAITERS ) {
676 int excess = waiterMap_.size() - MAX_WAITERS + 1;
677 List keyList = new ArrayList( waiterMap_.keySet() );
678 Collections.sort( keyList, MessageId.AGE_COMPARATOR );
679 logger_.warning( "Pending synchronous calls exceeds limit "
680 + MAX_WAITERS + " - giving up on " + excess
681 + " oldest" );
682 for ( int ie = 0; ie < excess; ie++ ) {
683 Object removed = waiterMap_.remove( keyList.get( ie ) );
684 assert removed != null;
685 }
686 waiterMap_.notifyAll();
687 }
688
689 // Place an entry for this synchronous call in the waiterMap.
690 waiterMap_.put( hubMsgId, null );
691 }
692
693 // Make the call asynchronously to the receiver.
694 try {
695 recipient.getCallable()
696 .receiveCall( caller.getId(), hubMsgId.toString(), msg );
697 }
698 catch ( SampException e ) {
699 throw e;
700 }
701 catch ( Exception e ) {
702 throw new SampException( e.getMessage(), e );
703 }
704
705 // Wait until either the timeout expires, or the response to the
706 // message turns up in the waiter map (placed there on another
707 // thread by this the reply() method).
708 timeout = Math.min( Math.max( 0, timeout ),
709 Math.max( 0, MAX_TIMEOUT ) );
710 long finish = timeout > 0
711 ? System.currentTimeMillis() + timeout * 1000
712 : Long.MAX_VALUE; // 3e8 years
713 synchronized ( waiterMap_ ) {
714 while ( waiterMap_.containsKey( hubMsgId ) &&
715 waiterMap_.get( hubMsgId ) == null &&
716 System.currentTimeMillis() < finish ) {
717 long millis = finish - System.currentTimeMillis();
718 if ( millis > 0 ) {
719 try {
720 waiterMap_.wait( millis );
721 }
722 catch ( InterruptedException e ) {
723 throw new SampException( "Wait interrupted", e );
724 }
725 }
726 }
727
728 // If the response is there, return it to the caller of this
729 // method (the sender of the message).
730 if ( waiterMap_.containsKey( hubMsgId ) ) {
731 Response response =
732 (Response) waiterMap_.remove( hubMsgId );
733 if ( response != null ) {
734 return response;
735 }
736
737 // Otherwise, it must have timed out. Exit with an error.
738 else {
739 assert System.currentTimeMillis() >= finish;
740 String millis =
741 Long.toString( System.currentTimeMillis() - start );
742 String emsg = new StringBuffer()
743 .append( "Synchronous call timeout after " )
744 .append( millis.substring( 0,
745 millis.length() - 3 ) )
746 .append( '.' )
747 .append( millis.substring( millis.length() - 3 ) )
748 .append( '/' )
749 .append( timeout )
750 .append( " sec" )
751 .toString();
752 throw new SampException( emsg );
753 }
754 }
755 else {
756 throw new SampException(
757 "Synchronous call aborted"
758 + " - server load exceeded maximum of " + MAX_WAITERS + "?" );
759 }
760 }
761 }
762
763 /**
764 * Returns the HubConnection object used by the hub itself to send
765 * and receive messages.
766 * This is the one which apparently sends samp.hub.event.shutdown messages
767 * etc.
768 *
769 * @return hub service's own hub connection
770 */
771 public HubConnection getServiceConnection() {
772 return serviceClientConnection_;
773 }
774
775 /**
776 * Forcibly disconnects a given client.
777 * This call does three things:
778 * <ol>
779 * <li>sends a <code>samp.hub.disconnect</code> message to the
780 * client which is about to be ejected, if the client is
781 * subscribed to that MType</li>
782 * <li>removes that client from this hub's client set so that any
783 * further communication attempts to or from it will fail</li>
784 * <li>broadcasts a <code>samp.hub.unregister</code> message to all
785 * remaining clients indicating that the client has disappeared</li>
786 * </ol>
787 *
788 * @param clientId public-id of client to eject
789 * @param reason short text string indicating reason for ejection
790 */
791 public void disconnect( String clientId, String reason ) {
792 Message discoMsg = new Message( "samp.hub.disconnect" );
793 if ( reason != null && reason.length() > 0 ) {
794 discoMsg.addParam( "reason", reason );
795 }
796 disconnect( new String[] { clientId }, discoMsg );
797 }
798
799 /**
800 * Forcibly disconnects a number of clients for the same reason.
801 *
802 * @param clientIds public-ids of clients to disconnect
803 * @param discoMsg message to send to clients which will effect
804 * disconnection (samp.hub.disconnect or samp.hub.event.shutdown)
805 */
806 private void disconnect( String[] clientIds, Message discoMsg ) {
807
808 // Send the message and remove clients from client set.
809 for ( int ic = 0; ic < clientIds.length; ic++ ) {
810 String clientId = clientIds[ ic ];
811 HubClient client = clientSet_.getFromPublicId( clientId );
812 if ( client != null ) {
813 if ( client.isSubscribed( discoMsg.getMType() ) ) {
814 try {
815 notify( serviceClient_, clientId, discoMsg );
816 }
817 catch ( SampException e ) {
818 logger_.log( Level.INFO,
819 discoMsg.getMType() + " to " + client
820 + " failed", e );
821 }
822 }
823 clientSet_.remove( client );
824 }
825 }
826
827 // Notify the remaining clients that the others have been removed.
828 for ( int ic = 0; ic < clientIds.length; ic++ ) {
829 hubEvent( new Message( "samp.hub.event.unregister" )
830 .addParam( "id", clientIds[ ic ] ) );
831 }
832 }
833
834 public boolean isHubRunning() {
835 return started_ && ! shutdown_;
836 }
837
838 public synchronized void shutdown() {
839 if ( ! shutdown_ ) {
840 shutdown_ = true;
841 if ( started_ ) {
842 hubEvent( new Message( "samp.hub.event.shutdown" ) );
843 }
844 serviceClientConnection_ = null;
845 }
846 }
847
848 /**
849 * Broadcast an event message to all subscribed clients.
850 * The sender of this message is the hub application itself.
851 *
852 * @param msg message to broadcast
853 */
854 private void hubEvent( Message msg ) {
855 try {
856 notifyAll( serviceClient_, msg );
857 }
858 catch ( SampException e ) {
859 assert false;
860 }
861 }
862
863 /**
864 * Returns the client object corresponding to a public client ID.
865 * If no such client is registered, throw an exception.
866 *
867 * @param id client public id
868 * @return HubClient object
869 */
870 private HubClient getClient( String id ) throws SampException {
871 HubClient client = clientSet_.getFromPublicId( id );
872 if ( client != null ) {
873 return client;
874 }
875 else if ( idGen_.hasUsed( id ) ) {
876 throw new SampException( "Client " + id
877 + " is no longer registered" );
878 }
879 else {
880 throw new SampException( "No registered client with ID \""
881 + id + "\"" );
882 }
883 }
884
885 /**
886 * Checks if a given send is permitted. Throws an exception if not.
887 *
888 * @param sender sending client
889 * @param recipient receiving client
890 * @param mtype MType
891 * @throws SampException if the send is not permitted
892 */
893 private void checkSend( HubClient sender, HubClient recipient,
894 String mtype ) throws SampException {
895 String errmsg = getSendError( sender, recipient, mtype );
896 if ( errmsg != null ) {
897 throw new SampException( errmsg );
898 }
899 }
900
901 /**
902 * Indicates whether a given send is permitted.
903 *
904 * @param sender sending client
905 * @param recipient receiving client
906 * @param mtype MType
907 * @return true iff send OK
908 */
909 private boolean canSend( HubClient sender, HubClient recipient,
910 String mtype ) {
911 return getSendError( sender, recipient, mtype ) == null;
912 }
913
914 /**
915 * Does the work to determine whether a given sending client is
916 * permitted to send a message with a given MType to a given recipient.
917 * Returns null if allowed, a useful message if not.
918 * Not intended for direct use, see {@link #canSend} and {@link #checkSend}.
919 *
920 * @param sender sending client
921 * @param recipient receiving client
922 * @param mtype MType
923 * @return null if send OK, otherwise explanation message
924 */
925 private String getSendError( HubClient sender, HubClient recipient,
926 String mtype ) {
927 if ( ! recipient.isCallable() ) {
928 return "Client " + recipient + " is not callable";
929 }
930 Subscriptions subs = recipient.getSubscriptions();
931 if ( ! subs.isSubscribed( mtype ) ) {
932 return "Client " + recipient + " is not subscribed to " + mtype;
933 }
934 ProfileToken ptoken = sender.getProfileToken();
935 MessageRestriction mrestrict = ptoken.getMessageRestriction();
936 if ( mrestrict != null ) {
937 Map subsInfo = subs.getSubscription( mtype );
938 if ( ! mrestrict.permitSend( mtype, subsInfo ) ) {
939 return "MType " + mtype + " blocked from "
940 + ptoken + " profile";
941 }
942 }
943 return null;
944 }
945
946 /**
947 * Returns the view of a given subscriptions map to be presented to
948 * a sending client. The result may be affected by any message
949 * restrictions in force for the client.
950 *
951 * @param client client to view subscriptions
952 * @param subs basic subscription map
953 * @return view of subscription map for <code>client</code>
954 */
955 private Subscriptions getSubscriptionsFor( HubClient client,
956 Subscriptions subs ) {
957 MessageRestriction mrestrict =
958 client.getProfileToken().getMessageRestriction();
959 if ( mrestrict == null ) {
960 return subs;
961 }
962 Subscriptions csubs = new Subscriptions();
963 for ( Iterator it = subs.entrySet().iterator(); it.hasNext(); ) {
964 Map.Entry entry = (Map.Entry) it.next();
965 String mtype = (String) entry.getKey();
966 Map note = (Map) entry.getValue();
967 if ( mrestrict.permitSend( mtype, note ) ) {
968 csubs.put( mtype, note );
969 }
970 }
971 return csubs;
972 }
973
974 /**
975 * Encapsulates information about a MessageId.
976 * A message ID can be represented as a string, but encodes information
977 * which can be retrieved later.
978 */
979 private static class MessageId {
980
981 private final String senderId_;
982 private final String senderTag_;
983 private final boolean isSynch_;
984 private final long birthday_;
985
986 private static final String T_SYNCH_FLAG = "S";
987 private static final String F_SYNCH_FLAG = "A";
988 private static final int CHECK_SEED = (int) System.currentTimeMillis();
989 private static final int CHECK_LENG = 4;
990 private static final Comparator AGE_COMPARATOR = new Comparator() {
991 public int compare( Object o1, Object o2 ) {
992 return (int) (((MessageId) o1).birthday_ -
993 ((MessageId) o2).birthday_);
994 }
995 };
996
997 /**
998 * Constructor.
999 *
1000 * @param senderId client id of the message sender
1001 * @param senderTag msgTag provided by the sender
1002 * @param isSynch whether the message was sent synchronously or not
1003 */
1004 public MessageId( String senderId, String senderTag, boolean isSynch ) {
1005 senderId_ = senderId;
1006 senderTag_ = senderTag;
1007 isSynch_ = isSynch;
1008 birthday_ = System.currentTimeMillis();
1009 }
1010
1011 /**
1012 * Returns the sender's public client id.
1013 *
1014 * @return sender's id
1015 */
1016 public String getSenderId() {
1017 return senderId_;
1018 }
1019
1020 /**
1021 * Returns the msgTag attached to the message by the sender.
1022 *
1023 * @return msgTag
1024 */
1025 public String getSenderTag() {
1026 return senderTag_;
1027 }
1028
1029 /**
1030 * Returns whether the message was sent synchronously.
1031 *
1032 * @return true iff message was sent using callAndWait
1033 */
1034 public boolean isSynch() {
1035 return isSynch_;
1036 }
1037
1038 public int hashCode() {
1039 return checksum( senderId_, senderTag_, isSynch_ ).hashCode();
1040 }
1041
1042 public boolean equals( Object o ) {
1043 if ( o instanceof MessageId ) {
1044 MessageId other = (MessageId) o;
1045 return this.senderId_.equals( other.senderId_ )
1046 && this.senderTag_.equals( other.senderTag_ )
1047 && this.isSynch_ == other.isSynch_;
1048 }
1049 else {
1050 return false;
1051 }
1052 }
1053
1054 /**
1055 * Returns the string representation of this MessageId.
1056 *
1057 * @return message ID string
1058 */
1059 public String toString() {
1060 Object checksum = checksum( senderId_, senderTag_, isSynch_ );
1061 return new StringBuffer()
1062 .append( senderId_ )
1063 .append( ID_DELIMITER )
1064 .append( isSynch_ ? T_SYNCH_FLAG : F_SYNCH_FLAG )
1065 .append( ID_DELIMITER )
1066 .append( checksum )
1067 .append( ID_DELIMITER )
1068 .append( senderTag_ )
1069 .toString();
1070 }
1071
1072 /**
1073 * Decodes a msgId string to return the corresponding MessageId object.
1074 * This is the opposite of the {@link #toString} method.
1075 *
1076 * @param msgId string representation of message ID
1077 * @return new MessageId object
1078 */
1079 public static MessageId decode( String msgId ) throws SampException {
1080 int delim1 = msgId.indexOf( ID_DELIMITER );
1081 int delim2 = msgId.indexOf( ID_DELIMITER, delim1 + 1 );
1082 int delim3 = msgId.indexOf( ID_DELIMITER, delim2 + 1 );
1083 if ( delim1 < 0 || delim2 < 0 || delim3 < 0 ) {
1084 throw new SampException( "Badly formed message ID " + msgId );
1085 }
1086 String senderId = msgId.substring( 0, delim1 );
1087 String synchFlag = msgId.substring( delim1 + 1, delim2 );
1088 String checksum = msgId.substring( delim2 + 1, delim3 );
1089 String senderTag = msgId.substring( delim3 + 1 );
1090 boolean isSynch;
1091 if ( T_SYNCH_FLAG.equals( synchFlag ) ) {
1092 isSynch = true;
1093 }
1094 else if ( F_SYNCH_FLAG.equals( synchFlag ) ) {
1095 isSynch = false;
1096 }
1097 else {
1098 throw new SampException( "Badly formed message ID "
1099 + msgId + " (synch flag)" );
1100 }
1101 if ( ! checksum( senderId, senderTag, isSynch )
1102 .equals( checksum ) ) {
1103 throw new SampException( "Bad message ID checksum" );
1104 }
1105 MessageId idObj = new MessageId( senderId, senderTag, isSynch );
1106 assert idObj.toString().equals( msgId );
1107 return idObj;
1108 }
1109
1110 /**
1111 * Returns a message ID string corresponding to the arguments.
1112 *
1113 * @param sender sender client
1114 * @param senderTag msgTag attached by sender
1115 * @param isSynch whether message was sent synchronously
1116 * @return string representation of message ID
1117 */
1118 public static String encode( HubClient sender, String senderTag,
1119 boolean isSynch ) {
1120 return new MessageId( sender.getId(), senderTag, isSynch )
1121 .toString();
1122 }
1123
1124 /**
1125 * Returns a checksum string which is a hash of the given arguments.
1126 *
1127 * @param senderId public client id of sender
1128 * @param senderTag msgTag attached by sender
1129 * @param isSynch whether message was sent synchronously
1130 * @return checksum string
1131 */
1132 private static String checksum( String senderId, String senderTag,
1133 boolean isSynch ) {
1134 int sum = CHECK_SEED;
1135 sum = 23 * sum + senderId.hashCode();
1136 sum = 23 * sum + senderTag.hashCode();
1137 sum = 23 * sum + ( isSynch ? 3 : 5 );
1138 String check = Integer.toHexString( sum );
1139 check =
1140 check.substring( Math.max( 0, check.length() - CHECK_LENG ) );
1141 while ( check.length() < CHECK_LENG ) {
1142 check = "0" + check;
1143 }
1144 assert check.length() == CHECK_LENG;
1145 return check;
1146 }
1147 }
1148
1149 /**
1150 * Generates client public IDs.
1151 * These must be unique, but don't need to be hard to guess.
1152 */
1153 private static class ClientIdGenerator {
1154 private int iseq_;
1155 private final String prefix_;
1156 private final Comparator comparator_;
1157
1158 /**
1159 * Constructor.
1160 *
1161 * @param prefix prefix for all generated ids
1162 */
1163 public ClientIdGenerator( String prefix ) {
1164 prefix_ = prefix;
1165
1166 // Prepare a comparator which will order the keys generated here
1167 // in sequence of generation.
1168 comparator_ = new Comparator() {
1169 public int compare( Object o1, Object o2 ) {
1170 String s1 = o1.toString();
1171 String s2 = o2.toString();
1172 Integer i1 = getIndex( s1 );
1173 Integer i2 = getIndex( s2 );
1174 if ( i1 == null && i2 == null ) {
1175 return s1.compareTo( s2 );
1176 }
1177 else if ( i1 == null ) {
1178 return +1;
1179 }
1180 else if ( i2 == null ) {
1181 return -1;
1182 }
1183 else {
1184 return i1.intValue() - i2.intValue();
1185 }
1186 }
1187 };
1188 }
1189
1190 /**
1191 * Returns the next unused id.
1192 *
1193 * @return next id
1194 */
1195 public synchronized String next() {
1196 return prefix_ + Integer.toString( ++iseq_ );
1197 }
1198
1199 /**
1200 * Indicates whether a given client ID has previously been dispensed
1201 * by this object.
1202 *
1203 * @param id id to test
1204 * @return true iff id has been returned by a previous call of
1205 * <code>next</code>
1206 */
1207 public boolean hasUsed( String id ) {
1208 Integer ix = getIndex( id );
1209 return ix != null && ix.intValue() <= iseq_;
1210 }
1211
1212 /**
1213 * Returns an Integer giving the sequence index of the given id string.
1214 * If <code>id</code> does not look like a string generated by this
1215 * object, null is returned.
1216 *
1217 * @param id identifier to test
1218 * @return object containing sequence index of <code>id</code>,
1219 * or null
1220 */
1221 private Integer getIndex( String id ) {
1222 if ( id.startsWith( prefix_ ) ) {
1223 try {
1224 int iseq =
1225 Integer.parseInt( id.substring( prefix_.length() ) );
1226 return Integer.valueOf( iseq );
1227 }
1228 catch ( NumberFormatException e ) {
1229 return null;
1230 }
1231 }
1232 else {
1233 return null;
1234 }
1235 }
1236
1237 /**
1238 * Returns a comparator which will order the IDs generated by this
1239 * object in generation sequence.
1240 *
1241 * @return id comparator
1242 */
1243 public Comparator getComparator() {
1244 return comparator_;
1245 }
1246 }
1247 }