Java Code Examples for com.beust.jcommander.JCommander

The following examples show how to use com.beust.jcommander.JCommander. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: google-ads-java   Source File: CodeSampleParams.java    License: Apache License 2.0 6 votes vote down vote up
boolean parseArguments(String[] args, Runtime runtime, PrintStream usageStream) {
  JCommander jc = new JCommander(this);

  if (args.length == 0) {
    return false;
  }

  jc.parse(args);

  if (help) {
    StringBuilder usageOut = new StringBuilder();
    jc.usage(usageOut);
    usageStream.println(usageOut.toString());
    runtime.exit(0);
  }

  return true;
}
 
Example 2
public static void main(String[] args) {
    JCommander jCommander = parseInputParams(args);
    File repoDir = evaluateM2Path(jCommander);
    String[] filter = argData.isDeleteSource() || argData.isDeleteJavadoc() ? null : new String[]{"pom"};
    FileUtils.listFiles(repoDir, filter, true).forEach(file -> parseAndEvaluate(file));
    processVersion();
    log.info("*********** Files to be deleted ***********");
    DELETE_MAP.forEach((k, v) -> log.info(LS + LS + k + " : " + LS + StringUtils.join(v.stream().sorted().iterator(), LS)));
    log.info(LS + LS + "*********** Files skipped ***********");
    SKIP_MAP.forEach((k, v) -> log.info(LS + LS + k + " : " + LS + StringUtils.join(v.stream().sorted().iterator(), LS)));
    if (!argData.isDryRun()) {
        log.info(LS + LS + "*********** Beginning to Delete Files ***********");
        deleteMarked();
        log.info(LS + LS + "*********** Deletion Completed ***********");
        log.info(LS + LS + "*********** Files having error in deletion ***********");
        log.info(StringUtils.join(DELETE_FAILURE_LIST.stream().sorted().iterator(), LS));
    } else {
        log.info(LS + LS + "*********** No files were deleted as program was run in DRY-RUN mode  ***********");
    }
}
 
Example 3
Source Project: kieker   Source File: TraceAnalysisToolMain.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected int execute(final JCommander commander, final String label) throws ConfigurationException {
	final DateFormat dateFormat = new SimpleDateFormat(DateConverter.DATE_FORMAT_PATTERN, Locale.US);
	dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

	if (this.parameterConfiguration.getIgnoreExecutionsBeforeDate() != null) {
		logger.info("Ignoring records before {} ({})", dateFormat.format(this.parameterConfiguration.getIgnoreExecutionsBeforeDate()),
				this.parameterConfiguration.getIgnoreExecutionsBeforeDate());
	}
	if (this.parameterConfiguration.getIgnoreExecutionsAfterDate() != null) {
		logger.info("Ignoring records after {} ({})", dateFormat.format(this.parameterConfiguration.getIgnoreExecutionsAfterDate()),
				this.parameterConfiguration.getIgnoreExecutionsAfterDate());
	}

	this.parameterConfiguration.dumpConfiguration(logger);

	if (new PerformAnalysis(logger, this.parameterConfiguration).dispatchTasks()) {
		logger.info("Analysis complete. See 'kieker.log' for details.");
		return SUCCESS_EXIT_CODE;
	} else {
		logger.error("Analysis incomplete. See 'kieker.log' for details.");
		return RUNTIME_ERROR;
	}
}
 
Example 4
Source Project: joyqueue   Source File: ConsoleProducer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    ConsoleProducerConfig config = new ConsoleProducerConfig();
    JCommander jcommander = JCommander.newBuilder()
            .addObject(config)
            .build();
    jcommander.parse(args);

    if (config.isHelp()) {
        jcommander.usage();
        return;
    }

    Producer producer = buildProducer(config);
    producer.start();

    send(producer, config);
    System.exit(0);
}
 
Example 5
Source Project: phoenix-omid   Source File: CompactorUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Config cmdline = new Config();
    JCommander jcommander = new JCommander(cmdline, args);
    if (cmdline.help) {
        jcommander.usage("CompactorUtil");
        System.exit(1);
    }

    HBaseLogin.loginIfNeeded(cmdline.loginFlags);

    Configuration conf = HBaseConfiguration.create();
    try (Connection conn = ConnectionFactory.createConnection(conf)) {
        if (cmdline.enable) {
            enableOmidCompaction(conn, TableName.valueOf(cmdline.table),
                    Bytes.toBytes(cmdline.columnFamily));
        } else if (cmdline.disable) {
            disableOmidCompaction(conn, TableName.valueOf(cmdline.table),
                    Bytes.toBytes(cmdline.columnFamily));
        } else {
            System.err.println("Must specify enable or disable");
        }
    }
}
 
