Java Code Examples for org.kohsuke.args4j.CmdLineParser

The following are top voted examples for showing how to use org.kohsuke.args4j.CmdLineParser. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: invesdwin-context-r   File: Main.java   View source code 6 votes vote down vote up
@Override
protected void startApplication(final CmdLineParser parser) throws Exception {
    final List<String> lines = FileUtils.readLines(input, Charset.defaultCharset());
    final List<List<Double>> tradesPerStrategy = new ArrayList<List<Double>>(lines.size());
    for (final String line : lines) {
        final String[] tradeStrs = Strings.split(line, ",");
        final List<Double> trades = new ArrayList<Double>(tradeStrs.length);
        for (final String tradeStr : tradeStrs) {
            trades.add(Double.parseDouble(tradeStr));
        }
        tradesPerStrategy.add(trades);
    }
    final List<Double> optimalFs = new OptimalfScriptTask(tradesPerStrategy).run();
    final StringBuilder optimalFsStr = new StringBuilder();
    for (final Double optimalF : optimalFs) {
        optimalFsStr.append(optimalF);
        optimalFsStr.append("\n");
    }
    FileUtils.writeStringToFile(output, optimalFsStr.toString(), Charset.defaultCharset());
}
 
Example 2
Project: omr-dataset-tools   File: CLI.java   View source code 6 votes vote down vote up
/**
 * Parse the CLI arguments and return the populated parameters structure.
 *
 * @param args the CLI arguments
 * @return the parsed parameters, or null if failed
 * @throws org.kohsuke.args4j.CmdLineException if cmd line is malformed
 */
public static CLI create (final String... args)
        throws CmdLineException
{
    logger.info("CLI args: {}", Arrays.toString(args));

    CLI cli = new CLI();

    final CmdLineParser parser = new CmdLineParser(cli);

    parser.parseArgument(args);

    if (args.length == 0) {
        cli.help = true;
    }

    if (cli.help) {
        printUsage(parser);
    }

    return cli;
}
 
Example 3
Project: omr-dataset-tools   File: CLI.java   View source code 6 votes vote down vote up
/**
 * Print out the general syntax for the command line.
 */
private static void printUsage (CmdLineParser parser)
{
    StringBuilder buf = new StringBuilder();

    buf.append("\n");
    buf.append("\nSyntax:");
    buf.append("\n   [OPTIONS] -- [INPUT_FILES]\n");

    buf.append("\[email protected]:");
    buf.append("\n Content to be extended in line");
    buf.append("\n");

    buf.append("\nOptions:\n");

    StringWriter writer = new StringWriter();
    parser.printUsage(writer, null);
    buf.append(writer.toString());

    buf.append("\nInput file extensions:");
    buf.append("\n .xml: annotations file");
    buf.append("\n");
    logger.info(buf.toString());
}
 
Example 4
Project: endpoint-health   File: Main.java   View source code 6 votes vote down vote up
public static void main(final String[] args) {
    try {
        final MainArgs mainArgs = new MainArgs();

        new CmdLineParser(mainArgs).parseArgument(args);

        if (mainArgs.isHelp()) {
            printUsage();
        } else if (mainArgs.isVersion()) {
            printVersion();
        } else {
            Guice.createInjector(new EndPointHealthModule())
                    .getInstance(Main.class).run(mainArgs);
        }
    } catch (final CmdLineException e) {
        System.err.println(e.getMessage());
        printUsage();
    }
}
 
Example 5
Project: kafka-mgd-sample   File: Consumer.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Consumer consumer = new Consumer();
    CmdLineParser parser = new CmdLineParser(consumer);

    try {
        parser.parseArgument(args);
    } catch (CmdLineException ce) {
        System.err.println(ce.getMessage());
        System.err.println();
        System.err.println(" Options are:");
        parser.printUsage(System.err); // print the list of available options
        System.err.println();
        System.exit(0);
    }

    consumer.run();
}
 
