Example usage for org.apache.commons.cli CommandLineParser parse

List of usage examples for org.apache.commons.cli CommandLineParser parse

Introduction

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

Prototype

CommandLine parse(Options options, String[] arguments) throws ParseException;

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:com.google.flightmap.parsing.faa.nfd.tools.RecordStructGenerator.java

public static void main(String args[]) {
    CommandLine line = null;/*from  ww  w  .  ja  v a2s. co  m*/
    try {
        final CommandLineParser parser = new PosixParser();
        line = parser.parse(OPTIONS, args);
    } catch (ParseException pEx) {
        System.err.println(pEx.getMessage());
        printHelp(line);
        System.exit(1);
    }

    if (line.hasOption(HELP_OPTION)) {
        printHelp(line);
        System.exit(0);
    }

    final String defPath = line.getOptionValue(DEF_FILE_OPTION);
    final File def = new File(defPath);

    try {
        (new RecordStructGenerator(def)).execute();
    } catch (IOException ioEx) {
        ioEx.printStackTrace();
        System.exit(2);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.argumentation.io.XmiFilePatternJsonStreamDumper.java

public static void main(final String[] args) throws ParseException, UIMAException, IOException {
    // TODO: It would be nice to be able to read from standard input but it
    // seems that ResourceCollectionReaderBase doesn't facilitate this
    final CommandLineParser parser = new DefaultParser();
    final Options opts = Parameter.createOptions();
    try {/*  w w w.  j  av a 2  s. co  m*/
        final CommandLine commandLine = parser.parse(opts, args);
        final String sourceLocation = commandLine.getOptionValue(Parameter.SOURCE_LOCATION.paramName);
        LOG.info(String.format("Source location is \"%s\".", sourceLocation));
        final String targetLocation = commandLine.getOptionValue(Parameter.TARGET_LOCATION.paramName);
        LOG.info(String.format("Target location is \"%s\".", targetLocation));
        new XmiFilePatternJsonStreamDumper(JsonStreamDumpWriter.class, sourceLocation, targetLocation).call();
    } catch (final ParseException e) {
        printHelp(opts);
        throw e;
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQueryRenameAllMethods.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);/*  w  ww.  j  a  v a  2s  .co m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryRenameAllMethods.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            ((CDONet4jSession) session).options().setCommitTimeout(50 * 1000);
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            String name = UUID.randomUUID().toString();
            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                JavaQueries.renameAllMethods(resource, name);
                long end = System.currentTimeMillis();
                transaction.commit();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            //            {
            //               transaction.close();
            //               session.close();
            //               
            //               session = server.openSession();
            //               transaction = session.openTransaction();
            //               resource = transaction.getRootResource();
            //               
            //               EList<? extends EObject> methodList = JavaQueries.getAllInstances(resource, JavaPackage.eINSTANCE.getMethodDeclaration());
            //               int i = 0;
            //               for (EObject eObject: methodList) {
            //                  MethodDeclaration method = (MethodDeclaration) eObject;
            //                  if (name.equals(method.getName())) {
            //                     i++;
            //                  }
            //               }
            //               LOG.log(Level.INFO, MessageFormat.format("Renamed {0} methods", i));
            //            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.act.biointerpretation.desalting.ChemicalDesalter.java

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

    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(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

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

    ChemicalDesalter runner = new ChemicalDesalter();
    String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX);
    if (cl.hasOption(OPTION_INCHI_INPUT_LIST)) {
        File inputFile = new File(cl.getOptionValue(OPTION_INCHI_INPUT_LIST));
        if (!inputFile.exists()) {
            System.err.format("Cannot find input file at %s\n", inputFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts,
                    null, true);
            System.exit(1);
        }
        runner.exampleChemicalsList(outAnalysis, inputFile);
    }
}

From source file:com.mozilla.bagheera.consumer.KafkaSequenceFileConsumer.java

public static void main(String[] args) {
    OptionFactory optFactory = OptionFactory.getInstance();
    Options options = KafkaConsumer.getOptions();
    options.addOption(optFactory.create("o", "output", true, "HDFS base path for output."));
    options.addOption(optFactory.create("df", "dateformat", true, "Date format for the date subdirectories."));
    options.addOption(optFactory.create("fs", "filesize", true, "Max file size for output files."));
    options.addOption(/*from  w w w . j a  va 2 s  . c o  m*/
            optFactory.create("b", "usebytes", false, "Use BytesWritable for value rather than Text."));
    options.addOption(optFactory.create("ts", "addtimestamp", false, "Adds bagheera timestamp to the json"));

    CommandLineParser parser = new GnuParser();
    ShutdownHook sh = ShutdownHook.getInstance();
    try {
        // Parse command line options
        CommandLine cmd = parser.parse(options, args);

        final KafkaConsumer consumer = KafkaConsumer.fromOptions(cmd);
        sh.addFirst(consumer);

        // Create a sink for storing data
        SinkConfiguration sinkConfig = new SinkConfiguration();
        sinkConfig.setString("hdfssink.hdfs.basedir.path", cmd.getOptionValue("output", "/bagheera"));
        sinkConfig.setString("hdfssink.hdfs.date.format", cmd.getOptionValue("dateformat", "yyyy-MM-dd"));
        sinkConfig.setLong("hdfssink.hdfs.max.filesize",
                Long.parseLong(cmd.getOptionValue("filesize", "536870912")));
        sinkConfig.setBoolean("hdfssink.hdfs.usebytes", cmd.hasOption("usebytes"));
        sinkConfig.setBoolean("hdfssink.hdfs.addtimestamp", cmd.hasOption("addtimestamp"));
        KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(SequenceFileSink.class, sinkConfig);
        sh.addLast(sinkFactory);

        // Set the sink for consumer storage
        consumer.setSinkFactory(sinkFactory);

        // Initialize metrics collection, reporting, etc.
        final MetricsManager manager = MetricsManager.getDefaultMetricsManager();

        prepareHealthChecks();

        // Begin polling
        consumer.poll();
    } catch (ParseException e) {
        LOG.error("Error parsing command line options", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(KafkaSequenceFileConsumer.class.getName(), options);
    } catch (NumberFormatException e) {
        LOG.error("Failed to parse filesize option", e);
    }
}

From source file:com.notifier.desktop.Main.java

public static void main(String[] args) {
    Options options = createCommandLineOptions();
    try {/*from   www  . j a  v  a2  s .  c o  m*/
        CommandLineParser commandLineParser = new GnuParser();
        CommandLine line = commandLineParser.parse(options, args);

        if (line.getOptions().length > 1) {
            showMessage("Only one parameter may be specified");
        }
        if (line.getArgs().length > 0) {
            showMessage("Non-recognized parameters: " + Arrays.toString(line.getArgs()));
        }
        if (line.hasOption(HELP_SHORT)) {
            printHelp(options);
            return;
        }
        if (line.hasOption(IS_RUNNING_SHORT)) {
            ServiceClient client = new ServiceClientImpl();
            if (client.isRunning()) {
                showMessage(Application.NAME + " is running");
            } else {
                showMessage(Application.NAME + " is not running");
            }
            return;
        }
        if (line.hasOption(STOP_SHORT)) {
            ServiceClient client = new ServiceClientImpl();
            if (client.stop()) {
                showMessage("Sent stop signal to " + Application.NAME + " successfully");
            } else {
                showMessage(Application.NAME + " is not running or an error occurred, see log for details");
            }
            return;
        }

        boolean trayIcon = !line.hasOption(NO_TRAY_SHORT);
        boolean showPreferences = line.hasOption(SHOW_PREFERENCES_SHORT);

        if (!getExclusiveExecutionLock()) {
            showMessage("There can be only one instance of " + Application.NAME + " running at a time");
            return;
        }
        Injector injector = Guice.createInjector(Stage.PRODUCTION, new ApplicationModule());
        Application application = injector.getInstance(Application.class);
        application.start(trayIcon, showPreferences);
    } catch (Throwable t) {
        System.out.println(t.getMessage());
        logger.error("Error starting", t);
    }
}

From source file:edu.sdsc.scigraph.owlapi.loader.BatchOwlLoader.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*from   w w  w. j  ava2s.  co m*/
    try {
        cmd = parser.parse(getOptions(), args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(BatchOwlLoader.class.getSimpleName(), getOptions());
        System.exit(-1);
    }

    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    OwlLoadConfiguration config = mapper.readValue(new File(cmd.getOptionValue('c').trim()),
            OwlLoadConfiguration.class);
    load(config);
    // TODO: Is Guice causing this to hang? #44
    System.exit(0);
}

From source file:edu.umd.shrawanraina.SequentialPersonalizedPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(/*from  w  ww  .ja va  2 s . c  o  m*/
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));
    options.addOption(OptionBuilder.withArgName("node").hasArg()
            .withDescription("source node (i.e., destination of the random jump)").create(SOURCE));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    final String source = cmdline.getOptionValue(SOURCE);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    if (!graph.containsVertex(source)) {
        System.err.println("Error: source node not found in the graph!");
        System.exit(-1);
    }

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute personalized PageRank.
    PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph,
            new Transformer<String, Double>() {
                public Double transform(String vertex) {
                    return vertex.equals(source) ? 1.0 : 0;
                }
            }, alpha);

    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:benchmark.hbase.controller.TestLauncher.java