Example 6
Source Project: googleads-java-lib   Source File: CodeSampleParams.java    License: Apache License 2.0 6 votes vote down vote up
boolean parseArguments(String[] args, Runtime runtime,
    PrintStream usageStream) {
  JCommander jc = new JCommander(this);

  if (args.length == 0) {
    return false;
  }

  jc.parse(args);

  if (help) {
    StringBuilder usageOut = new StringBuilder();
    jc.usage(usageOut);
    usageStream.println(usageOut.toString());
    runtime.exit(0);
  }

  return true;
}
 
Example 7
Source Project: ratis   Source File: LogServer.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    ServerOpts opts = new ServerOpts();
    JCommander.newBuilder()
            .addObject(opts)
            .build()
            .parse(args);

    try (LogServer worker = new LogServer(opts)) {
      worker.start();
      while (true) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
          return;
        }
      }
    }
}
 
Example 8
/**
 * Initialize and start the PubsubEmulatorServer.
 *
 * <p>To set an external configuration file must be considered argument
 * `configuration.location=/to/path/application.yaml` the properties will be merged.
 */
public static void main(String[] args) {
  Args argObject = new Args();
  JCommander jCommander = JCommander.newBuilder().addObject(argObject).build();
  jCommander.parse(args);
  if (argObject.help) {
    jCommander.usage();
    return;
  }
  Injector injector =
      Guice.createInjector(new DefaultModule(argObject.configurationFile, argObject.pubSubFile));
  PubsubEmulatorServer pubsubEmulatorServer = injector.getInstance(PubsubEmulatorServer.class);
  try {
    pubsubEmulatorServer.start();
    pubsubEmulatorServer.blockUntilShutdown();
  } catch (IOException | InterruptedException e) {
    logger.atSevere().withCause(e).log("Unexpected server failure");
  }
}
 
Example 9
Source Project: cramtools   Source File: QualityScoreStats.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	Params params = new Params();
	JCommander jc = new JCommander(params);
	try {
		jc.parse(args);
	} catch (Exception e) {
		System.out.println("Failed to parse parameteres, detailed message below: ");
		System.out.println(e.getMessage());
		System.out.println();
		System.out.println("See usage: -h");
		System.exit(1);
	}

	if (args.length == 0 || params.help) {
		printUsage(jc);
		System.exit(1);
	}

	Log.setGlobalLogLevel(params.logLevel);

	dist(params.inputFile, (byte) (0xFF & params.defaultQualityScore));
}
 
Example 10
public static String buildUsageText(JCommander jcommander) {
	StringBuilder usage = new StringBuilder();

	String allCommandsDescription = null;
	if ( jcommander != null && jcommander.getCommands() != null ) {
		for ( String command : jcommander.getCommands().keySet() ) {
			allCommandsDescription += jcommander.getCommandDescription(command) + PMD.EOL;
		}
	}

	// TODO: Externalize that to a file available within the classpath ? - with a poor's man templating ?
	String fullText = PMD.EOL
	+ "Mandatory arguments:"																+ PMD.EOL
	+ "1) A java source code filename or directory"											+ PMD.EOL
	+ "2) A report format "																	+ PMD.EOL
	+ "3) A ruleset filename or a comma-delimited string of ruleset filenames"				+ PMD.EOL
	+ PMD.EOL
	+ "For example: "																		+ PMD.EOL
	+ getWindowsLaunchCmd() + " -d c:\\my\\source\\code -f html -R java-unusedcode"			+ PMD.EOL
	+ PMD.EOL;

	fullText += supportedVersions() + PMD.EOL;

	if ( allCommandsDescription != null ) {
		fullText += "Optional arguments that may be put before or after the mandatory arguments: "		+ PMD.EOL
				+ allCommandsDescription							 									+ PMD.EOL;
	}

	fullText += "Available report formats and their configuration properties are:"					+ PMD.EOL
	+ getReports()																			+ PMD.EOL
	+ getExamples() + PMD.EOL
	+ PMD.EOL + PMD.EOL;

	return fullText += usage.toString();
}
 
Example 11
CommandLine(String progName, String[] args) throws ParameterException {
  this.jc = new JCommander(this, args); // Parses args and uses them to initialize *this*.
  jc.setProgramName(progName); // Displayed in the usage information.

  // Set the ordering of of parameters in the usage information.
  jc.setParameterDescriptionComparator(new ParameterDescriptionComparator());
}
 
