Example usage for org.apache.commons.cli DefaultParser DefaultParser

List of usage examples for org.apache.commons.cli DefaultParser DefaultParser

Introduction

In this page you can find the example usage for org.apache.commons.cli DefaultParser DefaultParser.

Prototype

DefaultParser

Source Link

Usage

From source file:com.uber.stream.kafka.mirrormaker.controller.ControllerStarter.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;//w  w  w .ja va  2  s  . c o  m
    cmd = parser.parse(ControllerConf.constructControllerOptions(), args);
    if (cmd.getOptions().length == 0 || cmd.hasOption("help")) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("OptionsTip", ControllerConf.constructControllerOptions());
        System.exit(0);
    }
    final ControllerStarter controllerStarter = ControllerStarter.init(cmd);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                controllerStarter.stop();
            } catch (Exception e) {
                LOGGER.error("Caught error during shutdown! ", e);
            }
        }
    });

    try {
        controllerStarter.start();
    } catch (Exception e) {
        LOGGER.error("Cannot start Helix Mirror Maker Controller: ", e);
    }
}

From source file:com.act.analysis.similarity.SubstructureSearch.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from   w w  w .ja  v a 2s.c  om*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    if (cl.hasOption(OPTION_LICENSE_FILE)) {
        LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE));
    }

    List<String> searchOpts = Collections.emptyList();
    if (cl.hasOption(OPTION_SEARCH_OPTIONS)) {
        searchOpts = Arrays.asList(cl.getOptionValues(OPTION_SEARCH_OPTIONS));
    }

    // Make sure we can initialize correctly before opening any file handles for writing.
    SubstructureSearch matcher = new SubstructureSearch();
    try {
        matcher.init(cl.getOptionValue(OPTION_QUERY), searchOpts);
    } catch (IllegalArgumentException e) {
        System.err.format("Unable to initialize substructure search.  %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    } catch (MolFormatException e) {
        System.err.format("Invalid SMILES structure query.  %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    Pair<List<String>, Iterator<Map<String, String>>> iterPair = null;
    if (cl.hasOption(OPTION_INPUT_FILE)) {
        File inFile = new File(cl.getOptionValue(OPTION_INPUT_FILE));
        if (!inFile.exists()) {
            System.err.format("File at %s does not exist", inFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }
        iterPair = iterateOverTSV(inFile);
    } else if (cl.hasOption(OPTION_INPUT_DB)) {
        iterPair = iterateOverDB(cl.getOptionValue(OPTION_INPUT_DB_HOST, DEFAULT_HOST),
                Integer.parseInt(cl.getOptionValue(OPTION_INPUT_DB_HOST, DEFAULT_PORT)),
                cl.getOptionValue(OPTION_INPUT_DB));
    } else {
        System.err.format("Must specify either input TSV file or input DB from which to read.\n");
        HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    TSVWriter<String, String> writer = new TSVWriter<>(iterPair.getLeft());
    writer.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE)));

    LOGGER.info("Seaching for substructure '%s'", cl.getOptionValue(OPTION_QUERY));

    try {
        int rowNum = 0;
        while (iterPair.getRight().hasNext()) {
            Map<String, String> row = iterPair.getRight().next();
            rowNum++;
            try {
                String inchi = row.get(FIELD_INCHI);
                Molecule target = null;
                try {
                    target = MolImporter.importMol(inchi);
                } catch (Exception e) {
                    LOGGER.warn("Skipping molecule %d due to exception: %s\n", rowNum, e.getMessage());
                    continue;
                }
                if (matcher.matchSubstructure(target)) {
                    writer.append(row);
                    writer.flush();
                } else {
                    // Don't output if not a match.
                    LOGGER.debug("Found non-matching molecule: %s", inchi);
                }
            } catch (SearchException e) {
                LOGGER.error("Exception on input line %d: %s\n", rowNum, e.getMessage());
                throw e;
            }
        }
    } finally {
        writer.close();
    }
    LOGGER.info("Done with substructure search");
}

From source file:com.stratuscom.harvester.deployer.CommandLineParsers.java

static CommandLine parseCommandLineAppRunnerLine(String[] args) throws ParseException {
    Options options = new Options();

    Option courses = Option.builder(WITH).argName(WITH).hasArg().valueSeparator(',')
            .desc("comma-separated list of applications to run with the main app").build();
    options.addOption(courses);// www.  j  a va2  s.  com
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = null;
    commandLine = parser.parse(options, args);
    return commandLine;
}

From source file:com.mycompany.localetopdf.CmdParser.java

public static boolean ConfigureAppEnviroment(String[] args, AppEnviroment AppEnvInst)
        throws IOException, FOPException, TransformerException {
    {//ww w .j  ava  2s  .  c o m
        CmdParser instance = new CmdParser();

        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine cmdLine = parser.parse(instance.getOptions(), args, true);

            if (cmdLine.hasOption("help")) {
                instance.printHelp();
                return false;
            } else if (cmdLine.hasOption("l")) {
                String[] localeArg = cmdLine.getOptionValues("locale");
                AppEnvInst.setLocale(new LocaleObject(localeArg[0], localeArg[1]));

                File PDF;
                if (cmdLine.hasOption("p")) {
                    PDF = new File(cmdLine.getOptionValue("p"));
                } else {
                    PDF = new File("Locale.pdf");
                }
                AppEnvInst.setOutputFile(PDF);

                File XSLT;
                if (cmdLine.hasOption("x")) {
                    XSLT = new File(cmdLine.getOptionValue("x"));
                } else {
                    XSLT = null;
                }

                boolean rewrite;
                if (cmdLine.hasOption("r")) {
                    rewrite = true;
                } else {
                    rewrite = false;
                }

                AppEnvInst.setView(new PdfView(XSLT, rewrite));
                return true;
            } else {
                instance.printHelp();
                return false;
            }

        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }

    }
}

