com.beust.jcommander.JCommander Java Examples

The following examples show how to use com.beust.jcommander.JCommander. 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 File: QualityScoreStats.java    From cramtools with 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 #2
Source File: CodeSampleParams.java    From googleads-java-lib with 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 #3
Source File: TraceAnalysisToolMain.java    From kieker with 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 File: ConsoleProducer.java    From joyqueue with 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 File: CompactorUtil.java    From phoenix-omid with 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 File: LogServer.java    From ratis with 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 #7
Source File: PubsubEmulatorServer.java    From kafka-pubsub-emulator with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #8
Source File: CleanM2.java    From mvn-repo-cleaner with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #9
Source File: CodeSampleParams.java    From google-ads-java with 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 #10
Source File: GenerateWorkspaceOptionsTest.java    From migration-tooling with Apache License 2.0 5 votes vote down vote up
@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/");
}
 
Example #11
Source File: HoodieWithTimelineServer.java    From hudi with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  final Config cfg = new Config();
  JCommander cmd = new JCommander(cfg, null, args);
  if (cfg.help || args.length == 0) {
    cmd.usage();
    System.exit(1);
  }

  HoodieWithTimelineServer service = new HoodieWithTimelineServer(cfg);
  service.run(UtilHelpers.buildSparkContext("client-server-hoodie", cfg.sparkMaster, cfg.sparkMemory));
}
 
Example #12
Source File: AppTest.java    From sherlock with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testHelp() throws IOException, SherlockException {
    JCommander jc = new JCommander();
    CLISettings settings = mock(CLISettings.class);
    CLISettingsTest.setField(CLISettingsTest.getField("jCommander", App.class), jc);
    CLISettingsTest.setField(CLISettingsTest.getField("settings", App.class), settings);
    App.main(new String[] {"--help"});
    verify(settings, times(1)).loadFromConfig();
    verify(settings, times(1)).print();
}
 
Example #13
Source File: GoldenImageFinder.java    From nomulus with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  GoldenImageFinder finder = new GoldenImageFinder();
  JCommander jCommander = new JCommander(finder);
  jCommander.addConverterFactory(new ParameterFactory());
  jCommander.parse(args);
  finder.run();
}
 
Example #14
Source File: SamRecordComparision.java    From cramtools with 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 " + Bam2Cram.class.getPackage().getImplementationVersion());
	System.out.println(sb.toString());
}
 
Example #15
Source File: LoadSimulationClient.java    From pulsar with Apache License 2.0 5 votes vote down vote up
/**
 * Start a client with command line arguments.
 *
 * @param args
 *            Command line arguments to pass in.
 */
public static void main(String[] args) throws Exception {
    final MainArguments mainArguments = new MainArguments();
    final JCommander jc = new JCommander(mainArguments);
    jc.setProgramName("pulsar-perf simulation-client");
    try {
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }
    (new LoadSimulationClient(mainArguments)).run();
}
 
Example #16
Source File: GenerateWorkspaceOptionsTest.java    From migration-tooling with Apache License 2.0 5 votes vote down vote up
@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)");
}
 
Example #17
Source File: GenerateWorkspaceOptionsTest.java    From migration-tooling with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #18
Source File: Main.java    From pomutils with Apache License 2.0 5 votes vote down vote up
protected static int mainInternal(String... args) {
	CommandMain mainCommand = new CommandMain();
	CommandPomMergeDriver mergeCommand = new CommandPomMergeDriver();
	CommandPomVersionReplacer versionReplacerCommand = new CommandPomVersionReplacer();

	JCommander jc = new JCommander(mainCommand);
	jc.addCommand("merge", mergeCommand);
	jc.addCommand("replace", versionReplacerCommand);

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

	String logLevel = mainCommand.isDebug() ? "debug" : "error";
	System.setProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, logLevel);

	logger = LoggerFactory.getLogger(Main.class);

	if (logger.isInfoEnabled()) {
		logger.info("PomUtils version {}", ManifestUtils.getImplementationVersion());
	}

	if ("merge".equals(jc.getParsedCommand())) {
		return executePomMergeDriver(mergeCommand);
	} else if ("replace".equals(jc.getParsedCommand())) {
		executePomVersionReplacer(versionReplacerCommand);
		return 0;
	}
	jc.usage();
	return 1;
}
 
Example #19
Source File: ClinicalModelServerInferenceExample.java    From SKIL_Examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ClinicalModelServerInferenceExample m = new ClinicalModelServerInferenceExample();

    JCommander.newBuilder()
            .addObject(m)
            .build()
            .parse(args);

    m.run();
}
 
Example #20
Source File: L10nJCommander.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link JCommander} instance for a single run (sub-sequent
 * parsing are not supported but required for testing).
 */