Example 6
Project: kafka-mgd-sample   File: Producer.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Producer producer = new Producer();
    CmdLineParser parser = new CmdLineParser(producer);

    try {
        parser.parseArgument(args);
    } catch (CmdLineException ce) {
        System.err.println(ce.getMessage());
        System.err.println();
        System.err.println(" Options are:");
        parser.printUsage(System.err); // print the list of available options
        System.err.println();
        System.exit(0);
    }

    producer.run();
}
 
Example 7
Project: java-cli-demos   File: Main.java   View source code 6 votes vote down vote up
private void doMain(final String[] arguments) throws IOException
{
   final CmdLineParser parser = new CmdLineParser(this);
   if (arguments.length < 1)
   {
      parser.printUsage(out);
      System.exit(-1);
   }
   try
   {
      parser.parseArgument(arguments);
   }
   catch (CmdLineException clEx)
   {
      out.println("ERROR: Unable to parse command-line options: " + clEx);
   }
   out.println("The file '" + fileName + "' was provided and verbosity is set to '" + verbose + "'.");
}
 
Example 8
Project: pgcodekeeper   File: CliArgs.java   View source code 6 votes vote down vote up
private void printUsage(PrintWriter writer) {
    // fix defaults for options like help and other 0-arg booleans
    OptionHandlerRegistry.getRegistry().registerHandler(Boolean.class, BooleanNoDefOptionHandler.class);
    OptionHandlerRegistry.getRegistry().registerHandler(boolean.class, BooleanNoDefOptionHandler.class);

    ParserProperties prop = ParserProperties.defaults()
            .withUsageWidth(80)
            .withOptionSorter(null);

    ByteArrayOutputStream buf = new ByteArrayOutputStream();

    // new args instance to get correct defaults
    new CmdLineParser(new CliArgs(), prop)
    .printUsage(new OutputStreamWriter(buf, StandardCharsets.UTF_8), null);

    writer.println(MessageFormat.format(Messages.UsageHelp.replace("${tab}", "\t"),
            new String(buf.toByteArray(), StandardCharsets.UTF_8),
            DangerStatementOptionHandler.getMetaVariable() + '\n' + DbObjTypeOptionHandler.getMetaVariable()));
}
 
Example 9
Project: cli-skeleton   File: Params.java   View source code 6 votes vote down vote up
/** Parse the command line options. 
 * @param args the command line args as passed to the main method of the
 * program.
 * @return the parsed command line options or {@code null} if
 * the program needs to exit. {@code null} will be returned
 * if the command lines are wrong or the command line help
 * was displayed.
 */
public static Params parse(String[] args) {
    Params result = new Params();
    CmdLineParser cmdLineParser = new CmdLineParser(result);
    try {
        if (log.isDebugEnabled()) {
            log.debug("Args: {}", Arrays.toString(args));
        }
        
        cmdLineParser.parseArgument(args);
        
        if (result.help) {
            cmdLineParser.printUsage(System.err);
            return null;
        }
                    
        return result;
    } catch (CmdLineException ex) {
        log.warn("Error in parsing", ex);
        System.err.println(ex.getMessage());
        cmdLineParser.printUsage(System.err);
    }
    return null;
}
 