From source file:com.cohesionforce.dis.ConvertCSV.java

/**
 * The main method of this converter. It could be more robust, but it is
 * intended to be a test tool.//from   w w  w . j  a  v  a2s .  com
 */
public static void main(String[] args) {

    HelpFormatter formatter = new HelpFormatter();
    // create Options object
    Options options = new Options();

    options.addOption("i", true, "CSV Log file");
    options.addOption("o", true, "Ouput directory for Avro files");
    options.addOption("c", true, "Compression Codec <snappy,deflate,none> Default is snappy");
    options.addOption("p", false, "Write to Parquet format");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    String inputFile = null;
    String outputFile = null;
    try {
        cmd = parser.parse(options, args);
        inputFile = cmd.getOptionValue("i");
        outputFile = cmd.getOptionValue("o");
        if (inputFile == null || outputFile == null) {
            formatter.printHelp("usage: ConvertCSV", options);
            return;
        }
        if (cmd.hasOption("p")) {
            LogWriter.setParquet(true);
        }
        if (cmd.hasOption("c")) {
            LogWriter.setCodec(cmd.getOptionValue("c"));
        }
    } catch (ParseException exc) {
        System.err.println("Problem with command line parameters: " + exc.getMessage());
        return;
    }

    // Make sure the output directory exists
    File outputDir = new File(outputFile);
    outputDir.mkdirs();

    // Start the logger thread listening
    final ConvertCSV converter = new ConvertCSV();
    if (cmd.hasOption("p")) {
        converter.setExtension("parquet");
    }
    converter.setOutputDirectory(outputFile);
    converter.setInputFile(inputFile);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println("Shutting down DIS Logger");
            synchronized (converter) {
                converter.shutdown();
            }
        }
    });
    converter.run();
    converter.shutdown();
}

From source file:maps.OptionsHandler.java

static void applyOptions(String[] args) {
    try {//from  ww  w  .j  a  v  a  2 s  . co m
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);
        checkOptions(cmd);
    } catch (ParseException e) {
        System.err.println("Error in options: " + e.toString());
        printHelpOption();
    }
}

From source file:net.openhft.chronicle.queue.ChronicleReaderMain.java

private static CommandLine parseCommandLine(final @NotNull String[] args, final Options options) {
    final CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = null;/*  www . ja  v a 2 s.c o m*/
    try {
        commandLine = parser.parse(options, args);

        if (commandLine.hasOption('h')) {
            new HelpFormatter().printHelp(ChronicleReaderMain.class.getSimpleName(), options);
            System.exit(0);
        }

        if (!commandLine.hasOption('d')) {
            System.out.println("Please specify the directory with -d\n");
            printUsageAndExit(options);
        }
    } catch (ParseException e) {
        printUsageAndExit(options);
    }

    return commandLine;
}

