Java 类com.beust.jcommander.JCommander 实例源码

项目:java-cli-demos    文件:Main.java   
/**
 * Use JCommander to process the provided command-line arguments.
 * This method is an instance method (not static) to allow JCommander
 * to use this instance's JCommander-annotated fields.
 *
 * @param arguments Command-line arguments.
 */
private void processCommandLineArguments(final String[] arguments)
{
   final JCommander commander
      = JCommander.newBuilder()
      .programName("JCommander Demonstration")
      .addObject(this)
      .verbose(1)
      .build();
   commander.parse(arguments);
   if (help)
   {
      commander.usage();
   }
   else
   {
      out.println("The file name provided is '" + file + "' and verbosity is set to " + verbose);
   }
}
项目:GitHub    文件:Arguments.java   
/**
 * Parses command line arguments and populates this command line instance.
 * <p>
 * If the command line arguments include the "help" argument, or if the
 * arguments have incorrect values or order, then usage information is
 * printed to {@link System#out} and the program terminates.
 *
 * @param args
 *            the command line arguments
 * @return an instance of the parsed arguments object
 */
public Arguments parse(String[] args) {

    JCommander jCommander = new JCommander(this);
    jCommander.setProgramName("jsonschema2pojo");

    try {
        jCommander.parse(args);

        if (this.showHelp) {
            jCommander.usage();
            exit(EXIT_OKAY);
        }
    } catch (ParameterException e) {
        System.err.println(e.getMessage());
        jCommander.usage();
        exit(EXIT_ERROR);
    }

    return this;
}
项目:ttc2017smartGrids    文件:Main.java   
public static void main(String[] args) {
    Main app = new Main();

    JCommander jc = new JCommander(app);
    try {
        jc.parse(args);
    } catch (ParameterException pe) {
        System.err.println(pe.getMessage());
        jc.usage();
        return;
    }
    try {
        app.run();
    } catch (IOException e) {
        e.printStackTrace();
        jc.usage();
        return;
    }
}
项目:ttc2017smartGrids    文件:App.java   
public static void main(String[] args) {

        App app = new App();
        JCommander jc = new JCommander(app);

        try {
            jc.parse(args);
        } catch (ParameterException pe) {
            System.err.println(pe.getMessage());
            jc.usage();
            return;
        }

        app.build();

    }
项目:Byter    文件:ComponentHelper.java   
public static Commander startCommander(final ExecutorService service){
    //build arguments
    final String configurationDirectory = System.getProperty("user.dir") + File.separator + "configurations" + File.separator + "test";
    final String[] argv = new String[]{"-s","commander","-cfg",configurationDirectory};
    final CliParameter params = new CliParameter();
    JCommander jcommander = new JCommander();
    JCommander.newBuilder().addObject(params)
            .build()
            .parse(argv);
    //build client runnable
    final Commander commander = new Commander(params,false);
    final Thread commanderThread = new Thread(commander);
    commanderThread.setDaemon(true);
    log.log(Level.INFO, "done building commander and deamon thread object");
    service.execute(commanderThread);
    log.log(Level.INFO,"done submitting daemon thread to service pool");
    ThreadManager.nap(3000);
    return commander;
}
项目:Byter    文件:Launcher.java   
/**
 * Main Method.
 * @param argv passed arguments
 */
