| 1 |
package org.astrogrid.samp.test; |
| 2 |
|
| 3 |
import java.io.IOException; |
| 4 |
import java.net.URL; |
| 5 |
import java.util.Arrays; |
| 6 |
import java.util.ArrayList; |
| 7 |
import java.util.Collections; |
| 8 |
import java.util.HashSet; |
| 9 |
import java.util.HashMap; |
| 10 |
import java.util.Iterator; |
| 11 |
import java.util.List; |
| 12 |
import java.util.Map; |
| 13 |
import java.util.Random; |
| 14 |
import java.util.Set; |
| 15 |
import java.util.logging.Level; |
| 16 |
import java.util.logging.Logger; |
| 17 |
import javax.swing.JFrame; |
| 18 |
import org.astrogrid.samp.Client; |
| 19 |
import org.astrogrid.samp.ErrInfo; |
| 20 |
import org.astrogrid.samp.Message; |
| 21 |
import org.astrogrid.samp.Metadata; |
| 22 |
import org.astrogrid.samp.RegInfo; |
| 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 |
import org.astrogrid.samp.gui.HubMonitor; |
| 32 |
import org.astrogrid.samp.xmlrpc.LockInfo; |
| 33 |
import org.astrogrid.samp.xmlrpc.StandardClientProfile; |
| 34 |
|
| 35 |
/** |
| 36 |
* Tester for a running hub. |
| 37 |
* Attempts to test as much of the SAMP standard as possible for an existing |
| 38 |
* hub implementation. |
| 39 |
* |
| 40 |
* @author Mark Taylor |
| 41 |
* @since 18 Jul 2008 |
| 42 |
*/ |
| 43 |
public class HubTester extends Tester { |
| 44 |
|
| 45 |
private final ClientProfile profile_; |
| 46 |
private final String hubId_; |
| 47 |
private final Client[] ignoreClients_; |
| 48 |
private final Set selfIds_; |
| 49 |
private final Set privateKeys_; |
| 50 |
private final ClientWatcher clientWatcher_; |
| 51 |
private final Random random_ = new Random( 233333L ); |
| 52 |
private static final String WAITMILLIS_KEY = "test.wait"; |
| 53 |
private static final String MSGIDQUERY_KEY = "test.msgid"; |
| 54 |
private static final String ECHO_MTYPE = "test.echo"; |
| 55 |
private static final String PING_MTYPE = "samp.app.ping"; |
| 56 |
private static final String FAIL_MTYPE = "test.fail"; |
| 57 |
private static final String REGISTER_MTYPE = "samp.hub.event.register"; |
| 58 |
private static final String UNREGISTER_MTYPE = "samp.hub.event.unregister"; |
| 59 |
private static final String METADATA_MTYPE = "samp.hub.event.metadata"; |
| 60 |
private static final String SUBSCRIPTIONS_MTYPE = |
| 61 |
"samp.hub.event.subscriptions"; |
| 62 |
private static final String ERROR_KEY = "test.error"; |
| 63 |
private static final char[] ALPHA_CHARS = createAlphaCharacters(); |
| 64 |
private static final char[] GENERAL_CHARS = createGeneralCharacters(); |
| 65 |
|
| 66 |
private static Logger logger_ = |
| 67 |
Logger.getLogger( HubTester.class.getName() ); |
| 68 |
|
| 69 |
/** |
| 70 |
* Constructor. |
| 71 |
* |
| 72 |
* @param profile hub discovery object |
| 73 |
*/ |
| 74 |
public HubTester( ClientProfile profile ) throws IOException { |
| 75 |
profile_ = profile; |
| 76 |
selfIds_ = new HashSet(); |
| 77 |
privateKeys_ = new HashSet(); |
| 78 |
|
| 79 |
// Set up basic information about the hub for use by other methods. |
| 80 |
// Perform some checks at the same time. |
| 81 |
// First register a probe client to make some basic queries about the |
| 82 |
// current hub state. |
| 83 |
HubConnection conn = profile_.register(); |
| 84 |
if ( conn == null ) { |
| 85 |
throw new IOException( "No hub is running" ); |
| 86 |
} |
| 87 |
conn.ping(); |
| 88 |
|
| 89 |
// Set up monitor to receive hub event messages. |
| 90 |
clientWatcher_ = new ClientWatcher( conn ); |
| 91 |
conn.setCallable( clientWatcher_ ); |
| 92 |
conn.declareSubscriptions( clientWatcher_.getSubscriptions() ); |
| 93 |
conn.declareMetadata( clientWatcher_.getMetadata() ); |
| 94 |
|
| 95 |
// Acquire, check and store information about the hub. |
| 96 |
RegInfo regInfo = conn.getRegInfo(); |
| 97 |
regInfo.check(); |
| 98 |
hubId_ = regInfo.getHubId(); |
| 99 |
|
| 100 |
// Keep a record of all clients which have registered on behalf of |
| 101 |
// this class. |
| 102 |
selfIds_.add( regInfo.getSelfId() ); |
| 103 |
privateKeys_.add( regInfo.getPrivateKey() ); |
| 104 |
|
| 105 |
// Get list of registered clients. |
| 106 |
String[] clientIds = conn.getRegisteredClients(); |
| 107 |
|
| 108 |
// Check that the hub's ID does appear in the list. |
| 109 |
assertTrue( Arrays.asList( clientIds ).contains( regInfo.getHubId() ) ); |
| 110 |
|
| 111 |
// Check that a client's own ID does not appear in the list. |
| 112 |
assertTrue( ! Arrays.asList( clientIds ) |
| 113 |
.contains( regInfo.getSelfId() ) ); |
| 114 |
|
| 115 |
// But prepare a list which contains the client's ID as well. |
| 116 |
String[] clientIds1 = new String[ clientIds.length + 1 ]; |
| 117 |
System.arraycopy( clientIds, 0, clientIds1, 0, clientIds.length ); |
| 118 |
clientIds1[ clientIds.length ] = regInfo.getSelfId(); |
| 119 |
clientIds = clientIds1; |
| 120 |
|
| 121 |
// Check that the metadata and subscriptions of all the existing |
| 122 |
// clients is legal. |
| 123 |
int nc = clientIds.length; |
| 124 |
Client[] clients = new Client[ nc ]; |
| 125 |
for ( int ic = 0; ic < nc; ic++ ) { |
| 126 |
final String id = clientIds[ ic ]; |
| 127 |
final Metadata meta = conn.getMetadata( id ); |
| 128 |
meta.check(); |
| 129 |
final Subscriptions subs = conn.getSubscriptions( id ); |
| 130 |
subs.check(); |
| 131 |
clients[ ic ] = new Client() { |
| 132 |
public String getId() { |
| 133 |
return id; |
| 134 |
} |
| 135 |
public Metadata getMetadata() { |
| 136 |
return meta; |
| 137 |
} |
| 138 |
public Subscriptions getSubscriptions() { |
| 139 |
return subs; |
| 140 |
} |
| 141 |
}; |
| 142 |
} |
| 143 |
ignoreClients_ = clients; |
| 144 |
} |
| 145 |
|
| 146 |
/** |
| 147 |
* Registers with the hub, performing various checks. |
| 148 |
* |
| 149 |
* @return new hub connection representing a newly-registered client |
| 150 |
*/ |
| 151 |
private HubConnection register() throws SampException { |
| 152 |
HubConnection conn = profile_.register(); |
| 153 |
RegInfo regInfo = conn.getRegInfo(); |
| 154 |
regInfo.check(); |
| 155 |
String selfId = regInfo.getSelfId(); |
| 156 |
String privateKey = regInfo.getPrivateKey(); |
| 157 |
|
| 158 |
// Check that the hub ID is the same for all clients. |
| 159 |
assertEquals( hubId_, regInfo.getHubId() ); |
| 160 |
|
| 161 |
// Check that client IDs are not being reused. |
| 162 |
assertTrue( ! selfIds_.contains( selfId ) ); |
| 163 |
selfIds_.add( selfId ); |
| 164 |
|
| 165 |
// Check that private keys are not being reused. |
| 166 |
assertTrue( ! privateKeys_.contains( privateKey ) ); |
| 167 |
privateKeys_.add( privateKey ); |
| 168 |
|
| 169 |
// Check that getRegisteredClients() excludes the caller's ID. |
| 170 |
assertTrue( ! Arrays.asList( conn.getRegisteredClients() ) |
| 171 |
.contains( selfId ) ); |
| 172 |
|
| 173 |
// Check that metadata and subscriptions for this application are |
| 174 |
// empty maps (since we have not yet declared their values). |
| 175 |
assertEquals( new HashMap(), conn.getMetadata( selfId ) ); |
| 176 |
assertEquals( new HashMap(), conn.getSubscriptions( selfId ) ); |
| 177 |
return conn; |
| 178 |
} |
| 179 |
|
| 180 |
/** |
| 181 |
* Perform a wide variety of tests on a running hub. |
| 182 |
*/ |
| 183 |
public void run() throws IOException { |
| 184 |
|
| 185 |
// Profile-specific tests. |
| 186 |
if ( profile_ == StandardClientProfile.getInstance() ) { |
| 187 |
testStandardLockfile(); |
| 188 |
} |
| 189 |
if ( profile_ instanceof StandardClientProfile ) { |
| 190 |
testLockInfo( ((StandardClientProfile) profile_).getLockInfo() ); |
| 191 |
} |
| 192 |
|
| 193 |
// General tests. |
| 194 |
testClients(); |
| 195 |
testStress(); |
| 196 |
} |
| 197 |
|
| 198 |
/** |
| 199 |
* Tests the content of the SAMP Standard Profile lockfile. |
| 200 |
* Does not currently test the permissions on it - that would be nice |
| 201 |
* but is hard to do from java since it's rather platform-specific. |
| 202 |
*/ |
| 203 |
private void testStandardLockfile() throws IOException { |
| 204 |
LockInfo lockInfo = StandardClientProfile.getInstance().getLockInfo(); |
| 205 |
if ( lockInfo == null ) { |
| 206 |
throw new TestException( "No lockfile (no hub)" ); |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
/** |
| 211 |
* Does tests on a LockInfo object used by the profile. |
| 212 |
* This is specific to a Standard-like (though not necessarily Standard) |
| 213 |
* profile, and will simply be skipped for non-standard profiles. |
| 214 |
* |
| 215 |
* @param lockInfo lock info object describing a running hub |
| 216 |
*/ |
| 217 |
private void testLockInfo( LockInfo lockInfo ) throws IOException { |
| 218 |
if ( lockInfo == null ) { |
| 219 |
throw new TestException( "No LockInfo (no hub)" ); |
| 220 |
} |
| 221 |
lockInfo.check(); |
| 222 |
String secret = lockInfo.getSecret(); |
| 223 |
URL hubUrl = lockInfo.getXmlrpcUrl(); |
| 224 |
TestXmlrpcClient xclient = new TestXmlrpcClient( hubUrl ); |
| 225 |
xclient.checkSuccessCall( "samp.hub.ping", new ArrayList() ); |
| 226 |
xclient.checkFailureCall( "samp.hub.register", |
| 227 |
Collections.singletonList( secret |
| 228 |
+ "-NOT!" ) ); |
| 229 |
xclient.checkFailureCall( "samp.hub.not-a-method", |
| 230 |
Collections.singletonList( secret ) ); |
| 231 |
} |
| 232 |
|
| 233 |
/** |
| 234 |
* Performs a wide variety of tests on a running hub from a limited |
| 235 |
* number of clients. |
| 236 |
*/ |
| 237 |
private void testClients() throws IOException { |
| 238 |
|
| 239 |
// Register client0, set metadata and subscriptions, and unregister. |
| 240 |
HubConnection c0 = register(); |
| 241 |
String id0 = c0.getRegInfo().getSelfId(); |
| 242 |
Metadata meta0 = new Metadata(); |
| 243 |
meta0.setName( "Shorty" ); |
| 244 |
meta0.setDescriptionText( "Short-lived test client" ); |
| 245 |
c0.declareMetadata( meta0 ); |
| 246 |
TestCallableClient callable0 = new TestCallableClient( c0 ); |
| 247 |
c0.setCallable( callable0 ); |
| 248 |
Subscriptions subs0 = new Subscriptions(); |
| 249 |
subs0.put( ECHO_MTYPE, new HashMap() ); |
| 250 |
subs0.check(); |
| 251 |
c0.declareSubscriptions( subs0 ); |
| 252 |
c0.unregister(); |
| 253 |
|
| 254 |
// Register client 1 with the hub and declare some metadata. |
| 255 |
HubConnection c1 = register(); |
| 256 |
String id1 = c1.getRegInfo().getSelfId(); |
| 257 |
Metadata meta1 = new Metadata(); |
| 258 |
meta1.setName( "Test1" ); |
| 259 |
meta1.setDescriptionText( "HubTester client application" ); |
| 260 |
meta1.put( "test.drink", "cider" ); |
| 261 |
c1.declareMetadata( meta1 ); |
| 262 |
|
| 263 |
// Check the list of clients known to the hub. |
| 264 |
assertTestClients( c1, new String[ 0 ] ); |
| 265 |
|
| 266 |
// Register client 2 with the hub and declare some metadata. |
| 267 |
HubConnection c2 = register(); |
| 268 |
String id2 = c2.getRegInfo().getSelfId(); |
| 269 |
Metadata meta2 = new Metadata( meta1 ); |
| 270 |
meta2.put( "test.drink", "ribena" ); |
| 271 |
c2.declareMetadata( meta2 ); |
| 272 |
|
| 273 |
// Check the list of clients known to the hub. |
| 274 |
assertTestClients( c2, new String[] { id1 } ); |
| 275 |
assertTestClients( c1, new String[] { id2 } ); |
| 276 |
|
| 277 |
// Check retrieved metadata matches declared metadata. |
| 278 |
assertEquals( meta1, c1.getMetadata( id1 ) ); |
| 279 |
assertEquals( meta1, c2.getMetadata( id1 ) ); |
| 280 |
assertEquals( meta2, c1.getMetadata( id2 ) ); |
| 281 |
assertEquals( meta2, c2.getMetadata( id2 ) ); |
| 282 |
assertEquals( "cider", c2.getMetadata( id1 ).get( "test.drink" ) ); |
| 283 |
|
| 284 |
// Redeclare metadata and check that the update has been noted. |
| 285 |
meta1.put( "test.drink", "scrumpy" ); |
| 286 |
c1.declareMetadata( meta1 ); |
| 287 |
assertEquals( meta1, c1.getMetadata( id1 ) ); |
| 288 |
assertEquals( meta1, c2.getMetadata( id1 ) ); |
| 289 |
assertEquals( "scrumpy", c2.getMetadata( id1 ).get( "test.drink" ) ); |
| 290 |
|
| 291 |
// Declare subscriptions and check that retrieved subscriptions match |
| 292 |
// declared ones. |
| 293 |
TestCallableClient callable1 = new TestCallableClient( c1 ); |
| 294 |
c1.setCallable( callable1 ); |
| 295 |
Subscriptions subs1 = new Subscriptions(); |
| 296 |
subs1.put( "test.dummy.1", new HashMap() ); |
| 297 |
subs1.put( "test.dummy.2", new HashMap() ); |
| 298 |
c1.declareSubscriptions( subs1 ); |
| 299 |
assertEquals( subs1, c1.getSubscriptions( id1 ) ); |
| 300 |
assertEquals( subs1, c2.getSubscriptions( id1 ) ); |
| 301 |
Map d3atts = new HashMap(); |
| 302 |
d3atts.put( "size", "big" ); |
| 303 |
d3atts.put( "colour", "blue" ); |
| 304 |
subs1.put( "test.dummy.3", d3atts ); |
| 305 |
c1.declareSubscriptions( subs1 ); |
| 306 |
assertEquals( subs1, c2.getSubscriptions( id1 ) ); |
| 307 |
assertEquals( new HashMap(), |
| 308 |
((Map) c2.getSubscriptions( id1 ).get( "test.dummy.1")) ); |
| 309 |
assertEquals( "big", |
| 310 |
((Map) c2.getSubscriptions( id1 ).get( "test.dummy.3" )) |
| 311 |
.get( "size" ) ); |
| 312 |
c1.declareSubscriptions( TestCallableClient.SUBS ); |
| 313 |
|
| 314 |
TestCallableClient callable2 = new TestCallableClient( c2 ); |
| 315 |
c2.setCallable( callable2 ); |
| 316 |
c2.declareSubscriptions( TestCallableClient.SUBS ); |
| 317 |
|
| 318 |
// Try to acquire information about non-existent clients. |
| 319 |
try { |
| 320 |
c1.getMetadata( "Sir Not-Appearing-in-this-Hub" ); |
| 321 |
fail(); |
| 322 |
} |
| 323 |
catch ( SampException e ) { |
| 324 |
} |
| 325 |
try { |
| 326 |
c1.getSubscriptions( "Sir Not-Appearing-in-this-Hub" ); |
| 327 |
fail(); |
| 328 |
} |
| 329 |
catch ( SampException e ) { |
| 330 |
} |
| 331 |
|
| 332 |
// New client which can re-use the same tag (not advisable, but legal). |
| 333 |
HubConnection c4 = register(); |
| 334 |
TestCallableClient callable4 = new TestCallableClient( c4 ); |
| 335 |
callable4.setAllowTagReuse( true ); |
| 336 |
c4.setCallable( callable4 ); |
| 337 |
|
| 338 |
// Send some concurrent ECHO messages via both notify and call. |
| 339 |
int necho = 5; |
| 340 |
Map[] echoParams = new Map[ necho ]; |
| 341 |
String[] msgIds2 = new String[ necho ]; |
| 342 |
String[] msgIds4 = new String[ necho ]; |
| 343 |
for ( int i = 0; i < necho; i++ ) { |
| 344 |
Message msg = new Message( ECHO_MTYPE ); |
| 345 |
Object val1 = createRandomObject( 2, false ); |
| 346 |
Object val2 = createRandomObject( 4, false ); |
| 347 |
Object val3 = new String( GENERAL_CHARS ); |
| 348 |
msg.put( WAITMILLIS_KEY, SampUtils.encodeInt( 200 + 100 * i ) ); |
| 349 |
msg.put( MSGIDQUERY_KEY, SampUtils.encodeBoolean( true ) ); |
| 350 |
msg.addParam( "val1", val1 ); |
| 351 |
msg.addParam( "val2", val2 ); |
| 352 |
msg.addParam( "val3", val3 ); |
| 353 |
echoParams[ i ] = msg.getParams(); |
| 354 |
c2.notify( id1, msg ); |
| 355 |
msgIds2[ i ] = callable2.call( id1, "tag" + i, msg ); |
| 356 |
msgIds4[ i ] = callable4.call( id1, "sametag", msg ); |
| 357 |
} |
| 358 |
|
| 359 |
// The call messages should complete quickly, so all the sends |
| 360 |
// are expected to complete before any of the replies are received |
| 361 |
// (there is a deliberate delay at the receiver end in all cases). |
| 362 |
// This isn't required, but hubs SHOULD work this way. |
| 363 |
// Warn if it looks like not. |
| 364 |
if ( callable2.getReplyCount() > necho / 2 ) { |
| 365 |
logger_.warning( "Looks like hub call()/notify() methods " |
| 366 |
+ "not completing quickly" |
| 367 |
+ " (" + callable2.getReplyCount() |
| 368 |
+ "/" + necho + ")" ); |
| 369 |
} |
| 370 |
|
| 371 |
// Spin-wait until all the replies are in. |
| 372 |
while ( callable2.getReplyCount() < necho || |
| 373 |
callable4.getReplyCount() < necho ) delay( 100 ); |
| 374 |
assertEquals( necho, callable2.getReplyCount() ); |
| 375 |
assertEquals( necho, callable4.getReplyCount() ); |
| 376 |
|
| 377 |
// Check that the replies are as expected (returned samp.result has |
| 378 |
// same content as sent samp.params). |
| 379 |
for ( int i = 0; i < necho; i++ ) { |
| 380 |
assertEquals( necho - i, callable2.getReplyCount() ); |
| 381 |
Response r2 = callable2.getReply( id1, "tag" + i ); |
| 382 |
assertEquals( Response.OK_STATUS, r2.getStatus() ); |
| 383 |
assertEquals( echoParams[ i ], r2.getResult() ); |
| 384 |
assertEquals( msgIds2[ i ], r2.get( MSGIDQUERY_KEY ) ); |
| 385 |
|
| 386 |
assertEquals( necho - i, callable4.getReplyCount() ); |
| 387 |
Response r4 = callable4.getReply( id1, "sametag" ); |
| 388 |
assertEquals( Response.OK_STATUS, r4.getStatus() ); |
| 389 |
} |
| 390 |
|
| 391 |
// Check that no more replies have arrived apart from the ones we |
| 392 |
// were expecting. |
| 393 |
assertEquals( 0, callable2.getReplyCount() ); |
| 394 |
assertEquals( 0, callable4.getReplyCount() ); |
| 395 |
|
| 396 |
// c4 no longer needed. |
| 397 |
c4.unregister(); |
| 398 |
|
| 399 |
// Send echo messages synchronously (using callAndWait). |
| 400 |
// These have deliberate delays at the receiver end, but there is |
| 401 |
// no timeout. |
| 402 |
for ( int i = 0; i < necho; i++ ) { |
| 403 |
Message msg = new Message( ECHO_MTYPE ); |
| 404 |
Object val1 = createRandomObject( 2, false ); |
| 405 |
Object val2 = createRandomObject( 4, false ); |
| 406 |
Object val3 = new String( GENERAL_CHARS ); |
| 407 |
msg.put( WAITMILLIS_KEY, SampUtils.encodeInt( 100 * i ) ); |
| 408 |
msg.addParam( "val1", val1 ); |
| 409 |
msg.addParam( "val2", val2 ); |
| 410 |
msg.addParam( "val3", val3 ); |
| 411 |
echoParams[ i ] = msg.getParams(); |
| 412 |
Response syncR = c2.callAndWait( id1, msg, 0 ); |
| 413 |
assertEquals( echoParams[ i ], syncR.getResult() ); |
| 414 |
} |
| 415 |
|
| 416 |
// Send some longer messages synchronously. |
| 417 |
{ |
| 418 |
for ( int ie = 0; ie < 5; ie++ ) { |
| 419 |
int num = (int) Math.pow( 10, ie ); |
| 420 |
List list = new ArrayList( num ); |
| 421 |
for ( int in = 0; in < num; in++ ) { |
| 422 |
list.add( SampUtils.encodeInt( in + 1 ) ); |
| 423 |
} |
| 424 |
Message msg = new Message( ECHO_MTYPE ); |
| 425 |
msg.addParam( "list", list ); |
| 426 |
msg.check(); |
| 427 |
Response response = c2.callAndWait( id1, msg, 0 ); |
| 428 |
response.check(); |
| 429 |
assertEquals( Response.OK_STATUS, response.getStatus() ); |
| 430 |
assertEquals( list, response.getResult().get( "list" ) ); |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
// Send an echo message synchronously, with a timeout which is shorter |
| 435 |
// than the delay which the receiver will introduce. So the hub |
| 436 |
// SHOULD time this attempt out before the response is received. |
| 437 |
// However, the standard does not REQUIRE this, so just warn in |
| 438 |
// case of no time out. |
| 439 |
{ |
| 440 |
Message msg = new Message( ECHO_MTYPE ); |
| 441 |
msg.addParam( "text", "copy" ); |
| 442 |
int delay = 10000; |
| 443 |
msg.put( WAITMILLIS_KEY, SampUtils.encodeInt( delay ) ); |
| 444 |
long start = System.currentTimeMillis(); |
| 445 |
try { |
| 446 |
c2.callAndWait( id1, msg, 1 ); |
| 447 |
assert System.currentTimeMillis() - start >= delay; |
| 448 |
logger_.warning( "callAndWait() did not timeout as requested" ); |
| 449 |
} |
| 450 |
catch ( SampException e ) { |
| 451 |
// timeout exception |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
// Register a new client. |
| 456 |
HubConnection c3 = register(); |
| 457 |
TestCallableClient callable3 = new TestCallableClient( c3 ); |
| 458 |
c3.setCallable( callable3 ); |
| 459 |
|
| 460 |
// Test callAll and notifyAll. |
| 461 |
{ |
| 462 |
|
| 463 |
// Check that getSubscribedClients returns the right list. |
| 464 |
// Note that it must not include the caller. |
| 465 |
Set recipientSet = c3.getSubscribedClients( ECHO_MTYPE ).keySet(); |
| 466 |
try { |
| 467 |
assertEquals( |
| 468 |
new HashSet( Arrays.asList( new String[] { id1, id2 } ) ), |
| 469 |
recipientSet ); |
| 470 |
} |
| 471 |
catch ( TestException e ) { |
| 472 |
throw new TestException( "You may need to shut down other " |
| 473 |
+ "SAMP clients first", e ); |
| 474 |
} |
| 475 |
|
| 476 |
// Send an echo message from client 3 using callAll and notifyAll. |
| 477 |
// Should go to clients 1 and 2. |
| 478 |
Message msg = new Message( ECHO_MTYPE ); |
| 479 |
Object val4 = createRandomObject( 4, false ); |
| 480 |
msg.addParam( "val4", val4 ); |
| 481 |
msg.put( WAITMILLIS_KEY, SampUtils.encodeInt( 400 ) ); |
| 482 |
List notifyList = c3.notifyAll( msg ); |
| 483 |
assertEquals( recipientSet, new HashSet( notifyList ) ); |
| 484 |
String tag = "tag99"; |
| 485 |
msg.put( MSGIDQUERY_KEY, "1" ); |
| 486 |
Map callMap = callable3.callAll( tag, msg ); |
| 487 |
if ( callable3.getReplyCount() != 0 ) { |
| 488 |
logger_.warning( "Looks like hub call()/notify() methods " |
| 489 |
+ "not completing quickly" ); |
| 490 |
} |
| 491 |
|
| 492 |
// Retrieve and check the results from the callAll for each |
| 493 |
// recipient client. |
| 494 |
for ( Iterator it = recipientSet.iterator(); it.hasNext(); ) { |
| 495 |
String rid = (String) it.next(); |
| 496 |
Response response = callable3.waitForReply( rid, tag ); |
| 497 |
assertEquals( Response.OK_STATUS, response.getStatus() ); |
| 498 |
assertEquals( val4, response.getResult().get( "val4" ) ); |
| 499 |
assertEquals( (String) callMap.get( rid ), |
| 500 |
response.get( MSGIDQUERY_KEY ) ); |
| 501 |
} |
| 502 |
|
| 503 |
// Check there are no replies beyond the ones we expect. |
| 504 |
assertEquals( 0, callable3.getReplyCount() ); |
| 505 |
delay( 500 ); |
| 506 |
|
| 507 |
// .. even after a while. |
| 508 |
assertEquals( 0, callable3.getReplyCount() ); |
| 509 |
} |
| 510 |
|
| 511 |
// Test that notify- and call-type messages are being received by |
| 512 |
// their intended recipients. |
| 513 |
{ |
| 514 |
Message pingMsg = new Message( PING_MTYPE ); |
| 515 |
pingMsg.put( WAITMILLIS_KEY, SampUtils.encodeInt( 100 ) ); |
| 516 |
int pingsCount = 50; |
| 517 |
Set recipients = c3.getSubscribedClients( PING_MTYPE ).keySet(); |
| 518 |
assertTrue( recipients.contains( id1 ) ); |
| 519 |
assertTrue( recipients.contains( id2 ) ); |
| 520 |
c3.declareSubscriptions( TestCallableClient.SUBS ); |
| 521 |
assertEquals( recipients, |
| 522 |
c3.getSubscribedClients( PING_MTYPE ).keySet() ); |
| 523 |
|
| 524 |
// Send a load of messages concurrently using various |
| 525 |
// asynchronous methods. |
| 526 |
for ( int i = 0; i < pingsCount; i++ ) { |
| 527 |
c3.notify( id1, pingMsg ); |
| 528 |
callable3.call( id1, "abc1-" + i, pingMsg ); |
| 529 |
List notifyList = c3.notifyAll( pingMsg ); |
| 530 |
Map callMap = callable3.callAll( "abc2-" + i, pingMsg ); |
| 531 |
assertEquals( recipients, new HashSet( notifyList ) ); |
| 532 |
assertEquals( recipients, callMap.keySet() ); |
| 533 |
} |
| 534 |
|
| 535 |
// Spin-wait until all the clients have received all the messages |
| 536 |
// we have sent. |
| 537 |
int np1 = pingsCount * 4; |
| 538 |
int np2 = pingsCount * 2; |
| 539 |
int np3 = 0; |
| 540 |
int nr3 = pingsCount * ( 1 + recipients.size() ); |
| 541 |
while ( callable1.pingCount_ < np1 || |
| 542 |
callable2.pingCount_ < np2 || |
| 543 |
callable3.pingCount_ < np3 || |
| 544 |
callable3.getReplyCount() < nr3 ) delay( 100 ); |
| 545 |
|
| 546 |
// And then wait a bit to see if any more come in (hopefully not). |
| 547 |
delay( 400 ); |
| 548 |
|
| 549 |
// Check that the number of messages received is exactly as |
| 550 |
// expected. |
| 551 |
assertEquals( np1, callable1.pingCount_ ); |
| 552 |
assertEquals( np2, callable2.pingCount_ ); |
| 553 |
assertEquals( np3, callable3.pingCount_ ); |
| 554 |
assertEquals( nr3, callable3.getReplyCount() ); |
| 555 |
|
| 556 |
// Redeclare client 3's subscriptions to the effect that it |
| 557 |
// will not receive any messages. |
| 558 |
c3.declareSubscriptions( new Subscriptions() ); |
| 559 |
} |
| 560 |
|
| 561 |
// Test that error data encoded in responses works as it should. |
| 562 |
{ |
| 563 |
Message failMsg = new Message( FAIL_MTYPE ); |
| 564 |
Map error = new HashMap(); |
| 565 |
error.put( "samp.errortxt", "failure" ); |
| 566 |
error.put( "samp.code", "999" ); |
| 567 |
error.put( "do.what", "do.that" ); |
| 568 |
failMsg.addParam( ERROR_KEY, error ); |
| 569 |
Response reply = c3.callAndWait( id2, failMsg, 0 ); |
| 570 |
ErrInfo errInfo = reply.getErrInfo(); |
| 571 |
errInfo.check(); |
| 572 |
assertEquals( Response.ERROR_STATUS, reply.getStatus() ); |
| 573 |
assertEquals( "failure", errInfo.getErrortxt() ); |
| 574 |
assertEquals( "999", errInfo.getCode() ); |
| 575 |
assertEquals( "do.that", errInfo.get( "do.what" ) ); |
| 576 |
} |
| 577 |
|
| 578 |
// Run tests on MTypes which have not been subscribed to. |
| 579 |
{ |
| 580 |
String dummyMtype = "not.an.mtype"; |
| 581 |
Message dummyMsg = new Message( dummyMtype ); |
| 582 |
|
| 583 |
// Check the hub does not report clients are subscribed to MTypes |
| 584 |
// they are not subscribed to. |
| 585 |
Set subscribed = c3.getSubscribedClients( dummyMtype ).keySet(); |
| 586 |
assertTrue( ! subscribed.contains( id1 ) ); |
| 587 |
assertTrue( ! subscribed.contains( id2 ) ); |
| 588 |
|
| 589 |
// Send a message using notify to an unsubscribed recipient. |
| 590 |
// This should result in an error. |
| 591 |
try { |
| 592 |
c3.notify( id1, dummyMsg ); |
| 593 |
fail(); |
| 594 |
} |
| 595 |
catch ( SampException e ) { |
| 596 |
} |
| 597 |
|
| 598 |
// Send a message using call to an unsubscribed recipient. |
| 599 |
// This should result in an error. |
| 600 |
try { |
| 601 |
c3.call( id1, "xxx", dummyMsg ); |
| 602 |
fail(); |
| 603 |
} |
| 604 |
catch ( SampException e ) { |
| 605 |
} |
| 606 |
|
| 607 |
|
| 608 |
// Send a message using callAndWait to an unsubscribed recipient. |
| 609 |
// This should result in an error. |
| 610 |
try { |
| 611 |
c3.callAndWait( id1, dummyMsg, 0 ); |
| 612 |
fail(); |
| 613 |
} |
| 614 |
catch ( SampException e ) { |
| 615 |
} |
| 616 |
|
| 617 |
// Send message using notifyAll and callAll to which nobody is |
| 618 |
// subscribed. Nobody will receive this, but it is not an error. |
| 619 |
List notifyList = c3.notifyAll( dummyMsg ); |
| 620 |
assertEquals( 0, notifyList.size() ); |
| 621 |
Map callMap = c3.callAll( "yyy", dummyMsg ); |
| 622 |
assertEquals( 0, callMap.size() ); |
| 623 |
} |
| 624 |
|
| 625 |
// Check that hub event messages arrived concerning client 0 which |
| 626 |
// we registered and unregistered earlier. Do it here to give |
| 627 |
// messages enough time to have arrived; SAMP offers no guarantees |
| 628 |
// of delivery sequence, but if they haven't showed up yet it's |
| 629 |
// very likely that they never will. |
| 630 |
Throwable cwError = clientWatcher_.getError(); |
| 631 |
if ( cwError != null ) { |
| 632 |
throw new TestException( "Error encountered during hub event " |
| 633 |
+ "processing", cwError ); |
| 634 |
} |
| 635 |
WatchedClient client0 = clientWatcher_.getClient( id0 ); |
| 636 |
assertTrue( client0 != null ); |
| 637 |
assertTrue( client0.reg_ ); |
| 638 |
assertTrue( client0.unreg_ ); |
| 639 |
assertEquals( meta0, client0.meta_ ); |
| 640 |
assertEquals( subs0, client0.subs_ ); |
| 641 |
|
| 642 |
// Check that the client watcher has received hub event messages |
| 643 |
// concerning itself as well. |
| 644 |
String cwId = clientWatcher_.getConnection().getRegInfo().getSelfId(); |
| 645 |
WatchedClient cwClient = clientWatcher_.getClient( cwId ); |
| 646 |
assertTrue( cwClient != null ); |
| 647 |
assertTrue( ! cwClient.unreg_ ); |
| 648 |
assertEquals( clientWatcher_.getMetadata(), cwClient.meta_ ); |
| 649 |
assertEquals( clientWatcher_.getSubscriptions(), cwClient.subs_ ); |
| 650 |
|
| 651 |
// Tidy up. |
| 652 |
c3.unregister(); |
| 653 |
assertTestClients( c1, new String[] { id2, } ); |
| 654 |
assertTestClients( c2, new String[] { id1, } ); |
| 655 |
|
| 656 |
c1.unregister(); |
| 657 |
c2.unregister(); |
| 658 |
} |
| 659 |
|
| 660 |
/** |
| 661 |
* Runs a lot of clients throwing a lot of messages at each other |
| 662 |
* simultaneously. |
| 663 |
*/ |
| 664 |
private void testStress() throws IOException { |
| 665 |
ClientProfile profile = new ClientProfile() { |
| 666 |
public boolean isHubRunning() { |
| 667 |
return HubTester.this.profile_.isHubRunning(); |
| 668 |
} |
| 669 |
public HubConnection register() throws SampException { |
| 670 |
return HubTester.this.register(); |
| 671 |
} |
| 672 |
}; |
| 673 |
new CalcStorm( profile, random_, 10, 20, Calculator.RANDOM_MODE ) |
| 674 |
.run(); |
| 675 |
} |
| 676 |
|
| 677 |
/** |
| 678 |
* Assert that the given list of registered clients has a certain content. |
| 679 |
* |
| 680 |
* @param conn connection from which to call getRegisteredClients |
| 681 |
* @param otherIds array of client public IDs that getRegisteredClients |
| 682 |
* should return - will not contain ID associated with |
| 683 |
* <code>conn</code> itself |
| 684 |
*/ |
| 685 |
private void assertTestClients( HubConnection conn, String[] otherIds ) |
| 686 |
throws IOException { |
| 687 |
|
| 688 |
// Call getRegisteredClients. |
| 689 |
Set knownOtherIds = |
| 690 |
new HashSet( Arrays.asList( conn.getRegisteredClients() ) ); |
| 691 |
|
| 692 |
// Remove from the list any clients which were already registered |
| 693 |
// before this test instance started up. |
| 694 |
for ( int ic = 0; ic < ignoreClients_.length; ic++ ) { |
| 695 |
String id = ignoreClients_[ ic ].getId(); |
| 696 |
knownOtherIds.remove( ignoreClients_[ ic ].getId() ); |
| 697 |
} |
| 698 |
|
| 699 |
// Assert that the (unordered) set retrieved is the same as that |
| 700 |
// asked about. |
| 701 |
assertEquals( knownOtherIds, |
| 702 |
new HashSet( Arrays.asList( otherIds ) ) ); |
| 703 |
} |
| 704 |
|
| 705 |
/** |
| 706 |
* Generates an object with random content for transmission using SAMP. |
| 707 |
* This may be a structure containing strings, lists and maps with |
| 708 |
* any legal values as defined by the SAMP data encoding rules. |
| 709 |
* |
| 710 |
* @param level maximum level of nesting (how deeply lists/maps |
| 711 |
* may appear within other lists/maps) |
| 712 |
* @param ugly if true, any legal SAMP content will be used; |
| 713 |
* if false, the returned object should be reasonably |
| 714 |
* human-readable if printed (toString) |
| 715 |
* @return random SAMP object |
| 716 |
*/ |
| 717 |
public Object createRandomObject( int level, boolean ugly ) { |
| 718 |
if ( level == 0 ) { |
| 719 |
return createRandomString( ugly ); |
| 720 |
} |
| 721 |
int type = random_.nextInt( 2 ); |
| 722 |
if ( type == 0 ) { |
| 723 |
int nel = random_.nextInt( ugly ? 23 : 3 ); |
| 724 |
List list = new ArrayList( nel ); |
| 725 |
for ( int i = 0; i < nel; i++ ) { |
| 726 |
list.add( createRandomObject( level - 1, ugly ) ); |
| 727 |
} |
| 728 |
SampUtils.checkList( list ); |
| 729 |
return list; |
| 730 |
} |
| 731 |
else if ( type == 1 ) { |
| 732 |
int nent = random_.nextInt( ugly ? 23 : 3 ); |
| 733 |
Map map = new HashMap( nent ); |
| 734 |
for ( int i = 0; i < nent; i++ ) { |
| 735 |
map.put( createRandomString( ugly ), |
| 736 |
createRandomObject( level - 1, ugly ) ); |
| 737 |
} |
| 738 |
SampUtils.checkMap( map ); |
| 739 |
return map; |
| 740 |
} |
| 741 |
else { |
| 742 |
throw new AssertionError(); |
| 743 |
} |
| 744 |
} |
| 745 |
|
| 746 |
/** |
| 747 |
* Creates a new random string for transmission using SAMP. |
| 748 |
* This may have any legal content according to the SAMP data encoding |
| 749 |
* rules. |
| 750 |
* |
| 751 |
* @param ugly if true, any legal SAMP content will be used; |
| 752 |
* if false, the returned object should be reasonably |
| 753 |
* human-readable if printed (toString) |
| 754 |
*/ |
| 755 |
public String createRandomString( boolean ugly ) { |
| 756 |
int nchar = random_.nextInt( ugly ? 99 : 4 ); |
| 757 |
StringBuffer sbuf = new StringBuffer( nchar ); |
| 758 |
char[] chrs = ugly ? GENERAL_CHARS : ALPHA_CHARS; |
| 759 |
for ( int i = 0; i < nchar; i++ ) { |
| 760 |
sbuf.append( chrs[ random_.nextInt( chrs.length ) ] ); |
| 761 |
} |
| 762 |
String str = sbuf.toString(); |
| 763 |
SampUtils.checkString( str ); |
| 764 |
return str; |
| 765 |
} |
| 766 |
|
| 767 |
/** |
| 768 |
* Waits for a given number of milliseconds. |
| 769 |
* |
| 770 |
* @param millis number of milliseconds |
| 771 |
*/ |
| 772 |
private static void delay( int millis ) { |
| 773 |
Object lock = new Object(); |
| 774 |
try { |
| 775 |
synchronized ( lock ) { |
| 776 |
lock.wait( millis ); |
| 777 |
} |
| 778 |
} |
| 779 |
catch ( InterruptedException e ) { |
| 780 |
throw new RuntimeException( "Interrupted", e ); |
| 781 |
} |
| 782 |
} |
| 783 |
|
| 784 |
/** |
| 785 |
* Returns a character array containing each distinct alphanumeric |
| 786 |
* character. |
| 787 |
* |
| 788 |
* @return array of alphanumeric characters |
| 789 |
*/ |
| 790 |
private static char[] createAlphaCharacters() { |
| 791 |
StringBuffer sbuf = new StringBuffer(); |
| 792 |
for ( char c = 'A'; c <= 'Z'; c++ ) { |
| 793 |
sbuf.append( c ); |
| 794 |
} |
| 795 |
for ( char c = '0'; c <= '9'; c++ ) { |
| 796 |
sbuf.append( c ); |
| 797 |
} |
| 798 |
return sbuf.toString().toCharArray(); |
| 799 |
} |
| 800 |
|
| 801 |
/** |
| 802 |
* Returns a character array containing every character which is legal |
| 803 |
* for inclusion in a SAMP <code>string</code>. |
| 804 |
* |
| 805 |
* @return array of string characters |
| 806 |
*/ |
| 807 |
private static char[] createGeneralCharacters() { |
| 808 |
StringBuffer sbuf = new StringBuffer(); |
| 809 |
sbuf.append( (char) 0x09 ); |
| 810 |
sbuf.append( (char) 0x0a ); |
| 811 |
|
| 812 |
// Character 0x0d is problematic. Although it is permissible to |
| 813 |
// transmit this in an XML document, it can get transformed to |
| 814 |
// 0x0a or (if adjacent to an existing 0x0a) elided. |
| 815 |
// The correct thing to do probably would be to note in the standard |
| 816 |
// that all bets are off when transmitting line end characters - |
| 817 |
// but sending a line-end will probably end up as a line-end. |
| 818 |
// However I can't be bothered to start up a new thread about this |
| 819 |
// on the apps-samp list, so for the purposes of this test just |
| 820 |
// avoid sending it. |
| 821 |
// sbuf.append( (char) 0x0d ); |
| 822 |
for ( char c = 0x20; c <= 0x7f; c++ ) { |
| 823 |
sbuf.append( c ); |
| 824 |
} |
| 825 |
return sbuf.toString().toCharArray(); |
| 826 |
} |
| 827 |
|
| 828 |
/** |
| 829 |
* Main method. Tests a hub which is currently running. |
| 830 |
*/ |
| 831 |
public static void main( String[] args ) throws IOException { |
| 832 |
int status = runMain( args ); |
| 833 |
if ( status != 0 ) { |
| 834 |
System.exit( status ); |
| 835 |
} |
| 836 |
} |
| 837 |
|
| 838 |
/** |
| 839 |
* Does the work for the main method. |
| 840 |
* Use -help flag. |
| 841 |
*/ |
| 842 |
public static int runMain( String[] args ) throws IOException { |
| 843 |
String usage = new StringBuffer() |
| 844 |
.append( "\n Usage:" ) |
| 845 |
.append( "\n " ) |
| 846 |
.append( HubTester.class.getName() ) |
| 847 |
.append( "\n " ) |
| 848 |
.append( " [-help]" ) |
| 849 |
.append( " [-/+verbose]" ) |
| 850 |
.append( "\n " ) |
| 851 |
.append( " [-gui]" ) |
| 852 |
.append( "\n" ) |
| 853 |
.toString(); |
| 854 |
List argList = new ArrayList( Arrays.asList( args ) ); |
| 855 |
boolean gui = false; |
| 856 |
int verbAdjust = 0; |
| 857 |
for ( Iterator it = argList.iterator(); it.hasNext(); ) { |
| 858 |
String arg = (String) it.next(); |
| 859 |
if ( arg.equals( "-gui" ) ) { |
| 860 |
it.remove(); |
| 861 |
gui = true; |
| 862 |
} |
| 863 |
else if ( arg.equals( "-nogui" ) ) { |
| 864 |
it.remove(); |
| 865 |
gui = false; |
| 866 |
} |
| 867 |
else if ( arg.startsWith( "-v" ) ) { |
| 868 |
it.remove(); |
| 869 |
verbAdjust--; |
| 870 |
} |
| 871 |
else if ( arg.startsWith( "+v" ) ) { |
| 872 |
it.remove(); |
| 873 |
verbAdjust++; |
| 874 |
} |
| 875 |
else if ( arg.startsWith( "-h" ) ) { |
| 876 |
it.remove(); |
| 877 |
System.out.println( usage ); |
| 878 |
return 0; |
| 879 |
} |
| 880 |
else { |
| 881 |
it.remove(); |
| 882 |
System.err.println( usage ); |
| 883 |
return 1; |
| 884 |
} |
| 885 |
} |
| 886 |
assert argList.isEmpty(); |
| 887 |
|
| 888 |
// Adjust logging in accordance with verboseness flags. |
| 889 |
int logLevel = Level.WARNING.intValue() + 100 * verbAdjust; |
| 890 |
Logger.getLogger( "org.astrogrid.samp" ) |
| 891 |
.setLevel( Level.parse( Integer.toString( logLevel ) ) ); |
| 892 |
|
| 893 |
// Get profile. |
| 894 |
ClientProfile profile = DefaultClientProfile.getProfile(); |
| 895 |
|
| 896 |
// Set up GUI monitor if required. |
| 897 |
JFrame frame; |
| 898 |
if ( gui ) { |
| 899 |
frame = new JFrame( "HubTester Monitor" ); |
| 900 |
frame.getContentPane().add( new HubMonitor( profile, true, 1 ) ); |
| 901 |
frame.pack(); |
| 902 |
frame.setVisible( true ); |
| 903 |
} |
| 904 |
else { |
| 905 |
frame = null; |
| 906 |
} |
| 907 |
new HubTester( profile ).run(); |
| 908 |
if ( frame != null ) { |
| 909 |
frame.dispose(); |
| 910 |
} |
| 911 |
return 0; |
| 912 |
} |
| 913 |
|
| 914 |
/** |
| 915 |
* CallableClient implementation for testing. |
| 916 |
*/ |
| 917 |
private static class TestCallableClient extends ReplyCollector |
| 918 |
implements CallableClient { |
| 919 |
private final HubConnection connection_; |
| 920 |
private int pingCount_; |
| 921 |
public static final Subscriptions SUBS = getSubscriptions(); |
| 922 |
|
| 923 |
/** |
| 924 |
* Constructor. |
| 925 |
* |
| 926 |
* @param connection hub connection |
| 927 |
*/ |
| 928 |
TestCallableClient( HubConnection connection ) { |
| 929 |
super( connection ); |
| 930 |
connection_ = connection; |
| 931 |
} |
| 932 |
|
| 933 |
public void receiveNotification( String senderId, Message msg ) { |
| 934 |
processCall( senderId, msg ); |
| 935 |
} |
| 936 |
|
| 937 |
public void receiveCall( String senderId, String msgId, Message msg ) |
| 938 |
throws SampException { |
| 939 |
|
| 940 |
// If the message contains a WAITMILLIS_KEY entry, interpret this |
| 941 |
// as a number of milliseconds to wait before the response is |
| 942 |
// sent back to the hub. |
| 943 |
String swaitMillis = (String) msg.get( WAITMILLIS_KEY ); |
| 944 |
if ( swaitMillis != null ) { |
| 945 |
int waitMillis = SampUtils.decodeInt( swaitMillis ); |
| 946 |
if ( waitMillis > 0 ) { |
| 947 |
delay( waitMillis ); |
| 948 |
} |
| 949 |
} |
| 950 |
Response response; |
| 951 |
|
| 952 |
// Process a FAIL_MTYPE message specially. |
| 953 |
if ( msg.getMType().equals( FAIL_MTYPE ) ) { |
| 954 |
Map errs = (Map) msg.getParam( ERROR_KEY ); |
| 955 |
if ( errs == null ) { |
| 956 |
throw new IllegalArgumentException(); |
| 957 |
} |
| 958 |
response = Response.createErrorResponse( new ErrInfo( errs ) ); |
| 959 |
} |
| 960 |
|
| 961 |
// For other MTypes, pass them to the processCall method. |
| 962 |
else { |
| 963 |
try { |
| 964 |
response = |
| 965 |
Response |
| 966 |
.createSuccessResponse( processCall( senderId, msg ) ); |
| 967 |
} |
| 968 |
catch ( Throwable e ) { |
| 969 |
response = Response.createErrorResponse( new ErrInfo( e ) ); |
| 970 |
} |
| 971 |
} |
| 972 |
|
| 973 |
// Insert the message ID into the response if requested to do so. |
| 974 |
String msgIdQuery = (String) msg.get( MSGIDQUERY_KEY ); |
| 975 |
if ( msgIdQuery != null && SampUtils.decodeBoolean( msgIdQuery ) ) { |
| 976 |
response.put( MSGIDQUERY_KEY, msgId ); |
| 977 |
} |
| 978 |
response.check(); |
| 979 |
|
| 980 |
// Return the reply, whatever it is, to the hub. |
| 981 |
connection_.reply( msgId, response ); |
| 982 |
} |
| 983 |
|
| 984 |
/** |
| 985 |
* Do the work of responding to a given SAMP message. |
| 986 |
* |
| 987 |
* @param senderId sender public ID |
| 988 |
* @param msg message object |
| 989 |
* @return content of the successful reply's samp.result entry |
| 990 |
*/ |
| 991 |
private Map processCall( String senderId, Message msg ) { |
| 992 |
String mtype = msg.getMType(); |
| 993 |
|
| 994 |
// Returns the samp.params entry as the samp.result entry. |
| 995 |
if ( ECHO_MTYPE.equals( mtype ) ) { |
| 996 |
return msg.getParams(); |
| 997 |
} |
| 998 |
|
| 999 |
// Just bumps a counter and returns an empty samp.result |
| 1000 |
else if ( PING_MTYPE.equals( mtype ) ) { |
| 1001 |
synchronized ( this ) { |
| 1002 |
pingCount_++; |
| 1003 |
} |
| 1004 |
return new HashMap(); |
| 1005 |
} |
| 1006 |
|
| 1007 |
// Shouldn't happen. |
| 1008 |
else { |
| 1009 |
throw new TestException( "Unsubscribed MType? " + mtype ); |
| 1010 |
} |
| 1011 |
} |
| 1012 |
|
| 1013 |
/** |
| 1014 |
* Returns the subscriptions object for this client. |
| 1015 |
* |
| 1016 |
* @return subscriptions |
| 1017 |
*/ |
| 1018 |
private static Subscriptions getSubscriptions() { |
| 1019 |
Subscriptions subs = new Subscriptions(); |
| 1020 |
subs.addMType( ECHO_MTYPE ); |
| 1021 |
subs.addMType( PING_MTYPE ); |
| 1022 |
subs.addMType( FAIL_MTYPE ); |
| 1023 |
subs.check(); |
| 1024 |
return subs; |
| 1025 |
} |
| 1026 |
} |
| 1027 |
|
| 1028 |
/** |
| 1029 |
* CallableClient implementation which watches hub.event messages |
| 1030 |
* concerning the registration and attributes of other clients. |
| 1031 |
*/ |
| 1032 |
private static class ClientWatcher implements CallableClient { |
| 1033 |
|
| 1034 |
private final HubConnection connection_; |
| 1035 |
private final Map clientMap_; |
| 1036 |
private Throwable error_; |
| 1037 |
|
| 1038 |
/** |
| 1039 |
* Constructor. |
| 1040 |
* |
| 1041 |
* @param connection hub connection |
| 1042 |
*/ |
| 1043 |
ClientWatcher( HubConnection connection ) { |
| 1044 |
connection_ = connection; |
| 1045 |
clientMap_ = Collections.synchronizedMap( new HashMap() ); |
| 1046 |
} |
| 1047 |
|
| 1048 |
/** |
| 1049 |
* Returns a WatchedClient object corresponding to a given client |
| 1050 |
* public ID. This will contain information about the hub event |
| 1051 |
* messages this watcher has received concerning that client up till |
| 1052 |
* now. |
| 1053 |
* |
| 1054 |
* @param id public id of a client which has been registered |
| 1055 |
* @return watchedClient object if any messages have been received |
| 1056 |
* about <code>id</code>, otherwise null |
| 1057 |
*/ |
| 1058 |
public WatchedClient getClient( String id ) { |
| 1059 |
return (WatchedClient) clientMap_.get( id ); |
| 1060 |
} |
| 1061 |
|
| 1062 |
/** |
| 1063 |
* Returns an error if any error has been thrown during processing |
| 1064 |
* of hub event messages. |
| 1065 |
* |
| 1066 |
* @return deferred throwable, or null in case of no problems |
| 1067 |
*/ |
| 1068 |
public Throwable getError() { |
| 1069 |
return error_; |
| 1070 |
} |
| 1071 |
|
| 1072 |
/** |
| 1073 |
* Returns the hub connection used by this client. |
| 1074 |
* |
| 1075 |
* @return hub connection |
| 1076 |
*/ |
| 1077 |
public HubConnection getConnection() { |
| 1078 |
return connection_; |
| 1079 |
} |
| 1080 |
|
| 1081 |
public void receiveCall( String senderId, String msgId, Message msg ) { |
| 1082 |
receiveNotification( senderId, msg ); |
| 1083 |
Response response = |
| 1084 |
error_ == null |
| 1085 |
? Response.createSuccessResponse( new HashMap() ) |
| 1086 |
: Response.createErrorResponse( new ErrInfo( "broken" ) ); |
| 1087 |
try { |
| 1088 |
connection_.reply( msgId, response ); |
| 1089 |
} |
| 1090 |
catch ( SampException e ) { |
| 1091 |
error_ = e; |
| 1092 |
} |
| 1093 |
} |
| 1094 |
|
| 1095 |
public void receiveNotification( String senderId, Message msg ) { |
| 1096 |
if ( error_ == null ) { |
| 1097 |
try { |
| 1098 |
processMessage( senderId, msg ); |
| 1099 |
} |
| 1100 |
catch ( Throwable e ) { |
| 1101 |
error_ = e; |
| 1102 |
} |
| 1103 |
} |
| 1104 |
} |
| 1105 |
|
| 1106 |
private void processMessage( String senderId, Message msg ) |
| 1107 |
throws IOException { |
| 1108 |
|
| 1109 |
// Check the message actually comes from the hub. |
| 1110 |
assertEquals( senderId, connection_.getRegInfo().getHubId() ); |
| 1111 |
String mtype = msg.getMType(); |
| 1112 |
Map params = msg.getParams(); |
| 1113 |
|
| 1114 |
// Get (if necessary lazily creating) a WatchedClient object |
| 1115 |
// which this message concerns. |
| 1116 |
String id = (String) msg.getParam( "id" ); |
| 1117 |
assertTrue( id != null ); |
| 1118 |
synchronized ( clientMap_ ) { |
| 1119 |
if ( ! clientMap_.containsKey( id ) ) { |
| 1120 |
clientMap_.put( id, new WatchedClient() ); |
| 1121 |
} |
| 1122 |
WatchedClient client = (WatchedClient) clientMap_.get( id ); |
| 1123 |
|
| 1124 |
// Handle the various hub event messages by updating fields of |
| 1125 |
// the right WatchedClient object. |
| 1126 |
if ( REGISTER_MTYPE.equals( mtype ) ) { |
| 1127 |
assertTrue( ! client.reg_ ); |
| 1128 |
client.reg_ = true; |
| 1129 |
} |
| 1130 |
else if ( UNREGISTER_MTYPE.equals( mtype ) ) { |
| 1131 |
assertTrue( ! client.unreg_ ); |
| 1132 |
client.unreg_ = true; |
| 1133 |
} |
| 1134 |
else if ( METADATA_MTYPE.equals( mtype ) ) { |
| 1135 |
assertTrue( params.containsKey( "metadata" ) ); |
| 1136 |
Metadata meta = |
| 1137 |
Metadata |
| 1138 |
.asMetadata( (Map) params.get( "metadata" ) ); |
| 1139 |
meta.check(); |
| 1140 |
client.meta_ = meta; |
| 1141 |
} |
| 1142 |
else if ( SUBSCRIPTIONS_MTYPE.equals( mtype ) ) { |
| 1143 |
assertTrue( params.containsKey( "subscriptions" ) ); |
| 1144 |
Subscriptions subs = |
| 1145 |
Subscriptions |
| 1146 |
.asSubscriptions( (Map) params.get( "subscriptions" ) ); |
| 1147 |
subs.check(); |
| 1148 |
client.subs_ = subs; |
| 1149 |
} |
| 1150 |
else { |
| 1151 |
fail(); |
| 1152 |
} |
| 1153 |
clientMap_.notifyAll(); |
| 1154 |
} |
| 1155 |
} |
| 1156 |
|
| 1157 |
public void receiveResponse( String responderId, String msgTag, |
| 1158 |
Response response ) { |
| 1159 |
throw new UnsupportedOperationException(); |
| 1160 |
} |
| 1161 |
|
| 1162 |
/** |
| 1163 |
* Returns a suitable subscriptions object for this client. |
| 1164 |
* |
| 1165 |
* @return subscriptions |
| 1166 |
*/ |
| 1167 |
public static Subscriptions getSubscriptions() { |
| 1168 |
Subscriptions subs = new Subscriptions(); |
| 1169 |
subs.addMType( REGISTER_MTYPE ); |
| 1170 |
subs.addMType( UNREGISTER_MTYPE ); |
| 1171 |
subs.addMType( METADATA_MTYPE ); |
| 1172 |
subs.addMType( SUBSCRIPTIONS_MTYPE ); |
| 1173 |
subs.check(); |
| 1174 |
return subs; |
| 1175 |
} |
| 1176 |
|
| 1177 |
/** |
| 1178 |
* Returns a suitable metadata object for this client. |
| 1179 |
*/ |
| 1180 |
public static Metadata getMetadata() { |
| 1181 |
Metadata meta = new Metadata(); |
| 1182 |
meta.setName( "ClientWatcher" ); |
| 1183 |
meta.setDescriptionText( "Tracks other clients for HubTester" ); |
| 1184 |
meta.check(); |
| 1185 |
return meta; |
| 1186 |
} |
| 1187 |
} |
| 1188 |
|
| 1189 |
/** |
| 1190 |
* Struct-type utility class which aggregates mutable information about |
| 1191 |
* a client, to be updated in response to hub event messages. |
| 1192 |
*/ |
| 1193 |
private static class WatchedClient { |
| 1194 |
|
| 1195 |
/** Whether this client has ever been registered. */ |
| 1196 |
boolean reg_; |
| 1197 |
|
| 1198 |
/** Whether this clent has ever been unregistered. */ |
| 1199 |
boolean unreg_; |
| 1200 |
|
| 1201 |
/** Current metadata object for this client. */ |
| 1202 |
Metadata meta_; |
| 1203 |
|
| 1204 |
/** Current subscriptions object for this client. */ |
| 1205 |
Subscriptions subs_; |
| 1206 |
} |
| 1207 |
} |