Example 10
Project: donut-nunit-adapter   File: Main.java   View source code 6 votes vote down vote up
private void doMain(
        String[] args) {
    CmdLineParser parser = new CmdLineParser(this);
    try {
        parser.parseArgument(args);
        ensureResultXmlDirectory();

        generateDonutJsonFiles();

    }catch (CmdLineException c){
        System.err.println(c.getMessage());
        System.err.println("usage: Main [options ...]");
        parser.printUsage(System.err);
        System.exit(1);
    }catch (Exception e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
}
 
Example 11
Project: invesdwin-context-matlab   File: Main.java   View source code 6 votes vote down vote up
@Override
protected void startApplication(final CmdLineParser parser) throws Exception {
    final List<String> lines = FileUtils.readLines(input, Charset.defaultCharset());
    final List<List<Double>> tradesPerStrategy = new ArrayList<List<Double>>(lines.size());
    for (final String line : lines) {
        final String[] tradeStrs = Strings.split(line, ",");
        final List<Double> trades = new ArrayList<Double>(tradeStrs.length);
        for (final String tradeStr : tradeStrs) {
            trades.add(Double.parseDouble(tradeStr));
        }
        tradesPerStrategy.add(trades);
    }
    final List<Double> optimalFs = new OrnsteinUhlenbeckScriptTask(tradesPerStrategy).run();
    final StringBuilder optimalFsStr = new StringBuilder();
    for (final Double optimalF : optimalFs) {
        optimalFsStr.append(optimalF);
        optimalFsStr.append("\n");
    }
    FileUtils.writeStringToFile(output, optimalFsStr.toString(), Charset.defaultCharset());
}
 
Example 12
Project: beepbeep   File: MainTest.java   View source code 6 votes vote down vote up
@Test
public void testCreatePipelineBuilder_Sql() throws Exception {
    // Given
    Main main = new Main();
    CmdLineParser cmdLineParser = new CmdLineParser(main);
    cmdLineParser.parseArgument(
        "--type", "sql",
        "--url", "jdbc:h2:mem:test",
        "--username", "sa",
        "--files", "target/test-classes/com/github/gquintana/beepbeep/**/*.sql");
    // When
    PipelineBuilder pipelineBuilder = main.createPipelineBuilder();
    // Then
    assertThat(main.url).isEqualTo("jdbc:h2:mem:test");
    assertThat(pipelineBuilder).isInstanceOf(SqlPipelineBuilder.class);

}
 
Example 13
Project: beepbeep   File: MainTest.java   View source code 6 votes vote down vote up
@Test
public void testCreatePipelineBuilder_SqlConfiguration() throws Exception {
    // Given
    File configFile = new File(temporaryFolder.getRoot(), "sql.yml");
    TestFiles.writeResource("config/sql1.yml", configFile);
    Main main = new Main();
    CmdLineParser cmdLineParser = new CmdLineParser(main);
    cmdLineParser.parseArgument(
        "--config", configFile.getPath());
    // When
    PipelineBuilder pipelineBuilder = main.createPipelineBuilder();
    // Then
    assertThat(pipelineBuilder).isInstanceOf(SqlPipelineBuilder.class);
    assertThat(getField(pipelineBuilder, "url")).isEqualTo("jdbc:h2:mem:test");

}
 
Example 14
Project: trello-to-markdown   File: EBoardRender.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws ClassNotFoundException {

        // https://martin-thoma.com/how-to-parse-command-line-arguments-in-java/
        EBoardRender.Config config = new EBoardRender.Config();

        CmdLineParser parser = new CmdLineParser(  config );
        try {
            parser.parseArgument(args);
        } catch (CmdLineException e) {
            e.printStackTrace();
        }

        Configuration conf = Configuration.getInstance(config.getConfig());
            String command = conf.getCommand().trim().toUpperCase();
            CommandHandler commandHandler = conf.getCommandHandlerFactory().getCommandHandler(command);
            commandHandler.execute(conf);
    }
 
Example 15
Project: flowchat   File: ChatService.java   View source code 6 votes vote down vote up
private void parseArguments(String[] args) {
    CmdLineParser parser = new CmdLineParser(this);

    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        // if there's a problem in the command line,
        // you'll get this exception. this will report
        // an error message.
        System.err.println(e.getMessage());
        System.err.println("java -jar reddit-history.jar [options...] arguments...");
        // print the list of available options
        parser.printUsage(System.err);
        System.err.println();
        System.exit(0);

        return;
    }
}
 
Example 16
Project: apiman-cli   File: ApiCreateCommand.java   View source code 6 votes vote down vote up
@Override
public void performAction(CmdLineParser parser) throws CommandException {
    LOGGER.debug("Creating {}", this::getModelName);

    final Api api = new Api(
            name,
            description,
            initialVersion);

    final ApiConfig config = new ApiConfig(
            endpoint,
            endpointType,
            publicApi,
            Lists.newArrayList(new ApiGateway(gateway)));

    // create
    final VersionAgnosticApi apiClient = buildServerApiClient(VersionAgnosticApi.class, serverVersion);
    ManagementApiUtil.invokeAndCheckResponse(() -> apiClient.create(orgName, api));

    // configure
    ManagementApiUtil.invokeAndCheckResponse(() -> apiClient.configure(orgName, name, initialVersion, config));
}
 