public static void main(final String... argv) {

    Runtime.getRuntime().addShutdownHook( new Thread() {
        @Override public void run() {
            log.log(Level.INFO,"Received Shutdown Hook - Shuting down Server/Client");
            if(client != null)
                client.stopJmxConnector();
            if(server != null)
                server.stopJmxConnector();
            if(commander != null)
                commander.stopJmxConnector();
        }
    });

    //globalArgs = argv;
    final CliParameter params = new CliParameter();
    jcommander = new JCommander();
    JCommander.newBuilder().addObject(params)
            .build()
            .parse(argv);
    new Launcher(params);
}
项目:centraldogma    文件:Main.java   
@Override
public synchronized void init(DaemonContext context) {
    if (state != State.NONE) {
        throw new IllegalStateException("initialized already");
    }

    final JCommander commander = new JCommander(this);
    commander.setProgramName(getClass().getName());
    commander.parse(context.getArguments());

    if (help != null && help) {
        commander.usage();
        final DaemonController controller = context.getController();
        if (controller != null) {
            controller.fail();
        }
        return;
    }

    state = State.INITIALIZED;
}
项目:accumulo-delimited-ingest    文件:ArgumentParser.java   
public ArgumentParsingResult parse(String[] args) {
  DelimitedIngestArguments argsPojo = new DelimitedIngestArguments();
  try {
    JCommander jcommander = new JCommander(argsPojo, args);

    // If the user requested help, print it and then signal to terminate the app.
    if (argsPojo.isHelp()) {
      jcommander.usage();
      return ArgumentParsingResult.terminate(argsPojo);
    }

    return ArgumentParsingResult.successful(argsPojo);
  } catch (Exception e) {
    return ArgumentParsingResult.failed(e);
  }
}
项目:devtools-driver    文件:SafariDriver.java   
public static void main(String[] args) throws Exception {
  WebDriverMain.getTmpIOSFolder(); // Ensures logging directory exists.
  SafariIOSServerConfiguration options = new SafariIOSServerConfiguration();
  new JCommander(options).parse(args);

  SafariBrowserLauncher launcher;
  if (options.getIsSimulator()) {
    launcher = SafariBrowserLauncher.onSimulator(true);
  } else {
    RealDeviceHost.Configuration hostConf = RealDeviceHost.withDeveloperDiskImagesFromXcode();
    if (!options.supervisionCert.isEmpty() && !options.supervisionKey.isEmpty()) {
      hostConf =
          hostConf.withSupervisionIdentity(
              Paths.get(options.supervisionCert), Paths.get(options.supervisionKey));
    } else if (options.supervisionCert.isEmpty() != options.supervisionKey.isEmpty()) {
      throw new IllegalArgumentException("Supervision cert passed without key, or vice-versa");
    }
    launcher = SafariBrowserLauncher.onRealDevice(hostConf.initialize());
  }

  WebDriverMain.run(options, launcher);
}
项目:Byter    文件:ComponentHelper.java   
/**
 * Start Client as Thread inside a ExecutorService.
 * @param service service to start in
 * @return running Client object
 */
public static Client startClient(final ExecutorService service){
    //build arguments
    final String[] argv = new String[]{"-s","client"};
    final CliParameter params = new CliParameter();
    JCommander jcommander = new JCommander();
    JCommander.newBuilder().addObject(params)
            .build()
            .parse(argv);
    //build client runnable
    final Client clientObj = new Client(params,false);
    final Thread clientThread = new Thread(clientObj);
    clientThread.setDaemon(true);
    log.log(Level.INFO, "done building client and deamon thread object");
    service.execute(clientThread);
    log.log(Level.INFO,"done submitting daemon thread to service pool");
    ThreadManager.nap(3000);
    return clientObj;
}
项目:incubator-ratis    文件:Runner.java   
public static void main(String[] args) throws Exception {
  initializeCommands();
  Runner runner = new Runner();
  Server server = new Server();

  JCommander.Builder builder = JCommander.newBuilder().addObject(runner);
  commands.forEach(command -> builder
      .addCommand(command.getClass().getSimpleName().toLowerCase(), command));
  JCommander jc = builder.build();
  try {
    jc.parse(args);
    Optional<SubCommandBase> selectedCommand = commands.stream().filter(
        command -> command.getClass().getSimpleName().toLowerCase()
            .equals(jc.getParsedCommand())).findFirst();
    if (selectedCommand.isPresent()) {
      selectedCommand.get().run();
    } else {
      jc.usage();
    }
  } catch (ParameterException exception) {
    System.err.println("Wrong parameters: " + exception.getMessage());
    jc.usage();
  }

}
项目:Byter    文件:ComponentHelper.java   
/**
 * Start Server as Thread inside a ExecutorService.
 * @param service service to start in
 * @return running Server object
 */