public void createJCommanderForRun() {
    logger.debug("Create JCommander instance");
    jCommander = new JCommander();

    jCommander.setAcceptUnknownOptions(true);

    logger.debug("Initialize the JCommander instance");
    jCommander.setProgramName(PROGRAM_NAME);

    logger.debug("Set the main command for version/help directly on the JCommander");
    jCommander.addObject(mainCommand);

    logger.debug("Register Commands retreived using Spring");
    for (Command command : applicationContext.getBeansOfType(Command.class).values()) {

        Map<String, JCommander> jCommands = jCommander.getCommands();

        for (String name : command.getNames()) {
            if (jCommands.keySet().contains(name)) {
                throw new RuntimeException("There must be only one module with name: " + name);
            }
        }

        commands.put(command.getName(), command);
        jCommander.addCommand(command);
    }
}
 
Example #21
Source File: QualityScoreStats.java    From cramtools with 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 " + QualityScoreStats.class.getPackage().getImplementationVersion());
	System.out.println(sb.toString());
}
 
Example #22
Source File: Application.java    From ethereum-paper-wallet with Apache License 2.0 5 votes vote down vote up
private void parseCommandLine(String [] args) {
	JCommander cmd = new JCommander(this, args);
	cmd.setProgramName(COMMAND_NAME);

	if(help) {
		cmd.usage();
		System.exit(0);
	}
}
 
Example #23
Source File: ShadowingCoordinator.java    From compass with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  ShadowingCoordinatorConfiguration config = new ShadowingCoordinatorConfiguration();
  JCommander.newBuilder()
      .addObject(config)
      .build()
      .parse(args);

  ShadowingCoordinator coo = new ShadowingCoordinator(config, SignatureSourceHelper.signatureSourceFromArgs(config.signatureSource, args));
  coo.setup();
  coo.start();
}
 
Example #24
Source File: WhenAsciidoctorAPICallIsCalled.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Test
public void api_parameters_should_be_transformed_to_cli_command() {

    AttributesBuilder attributesBuilder = AttributesBuilder.attributes()
            .attribute("myAtribute", "myValue").sectionNumbers(true)
            .copyCss(false);

    OptionsBuilder optionsBuilder = OptionsBuilder.options()
            .backend("docbook").templateDirs(new File("a"), new File("b"))
            .safe(SafeMode.UNSAFE).attributes(attributesBuilder.get());

    List<String> command = AsciidoctorUtils.toAsciidoctorCommand(
            optionsBuilder.asMap(), "file.adoc");

    String currentDirectory = new File( "" ).getAbsolutePath() + File.separator;

    String[] parameters = command.subList(1, command.size()).toArray(new String[0]);
    
    AsciidoctorCliOptions asciidoctorCliOptions = new AsciidoctorCliOptions();
    new JCommander(asciidoctorCliOptions,
            parameters);
    
    assertThat(asciidoctorCliOptions.getTemplateDir(), containsInAnyOrder(currentDirectory+"a", currentDirectory+"b"));
    assertThat(asciidoctorCliOptions.getSafeMode(), is(SafeMode.UNSAFE));
    assertThat(asciidoctorCliOptions.getBackend(), is("docbook"));
    assertThat(asciidoctorCliOptions.getParameters(), containsInAnyOrder("file.adoc"));
    
    assertThat(asciidoctorCliOptions.getAttributes(), hasEntry("myAtribute", (Object)"myValue"));
    assertThat(asciidoctorCliOptions.getAttributes(), hasKey("numbered"));
    assertThat(asciidoctorCliOptions.getAttributes(), hasKey("copycss!"));
    
}
 
Example #25
Source File: GenerateWorkspaceOptionsTest.java    From migration-tooling with Apache License 2.0 5 votes vote down vote up
@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,)");
}
 
Example #26
Source File: Main.java    From digdag with Apache License 2.0 5 votes vote down vote up
private static Command getParsedCommand(JCommander jc)
{
    String commandName = jc.getParsedCommand();
    if (commandName == null) {
        return null;
    }

    return (Command) jc.getCommands().get(commandName).getObjects().get(0);
}
 
Example #27
Source File: JCommanderPrefixTranslatorTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullDelegate() {
  final JCommanderPrefixTranslator translator = new JCommanderPrefixTranslator();
  translator.addObject(new NullDelegate());
  final JCommander commander = prepareCommander(translator.translate());
  commander.parse();
}
 
Example #28
Source File: AppAdmin.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
public void process(String command, CommandArgs arguments, JCommander jCommander) throws Exception {
    Command type=Command.type(command);
    switch (type){
        case token:
            token((TokenArg)arguments,jCommander);
            break;
        case list:
            tokens((TokensArg) arguments,jCommander);
        default:
            jCommander.usage();
            System.exit(-1);
            break;
    }
}
 
Example #29
Source File: BrokerAdmin.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
/**
 *  Process  commands
 *
 **/
public  void process(String command, CommandArgs arguments, JCommander jCommander) throws Exception{
    Command type=Command.type(command);
    switch (type){
        case list:
            list(arguments,jCommander);
            break;
        default:
            jCommander.usage();
            System.exit(-1);
            break;
    }
}
 
Example #30
Source File: PMDCommandLineInterface.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
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();
}