public static void main(final String[] args) throws Exception {
    // create the parser
    final CommandLineParser parser = new BasicParser();

    // parse the command line arguments
    final CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("u")) {
        displayHelp();/*from   w  ww. j ava 2s. c  o m*/
    }

    final String connectionUrl = cmd.getOptionValue("connection-url");
    final StoreType storeType = StoreType.fromName(cmd.getOptionValue("store-type"));

    final Optional<String> optionalNumReads = Optional.fromNullable(cmd.getOptionValue("num-reads"));
    final Optional<String> optionalNumWrites = Optional.fromNullable(cmd.getOptionValue("num-writes"));
    final int readConcurrancy = Integer.parseInt(cmd.getOptionValue("read-concurrancy"));
    final int writeConcurrancy = Integer.parseInt(cmd.getOptionValue("write-concurrancy"));

    int numReads = 0;
    int numWrites = 0;

    BenchmarkType benchmarkType = BenchmarkType.READ_ONLY;
    if (optionalNumReads.isPresent() && optionalNumWrites.isPresent()) {
        benchmarkType = BenchmarkType.READ_AND_WRITE;
        numReads = Integer.parseInt(optionalNumReads.get());
        numWrites = Integer.parseInt(optionalNumWrites.get());
    } else if (optionalNumReads.isPresent()) {
        benchmarkType = BenchmarkType.READ_ONLY;
        numReads = Integer.parseInt(optionalNumReads.get());
    } else if (optionalNumWrites.isPresent()) {
        benchmarkType = BenchmarkType.WRITE_ONLY;
        numWrites = Integer.parseInt(optionalNumWrites.get());
    }

    log.info("connectionUrl: {}", connectionUrl);
    log.info("storeType: {}", storeType);
    log.info("numReads: {}", numReads);
    log.info("numWrites: {}", numWrites);
    log.info("readConcurrancy: {}", readConcurrancy);
    log.info("writeConcurrancy: {}", writeConcurrancy);
    log.info("benchmarkType: {}", benchmarkType);

    TestLauncher.start(storeType, benchmarkType, numReads, numWrites, readConcurrancy, connectionUrl);

    System.exit(0);
}

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

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

    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(ROBinning.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

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

    String dbName = cl.getOptionValue(OPTION_DB);

    // We read and write to the same database
    NoSQLAPI api = new NoSQLAPI(dbName, dbName);
    ErosCorpus erosCorpus = new ErosCorpus();
    erosCorpus.loadValidationCorpus();

    ROBinning roBinning = new ROBinning(erosCorpus, api);
    roBinning.init();
    roBinning.processChemicals();
}