Example 17
Project: apiman-cli   File: ApiDefinitionCommand.java   View source code 6 votes vote down vote up
@Override
public void performAction(CmdLineParser parser) throws CommandException {
    if (!definitionStdIn && null == definitionFile) {
        throw new ExitWithCodeException(1, "API definition must be provided", true);
    }

    // read definition from STDIN or file
    String definition;
    try (InputStream is = (definitionStdIn ? System.in : Files.newInputStream(definitionFile))) {
        definition = CharStreams.toString(new InputStreamReader(is));

    } catch (IOException e) {
        throw new CommandException(e);
    }

    LOGGER.debug("Adding definition to API '{}' with contents: {}", this::getModelName, () -> definition);

    ManagementApiUtil.invokeAndCheckResponse(() ->
            buildServerApiClient(VersionAgnosticApi.class, serverVersion).setDefinition(orgName, name, version, definitionType, new TypedString(definition)));
}
 
Example 18
Project: apiman-cli   File: ApiPolicyAddCommand.java   View source code 6 votes vote down vote up
@Override
public void performAction(CmdLineParser parser) throws CommandException {
    if (!configStdIn && null == configFile) {
        throw new ExitWithCodeException(1, "Policy configuration must be provided", true);
    }

    // read configuration from STDIN or file
    String policyConfig;
    try (InputStream is = (configStdIn ? System.in : Files.newInputStream(configFile))) {
        policyConfig = CharStreams.toString(new InputStreamReader(is));

    } catch (IOException e) {
        throw new CommandException(e);
    }

    LOGGER.debug("Adding policy '{}' to API '{}' with configuration: {}",
            () -> policyName, this::getModelName, () -> policyConfig);

    final ApiPolicy apiPolicy = new ApiPolicy(policyName);
    apiPolicy.setDefinitionId(policyName);

    ManagementApiUtil.invokeAndCheckResponse(() ->
            buildServerApiClient(VersionAgnosticApi.class, serverVersion).addPolicy(orgName, name, version, apiPolicy));
}
 
Example 19
Project: apiman-cli   File: ModelShowCommand.java   View source code 6 votes vote down vote up
@Override
public void performAction(CmdLineParser parser) throws CommandException {
    LOGGER.debug("Showing {}", this::getModelName);

    try {
        final A apiClient = this.buildServerApiClient(getApiClass());
        final Method fetchMethod = apiClient.getClass().getMethod("fetch", String.class);

        @SuppressWarnings("unchecked")
        final M model = (M) fetchMethod.invoke(apiClient, getModelId());
        LOGGER.debug("{} received: {}", this::getModelName, () -> MappingUtil.safeWriteValueAsJson(model));

        processModel(model);

    } catch (Exception e) {
        throw new CommandException(e);
    }
}
 
Example 20
Project: apiman-cli   File: AbstractCommand.java   View source code 6 votes vote down vote up
/**
 * @param args   the arguments
 * @param parser the command line parser containing usage information
 * @return a child Command for the given args, or <code>null</code> if not found
 */
protected Command getChildAction(List<String> args, CmdLineParser parser) {
    final String commandName = args.get(0);

    // find implementation
    final Class<? extends Command> commandClass = commandMap.get(commandName);
    if (null != commandClass) {
        try {
            final Command command = InjectionUtil.getInjector().getInstance(commandClass);
            command.setParent(this);
            command.setCommandName(commandName);

            return command;
        } catch (ProvisionException | ConfigurationException e) {
            throw new CommandException(String.format("Error getting child command for args: %s", args), e);
        }
    }
    return null;
}
 
Example 21
Project: reddit-history   File: App.java   View source code 6 votes vote down vote up
private void parseArguments(String[] args) {
    CmdLineParser parser = new CmdLineParser(this);

    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        // if there's a problem in the command line,
        // you'll get this exception. this will report
        // an error message.
        System.err.println(e.getMessage());
        System.err.println("java -jar reddit-history.jar [options...] arguments...");
        // print the list of available options
        parser.printUsage(System.err);
        System.err.println();
        System.exit(0);

        return;
    }
}
 