Example 12
Source Project: deeplearning4j   Source File: NearestNeighborsServer.java    License: Apache License 2.0 5 votes vote down vote up
public static void runMain(String... args) {
    RunArgs r = new RunArgs();
    JCommander jcmdr = new JCommander(r);

    try {
        jcmdr.parse(args);
    } catch (ParameterException e) {
        log.error("Error in NearestNeighboursServer parameters", e);
        StringBuilder sb = new StringBuilder();
        jcmdr.usage(sb);
        log.error("Usage: {}", sb.toString());

        //User provides invalid input -> print the usage info
        jcmdr.usage();
        if (r.ndarrayPath == null)
            log.error("Json path parameter is missing (null)");
        try {
            Thread.sleep(500);
        } catch (Exception e2) {
        }
        System.exit(1);
    }

    instanceArgs = r;
    try {
        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(NearestNeighborsServer.class.getName());
    } catch (Throwable t){
        log.error("Error in NearestNeighboursServer run method",t);
    }
}
 
Example 13
Source Project: geowave   Source File: VectorIngestRunnerTest.java    License: Apache License 2.0 5 votes vote down vote up
private DataStorePluginOptions getStorePluginOptions(final OperationParams params) {
  final File configFile = (File) params.getContext().get(ConfigOptions.PROPERTIES_FILE_CONTEXT);

  final StoreLoader inputStoreLoader = new StoreLoader("memorystore");
  if (!inputStoreLoader.loadFromConfig(configFile, new JCommander().getConsole())) {
    throw new ParameterException("Cannot find store name: " + inputStoreLoader.getStoreName());
  }
  return inputStoreLoader.getDataStorePlugin();
}
 
Example 14
private static UserArguments parseUserArguments(String[] args) {
    UserArguments userArguments = new UserArguments();
    try {
        new JCommander(userArguments, args);
    } catch (ParameterException e) {
        e.printStackTrace(System.err);
        new JCommander(userArguments, new String[] { "-help" }).usage();
    }
    return userArguments;
}
 
Example 15
Source Project: Bats   Source File: StartupOptions.java    License: Apache License 2.0 5 votes vote down vote up
public static StartupOptions parse(String[] cliArgs) {
  logger.debug("Parsing arguments.");
  StartupOptions args = new StartupOptions();
  JCommander jc = new JCommander(args, cliArgs);
  if(args.help){
    jc.usage();
    System.exit(0);
  }
  return args;
}
 
Example 16
Source Project: cramtools   Source File: Cram2Fastq.java    License: Apache License 2.0 5 votes vote down vote up
private static void printUsage(JCommander jc) {
	StringBuilder sb = new StringBuilder();
	sb.append("\n");
	jc.usage(sb);

	System.out.println("Version " + Cram2Fastq.class.getPackage().getImplementationVersion());
	System.out.println(sb.toString());
}
 
Example 17
public static void main(final String[] args) throws Exception {

		final Parameters params = new Parameters();
		final JCommander jc = new JCommander(params);

		try {
			jc.parse(args);
			trainTopicModel(params.workingDir, params.projectsDir,
					params.iterations);
		} catch (final ParameterException e) {
			System.out.println(e.getMessage());
			jc.usage();
		}

	}
 
Example 18
Source Project: rya   Source File: StreamResultsCommand.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean validArguments(final String[] args) {
    boolean valid = true;
    try {
        new JCommander(new StreamResultsParameters(), args);
    } catch(final ParameterException e) {
        valid = false;
    }
    return valid;
}
 
Example 19
Source Project: geowave   Source File: JCommanderPrefixTranslatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPrefixParameter() {
  final JCommanderPrefixTranslator translator = new JCommanderPrefixTranslator();
  final PrefixedArguments args = new PrefixedArguments();
  translator.addObject(args);
  final JCommanderTranslationMap map = translator.translate();
  final JCommander commander = prepareCommander(map);
  commander.parse("--abc.arg", "5", "--arg", "blah");
  map.transformToOriginal();
  Assert.assertEquals("5", args.child.arg);
  Assert.assertEquals("blah", args.blah);
}
 
Example 20
Source Project: acme_client   Source File: Application.java    License: MIT License 5 votes vote down vote up
private static void printHelpInfo(JCommander jCommander){
    StringBuilder usage = new StringBuilder();
    jCommander.usage(usage);
    System.out.println(usage.toString());
    String format = "%10s%n";
    System.out.format(format, Parameters.MAIN_USAGE.toString());
}
 
Example 21
Source Project: android-reverse-r   Source File: Reverser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Parse command line args into an object.
 *
 * @param args raw command line arguments
 * @return a populated settings object
 */
