Debian Codegraph @

src/java/org/astrogrid/samp/test/MessageSender.java

raw
1 package org.astrogrid.samp.test;
2
3 import java.io.IOException;
4 import java.io.PrintStream;
5 import java.util.AbstractMap;
6 import java.util.AbstractSet;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.BitSet;
10 import java.util.Collection;
11 import java.util.Collections;
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Set;
18 import java.util.logging.Level;
19 import java.util.logging.Logger;
20 import org.astrogrid.samp.Client;
21 import org.astrogrid.samp.Message;
22 import org.astrogrid.samp.Metadata;
23 import org.astrogrid.samp.Response;
24 import org.astrogrid.samp.SampUtils;
25 import org.astrogrid.samp.Subscriptions;
26 import org.astrogrid.samp.client.CallableClient;
27 import org.astrogrid.samp.client.ClientProfile;
28 import org.astrogrid.samp.client.DefaultClientProfile;
29 import org.astrogrid.samp.client.HubConnection;
30 import org.astrogrid.samp.client.SampException;
31
32 /**
33 * Sends a message to one or more other SAMP clients.
34 * Intended for use from the command line.
35 *
36 * @author Mark Taylor
37 * @since 23 Jul 2008
38 */
39 public abstract class MessageSender {
40
41 private static Logger logger_ =
42 Logger.getLogger( MessageSender.class.getName() );
43
44 /**
45 * Sends a message to a given list of recipients.
46 * If <code>recipientIds</code> is null, then will be sent to all
47 * subscribed clients.
48 *
49 * @param connection hub connection
50 * @param msg message to send
51 * @param recipientIds array of recipients to target, or null
52 * @return responder Client -> Response map
53 */
54 abstract Map getResponses( HubConnection connection, Message msg,
55 String[] recipientIds )
56 throws IOException;
57
58 /**
59 * Sends a message to a list of recipients and displays the results
60 * on an output stream.
61 *
62 * @param connection hub connection
63 * @param msg message to send
64 * @param recipientIds array of recipients to target, or null
65 * @param destination print stream
66 */
67 void showResults( HubConnection connection, Message msg,
68 String[] recipientIds, PrintStream out )
69 throws IOException {
70 Map responses = getResponses( connection, msg, recipientIds );
71 for ( Iterator it = responses.entrySet().iterator(); it.hasNext(); ) {
72 Map.Entry entry = (Map.Entry) it.next();
73 String responderId = (String) entry.getKey();
74 Client responder = new MetaClient( responderId, connection );
75 Object response = entry.getValue();
76 out.println();
77 out.println( responder );
78 if ( response instanceof Throwable ) {
79 ((Throwable) response).printStackTrace( out );
80 }
81 else {
82 out.println( SampUtils.formatObject( response, 3 ) );
83 }
84 }
85 }
86
87 /**
88 * Translates an array of client names to client IDs.
89 * If some or all cannot be identified, an exception is thrown.
90 *
91 * @param conn hub connection
92 * @param names array of client names, interpreted case-insensitively
93 * @return array of client ids corresponding to <code>names</code>
94 */
95 private static String[] namesToIds( HubConnection conn, String[] names )
96 throws SampException {
97 int count = names.length;
98 if ( count == 0 ) {
99 return new String[ 0 ];
100 }
101 String[] ids = new String[ count ];
102 BitSet flags = new BitSet( count );
103 String[] allIds = conn.getRegisteredClients();
104 for ( int ic = 0; ic < allIds.length; ic++ ) {
105 String id = allIds[ ic ];
106 Metadata meta = conn.getMetadata( id );
107 String name = meta.getName();
108 for ( int in = 0; in < count; in++ ) {
109 if ( names[ in ].equalsIgnoreCase( name ) ) {
110 ids[ in ] = id;
111 flags.set( in );
112 }
113 }
114 if ( flags.cardinality() == count ) {
115 return ids;
116 }
117 }
118 assert flags.cardinality() < count;
119 List unknownList = new ArrayList();
120 for ( int in = 0; in < count; in++ ) {
121 if ( ids[ in ] == null ) {
122 unknownList.add( names[ in ] );
123 }
124 }
125 throw new SampException( "Unknown client "
126 + ( unknownList.size() == 1
127 ? ( "name " + unknownList.get( 0 ) )
128 : ( "names " + unknownList ) ) );
129 }
130
131 /**
132 * Main method.
133 * Use -help flag for documentation.
134 */
135 public static void main( String[] args ) throws IOException {
136 int status = runMain( args );
137 if ( status != 0 ) {
138 System.exit( status );
139 }
140 }
141
142 /**
143 * Does the work for the main method.
144 */
145 public static int runMain( String[] args ) throws IOException {
146
147 // Assemble usage string.
148 String usage = new StringBuffer()
149 .append( "\n Usage:" )
150 .append( "\n " + MessageSender.class.getName() )
151 .append( "\n " )
152 .append( " [-help]" )
153 .append( " [-/+verbose]" )
154 .append( "\n " )
155 .append( " -mtype <mtype>" )
156 .append( " [-param <name> <value> ...]" )
157 .append( " [-mode sync|async|notify]" )
158 .append( "\n " )
159 .append( " [-targetid <receiverId> ...]" )
160 .append( " [-targetname <receiverName> ...]" )
161 .append( "\n " )
162 .append( " [-sendername <appname>]" )
163 .append( " [-sendermeta <metaname> <metavalue>]" )
164 .append( "\n" )
165 .toString();
166
167 // Set up variables which can be set or changed by the argument list.
168 String mtype = null;
169 List targetIdList = new ArrayList();
170 List targetNameList = new ArrayList();
171 Map paramMap = new HashMap();
172 String mode = "sync";
173 Metadata meta = new Metadata();
174 int timeout = 0;
175 int verbAdjust = 0;
176
177 // Parse the argument list.
178 List argList = new ArrayList( Arrays.asList( args ) );
179 for ( Iterator it = argList.iterator(); it.hasNext(); ) {
180 String arg = (String) it.next();
181 if ( arg.equals( "-mtype" ) && it.hasNext() ) {
182 it.remove();
183 if ( mtype != null ) {
184 System.err.println( usage );
185 return 1;
186 }
187 mtype = (String) it.next();
188 it.remove();
189 }
190 else if ( arg.equals( "-targetid" ) && it.hasNext() ) {
191 it.remove();
192 targetIdList.add( (String) it.next() );
193 it.remove();
194 }
195 else if ( arg.equals( "-targetname" ) && it.hasNext() ) {
196 it.remove();
197 targetNameList.add( (String) it.next() );
198 it.remove();
199 }
200 else if ( arg.equals( "-param" ) && it.hasNext() ) {
201 it.remove();
202 String pName = (String) it.next();
203 it.remove();
204 String pValue;
205 if ( it.hasNext() ) {
206 pValue = (String) it.next();
207 it.remove();
208 }
209 else {
210 System.err.println( usage );
211 return 1;
212 }
213 paramMap.put( pName, SampUtils.parseValue( pValue ) );
214 }
215 else if ( arg.equals( "-mode" ) && it.hasNext() ) {
216 it.remove();
217 mode = (String) it.next();
218 it.remove();
219 }
220 else if ( arg.equals( "-sendername" ) && it.hasNext() ) {
221 it.remove();
222 meta.setName( (String) it.next() );
223 it.remove();
224 }
225 else if ( arg.equals( "-sendermeta" ) && it.hasNext() ) {
226 it.remove();
227 String mName = (String) it.next();
228 it.remove();
229 String mValue;
230 if ( it.hasNext() ) {
231 mValue = (String) it.next();
232 it.remove();
233 }
234 else {
235 System.err.println( usage );
236 return 1;
237 }
238 meta.put( mName, SampUtils.parseValue( mValue ) );
239 }
240 else if ( arg.equals( "-timeout" ) && it.hasNext() ) {
241 it.remove();
242 String stimeout = (String) it.next();
243 it.remove();
244 try {
245 timeout = Integer.parseInt( stimeout );
246 }
247 catch ( NumberFormatException e ) {
248 System.err.println( "Not numeric: " + stimeout );
249 System.err.println( usage );
250 return 1;
251 }
252 }
253 else if ( arg.startsWith( "-v" ) ) {
254 it.remove();
255 verbAdjust--;
256 }
257 else if ( arg.startsWith( "+v" ) ) {
258 it.remove();
259 verbAdjust++;
260 }
261 else if ( arg.startsWith( "-h" ) ) {
262 it.remove();
263 System.out.println( usage );
264 return 0;
265 }
266 else {
267 it.remove();
268 System.err.println( usage );
269 return 1;
270 }
271 }
272 if ( ! argList.isEmpty() ) {
273 System.err.println( usage );
274 return 1;
275 }
276 if ( mtype == null ) {
277 System.err.println( usage );
278 return 1;
279 }
280
281 // Set logging levels in accordance with flags.
282 int logLevel = Level.WARNING.intValue() + 100 * verbAdjust;
283 Logger.getLogger( "org.astrogrid.samp" )
284 .setLevel( Level.parse( Integer.toString( logLevel ) ) );
285
286 // Get profile.
287 ClientProfile profile = DefaultClientProfile.getProfile();
288
289 // Create a message sender object.
290 final MessageSender sender;
291 if ( mode.toLowerCase().startsWith( "async" ) ) {
292 sender = new AsynchSender();
293 }
294 else if ( mode.toLowerCase().startsWith( "sync" ) ) {
295 sender = new SynchSender( timeout );
296 }
297 else if ( mode.toLowerCase().startsWith( "notif" ) ) {
298 sender = new NotifySender();
299 }
300 else {
301 System.err.println( usage );
302 return 1;
303 }
304
305 // Prepare to send the message.
306 Message msg = new Message( mtype, paramMap );
307
308 // Register.
309 HubConnection connection = profile.register();
310 if ( connection == null ) {
311 System.err.println( "No hub is running" );
312 return 1;
313 }
314 connection.declareMetadata( meta );
315
316 // Assemble target list.
317 String[] targetNames =
318 (String[]) targetNameList.toArray( new String[ 0 ] );
319 targetIdList.addAll( Arrays.asList( namesToIds( connection,
320 targetNames ) ) );
321 String[] targets = targetIdList.isEmpty()
322 ? null
323 : (String[]) targetIdList.toArray( new String[ 0 ] );
324
325 // Send the message, displaying the results on System.out.
326 sender.showResults( connection, msg, targets, System.out );
327
328 // Tidy up and exit.
329 connection.unregister();
330 return 0;
331 }
332
333 /**
334 * MessageSender implementation which uses the Notify pattern.
335 */
336 private static class NotifySender extends MessageSender {
337 public Map getResponses( HubConnection connection, Message msg,
338 String[] recipientIds )
339 throws IOException {
340 final List recipientList;
341 if ( recipientIds == null ) {
342 recipientList = connection.notifyAll( msg );
343 if ( recipientList.size() == 0 ) {
344 logger_.warning( "No clients subscribed to "
345 + msg.getMType() );
346 }
347 }
348 else {
349 for ( int ir = 0; ir < recipientIds.length; ir++ ) {
350 connection.notify( recipientIds[ ir ], msg );
351 }
352 recipientList = Arrays.asList( recipientIds );
353 }
354 Map responseMap = new HashMap();
355 for ( Iterator it = recipientList.iterator(); it.hasNext(); ) {
356 responseMap.put( it.next(), "<no response from notify>" );
357 }
358 return responseMap;
359 }
360 }
361
362 /**
363 * MessageSender implementation which uses the Synchronous Call/Response
364 * pattern.
365 */
366 private static class SynchSender extends MessageSender {
367 private final int timeout_;
368
369 /**
370 * Constructor.
371 *
372 * @param timeout in seconds
373 */
374 SynchSender( int timeout ) {
375 timeout_ = timeout;
376 }
377
378 public Map getResponses( final HubConnection connection,
379 final Message msg,
380 String[] recIds )
381 throws IOException {
382 final String[] recipientIds = recIds == null
383 ? (String[]) connection.getSubscribedClients( msg.getMType() )
384 .keySet().toArray( new String[ 0 ] )
385 : recIds;
386 if ( recipientIds.length == 0 ) {
387 logger_.warning( "No clients subscribed to " + msg.getMType() );
388 return new HashMap();
389 }
390 else {
391 int nsend = recipientIds.length;
392 logger_.log( nsend == 0 ? Level.WARNING : Level.INFO,
393 "Waiting for " + nsend + " responses" );
394 }
395 final BlockingMap map = new BlockingMap();
396 for ( int ir = 0; ir < recipientIds.length; ir++ ) {
397 final String id = recipientIds[ ir ];
398 new Thread() {
399 public void run() {
400 Object result;
401 try {
402 result =
403 connection.callAndWait( id, msg, timeout_ );
404 }
405 catch ( Throwable e ) {
406 result = e;
407 }
408 map.put( id, result );
409 if ( map.size() >= recipientIds.length ) {
410 map.done();
411 }
412 }
413 }.start();
414 }
415 return map;
416 }
417 }
418
419 /**
420 * MessageSender implementation which uses the Asynchronous Call/Response
421 * pattern.
422 */
423 private static class AsynchSender extends MessageSender {
424 private int iseq_;
425
426 public Map getResponses( HubConnection connection, Message msg,
427 String[] recipientIds )
428 throws IOException {
429 String msgTag = "tag-" + ++iseq_;
430 Collector collector = new Collector();
431
432 // Sets the connection's callable client to a new object.
433 // Since the Standard Profile doesn't say it's OK to do this
434 // more than once, this means that this it is not really safe
435 // to call getResponses more than once for this object.
436 connection.setCallable( collector );
437 if ( recipientIds == null ) {
438 Set recipientSet = connection.callAll( msgTag, msg ).keySet();
439 collector.setRecipients( recipientSet );
440 }
441 else {
442 Set recipientSet = new HashSet( Arrays.asList( recipientIds ) );
443 for ( Iterator it = recipientSet.iterator(); it.hasNext(); ) {
444 String recipientId = (String) it.next();
445 connection.call( recipientId, msgTag, msg );
446 }
447 collector.setRecipients( recipientSet );
448 }
449 return collector.map_;
450 }
451
452 /**
453 * CallableClient implementation which collects asynchronous message
454 * responses.
455 */
456 private static class Collector implements CallableClient {
457 final BlockingMap map_;
458 Collection recipients_;
459
460 /**
461 * Constructor.
462 *
463 * @param nExpected number of responses expected by this collector
464 */
465 Collector() {
466 map_ = new BlockingMap();
467 }
468
469 /**
470 * Notifies this object which clients it should expect a response
471 * from. Must be called at some point, or the returned map's
472 * iterator will block indefinitely.
473 *
474 * @param recipients set of client ids for expected responders
475 */
476 public void setRecipients( Collection recipients ) {
477 int nsend = recipients.size();
478 logger_.log( nsend == 0 ? Level.WARNING : Level.INFO,
479 "Waiting for " + nsend + " responses" );
480 recipients_ = recipients;
481 if ( map_.keySet().containsAll( recipients_ ) ) {
482 map_.done();
483 }
484 }
485
486 public void receiveCall( String senderId, String msgId,
487 Message msg ) {
488 throw new UnsupportedOperationException();
489 }
490
491 public void receiveNotification( String senderId, Message msg ) {
492 throw new UnsupportedOperationException();
493 }
494
495 public void receiveResponse( String responderId, String msgTag,
496 Response response ) {
497 map_.put( responderId, response );
498 if ( recipients_ != null &&
499 map_.keySet().containsAll( recipients_ ) ) {
500 map_.done();
501 }
502 }
503 }
504 }
505
506 /**
507 * Client implementation which may know about metadata.
508 */
509 private static class MetaClient implements Client {
510 private final String id_;
511 private final Metadata meta_;
512
513 /**
514 * Constructor which attempts to acquire metadata from a given
515 * hub connection.
516 *
517 * @param client id
518 * @param connection hub connection
519 */
520 public MetaClient( String id, HubConnection connection )
521 throws SampException {
522 this( id, connection.getMetadata( id ) );
523 }
524
525 /**
526 * Constructor which uses supplied metadata.
527 *
528 * @param id client id
529 * @param meta metadata (may be null)
530 */
531 public MetaClient( String id, Metadata meta ) {
532 id_ = id;
533 meta_ = meta;
534 }
535
536 public String getId() {
537 return id_;
538 }
539
540 public Metadata getMetadata() {
541 return meta_;
542 }
543
544 public Subscriptions getSubscriptions() {
545 return null;
546 }
547
548 public String toString() {
549 StringBuffer sbuf = new StringBuffer();
550 sbuf.append( getId() );
551 String name = meta_ == null ? null
552 : meta_.getName();
553 if ( name != null ) {
554 sbuf.append( " (" )
555 .append( name )
556 .append( ')' );
557 }
558 return sbuf.toString();
559 }
560 }
561
562 /**
563 * Map implementation which dispenses its contents via an iterator
564 * which will block until all the results are in. This makes it
565 * suitable for use from other threads.
566 */
567 private static class BlockingMap extends AbstractMap {
568 private final BlockingSet entrySet_;
569
570 /**
571 * Constructor.
572 */
573 BlockingMap() {
574 entrySet_ = new BlockingSet();
575 }
576
577 public Set entrySet() {
578 return entrySet_;
579 }
580
581 public synchronized Object put( final Object key, final Object value ) {
582 entrySet_.add( new Map.Entry() {
583 public Object getKey() {
584 return key;
585 }
586 public Object getValue() {
587 return value;
588 }
589 public Object setValue( Object value ) {
590 throw new UnsupportedOperationException();
591 }
592 } );
593 return null;
594 }
595
596 /**
597 * Indicates that no more entries will be added to this map.
598 * Must be called by populator or entry set iterator will block
599 * indefinitely.
600 */
601 synchronized void done() {
602 entrySet_.done();
603 }
604 }
605
606 /**
607 * Set implementation which dispenses its contents via an iterator
608 * which will block until all results are in.
609 */
610 private static class BlockingSet extends AbstractSet {
611 private final List list_;
612 private boolean done_;
613
614 /**
615 * Constructor.
616 */
617 BlockingSet() {
618 list_ = Collections.synchronizedList( new ArrayList() );
619 }
620
621 public boolean add( Object o ) {
622 assert ! list_.contains( o );
623 synchronized ( list_ ) {
624 list_.add( o );
625 list_.notifyAll();
626 }
627 return true;
628 }
629
630 /**
631 * Indicates that no more items will be added to this set.
632 * Must be called by populator or iterator will block
633 * indefinitely.
634 */
635 public void done() {
636 done_ = true;
637 synchronized ( list_ ) {
638 list_.notifyAll();
639 }
640 }
641
642 public int size() {
643 return list_.size();
644 }
645
646 public Iterator iterator() {
647 return new Iterator() {
648 int index_;
649
650 public void remove() {
651 throw new UnsupportedOperationException();
652 }
653
654 public Object next() {
655 return list_.get( index_++ );
656 }
657
658 public boolean hasNext() {
659 synchronized ( list_ ) {
660 while ( index_ >= list_.size() && ! done_ ) {
661 try {
662 list_.wait();
663 }
664 catch ( InterruptedException e ) {
665 throw new RuntimeException( "Interrupted", e );
666 }
667 }
668 return index_ < list_.size();
669 }
670 }
671 };
672 }
673 }
674 }