Example 22
Project: JmsTools   File: LogAnalyzer.java   View source code 6 votes vote down vote up
/**
 * Parse the command line into the specified configuration.
 * 
 * @param args The command line.
 * @param config The configuration class.
 * @return true if successful, false on errors such as missing arguments.
 */
private boolean parseCommandLine(String[] args, Configuration config) {
    CmdLineParser parser = new CmdLineParser(config);
    try {
        parser.parseArgument(args);
        if (config.getRemainingArguments() == null || config.getRemainingArguments().isEmpty()) {
            printUsage(parser);
            return false;
        } else {
            return true;
        }
    } catch (CmdLineException e) {
        printUsage(parser);
        System.out.println("Error: " + e.getMessage());
        return false;
    }
}
 
Example 23
Project: torfiles   File: WebService.java   View source code 6 votes vote down vote up
private void parseArguments(String[] args) {
    CmdLineParser parser = new CmdLineParser(this);

    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        // if there's a problem in the command line,
        // you'll get this exception. this will report
        // an error message.
        System.err.println(e.getMessage());
        System.err.println("java -jar torfiles.jar [options...] arguments...");
        // print the list of available options
        parser.printUsage(System.err);
        System.err.println();
        System.exit(0);

        return;
    }
}
 
Example 24
Project: osm-parquetizer   File: App.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    final MultiEntitySinkConfig config = new MultiEntitySinkConfig();
    final CmdLineParser cmdLineParser = new CmdLineParser(config);
    try {
        cmdLineParser.parseArgument(args);
        final OsmosisReader reader = new OsmosisReader(newInputStream(config.getSource()));
        final MultiEntitySink sink = new MultiEntitySink(config);
        sink.addObserver(new MultiEntitySinkObserver());
        reader.setSink(sink);
        reader.run();
    } catch (CmdLineException e) {
        System.out.println(e.getMessage());
        System.out.print("Usage: java -jar osm-parquetizer.jar");
        System.out.println();
        cmdLineParser.printSingleLineUsage(System.out);
    }
}
 
Example 25
Project: PersonaExtraction   File: ImageCatPageGrabber.java   View source code 6 votes vote down vote up
private void processArgs(String[] args) throws CmdLineException {
  CmdLineParser parser = new CmdLineParser(this);
  try {
    parser.parseArgument(args);
    if (arguments.isEmpty() && 
        (outDir == null || imagecatUrl == null || hostPart == null || pagePrefix == null)){
      throw new CmdLineException("Usage Error!");
    }
    
    // make outputDir
    if (!outDir.exists() && outDir.isDirectory()){
      LOG.info("Creating ["+outDir.getAbsolutePath()+"]");
      outDir.mkdirs();
    }
  } catch (CmdLineException e) {
    System.err.println(e.getMessage());
    System.err.println(USAGE);
    parser.printUsage(System.err);
    throw e;
  }
}
 
Example 26
Project: PersonaExtraction   File: PersonaIndexer.java   View source code 6 votes vote down vote up
private void processArgs(String[] args) throws CmdLineException {
  CmdLineParser parser = new CmdLineParser(this);
  try {
    parser.parseArgument(args);
    if (arguments.isEmpty()
        && (pageDir == null || configFile == null || solrUrl == null)) {
      throw new CmdLineException("Usage Error!");
    }

  } catch (CmdLineException e) {
    System.err.println(e.getMessage());
    System.err.println(USAGE);
    parser.printUsage(System.err);
    throw e;
  }
}
 
Example 27
Project: monsoon   File: Exporter.java   View source code 6 votes vote down vote up
public Exporter(String[] args) {
    final CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(80));
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        print_usage_and_exit_(parser);
        /* UNREACHABLE */
    }

    // If help is requested, simply print that.
    if (help) {
        print_usage_and_exit_(parser);
        /* UNREACHABLE */
    }

    // If there are no files, comlain with a non-zero exit code.
    if (dir == null)
        System.exit(EX_USAGE);

    dirPath = FileSystems.getDefault().getPath(dir);
}
 