public static Server startServer(final ExecutorService service){
    //build arguments
    final String[] argv = new String[]{"-s","server"};
    final CliParameter params = new CliParameter();
    JCommander jcommander = new JCommander();
    JCommander.newBuilder().addObject(params)
            .build()
            .parse(argv);
    //build server runnable
    final Server serverObj = new Server(params,false);
    final Thread serverThread = new Thread(serverObj);
    serverThread.setDaemon(true);
    log.log(Level.INFO, "done building server and deamon thread object");
    //start inside service
    service.execute(serverThread);
    log.log(Level.INFO,"done submitting daemon thread to service pool");
    ThreadManager.nap(3000);
    return serverObj;
}
项目:Byter    文件:JmxNetworkManagerTest.java   
/**
 * Start Method for everything related to this Test-Case.
 */
@BeforeClass
public static void startup(){
    //set up test-space if not already done
    FileManager.createFolder(testSpaceDir);
    //build arguments
    final String[] argv = new String[]{"-s","server"};
    final CliParameter params = new CliParameter();
    jcommander = new JCommander();
    JCommander.newBuilder().addObject(params)
            .build()
            .parse(argv);
    //build service
    service = Executors.newFixedThreadPool(1);
    serverObj = ComponentHelper.startServer(service);
    log.log(Level.INFO, "JmxNetworkManagerTest running on port: " + serverObj.getConnectorSystemPort());
}
项目:clearwsd    文件:WordSenseCLI.java   
WordSenseCLI(String[] args) {
    cmd = new JCommander(this);
    cmd.setProgramName(WordSenseCLI.class.getSimpleName());
    try {
        cmd.parse(args);
        if (help || args.length == 0) {
            System.out.println(helpMessage);
            cmd.usage();
            System.exit(0);
        }
    } catch (ParameterException e) {
        System.err.println(e.getMessage());
        cmd.usage();
        System.exit(1);
    }
}
项目:winter    文件:Executable.java   
protected boolean parseCommandLine(Class<?> cls, String... args) {
     try {
        if(!silent) {
        System.err.println(BuildInfo.getJarPath(getClass()));
        System.err.println(String.format("%s version %s", cls.getName(), BuildInfo.getBuildTimeString(cls)));
            System.err.println("         __      __.___        __                     ");
            System.err.println("         /  \\    /  \\   | _____/  |_  ____     _______ ");
            System.err.println("         \\   \\/\\/   /   |/    \\   __\\/ __ \\    \\_  __ \\");
            System.err.println("          \\        /|   |   |  \\  | \\  ___/     |  | \\/");
            System.err.println("           \\__/\\  / |___|___|  /__|  \\___  > /\\ |__|   ");
            System.err.println("                \\/           \\/          \\/  \\/        ");
        }

         @SuppressWarnings("unused")
JCommander cmd = new JCommander(this, args);

         return true;
     } catch(Exception e) {
        System.err.println(e.getMessage());
        usage(args);
         return false;
     }
 }
