protected static void main ( String [ ] args , CliTool ... commands ) { if ( commands . length == 1 ) { main ( args , commands [ 0 ] ) ; } else { JCommander jc = new JCommander ( ) ; for ( CliTool command : commands ) { jc . addCommand ( command ) ; } jc . addConverterFactory ( new CustomParameterConverters ( ) ) ; jc . setProgramName ( "" ) ; ExitStatus exitStatus = ExitStatus . SUCCESS ; try { jc . parse ( args ) ; final String commandName = jc . getParsedCommand ( ) ; if ( commandName == null ) { helpDisplayCommandOptions ( System . err , jc ) ; } else { List < Object > objects = jc . getCommands ( ) . get ( commandName ) . getObjects ( ) ; if ( objects . size ( ) != 1 ) { throw new RuntimeException ( ) ; } CliTool command = CliTool . class . cast ( objects . get ( 0 ) ) ; exitStatus = command . call ( ) ; if ( command . callSystemExit ) { System . exit ( exitStatus . code ) ; } } } catch ( ExitStatusException e ) { System . err . println ( e . getMessage ( ) ) ; if ( e . getCause ( ) != null ) { e . getCause ( ) . printStackTrace ( System . err ) ; } exitStatus = e . exitStatus ; } catch ( MissingCommandException e ) { System . err . println ( "Invalid argument: " + e ) ; System . err . println ( ) ; helpDisplayCommandOptions ( System . err , jc ) ; exitStatus = ExitStatus . ERROR_INVALID_ARGUMENTS ; } catch ( ParameterException e ) { System . err . println ( "Invalid argument: " + e . getMessage ( ) ) ; System . err . println ( ) ; if ( jc . getParsedCommand ( ) == null ) { helpDisplayCommandOptions ( System . err , jc ) ; } else { helpDisplayCommandOptions ( System . err , jc . getParsedCommand ( ) , jc ) ; } exitStatus = ExitStatus . ERROR_INVALID_ARGUMENTS ; } catch ( Throwable t ) { System . err . println ( "An unhandled exception occurred. Stack trace below." ) ; t . printStackTrace ( System . err ) ; exitStatus = ExitStatus . ERROR_OTHER ; } } }
Parse and execute one of the commands .