Example 28
Project: monsoon   File: ApiBin.java   View source code 6 votes vote down vote up
public ApiBin(String[] args) {
    final CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(80));
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        print_usage_and_exit_(parser);
        /* UNREACHABLE */
    }

    // If help is requested, simply print that.
    if (help) {
        print_usage_and_exit_(parser);
        /* UNREACHABLE */
    }
}
 
Example 29
Project: axisviewer   File: AxisViewer.java   View source code 6 votes vote down vote up
private void doMain(final String[] args) throws Exception {
    final ParserProperties properties = ParserProperties.defaults().withUsageWidth(80);
    final CmdLineParser parser = new CmdLineParser(this, properties);
    try {
        parser.parseArgument(args);
        if (_url == null) {
            throw new CmdLineException(parser, "URL to camera stream required.", null);
        }
        // http://1.0.0.6:8085/axis-cgi/jpg/image.cgi?resolution=640x480
        Camera axis = new Camera("Axis 2100 Network Camera", _url, "", "", Constants.REFRESH_RATE );

        CameraFrame frame = new CameraFrame( axis );
        frame.setVisible(true);
        frame.run();
    } catch (Exception e) {
        System.err.println("Usage:");
        parser.printUsage(System.err);
    }
}
 
Example 30
Project: monsoon   File: RhistMain.java   View source code 6 votes vote down vote up
/**
 * Initialize the verifier, using command-line arguments.
 *
 * @param args The command-line arguments passed to the program.
 */
public RhistMain(String[] args) {
    final CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(80));
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        print_usage_and_exit_(parser);
        /* UNREACHABLE */
    }

    // If help is requested, simply print that.
    if (help) {
        print_usage_and_exit_(parser);
        /* UNREACHABLE */
    }

    // If there are no files, comlain with a non-zero exit code.
    if (dir == null)
        System.exit(EX_USAGE);

    path_ = FileSystems.getDefault().getPath(dir);
}
 
Example 31
Project: monsoon   File: Verify.java   View source code 6 votes vote down vote up
/**
 * Initialize the verifier, using command-line arguments.
 * @param args The command-line arguments passed to the program.
 */
public Verify(String[] args) {
    final CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(80));
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        print_usage_and_exit_(parser);
        /* UNREACHABLE */
    }

    // If help is requested, simply print that.
    if (help) {
        print_usage_and_exit_(parser);
        /* UNREACHABLE */
    }

    // If there are no files, comlain with a non-zero exit code.
    if (files.isEmpty())
        System.exit(EX_USAGE);
}
 
Example 32
Project: basekb-search   File: DumpTypesForMallet.java   View source code 6 votes vote down vote up
public void setup(String[] args) {
    CmdLineParser parser = new CmdLineParser(this);
    try {
        parser.parseArgument(args);
        if (showUsage) {
            System.err.println(versionString);
            System.err.println("Usage:");
            parser.printUsage(System.err);
            System.exit(0);
        }
    }
    catch (CmdLineException e) {
        System.err.println("ERROR: " + e.getMessage());
        System.err.println("Usage:");
        parser.printUsage(System.err);
        System.exit(1);
    }

    tools.INDEX_DIRECTORY_NAME = index_location;
}
 
Example 33
Project: basekb-search   File: FreebaseToolsRunner.java   View source code 6 votes vote down vote up
public FreebaseToolsRunner(String[] initArgs) {
    // Use this to construct a tools instance with a set of command-line `initArgs',
    // for example, `new FreebaseTools(new String[]{"--version"})'.
    CmdLineParser parser = new CmdLineParser(this);
    try {
        parser.parseArgument(initArgs);
        if (showUsage) {
            System.err.println(versionString);
            System.err.println("Usage:");
            parser.printUsage(System.err);
            System.exit(0);
        }
    } catch (CmdLineException e) {
        System.err.println("ERROR: " + e.getMessage());
        System.err.println("Usage:");
        parser.printUsage(System.err);
        System.exit(1);
    }
}
 
