| 1 |
package org.astrogrid.samp.hub; |
| 2 |
|
| 3 |
import java.io.File; |
| 4 |
import java.io.IOException; |
| 5 |
import java.io.InputStream; |
| 6 |
import java.util.ArrayList; |
| 7 |
import java.util.Arrays; |
| 8 |
import java.util.Iterator; |
| 9 |
import java.util.List; |
| 10 |
import java.util.Map; |
| 11 |
import java.util.WeakHashMap; |
| 12 |
import java.util.logging.Level; |
| 13 |
import java.util.logging.Logger; |
| 14 |
import javax.swing.JFrame; |
| 15 |
import org.astrogrid.samp.ShutdownManager; |
| 16 |
import org.astrogrid.samp.SampUtils; |
| 17 |
import org.astrogrid.samp.client.ClientProfile; |
| 18 |
import org.astrogrid.samp.client.HubConnection; |
| 19 |
import org.astrogrid.samp.client.SampException; |
| 20 |
import org.astrogrid.samp.httpd.UtilServer; |
| 21 |
import org.astrogrid.samp.web.WebHubProfile; |
| 22 |
import org.astrogrid.samp.web.WebHubProfileFactory; |
| 23 |
import org.astrogrid.samp.xmlrpc.StandardHubProfile; |
| 24 |
import org.astrogrid.samp.xmlrpc.StandardHubProfileFactory; |
| 25 |
import org.astrogrid.samp.xmlrpc.XmlRpcKit; |
| 26 |
|
| 27 |
/** |
| 28 |
* Class which manages a hub and its associated profiles. |
| 29 |
* Static methods are provided for starting a hub in the current or an |
| 30 |
* external JVM, and a <code>main()</code> method is provided for |
| 31 |
* use from the command line. |
| 32 |
* |
| 33 |
* <p>Some of the static methods allow you to indicate which hub profiles |
| 34 |
* should be used, others use a default. The default list can be set |
| 35 |
* programmatically by using the {@link #setDefaultProfileClasses} method |
| 36 |
* or externally by using the |
| 37 |
* {@value #HUBPROFILES_PROP} and {@value #EXTRAHUBPROFILES_PROP} |
| 38 |
* system properties. |
| 39 |
* So, for instance, running an application with |
| 40 |
* <code>-Djsamp.hub.profiles=web,std</code> will cause it to run hubs |
| 41 |
* using both the Standard and Web profiles if it does not explicitly choose |
| 42 |
* profiles. |
| 43 |
* |
| 44 |
* @author Mark Taylor |
| 45 |
* @author Sylvain Lafrasse |
| 46 |
* @since 31 Jan 2011 |
| 47 |
*/ |
| 48 |
public class Hub { |
| 49 |
|
| 50 |
private final HubService service_; |
| 51 |
private final List profileList_; |
| 52 |
private static Class[] defaultDefaultProfileClasses_ = { |
| 53 |
StandardHubProfile.class, |
| 54 |
WebHubProfile.class, |
| 55 |
}; |
| 56 |
private static Class[] defaultDefaultExtraProfileClasses_ = { |
| 57 |
}; |
| 58 |
private static Class[] defaultProfileClasses_ = |
| 59 |
createDefaultProfileClasses( false ); |
| 60 |
private static Class[] defaultExtraProfileClasses_ = |
| 61 |
createDefaultProfileClasses( true ); |
| 62 |
private static final Map hubList_ = new WeakHashMap(); |
| 63 |
private static final Logger logger_ = |
| 64 |
Logger.getLogger( Hub.class.getName() ); |
| 65 |
|
| 66 |
/** |
| 67 |
* System property name for supplying default profiles ({@value}) |
| 68 |
* available at hub startup. |
| 69 |
* The value of this property, if any, will be fed to |
| 70 |
* {@link #parseProfileList}. |
| 71 |
*/ |
| 72 |
public static final String HUBPROFILES_PROP = |
| 73 |
"jsamp.hub.profiles"; |
| 74 |
|
| 75 |
/** |
| 76 |
* System property name for supplying default profiles ({@value}) |
| 77 |
* additional to those in {@link #HUBPROFILES_PROP} which will be |
| 78 |
* supported by the hub but switched off at hub startup time. |
| 79 |
* The value of this property, if any, will be fed to |
| 80 |
* {@link #parseProfileList}. |
| 81 |
*/ |
| 82 |
public static final String EXTRAHUBPROFILES_PROP = |
| 83 |
"jsamp.hub.profiles.extra"; |
| 84 |
|
| 85 |
/** |
| 86 |
* Constructor. |
| 87 |
* Note that this object does not start the service, it must be |
| 88 |
* started explicitly, either before or after this constructor is called. |
| 89 |
* |
| 90 |
* @param service hub service |
| 91 |
*/ |
| 92 |
public Hub( HubService service ) { |
| 93 |
service_ = service; |
| 94 |
profileList_ = new ArrayList(); |
| 95 |
synchronized ( hubList_ ) { |
| 96 |
hubList_.put( this, null ); |
| 97 |
} |
| 98 |
} |
| 99 |
|
| 100 |
/** |
| 101 |
* Stops this hub and its profiles running. |
| 102 |
*/ |
| 103 |
public synchronized void shutdown() { |
| 104 |
logger_.info( "Shutting down hub service" ); |
| 105 |
try { |
| 106 |
service_.shutdown(); |
| 107 |
} |
| 108 |
catch ( Throwable e ) { |
| 109 |
logger_.log( Level.WARNING, "Service shutdown error: " + e, e ); |
| 110 |
} |
| 111 |
for ( Iterator it = profileList_.iterator(); it.hasNext(); ) { |
| 112 |
HubProfile profile = (HubProfile) it.next(); |
| 113 |
logger_.info( "Shutting down hub profile " |
| 114 |
+ profile.getProfileName() ); |
| 115 |
try { |
| 116 |
profile.stop(); |
| 117 |
} |
| 118 |
catch ( IOException e ) { |
| 119 |
logger_.log( Level.WARNING, |
| 120 |
"Failed to stop profile " |
| 121 |
+ profile.getProfileName(), e ); |
| 122 |
} |
| 123 |
it.remove(); |
| 124 |
} |
| 125 |
synchronized ( hubList_ ) { |
| 126 |
hubList_.remove( this ); |
| 127 |
} |
| 128 |
ShutdownManager.getInstance().unregisterHook( this ); |
| 129 |
} |
| 130 |
|
| 131 |
/** |
| 132 |
* Starts a profile running on behalf of this hub. |
| 133 |
* |
| 134 |
* @param profile to start |
| 135 |
*/ |
| 136 |
public synchronized void startProfile( final HubProfile profile ) |
| 137 |
throws IOException { |
| 138 |
if ( profileList_.contains( profile ) ) { |
| 139 |
logger_.info( "Profile " + profile.getProfileName() |
| 140 |
+ " already started in this hub" ); |
| 141 |
} |
| 142 |
else { |
| 143 |
profile.start( new ClientProfile() { |
| 144 |
public HubConnection register() throws SampException { |
| 145 |
return service_.register( profile ); |
| 146 |
} |
| 147 |
public boolean isHubRunning() { |
| 148 |
return service_.isHubRunning(); |
| 149 |
} |
| 150 |
} ); |
| 151 |
profileList_.add( profile ); |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
/** |
| 156 |
* Stops a profile running on behalf of this hub, and disconnects |
| 157 |
* all clients registered with it. |
| 158 |
* |
| 159 |
* @param profile profile to stop |
| 160 |
*/ |
| 161 |
public synchronized void stopProfile( HubProfile profile ) { |
| 162 |
logger_.info( "Shutting down hub profile " + profile.getProfileName() |
| 163 |
+ " and disconnecting clients" ); |
| 164 |
try { |
| 165 |
profile.stop(); |
| 166 |
} |
| 167 |
catch ( IOException e ) { |
| 168 |
logger_.log( Level.WARNING, |
| 169 |
"Failed to stop profile " |
| 170 |
+ profile.getProfileName(), e ); |
| 171 |
} |
| 172 |
profileList_.remove( profile ); |
| 173 |
service_.disconnectAll( profile ); |
| 174 |
} |
| 175 |
|
| 176 |
/** |
| 177 |
* Returns the hub service associated with this hub. |
| 178 |
* |
| 179 |
* @return hub service |
| 180 |
*/ |
| 181 |
public HubService getHubService() { |
| 182 |
return service_; |
| 183 |
} |
| 184 |
|
| 185 |
/** |
| 186 |
* Returns the hub profiles currently running on behalf of this hub. |
| 187 |
* |
| 188 |
* @return profiles that have been started and not yet stopped by this hub |
| 189 |
*/ |
| 190 |
public HubProfile[] getRunningProfiles() { |
| 191 |
return (HubProfile[]) profileList_.toArray( new HubProfile[ 0 ] ); |
| 192 |
} |
| 193 |
|
| 194 |
/** |
| 195 |
* Returns a window for user monitoring and control of this hub, |
| 196 |
* if available. |
| 197 |
* The default implementation returns null, but this may be overridden |
| 198 |
* depending on how this hub was instantiated. |
| 199 |
* |
| 200 |
* @return hub monitor/control window, or null |
| 201 |
*/ |
| 202 |
public JFrame getWindow() { |
| 203 |
return null; |
| 204 |
} |
| 205 |
|
| 206 |
/** |
| 207 |
* Returns a standard list of known HubProfileFactories. |
| 208 |
* This is used when parsing hub profile lists |
| 209 |
* ({@link #parseProfileList} to supply the well-known named profiles. |
| 210 |
* |
| 211 |
* @return array of known hub profile factories |
| 212 |
*/ |
| 213 |
public static HubProfileFactory[] getKnownHubProfileFactories() { |
| 214 |
return new HubProfileFactory[] { |
| 215 |
new StandardHubProfileFactory(), |
| 216 |
new WebHubProfileFactory(), |
| 217 |
}; |
| 218 |
} |
| 219 |
|
| 220 |
/** |
| 221 |
* Returns a copy of the default set of HubProfile classes used |
| 222 |
* when a hub is run and the list of profiles is not set explicitly. |
| 223 |
* Each element should be an implementation of {@link HubProfile} |
| 224 |
* with a no-arg constructor. |
| 225 |
* |
| 226 |
* @param extra false for starting classes, true for additional ones |
| 227 |
* @return array of hub profile classes |
| 228 |
*/ |
| 229 |
public static Class[] getDefaultProfileClasses( boolean extra ) { |
| 230 |
return (Class[]) ( extra ? defaultExtraProfileClasses_ |
| 231 |
: defaultProfileClasses_ ).clone(); |
| 232 |
} |
| 233 |
|
| 234 |
/** |
| 235 |
* Sets the default set of HubProfile classes. |
| 236 |
* |
| 237 |
* @param clazzes array to be returned by getDefaultProfileClasses |
| 238 |
* @param extra false for starting classes, true for additional ones |
| 239 |
*/ |
| 240 |
public static void setDefaultProfileClasses( Class[] clazzes, |
| 241 |
boolean extra ) { |
| 242 |
for ( int ip = 0; ip < clazzes.length; ip++ ) { |
| 243 |
Class clazz = clazzes[ ip ]; |
| 244 |
if ( ! HubProfile.class.isAssignableFrom( clazz ) ) { |
| 245 |
throw new IllegalArgumentException( "Class " + clazz.getName() |
| 246 |
+ " not a HubProfile" ); |
| 247 |
} |
| 248 |
} |
| 249 |
clazzes = (Class[]) clazzes.clone(); |
| 250 |
if ( extra ) { |
| 251 |
defaultExtraProfileClasses_ = clazzes; |
| 252 |
} |
| 253 |
else { |
| 254 |
defaultProfileClasses_ = clazzes; |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
/** |
| 259 |
* Invoked at class load time to come up with the list of hub |
| 260 |
* profiles to use when no profiles are specified explicitly. |
| 261 |
* By default this is just the standard profile, but if the |
| 262 |
* {@link #HUBPROFILES_PROP} system property is defined its value |
| 263 |
* is used instead. |
| 264 |
* |
| 265 |
* @param extra false for starting classes, true for additional ones |
| 266 |
* @return default array of hub profile classes |
| 267 |
*/ |
| 268 |
private static Class[] createDefaultProfileClasses( boolean extra ) { |
| 269 |
String listTxt = System.getProperty( extra ? EXTRAHUBPROFILES_PROP |
| 270 |
: HUBPROFILES_PROP ); |
| 271 |
if ( listTxt != null ) { |
| 272 |
HubProfileFactory[] facts = parseProfileList( listTxt ); |
| 273 |
Class[] clazzes = new Class[ facts.length ]; |
| 274 |
for ( int i = 0; i < facts.length; i++ ) { |
| 275 |
clazzes[ i ] = facts[ i ].getHubProfileClass(); |
| 276 |
} |
| 277 |
return clazzes; |
| 278 |
} |
| 279 |
else { |
| 280 |
return extra ? defaultDefaultExtraProfileClasses_ |
| 281 |
: defaultDefaultProfileClasses_; |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
/** |
| 286 |
* Parses a string representing a list of hub profiles. |
| 287 |
* The result is an array of HubProfileFactories. |
| 288 |
* The list is comma-separated, and each element may be |
| 289 |
* <em>either</em> the {@link HubProfileFactory#getName name} |
| 290 |
* of a HubProfileFactory |
| 291 |
* <em>or</em> the classname of a {@link HubProfile} implementation |
| 292 |
* with a suitable no-arg constructor. |
| 293 |
* |
| 294 |
* @param listTxt comma-separated list |
| 295 |
* @return array of hub profile factories |
| 296 |
* @throws IllegalArgumentException if unknown |
| 297 |
*/ |
| 298 |
public static HubProfileFactory[] parseProfileList( String listTxt ) { |
| 299 |
String[] txtItems = listTxt == null || listTxt.trim().length() == 0 |
| 300 |
? new String[ 0 ] |
| 301 |
: listTxt.split( "," ); |
| 302 |
List factoryList = new ArrayList(); |
| 303 |
for ( int i = 0; i < txtItems.length; i++ ) { |
| 304 |
factoryList.add( parseProfileClass( txtItems[ i ] ) ); |
| 305 |
} |
| 306 |
return (HubProfileFactory[]) |
| 307 |
factoryList.toArray( new HubProfileFactory[ 0 ] ); |
| 308 |
} |
| 309 |
|
| 310 |
/** |
| 311 |
* Parses a string representing a hub profile. Each element may be |
| 312 |
* <em>either</em> the {@link HubProfileFactory#getName name} |
| 313 |
* of a HubProfileFactory |
| 314 |
* <em>or</em> the classname of a {@link HubProfile} implementation |
| 315 |
* with a suitable no-arg constructor. |
| 316 |
* |
| 317 |
* @param txt string |
| 318 |
* @return hub profile factory |
| 319 |
* @throws IllegalArgumentException if unknown |
| 320 |
*/ |
| 321 |
private static HubProfileFactory parseProfileClass( String txt ) { |
| 322 |
HubProfileFactory[] profFacts = getKnownHubProfileFactories(); |
| 323 |
for ( int i = 0; i < profFacts.length; i++ ) { |
| 324 |
if ( txt.equals( profFacts[ i ].getName() ) ) { |
| 325 |
return profFacts[ i ]; |
| 326 |
} |
| 327 |
} |
| 328 |
final Class clazz; |
| 329 |
try { |
| 330 |
clazz = Class.forName( txt ); |
| 331 |
} |
| 332 |
catch ( ClassNotFoundException e ) { |
| 333 |
throw (IllegalArgumentException) |
| 334 |
new IllegalArgumentException( "No known hub/class " + txt ) |
| 335 |
.initCause( e ); |
| 336 |
} |
| 337 |
if ( HubProfile.class.isAssignableFrom( clazz ) ) { |
| 338 |
return new HubProfileFactory() { |
| 339 |
public Class getHubProfileClass() { |
| 340 |
return clazz; |
| 341 |
} |
| 342 |
public String[] getFlagsUsage() { |
| 343 |
return new String[ 0 ]; |
| 344 |
} |
| 345 |
public String getName() { |
| 346 |
return clazz.getName(); |
| 347 |
} |
| 348 |
public HubProfile createHubProfile( List flagList ) |
| 349 |
throws IOException { |
| 350 |
try { |
| 351 |
return (HubProfile) clazz.newInstance(); |
| 352 |
} |
| 353 |
catch ( IllegalAccessException e ) { |
| 354 |
throw (IOException) |
| 355 |
new IOException( "Can't create " + clazz.getName() |
| 356 |
+ " instance" ) |
| 357 |
.initCause( e ); |
| 358 |
} |
| 359 |
catch ( InstantiationException e ) { |
| 360 |
throw (IOException) |
| 361 |
new IOException( "Can't create " + clazz.getName() |
| 362 |
+ " instance" ) |
| 363 |
.initCause( e ); |
| 364 |
} |
| 365 |
catch ( ExceptionInInitializerError e ) { |
| 366 |
Throwable cause = e.getCause(); |
| 367 |
if ( cause instanceof IOException ) { |
| 368 |
throw (IOException) cause; |
| 369 |
} |
| 370 |
else { |
| 371 |
throw (IOException) |
| 372 |
new IOException( "Can't create " |
| 373 |
+ clazz.getName() |
| 374 |
+ " instance" ) |
| 375 |
.initCause( e ); |
| 376 |
} |
| 377 |
} |
| 378 |
} |
| 379 |
}; |
| 380 |
} |
| 381 |
else { |
| 382 |
throw new IllegalArgumentException( clazz + " is not a " |
| 383 |
+ HubProfile.class.getName() ); |
| 384 |
} |
| 385 |
} |
| 386 |
|
| 387 |
/** |
| 388 |
* Returns an array of default Hub Profiles. |
| 389 |
* This is the result of calling the no-arg constructor |
| 390 |
* for each element of the result of {@link #getDefaultProfileClasses}. |
| 391 |
* |
| 392 |
* @param extra false for starting profiles, true for additional ones |
| 393 |
* @return array of hub profiles to use by default |
| 394 |
*/ |
| 395 |
public static HubProfile[] createDefaultProfiles( boolean extra ) { |
| 396 |
Class[] clazzes = getDefaultProfileClasses( extra ); |
| 397 |
List hubProfileList = new ArrayList(); |
| 398 |
for ( int ip = 0; ip < clazzes.length; ip++ ) { |
| 399 |
Class clazz = clazzes[ ip ]; |
| 400 |
try { |
| 401 |
hubProfileList.add( (HubProfile) clazz.newInstance() ); |
| 402 |
} |
| 403 |
catch ( ClassCastException e ) { |
| 404 |
logger_.warning( "No hub profile " + clazz.getName() |
| 405 |
+ " - not a " + HubProfile.class.getName() ); |
| 406 |
} |
| 407 |
catch ( InstantiationException e ) { |
| 408 |
logger_.warning( "No hub profile " + clazz.getName() |
| 409 |
+ " - failed to instantiate (" + e + ")" ); |
| 410 |
} |
| 411 |
catch ( IllegalAccessException e ) { |
| 412 |
logger_.warning( "No hub profile " + clazz.getName() |
| 413 |
+ " - inaccessible constructor (" + e + ")" ); |
| 414 |
} |
| 415 |
catch ( ExceptionInInitializerError e ) { |
| 416 |
logger_.warning( "No hub profile " + clazz.getName() |
| 417 |
+ " - construction error" |
| 418 |
+ " (" + e.getCause() + ")" ); |
| 419 |
} |
| 420 |
} |
| 421 |
return (HubProfile[]) hubProfileList.toArray( new HubProfile[ 0 ] ); |
| 422 |
} |
| 423 |
|
| 424 |
/** |
| 425 |
* Starts a SAMP hub with given sets of profiles. |
| 426 |
* The returned hub is running. |
| 427 |
* |
| 428 |
* <p>The <code>profiles</code> argument gives the profiles which will |
| 429 |
* be started initially, and the <code>extraProfiles</code> argument |
| 430 |
* lists more that can be started under user control later. |
| 431 |
* If either or both list is given as null, suitable defaults will be used. |
| 432 |
* |
| 433 |
* <p>If the hub mode corresponds to one of the GUI options, |
| 434 |
* one of two things will happen. An attempt will be made to install |
| 435 |
* an icon in the "system tray"; if this is successful, the attached |
| 436 |
* popup menu will provide options for displaying the hub window and |
| 437 |
* for shutting it down. If no system tray is available, the hub window |
| 438 |
* will be posted directly, and the hub will shut down when this window |
| 439 |
* is closed. System tray functionality is only available when running |
| 440 |
* under Java 1.6 or later, and when using a suitable display manager. |
| 441 |
* |
| 442 |
* @param hubMode hub mode |
| 443 |
* @param profiles SAMP profiles to support on hub startup; |
| 444 |
* if null a default set will be used |
| 445 |
* @param extraProfiles SAMP profiles to offer for later startup under |
| 446 |
* user control; if null a default set will be used |
| 447 |
* @return running hub |
| 448 |
*/ |
| 449 |
public static Hub runHub( HubServiceMode hubMode, HubProfile[] profiles, |
| 450 |
HubProfile[] extraProfiles ) |
| 451 |
throws IOException { |
| 452 |
|
| 453 |
// Get values for the list of starting profiles, and the list of |
| 454 |
// additional profiles that may be started later. |
| 455 |
// If these have not been specified explicitly, use defaults. |
| 456 |
if ( profiles == null ) { |
| 457 |
profiles = createDefaultProfiles( false ); |
| 458 |
} |
| 459 |
if ( extraProfiles == null ) { |
| 460 |
extraProfiles = createDefaultProfiles( true ); |
| 461 |
} |
| 462 |
List profList = new ArrayList(); |
| 463 |
profList.addAll( Arrays.asList( profiles ) ); |
| 464 |
for ( int ip = 0; ip < extraProfiles.length; ip++ ) { |
| 465 |
HubProfile ep = extraProfiles[ ip ]; |
| 466 |
boolean gotit = false; |
| 467 |
for ( int jp = 0; jp < profiles.length; jp++ ) { |
| 468 |
gotit = gotit |
| 469 |
|| profiles[ jp ].getClass().equals( ep.getClass() ); |
| 470 |
} |
| 471 |
if ( ! gotit ) { |
| 472 |
profList.add( ep ); |
| 473 |
} |
| 474 |
} |
| 475 |
HubProfile[] allProfiles = |
| 476 |
(HubProfile[]) profList.toArray( new HubProfile[ 0 ] ); |
| 477 |
|
| 478 |
// Construct a hub service ready to use the full profile list. |
| 479 |
final Hub[] runners = new Hub[ 1 ]; |
| 480 |
final HubServiceMode.ServiceGui serviceGui = |
| 481 |
hubMode.createHubService( KeyGenerator.createRandom(), |
| 482 |
allProfiles, runners ); |
| 483 |
HubService hubService = serviceGui.getHubService(); |
| 484 |
final Hub hub = new Hub( hubService ) { |
| 485 |
public JFrame getWindow() { |
| 486 |
return serviceGui.getWindow(); |
| 487 |
} |
| 488 |
}; |
| 489 |
runners[ 0 ] = hub; |
| 490 |
|
| 491 |
// Start the initial profiles. |
| 492 |
int nStarted = 0; |
| 493 |
IOException error1 = null; |
| 494 |
for ( int ip = 0; ip < profiles.length; ip++ ) { |
| 495 |
HubProfile prof = profiles[ ip ]; |
| 496 |
String pname = prof.getProfileName(); |
| 497 |
try { |
| 498 |
logger_.info( "Starting hub profile " + pname ); |
| 499 |
hub.startProfile( prof ); |
| 500 |
nStarted++; |
| 501 |
} |
| 502 |
catch ( IOException e ) { |
| 503 |
if ( error1 == null ) { |
| 504 |
error1 = e; |
| 505 |
} |
| 506 |
logger_.log( Level.WARNING, |
| 507 |
"Failed to start SAMP hub profile " + pname, e ); |
| 508 |
} |
| 509 |
} |
| 510 |
logger_.info( "Started " + nStarted + "/" + profiles.length |
| 511 |
+ " SAMP profiles" ); |
| 512 |
if ( nStarted == 0 && profiles.length > 0 ) { |
| 513 |
assert error1 != null; |
| 514 |
throw (IOException) |
| 515 |
new IOException( "No SAMP profiles started: " + error1 ) |
| 516 |
.initCause( error1 ); |
| 517 |
} |
| 518 |
|
| 519 |
// Start the hub service itself. |
| 520 |
logger_.info( "Starting hub service" ); |
| 521 |
hubService.start(); |
| 522 |
ShutdownManager.getInstance() |
| 523 |
.registerHook( hub, ShutdownManager.HUB_SEQUENCE, |
| 524 |
new Runnable() { |
| 525 |
public void run() { |
| 526 |
hub.shutdown(); |
| 527 |
} |
| 528 |
} ); |
| 529 |
|
| 530 |
// Return the running hub. |
| 531 |
return hub; |
| 532 |
} |
| 533 |
|
| 534 |
/** |
| 535 |
* Starts a SAMP hub with a default set of profiles. |
| 536 |
* This convenience method invokes <code>runHub(hubMode,null,null)</code>. |
| 537 |
* |
| 538 |
* @param hubMode hub mode |
| 539 |
* @return running hub |
| 540 |
* @see #runHub(HubServiceMode,HubProfile[],HubProfile[]) |
| 541 |
*/ |
| 542 |
public static Hub runHub( HubServiceMode hubMode ) throws IOException { |
| 543 |
return runHub( hubMode, null, null ); |
| 544 |
} |
| 545 |
|
| 546 |
/** |
| 547 |
* Attempts to start a hub in a new JVM with a given set |
| 548 |
* of profiles. The resulting hub can therefore outlast the |
| 549 |
* lifetime of the current application. |
| 550 |
* Because of the OS interaction required, it's hard to make this |
| 551 |
* bulletproof, and it may fail without an exception, but we do our best. |
| 552 |
* |
| 553 |
* <p>The classes specified by the <code>profileClasses</code> and |
| 554 |
* <code>extraProfileClasses</code> arguments must implement |
| 555 |
* {@link HubProfile} and must have a no-arg constructor. |
| 556 |
* If null is given in either case suitable defaults, taken from the |
| 557 |
* current JVM, are used. |
| 558 |
* |
| 559 |
* @param hubMode hub mode |
| 560 |
* @param profileClasses hub profile classes to start on hub startup |
| 561 |
* @param extraProfileClasses hub profile classes which may be started |
| 562 |
* later under user control |
| 563 |
* @see #checkExternalHubAvailability |
| 564 |
*/ |
| 565 |
public static void runExternalHub( HubServiceMode hubMode, |
| 566 |
Class[] profileClasses, |
| 567 |
Class[] extraProfileClasses ) |
| 568 |
throws IOException { |
| 569 |
String classpath = System.getProperty( "java.class.path" ); |
| 570 |
if ( classpath == null || classpath.trim().length() == 0 ) { |
| 571 |
throw new IOException( "No classpath available - JNLP context?" ); |
| 572 |
} |
| 573 |
File javaHome = new File( System.getProperty( "java.home" ) ); |
| 574 |
File javaExec = new File( new File( javaHome, "bin" ), "java" ); |
| 575 |
String javacmd = ( javaExec.exists() && ! javaExec.isDirectory() ) |
| 576 |
? javaExec.toString() |
| 577 |
: "java"; |
| 578 |
String[] propagateProps = new String[] { |
| 579 |
XmlRpcKit.IMPL_PROP, |
| 580 |
UtilServer.PORT_PROP, |
| 581 |
SampUtils.LOCALHOST_PROP, |
| 582 |
HUBPROFILES_PROP, |
| 583 |
EXTRAHUBPROFILES_PROP, |
| 584 |
"java.awt.Window.locationByPlatform", |
| 585 |
}; |
| 586 |
List argList = new ArrayList(); |
| 587 |
argList.add( javacmd ); |
| 588 |
for ( int ip = 0; ip < propagateProps.length; ip++ ) { |
| 589 |
String propName = propagateProps[ ip ]; |
| 590 |
String propVal = System.getProperty( propName ); |
| 591 |
if ( propVal != null ) { |
| 592 |
argList.add( "-D" + propName + "=" + propVal ); |
| 593 |
} |
| 594 |
} |
| 595 |
argList.add( "-classpath" ); |
| 596 |
argList.add( classpath ); |
| 597 |
argList.add( Hub.class.getName() ); |
| 598 |
argList.add( "-mode" ); |
| 599 |
argList.add( hubMode.toString() ); |
| 600 |
if ( profileClasses != null ) { |
| 601 |
argList.add( "-profiles" ); |
| 602 |
StringBuffer profArg = new StringBuffer(); |
| 603 |
for ( int ip = 0; ip < profileClasses.length; ip++ ) { |
| 604 |
if ( ip > 0 ) { |
| 605 |
profArg.append( ',' ); |
| 606 |
} |
| 607 |
profArg.append( profileClasses[ ip ].getName() ); |
| 608 |
} |
| 609 |
argList.add( profArg.toString() ); |
| 610 |
} |
| 611 |
if ( extraProfileClasses != null ) { |
| 612 |
argList.add( "-extraprofiles" ); |
| 613 |
StringBuffer eprofArg = new StringBuffer(); |
| 614 |
for ( int ip = 0; ip < profileClasses.length; ip++ ) { |
| 615 |
if ( ip > 0 ) { |
| 616 |
eprofArg.append( ',' ); |
| 617 |
} |
| 618 |
eprofArg.append( extraProfileClasses[ ip ].getName() ); |
| 619 |
} |
| 620 |
argList.add( eprofArg.toString() ); |
| 621 |
} |
| 622 |
String[] args = (String[]) argList.toArray( new String[ 0 ] ); |
| 623 |
StringBuffer cmdbuf = new StringBuffer(); |
| 624 |
for ( int iarg = 0; iarg < args.length; iarg++ ) { |
| 625 |
if ( iarg > 0 ) { |
| 626 |
cmdbuf.append( ' ' ); |
| 627 |
} |
| 628 |
cmdbuf.append( args[ iarg ] ); |
| 629 |
} |
| 630 |
logger_.info( "Starting external hub" ); |
| 631 |
logger_.info( cmdbuf.toString() ); |
| 632 |
execBackground( args ); |
| 633 |
} |
| 634 |
|
| 635 |
/** |
| 636 |
* Attempts to run a hub in a new JVM with a default set of profiles. |
| 637 |
* The default set is taken from that in this JVM. |
| 638 |
* This convenience method invokes |
| 639 |
* <code>runExternalHub(hubMode,null,null)</code>. |
| 640 |
* |
| 641 |
* @param hubMode hub mode |
| 642 |
* @see #runExternalHub(HubServiceMode,java.lang.Class[],java.lang.Class[]) |
| 643 |
*/ |
| 644 |
public static void runExternalHub( HubServiceMode hubMode ) |
| 645 |
throws IOException { |
| 646 |
runExternalHub( hubMode, null, null ); |
| 647 |
} |
| 648 |
|
| 649 |
/** |
| 650 |
* Returns an array of all the instances of this class which are |
| 651 |
* currently running. |
| 652 |
* |
| 653 |
* @return running hubs |
| 654 |
*/ |
| 655 |
public static Hub[] getRunningHubs() { |
| 656 |
List list; |
| 657 |
synchronized ( hubList_ ) { |
| 658 |
list = new ArrayList( hubList_.keySet() ); |
| 659 |
} |
| 660 |
for ( Iterator it = list.iterator(); it.hasNext(); ) { |
| 661 |
Hub hub = (Hub) it.next(); |
| 662 |
if ( ! hub.getHubService().isHubRunning() ) { |
| 663 |
it.remove(); |
| 664 |
} |
| 665 |
} |
| 666 |
return (Hub[]) list.toArray( new Hub[ 0 ] ); |
| 667 |
} |
| 668 |
|
| 669 |
/** |
| 670 |
* Attempts to determine whether an external hub can be started using |
| 671 |
* {@link #runExternalHub runExternalHub}. |
| 672 |
* If it can be determined that such an |
| 673 |
* attempt would fail, this method will throw an exception with |
| 674 |
* an informative message. This method succeeding is not a guarantee |
| 675 |
* that an external hub can be started successfullly. |
| 676 |
* The behaviour of this method is not expected to change over the |
| 677 |
* lifetime of a given JVM. |
| 678 |
*/ |
| 679 |
public static void checkExternalHubAvailability() throws IOException { |
| 680 |
String classpath = System.getProperty( "java.class.path" ); |
| 681 |
if ( classpath == null || classpath.trim().length() == 0 ) { |
| 682 |
throw new IOException( "No classpath available - JNLP context?" ); |
| 683 |
} |
| 684 |
if ( System.getProperty( "jnlpx.jvm" ) != null ) { |
| 685 |
throw new IOException( "Running under WebStart" |
| 686 |
+ " - external hub not likely to work" ); |
| 687 |
} |
| 688 |
} |
| 689 |
|
| 690 |
/** |
| 691 |
* Main method, which allows configuration of which profiles will run |
| 692 |
* and configuration of those individual profiles. |
| 693 |
* Use the <code>-h</code> flag for usage. |
| 694 |
*/ |
| 695 |
public static void main( String[] args ) { |
| 696 |
try { |
| 697 |
int status = runMain( args ); |
| 698 |
if ( status != 0 ) { |
| 699 |
System.exit( status ); |
| 700 |
} |
| 701 |
} |
| 702 |
|
| 703 |
// Explicit exit on error may be necessary to kill Swing. |
| 704 |
catch ( Throwable e ) { |
| 705 |
e.printStackTrace(); |
| 706 |
System.exit( 2 ); |
| 707 |
} |
| 708 |
} |
| 709 |
|
| 710 |
/** |
| 711 |
* Invoked by main. |
| 712 |
* In case of a usage error, it returns a non-zero value, but does not |
| 713 |
* call System.exit. |
| 714 |
* |
| 715 |
* @param args command-line argument array |
| 716 |
* @return non-zero for error completion |
| 717 |
*/ |
| 718 |
public static int runMain( String[] args ) throws IOException { |
| 719 |
HubProfileFactory[] knownProfileFactories = |
| 720 |
getKnownHubProfileFactories(); |
| 721 |
|
| 722 |
// Assemble usage message. |
| 723 |
StringBuffer pbuf = new StringBuffer(); |
| 724 |
for ( int ip = 0; ip < knownProfileFactories.length; ip++ ) { |
| 725 |
pbuf.append( knownProfileFactories[ ip ].getName() ) |
| 726 |
.append( '|' ); |
| 727 |
} |
| 728 |
pbuf.append( "<hubprofile-class>" ) |
| 729 |
.append( "[,...]" ); |
| 730 |
String profUsage = pbuf.toString(); |
| 731 |
StringBuffer ubuf = new StringBuffer(); |
| 732 |
ubuf.append( "\n Usage:" ) |
| 733 |
.append( "\n " ) |
| 734 |
.append( Hub.class.getName() ) |
| 735 |
.append( "\n " ) |
| 736 |
.append( " [-help]" ) |
| 737 |
.append( " [-/+verbose]" ) |
| 738 |
.append( "\n " ) |
| 739 |
.append( " [-mode " ); |
| 740 |
HubServiceMode[] modes = HubServiceMode.getAvailableModes(); |
| 741 |
for ( int im = 0; im < modes.length; im++ ) { |
| 742 |
if ( im > 0 ) { |
| 743 |
ubuf.append( '|' ); |
| 744 |
} |
| 745 |
ubuf.append( modes[ im ].getName() ); |
| 746 |
} |
| 747 |
ubuf.append( ']' ) |
| 748 |
.append( "\n " ) |
| 749 |
.append( " [" ) |
| 750 |
.append( "-profiles " ) |
| 751 |
.append( profUsage ) |
| 752 |
.append( "]" ) |
| 753 |
.append( "\n " ) |
| 754 |
.append( " [" ) |
| 755 |
.append( "-extraprofiles " ) |
| 756 |
.append( profUsage ) |
| 757 |
.append( "]" ); |
| 758 |
for ( int ip = 0; ip < knownProfileFactories.length; ip++ ) { |
| 759 |
List pusageList = |
| 760 |
new ArrayList( Arrays.asList( knownProfileFactories[ ip ] |
| 761 |
.getFlagsUsage() ) ); |
| 762 |
while ( ! pusageList.isEmpty() ) { |
| 763 |
StringBuffer sbuf = new StringBuffer() |
| 764 |
.append( "\n " ); |
| 765 |
for ( Iterator it = pusageList.iterator(); it.hasNext(); ) { |
| 766 |
String pusage = (String) it.next(); |
| 767 |
if ( sbuf.length() + pusage.length() < 78 ) { |
| 768 |
sbuf.append( ' ' ) |
| 769 |
.append( pusage ); |
| 770 |
it.remove(); |
| 771 |
} |
| 772 |
else { |
| 773 |
break; |
| 774 |
} |
| 775 |
} |
| 776 |
ubuf.append( sbuf ); |
| 777 |
} |
| 778 |
} |
| 779 |
ubuf.append( '\n' ); |
| 780 |
String usage = ubuf.toString(); |
| 781 |
|
| 782 |
// Get default hub mode. |
| 783 |
HubServiceMode hubMode = HubServiceMode.MESSAGE_GUI; |
| 784 |
if ( ! Arrays.asList( HubServiceMode.getAvailableModes() ) |
| 785 |
.contains( hubMode ) ) { |
| 786 |
hubMode = HubServiceMode.NO_GUI; |
| 787 |
} |
| 788 |
|
| 789 |
// Parse general command-line arguments. |
| 790 |
List argList = new ArrayList( Arrays.asList( args ) ); |
| 791 |
int verbAdjust = 0; |
| 792 |
String stdSecret = null; |
| 793 |
boolean stdHttplock = false; |
| 794 |
String webAuth = "swing"; |
| 795 |
String webLog = "none"; |
| 796 |
boolean webRemote = false; |
| 797 |
String profilesTxt = null; |
| 798 |
String extraProfilesTxt = null; |
| 799 |
for ( Iterator it = argList.iterator(); it.hasNext(); ) { |
| 800 |
String arg = (String) it.next(); |
| 801 |
if ( arg.equals( "-mode" ) && it.hasNext() ) { |
| 802 |
it.remove(); |
| 803 |
String mode = (String) it.next(); |
| 804 |
it.remove(); |
| 805 |
hubMode = HubServiceMode.getModeFromName( mode ); |
| 806 |
if ( hubMode == null ) { |
| 807 |
System.err.println( "Unkown mode " + mode ); |
| 808 |
System.err.println( usage ); |
| 809 |
return 1; |
| 810 |
} |
| 811 |
} |
| 812 |
else if ( arg.equals( "-profiles" ) ) { |
| 813 |
it.remove(); |
| 814 |
if ( it.hasNext() ) { |
| 815 |
profilesTxt = (String) it.next(); |
| 816 |
it.remove(); |
| 817 |
} |
| 818 |
else { |
| 819 |
System.err.println( usage ); |
| 820 |
return 1; |
| 821 |
} |
| 822 |
} |
| 823 |
else if ( arg.equals( "-extraprofiles" ) ) { |
| 824 |
it.remove(); |
| 825 |
if ( it.hasNext() ) { |
| 826 |
extraProfilesTxt = (String) it.next(); |
| 827 |
it.remove(); |
| 828 |
} |
| 829 |
else { |
| 830 |
System.err.println( usage ); |
| 831 |
return 1; |
| 832 |
} |
| 833 |
} |
| 834 |
else if ( arg.equals( "-v" ) || arg.equals( "-verbose" ) ) { |
| 835 |
it.remove(); |
| 836 |
verbAdjust--; |
| 837 |
} |
| 838 |
else if ( arg.equals( "+v" ) || arg.equals( "+verbose" ) ) { |
| 839 |
it.remove(); |
| 840 |
verbAdjust++; |
| 841 |
} |
| 842 |
else if ( arg.equals( "-h" ) || arg.equals( "-help" ) ) { |
| 843 |
it.remove(); |
| 844 |
System.out.println( usage ); |
| 845 |
return 0; |
| 846 |
} |
| 847 |
} |
| 848 |
|
| 849 |
// Adjust logging in accordance with verboseness flags. |
| 850 |
int logLevel = Level.WARNING.intValue() + 100 * verbAdjust; |
| 851 |
Logger.getLogger( "org.astrogrid.samp" ) |
| 852 |
.setLevel( Level.parse( Integer.toString( logLevel ) ) ); |
| 853 |
|
| 854 |
// Assemble lists of profiles to use. |
| 855 |
HubProfile[] profiles = |
| 856 |
getProfiles( profilesTxt, argList, false, |
| 857 |
"-profiles " + profUsage ); |
| 858 |
if ( profiles == null ) { |
| 859 |
return 1; |
| 860 |
} |
| 861 |
HubProfile[] extraProfiles = |
| 862 |
getProfiles( extraProfilesTxt, argList, true, |
| 863 |
"-extraprofiles " + profUsage ); |
| 864 |
if ( profiles == null ) { |
| 865 |
return 1; |
| 866 |
} |
| 867 |
|
| 868 |
// Check all command line args have been used. |
| 869 |
if ( ! argList.isEmpty() ) { |
| 870 |
System.err.println( "Some args not used " + argList ); |
| 871 |
System.err.println( usage ); |
| 872 |
return 1; |
| 873 |
} |
| 874 |
|
| 875 |
// Start hub service and install profile-specific interfaces. |
| 876 |
runHub( hubMode, profiles, extraProfiles ); |
| 877 |
|
| 878 |
// For non-GUI case block indefinitely otherwise the hub (which uses |
| 879 |
// a daemon thread) will just exit immediately. |
| 880 |
if ( hubMode.isDaemon() ) { |
| 881 |
Object lock = new String( "Indefinite" ); |
| 882 |
synchronized ( lock ) { |
| 883 |
try { |
| 884 |
lock.wait(); |
| 885 |
} |
| 886 |
catch ( InterruptedException e ) { |
| 887 |
} |
| 888 |
} |
| 889 |
} |
| 890 |
|
| 891 |
// Success return. |
| 892 |
return 0; |
| 893 |
} |
| 894 |
|
| 895 |
/** |
| 896 |
* Parses profile list command-line argument and associated |
| 897 |
* command-line arguments to construct a list of required profiles. |
| 898 |
* If there is an argument processing error, an error message will |
| 899 |
* be written to standard error and a null value will be returned. |
| 900 |
* |
| 901 |
* @param profTxt string value of profiles parameter (may be null) |
| 902 |
* @param argList complete list of other so far unused command line |
| 903 |
* args |
| 904 |
* @param isExtra true for extraProfiles, false for main ones |
| 905 |
* @param usage profile flag usage string, used for error messages |
| 906 |
* @return profiles array, or null |
| 907 |
*/ |
| 908 |
private static HubProfile[] getProfiles( String profTxt, List argList, |
| 909 |
boolean isExtra, String usage ) |
| 910 |
throws IOException { |
| 911 |
if ( profTxt == null ) { |
| 912 |
Class[] dflts = isExtra ? defaultDefaultExtraProfileClasses_ |
| 913 |
: defaultDefaultProfileClasses_; |
| 914 |
if ( Arrays.equals( createDefaultProfileClasses( isExtra ), |
| 915 |
dflts ) ) { |
| 916 |
profTxt = isExtra ? "" : "std,web"; |
| 917 |
} |
| 918 |
else { |
| 919 |
logger_.warning( "Non-default profiles set external to flags; " |
| 920 |
+ "web: and std: flags will be ignored" ); |
| 921 |
return createDefaultProfiles( isExtra ); |
| 922 |
} |
| 923 |
} |
| 924 |
HubProfileFactory[] pfacts; |
| 925 |
try { |
| 926 |
pfacts = parseProfileList( profTxt ); |
| 927 |
} |
| 928 |
catch ( IllegalArgumentException e ) { |
| 929 |
System.err.println( e.getMessage() ); |
| 930 |
System.err.println( usage ); |
| 931 |
return null; |
| 932 |
} |
| 933 |
HubProfile[] profiles = new HubProfile[ pfacts.length ]; |
| 934 |
for ( int i = 0; i < pfacts.length; i++ ) { |
| 935 |
HubProfileFactory pfact = pfacts[ i ]; |
| 936 |
try { |
| 937 |
profiles[ i ] = pfact.createHubProfile( argList ); |
| 938 |
} |
| 939 |
catch ( RuntimeException e ) { |
| 940 |
System.err.println( "Error configuring profile " |
| 941 |
+ pfact.getName() + ":\n" |
| 942 |
+ e.getMessage() ); |
| 943 |
return null; |
| 944 |
} |
| 945 |
} |
| 946 |
return profiles; |
| 947 |
} |
| 948 |
|
| 949 |
/** |
| 950 |
* Executes a command in a separate process, and discards any stdout |
| 951 |
* or stderr output generated by it. |
| 952 |
* Simply calling <code>Runtime.exec</code> can block the process |
| 953 |
* until its output is consumed. |
| 954 |
* |
| 955 |
* @param cmdarray array containing the command to call and its args |
| 956 |
*/ |
| 957 |
private static void execBackground( String[] cmdarray ) throws IOException { |
| 958 |
Process process = Runtime.getRuntime().exec( cmdarray ); |
| 959 |
discardBytes( process.getInputStream() ); |
| 960 |
discardBytes( process.getErrorStream() ); |
| 961 |
} |
| 962 |
|
| 963 |
/** |
| 964 |
* Ensures that any bytes from a given input stream are discarded. |
| 965 |
* |
| 966 |
* @param in input stream |
| 967 |
*/ |
| 968 |
private static void discardBytes( final InputStream in ) { |
| 969 |
Thread eater = new Thread( "StreamEater" ) { |
| 970 |
public void run() { |
| 971 |
try { |
| 972 |
while ( in.read() >= 0 ) {} |
| 973 |
in.close(); |
| 974 |
} |
| 975 |
catch ( IOException e ) { |
| 976 |
} |
| 977 |
} |
| 978 |
}; |
| 979 |
eater.setDaemon( true ); |
| 980 |
eater.start(); |
| 981 |
} |
| 982 |
} |