项目:jet-gatling    文件:JetGatling.java   
private static int startGatling(String[] args) {
    JetGatlingOptions options = new JetGatlingOptions();
    JCommander jcommander = new JCommander(options, args);

    if (args.length == 0 || options.isHelp()) {
        jcommander.usage();
        return 0;
    }

    if (!options.check()) {
        return 10;
    }

    OPTIONS = options;
    return GatlingExecutor.execute(options);
}
项目:JavaNRPC    文件:TestEnty.java   
public static void main(String[] args){
    //构造一个参数解析对象
    Args argsObj = new Args();
    JCommander.newBuilder()
            .addObject(argsObj)
            .build()
            .parse(args);

    //区分服务器或客户端两种模式运行
    if(argsObj.mode == 1){
        //server
        Server server = new Server();
        server.start(argsObj.nodeIp,argsObj.nodePort,argsObj.etcdIp,argsObj.etcdPort);
    }else{
        //client
        Client client = new Client();
        client.start(argsObj.etcdIp,argsObj.etcdPort);
    }

}
项目:azure-documentdb-rxjava    文件:Main.java   
public static void main(String[] args) throws Exception {
    try {
        LOGGER.debug("Parsing the arguments ...");
        Configuration cfg = new Configuration();
        JCommander jcommander = new JCommander(cfg, args);

        if (cfg.isHelp()) {
            // prints out the usage help
            jcommander.usage();
            return;
        }

        cfg.validate();

        AbstractBulkInsertBenchmark benchmark;
        switch (cfg.getClientType()) {

        case rxNonBlocking:
            benchmark = RxAsyncBulkInsertBenchmark.fromConfiguration(cfg);
            break;
        case blocking:
            benchmark = SyncBulkInsertBenchmark.fromConfiguration(cfg);
            break;

        default:
            throw new RuntimeException(cfg.getClientType() + " is not supported");
        }

        benchmark.init();
        benchmark.run();
        benchmark.shutdown();

    } catch (ParameterException e) {
        // if any error in parsing the cmd-line options print out the usage help
        System.err.println("Invalid Usage: " + e.getMessage());
        System.err.println("Try '-help' for more information.");

        System.exit(1);
    }
}
项目:clearwsd    文件:OntoNotesConverter.java   
private OntoNotesConverter(String... args) {
    JCommander cmd = new JCommander(this);
    cmd.setProgramName(this.getClass().getSimpleName());
    try {
        cmd.parse(args);
    } catch (ParameterException e) {
        System.err.println(e.getMessage());
        cmd.usage();
        System.exit(1);
    }
}
项目:Selenium-Foundation    文件:SeleniumConfigTest.java   
@Test
public void testHubArgs() {
    SeleniumConfig config = SeleniumConfig.getConfig();
    GridHubConfiguration hubConfig = new GridHubConfiguration();
    String[] hubArgs = config.getHubArgs();
    new JCommander(hubConfig, hubArgs);
    assertEquals(hubConfig.role, "hub");
    String path = hubConfig.hubConfig;
    assertTrue(path.endsWith("hubConfig.json"));
}
项目:hands-on-neo4j-devoxx-fr-2017    文件:Main.java   
private static JCommander getJCommander(String[] args, Main main) {
    try {
        return new JCommander(main, args);
    } catch (ParameterException pe) {
        main.help = true;
        return new JCommander(main);
    }
}
项目:hands-on-neo4j-devoxx-fr-2017    文件:Main.java   
private static JCommander getJCommander(String[] args, Main main) {
    try {
        return new JCommander(main, args);
    } catch (ParameterException pe) {
        main.help = true;
        return new JCommander(main);
    }
}
项目:RadarGun    文件:Main.java   
public static void main(final String[] args) {
    final Options options = new Options();
    final JCommander jCommander = JCommander.newBuilder().addObject(options).build();
    jCommander.setProgramName(PROGRAM_NAME);
    jCommander.parse(args);
    if (options.isHelp()) {
        jCommander.usage();
    } else {
        new Main(options).execute();
    }
}
项目:influx-jmh-reporter    文件:InfluxJmhReporterMain.java   
@SuppressWarnings("checkstyle:Regexp")
private static void printUsage(final JCommander jCommander)
{
    final StringBuilder usage = new StringBuilder();
    jCommander.usage(usage);
    System.err.println(usage.toString());
}
项目:redhat-sso    文件:GreetingAuthzClient.java   
public static void main(String[] args) throws Exception {
    CommandArgs cmdArgs = new CommandArgs();
    JCommander cmdParser = new JCommander(cmdArgs);
    try {
        cmdParser.setProgramName(GreetingAuthzClient.class.getName());
        cmdParser.parse(args);
    } catch (ParameterException e) {
        StringBuilder info = new StringBuilder("Specifiy the name of the application endpoint with --app\n");
        cmdParser.usage(info);
        System.err.printf(info.toString());
        System.exit(1);
    }
    // Handle outputCurlScript
    if(cmdArgs.outputCurlScript != null) {
        InputStream scriptStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("token_req_template.sh");
        Path path = FileSystems.getDefault().getPath(cmdArgs.outputCurlScript);
        Files.copy(scriptStream, path, StandardCopyOption.REPLACE_EXISTING);
        scriptStream.close();
        System.out.printf("Wrote script to: %s\n", path.toFile().getAbsolutePath());
        System.exit(0);
    }

    GreetingAuthzClient client = new GreetingAuthzClient();
    client.init(cmdArgs);
    System.out.printf("\nRequesting greeting...\n");
    Greeting greeting = client.getGreeting(cmdArgs.app, cmdArgs.from);
    System.out.printf("%s\n", greeting);
}
项目:migration-tooling    文件:GenerateWorkspaceOptionsTest.java   
@Test
public void equalsSeparator() throws Exception {
  GenerateWorkspaceOptions options = new GenerateWorkspaceOptions();
  JCommander optionParser = JCommander.newBuilder().addObject(options).build();
  optionParser.parse("--artifact=foo:bar:1.2.3");
  assertThat(options.artifacts).contains("foo:bar:1.2.3");
}
项目:migration-tooling    文件:GenerateWorkspaceOptionsTest.java   
@Test
public void spaceSeparator() throws Exception {
  GenerateWorkspaceOptions options = new GenerateWorkspaceOptions();
  JCommander optionParser = JCommander.newBuilder().addObject(options).build();
  optionParser.parse("--artifact", "foo:bar:1.2.3");
  assertThat(options.artifacts).contains("foo:bar:1.2.3");
}
项目:migration-tooling    文件:GenerateWorkspaceOptionsTest.java   
@Test
public void noCommaDelimiter() throws Exception {
  GenerateWorkspaceOptions options = new GenerateWorkspaceOptions();
  JCommander optionParser = JCommander.newBuilder().addObject(options).build();
  optionParser.parse("--artifact", "foo:bar:[1.2.3,)");
  assertThat(options.artifacts).contains("foo:bar:[1.2.3,)");
}
项目:migration-tooling    文件:GenerateWorkspaceOptionsTest.java   
@Test
public void multipleArtifacts() throws Exception {
  GenerateWorkspaceOptions options = new GenerateWorkspaceOptions();
  JCommander optionParser = JCommander.newBuilder().addObject(options).build();
  optionParser.parse("--artifact", "a:b1:[1.2,2.0]", "--artifact", "a:b2:[1.0,2.0)");
  assertThat(options.artifacts).containsExactly("a:b1:[1.2,2.0]", "a:b2:[1.0,2.0)");
}
项目:migration-tooling    文件:GenerateWorkspaceOptionsTest.java   
@Test
public void repository() throws Exception {
  GenerateWorkspaceOptions options = new GenerateWorkspaceOptions();
  JCommander optionParser = JCommander.newBuilder().addObject(options).build();
  optionParser.parse("--repositories", "http://central.maven.org/maven2/");
  assertThat(options.repositories).contains("http://central.maven.org/maven2/");
}
项目:migration-tooling    文件:GenerateWorkspaceOptionsTest.java   
@Test
public void multipleRepositories() throws Exception {
  GenerateWorkspaceOptions options = new GenerateWorkspaceOptions();
  JCommander optionParser = JCommander.newBuilder().addObject(options).build();
  optionParser.parse(
      "--repositories", "http://central.maven.org/maven2/,http://repo.spring.io/libs-milestone/");
  assertThat(options.repositories)
      .containsExactly(
          "http://central.maven.org/maven2/", "http://repo.spring.io/libs-milestone/");
}
项目:migration-tooling    文件:GenerateWorkspaceOptionsTest.java   
@Test
public void alias() throws Exception {
  GenerateWorkspaceOptions options = new GenerateWorkspaceOptions();
  JCommander optionParser = JCommander.newBuilder().addObject(options).build();
  optionParser.parse("--declare=a:b=c");
  assertThat(options.aliases).hasSize(1);
  Rule aliasedRule = options.aliases.get(0);
  assertThat(aliasedRule.name()).isEqualTo("c");
  assertThat(aliasedRule.toMavenArtifactString()).isEqualTo("a:b:0");
}
项目:migration-tooling    文件:GenerateWorkspaceOptionsTest.java   
@Test
public void versionedAlias() throws Exception {
  GenerateWorkspaceOptions options = new GenerateWorkspaceOptions();
  JCommander optionParser = JCommander.newBuilder().addObject(options).build();
  optionParser.parse("--declare=a:b:1.2.3=c");
  assertThat(options.aliases).hasSize(1);
  Rule aliasedRule = options.aliases.get(0);
  assertThat(aliasedRule.name()).isEqualTo("c");
  assertThat(aliasedRule.toMavenArtifactString()).isEqualTo("a:b:1.2.3");
}
项目:migration-tooling    文件:GenerateWorkspaceOptionsTest.java   
@Test
public void declareDefault() throws Exception {
  GenerateWorkspaceOptions options = new GenerateWorkspaceOptions();
  JCommander optionParser = JCommander.newBuilder().addObject(options).build();
  optionParser.parse("--declare=a:b");
  assertThat(options.aliases).hasSize(1);
  Rule aliasedRule = options.aliases.get(0);
  assertThat(aliasedRule.name()).isEqualTo("a_b");
}
项目:grade-buddy    文件:Application.java   
/**
 * Main method.
 * @param args This program's arguments
 */