private Settings parseCli(String... args) {
    Settings settings = new Settings();
    JCommander commander = new JCommander(settings);
    try {
        commander.parse(args);
    } catch (ParameterException e) {
        System.err.println(e.getMessage());
        commander.usage();
        System.exit(0);
    }
    return settings;
}
 
Example 22
Source Project: incubator-ratis   Source File: Runner.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (args.length == 0) {
    System.err.println("No command type specified: ");
    return;
  }
  List<SubCommandBase> commands = initializeCommands(args[0]);
  Runner runner = new Runner();

  if (commands == null) {
    System.err.println("Wrong command type: " + args[0]);
    return;
  }
  String[] newArgs = new String[args.length - 1];
  System.arraycopy(args, 1, newArgs, 0, args.length - 1);

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

}
 
Example 23
Source Project: geowave   Source File: GeoServerRestClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void prepare() {
  webTarget = mockedWebTarget();
  final Console console = new JCommander().getConsole();
  config = new GeoServerConfig(console);
  client = GeoServerRestClient.getInstance(config, console);
  client.setWebTarget(webTarget);
}
 
Example 24
Source Project: cramtools   Source File: Cram2Bam.java    License: Apache License 2.0 5 votes vote down vote up
private static void printUsage(JCommander jc) {
	StringBuilder sb = new StringBuilder();
	sb.append("\n");
	jc.usage(sb);

	System.out.println("Version " + Cram2Bam.class.getPackage().getImplementationVersion());
	System.out.println(sb.toString());
}
 
Example 25
Source Project: gocd   Source File: AgentCLI.java    License: Apache License 2.0 5 votes vote down vote up
private void printUsageAndExit(int exitCode) {
    StringBuilder out = new StringBuilder();
    JCommander jCommander = new JCommander(new AgentBootstrapperArgs());
    jCommander.setProgramName("java -jar agent-bootstrapper.jar");
    jCommander.getUsageFormatter().usage(out);
    stderr.print(out);
    exit(exitCode);
}
 
Example 26
Source Project: copybara   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private static String usage(JCommander jcommander, String version) {
  StringBuilder fullUsage = new StringBuilder();
  fullUsage.append("Copybara version: ").append(version).append("\n");
  jcommander.usage(fullUsage);
  fullUsage
      .append("\n")
      .append("Example:\n")
      .append("  copybara ").append(COPYBARA_SKYLARK_CONFIG_FILENAME).append(" origin/master\n");
  return fullUsage.toString();
}
 
Example 27
Source Project: joyqueue   Source File: TopicAdmin.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 *  Topic partition group
 *
 **/
public String partitionGroups(PartitionGroupArg args,JCommander jCommander) throws Exception{
    PartitionGroupQuery query=new PartitionGroupQuery();
    query.setTopic(args.topic);
    query.setNamespace(args.namespace);
    Future<String> futureResult=httpClient.post(args.host,"/partitiongroup/list",JSON.toJSONString(query),String.class);
    String result=futureResult.get(AdminConfig.TIMEOUT_MS,TimeUnit.MILLISECONDS);
    System.out.println(result);
    logger.info("partition groups:{}",result);
    return result;
}
 
Example 28
Source Project: swagger-diff   Source File: CLITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCLI() {
    CLI cli = new CLI();
    String[] argv = { "-v", "2.0", "-old", "http://petstore.swagger.io/v2/swagger.json",
            "--help" };
    JCommander commander = JCommander.newBuilder().addObject(cli).build();

    commander.setProgramName("java swagger-diff.jar");
    commander.usage();
    commander.parse(argv);
    Assert.assertEquals(cli.getVersion(), "2.0");
    Assert.assertEquals(cli.getOldSpec(), "http://petstore.swagger.io/v2/swagger.json");
}
 
Example 29
public static void main(String[] args) throws IOException {
    VRPRunner jct = new VRPRunner();
    JCommander jCommander = new JCommander(jct, args);
    jCommander.setProgramName(VRPRunner.class.getSimpleName());

    switch (jct.alg) {
        case "acs":
            VrpAcsSolver aco = new VrpAcsSolver(jct);

            ExecutionStats
                    .execute(aco, aco.getProblem())
                    .printStats();
            break;
        case "tabu": {
            new TabuSearchSolver(jct)
                    .solve()
                    .print();
            break;
        }
        default:
        case "greedy": {
            new GreedySolver(jct)
                    .solve()
                    .print();
            break;
        }
    }
}
 
Example 30
Source Project: rya   Source File: DeleteQueryCommand.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean validArguments(final String[] args) {
    boolean valid = true;
    try {
        new JCommander(new RemoveParameters(), args);
    } catch(final ParameterException e) {
        valid = false;
    }
    return valid;
}