Example 34
Project: Ardulink-2   File: MqttMain.java   View source code 6 votes vote down vote up
public void doMain(String... args) throws Exception {
	CmdLineParser cmdLineParser = new CmdLineParser(this);
	try {
		cmdLineParser.parseArgument(args);
	} catch (CmdLineException e) {
		System.err.println(e.getMessage());
		cmdLineParser.printUsage(System.err);
		return;
	}

	connectToMqttBroker();
	try {
		wait4ever();
	} finally {
		close();
	}

}
 
Example 35
Project: indexr   File: Tools.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Hack, make jvm init the static fields.
    RealtimeConfig.loadSubtypes();
    MyOptions options = new MyOptions();
    CmdLineParser parser = RuntimeUtil.parseArgs(args, options);
    if (options.help) {
        parser.printUsage(System.out);
        return;
    }

    Plugins.loadPlugins();
    IndexRConfig config = new IndexRConfig();
    boolean ok = false;
    try {
        ok = runTool(options, config);
    } catch (Exception e) {
        logger.error("", e);
    } finally {
        IOUtils.closeQuietly(config);
    }
    if (ok) {
        System.exit(0);
    } else {
        System.exit(1);
    }
}
 
Example 36
Project: indexr   File: Rt2His.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    RealtimeConfig.loadSubtypes();
    MyOptions options = new MyOptions();
    CmdLineParser parser = RuntimeUtil.parseArgs(args, options);
    if (options.help) {
        parser.printUsage(System.out);
        return;
    }

    Plugins.loadPlugins();
    if (!hiveMode(options)) {
        logger.info("Failed. options: {}", options.toString());
        System.exit(1);
    } else {
        logger.info("Succeed. options: {}", options.toString());
    }
}
 
Example 37
Project: jailer   File: CommandLineParser.java   View source code 6 votes vote down vote up
/**
 * Parses arguments and initializes the parser.
 * 
 * @param args the arguments
 * @param silent if <code>true</code>, no error messages will be written
 */
public static boolean parse(String[] args, boolean silent) throws Exception {
	CommandLineParser p = new CommandLineParser();
    commandLineParser.set(p);
    p.cmdLineParser = null;
    try {
    	p.cmdLineParser = new CmdLineParser(p);
    	p.cmdLineParser.parseArgument(args);
        if (p.arguments.isEmpty()) {
        	if (!silent) {
        		printUsage();
        		return false;
        	}
        }
        if (p.tabuFileName != null) {
            p.loadTabuTables(p.tabuFileName);
        }
        return true;
    } catch (CmdLineException e) {
        System.out.println(e.getMessage());
        printUsage();
        throw e;
    }
}
 
Example 38
Project: BUILD_file_generator   File: Bfg.java   View source code 5 votes vote down vote up
private static Pattern compilePattern(CmdLineParser cmdLineParser, String patternString) {
  try {
    return Pattern.compile(patternString);
  } catch (IllegalArgumentException e) {
    explainUsageErrorAndExit(cmdLineParser, String.format("Invalid regex: %s", e.getMessage()));
    return null;
  }
}
 
Example 39
Project: jbake-rtl-jalaali   File: Main.java   View source code 5 votes vote down vote up
private LaunchOptions parseArguments(String[] args) {
	LaunchOptions res = new LaunchOptions();
	CmdLineParser parser = new CmdLineParser(res);

	try {
		parser.parseArgument(args);
	} catch (final CmdLineException e) {
		printUsage(res);
		throw new JBakeException("Invalid commandline arguments: " + e.getMessage(), e);
	}

	return res;
}
 
Example 40
Project: jbake-rtl-jalaali   File: Main.java   View source code 5 votes vote down vote up
private void printUsage(Object options) {
	CmdLineParser parser = new CmdLineParser(options);
	StringWriter sw = new StringWriter();
	sw.append(USAGE_PREFIX + "\n");
	sw.append(ALT_USAGE_PREFIX + " <source> <destination>\n");
	sw.append(ALT_USAGE_PREFIX + " [OPTION]... [<value>...]\n\n");
	sw.append("Options:");
	System.out.println(sw.toString());
	parser.setUsageWidth(100);
	parser.printUsage(System.out);
}