public static void main(String[] args) {
    Application app = new Application();
    try {
        JCommander jc = JCommander.newBuilder()
            .addObject(app)
            .programName("<program>")
            .build();
        jc.parse(args);
        if (app.help) {
            jc.usage();
            return;
        } else if (!app.parameters.isEmpty()) {
            System.err.printf("Unknown parameter(s) %s\n", app.parameters);
            System.exit(1);
        } else if (app.backup == null && (
            app.directory == null
            || app.namingScript == null
            || app.markingScripts.isEmpty())) {
            System.err.println(
                "Expecting parameters Directory, Naming script, and "
                + "Marking script"
            );
            jc.usage();
            System.exit(1);
        }
    } catch (ParameterException e) {
        System.err.println(e.getMessage());
        new JCommander(new Application()).usage();
        System.exit(2);
    }
    app.run();
}
项目:ontolib    文件:Main.java   
public static void main(String[] argv) {
  final PrecomputeScoresOptions precomputeScoresOptions = new PrecomputeScoresOptions();
  final MergeScoresOptions mergeScoresOptions = new MergeScoresOptions();
  final JCommander jc =
      JCommander.newBuilder().addCommand(PRECOMPUTE_SCORES, precomputeScoresOptions)
          .addCommand(MERGE_SCORES, mergeScoresOptions).build();
  try {
    jc.parse(argv);
  } catch (ParameterException e) {
    LOGGER.error("ERROR: " + e.getMessage());
    jc.usage();
    System.exit(1);
  }

  if (jc.getParsedCommand() == null) {
    jc.usage();
    System.exit(1);
  }

  switch (jc.getParsedCommand()) {
    case PRECOMPUTE_SCORES:
      new PrecomputeScoresCommand(precomputeScoresOptions).run();
      break;
    case MERGE_SCORES:
      new MergeScoresCommand(mergeScoresOptions).run();
      break;
  }
}
项目:graphouse    文件:InsertTest.java   
public static void main(String[] args) throws InterruptedException {
    PerfArgs perfArgs = new PerfArgs();
    JCommander jCommander = new JCommander(perfArgs, args);
    if (perfArgs.help) {
        jCommander.usage();
        System.exit(0);
    }
    if (!perfArgs.metricPrefix.endsWith(".")) {
        perfArgs.metricPrefix += ".";
    }
    InsertTest insertTest = new InsertTest(perfArgs);
    insertTest.startAsync().awaitRunning();
}
项目:je2sh    文件:TestUtils.java   
public static void parseCommand(String name, AbstractCommand cmd, String... args) {
    JCommander.newBuilder()
              .addObject(cmd)
              .programName(name)
              .build()
              .parse(args);
}
项目:light-codegen    文件:Cli.java   
public static void main(String ... argv) {
    Cli cli = new Cli();
    JCommander.newBuilder()
            .addObject(cli)
            .build()
            .parse(argv);
    cli.run();
}
项目:clearwsd    文件:EmbeddingBinarizer.java   
private EmbeddingBinarizer(String... args) {
    JCommander cmd = new JCommander(this);
    cmd.setProgramName(this.getClass().getSimpleName());
    try {
        cmd.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        cmd.usage();
        System.exit(1);
    }
}