From source file:edu.illinois.cs.cogcomp.temporal.normalizer.main.TemporalNormalizerBenchmark.java

/**
 *
 * @param args 1. -verbose, this is optional
 *             2. -useGoldChunk, optional, if not set, temporal chunker will be used
 *             3. -inputFolder <filepath>, mandatory
 *             4. -outputFolder <filepath>, mandatory
 * @throws ParserConfigurationException//from  ww w  .ja v  a 2 s. c  om
 * @throws SAXException
 * @throws IOException
 */
public static void main(String[] args) throws Exception {
    CommandLine commandLine;
    Options options = new Options();
    options.addOption("useHeidelTime", false, "If user wants to use HeidelTime to normalize");
    options.addOption("useGoldChunk", false, "If user wants to use gold timex extraction");
    options.addOption("verbose", false, "If user wants to print execution details");
    Option input_opt = Option.builder("inputFolder").required(true).hasArg().desc("The folder of input data")
            .build();
    Option output_opt = Option.builder("outputFolder").required(true).hasArg()
            .desc("The folder where user wants to write data").build();
    options.addOption(input_opt);
    options.addOption(output_opt);

    CommandLineParser parser = new DefaultParser();
    commandLine = parser.parse(options, args);

    boolean useHeidelTime = commandLine.hasOption("useHeidelTime");
    boolean useGoldChunk = commandLine.hasOption("useGoldChunk");
    boolean verbose = commandLine.hasOption("verbose");
    String inputFolder = commandLine.getOptionValue("inputFolder");
    String outputFolder = commandLine.getOptionValue("outputFolder");

    TemporalNormalizerBenchmark benchmark = new TemporalNormalizerBenchmark();

    benchmark.setUp(inputFolder, useHeidelTime);
    if (useGoldChunk) {
        benchmark.testNormalizationWithTrueExtraction(outputFolder, verbose);
    } else {
        benchmark.testTemporalChunker(outputFolder, verbose);
    }

}

From source file:com.cronutils.cli.CronUtilsCLI.java

private static void cronValidation(String[] args) throws ParseException {
    Options options = new Options();
    options.addOption("v", "validate", false, "Action of validation (default)");
    options.addOption("f", "format", true,
            "Cron expression format to validate. Possible values are: CRON4J, QUARTZ, UNIX");
    options.addOption("e", "expression", true, "Cron expression to validate. Example: '* 1 * * *'");
    options.addOption("h", HELP, false, "Help");

    String header = "Cron expressions validation by cron-utils\n\n";
    String footer = "\nPlease report issues at https://github.com/jmrozanec/cron-utils/issues";

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption(HELP) || cmd.getOptions().length == 0) {
        showHelp(options, header, footer);
        return;//from ww w.jav  a  2 s .  co m
    }
    if (!cmd.hasOption("validate")) {
        showHelp(options, header, footer);
        return;
    }
    if (cmd.hasOption('v')) {
        String format = cmd.getOptionValue("f");
        String expression = cmd.getOptionValue("e");

        CronType cronType = CronType.valueOf(format);
        CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(cronType);
        CronParser cronParser = new CronParser(cronDefinition);
        Cron quartzCron = cronParser.parse(expression);
        quartzCron.validate();
    }
}

From source file:com.github.e2point718.har2jmx.HAR2JMX.java

private static CommandLine parseCommandLine(String[] args) throws ParseException {
    Options options = new Options();
    Option jMeterHome = Option.builder(CMD_SWITCH_jmeterHome).hasArg().required().desc("JMeter Home folder")
            .build();//w  w  w . j a v a 2 s.co  m
    options.addOption(jMeterHome);
    CommandLineParser parser = new DefaultParser();
    CommandLine line;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("har2jmx", options);
        throw e;
    }
    File jMeterHomeFolder = new File(line.getOptionValue(CMD_SWITCH_jmeterHome));
    if (!jMeterHomeFolder.exists()) {
        throw new ParseException(jMeterHomeFolder.getAbsolutePath() + " is not accessible");
    }
    File jMeterSaveServiceFile = new File(jMeterHomeFolder, "bin/saveservice.properties");
    if (!jMeterSaveServiceFile.exists()) {
        throw new ParseException(jMeterSaveServiceFile.getAbsolutePath()
                + " is not accessible. Please verify jmeterHome location "
                + jMeterHomeFolder.getAbsolutePath());
    }
    return line;
}