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.servioticy.dispatcher.DispatcherTopology.java

/**
 * @param args/*from ww w  . j a  v a 2  s.c  om*/
 * @throws InvalidTopologyException
 * @throws AlreadyAliveException
 * @throws InterruptedException
 */
public static void main(String[] args)
        throws AlreadyAliveException, InvalidTopologyException, InterruptedException, ParseException {

    Options options = new Options();

    options.addOption(
            OptionBuilder.withArgName("file").hasArg().withDescription("Config file path.").create("f"));
    options.addOption(OptionBuilder.withArgName("topology").hasArg()
            .withDescription("Name of the topology in storm. If no name is given it will run in local mode.")
            .create("t"));
    options.addOption(OptionBuilder.withDescription("Enable debugging").create("d"));

    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);

    String path = null;
    if (cmd.hasOption("f")) {
        path = cmd.getOptionValue("f");
    }

    DispatcherContext dc = new DispatcherContext();
    dc.loadConf(path);

    TopologyBuilder builder = new TopologyBuilder();

    // TODO Auto-assign workers to the spout in function of the number of Kestrel IPs
    builder.setSpout("updates", new KestrelThriftSpout(Arrays.asList(dc.updatesAddresses), dc.updatesPort,
            dc.updatesQueue, new UpdateDescriptorScheme()));
    builder.setSpout("actions", new KestrelThriftSpout(Arrays.asList(dc.actionsAddresses), dc.actionsPort,
            dc.actionsQueue, new ActuationScheme()));

    builder.setBolt("prepare", new PrepareBolt(dc)).shuffleGrouping("updates");

    builder.setBolt("actuationdispatcher", new ActuationDispatcherBolt(dc)).shuffleGrouping("actions");

    builder.setBolt("subretriever", new SubscriptionRetrieveBolt(dc)).shuffleGrouping("prepare",
            "subscription");

    builder.setBolt("externaldispatcher", new ExternalDispatcherBolt(dc)).fieldsGrouping("subretriever",
            "externalSub", new Fields("subid"));
    builder.setBolt("internaldispatcher", new InternalDispatcherBolt(dc)).fieldsGrouping("subretriever",
            "internalSub", new Fields("subid"));

    builder.setBolt("streamdispatcher", new StreamDispatcherBolt(dc))
            .shuffleGrouping("subretriever", "streamSub").shuffleGrouping("prepare", "stream");
    builder.setBolt("streamprocessor", new StreamProcessorBolt(dc)).shuffleGrouping("streamdispatcher",
            "default");

    if (dc.benchmark) {
        builder.setBolt("benchmark", new BenchmarkBolt(dc)).shuffleGrouping("streamdispatcher", "benchmark")
                .shuffleGrouping("subretriever", "benchmark").shuffleGrouping("streamprocessor", "benchmark")
                .shuffleGrouping("prepare", "benchmark");
    }

    Config conf = new Config();
    conf.setDebug(cmd.hasOption("d"));
    if (cmd.hasOption("t")) {
        StormSubmitter.submitTopology(cmd.getOptionValue("t"), conf, builder.createTopology());
    } else {
        conf.setMaxTaskParallelism(4);
        LocalCluster cluster = new LocalCluster();
        cluster.submitTopology("dispatcher", conf, builder.createTopology());

    }

}

From source file:com.svds.tailer2kafka.main.Main.java

/**
 * Given command-line arguments, create GenericConsumerGroup
 * /*from w  ww .  j  a v  a 2  s  .  c  o m*/
 * @param args  command-line arguments to parse
 * @throws IOException 
 */
public static void main(String[] args) throws IOException, InterruptedException {

    Options options = new Options();

    options.addOption(OptionBuilder.isRequired().withLongOpt(TOPICNAME).withDescription("Kafka topic name")
            .hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(METADATABROKERLIST)
            .withDescription("Kafka metadata.broker.list").hasArg().create());

    options.addOption(
            OptionBuilder.isRequired().withLongOpt(FILENAME).withDescription("Log filename").hasArg().create());

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);

    } catch (ParseException e) {
        LOG.error(e.getMessage(), e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("com.svds.tailer2kafka.main.Main", options);

        throw new IOException("Missing Args");
    }

    Main main = new Main();
    main.doWork(cmd);
}

From source file:cc.twittertools.corpus.demo.ReadStatuses.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input directory or file")
            .create(INPUT_OPTION));/*  w w  w .  j ava  2 s . c om*/
    options.addOption(VERBOSE_OPTION, false, "print logging output every 10000 tweets");
    options.addOption(DUMP_OPTION, false, "dump statuses");

    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_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ReadStatuses.class.getName(), options);
        System.exit(-1);
    }

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    StatusStream stream;
    // Figure out if we're reading from HTML SequenceFiles or JSON.
    File file = new File(cmdline.getOptionValue(INPUT_OPTION));
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    if (file.isDirectory()) {
        stream = new JsonStatusCorpusReader(file);
    } else {
        stream = new JsonStatusBlockReader(file);
    }

    int cnt = 0;
    Status status;
    while ((status = stream.next()) != null) {
        if (cmdline.hasOption(DUMP_OPTION)) {
            String text = status.getText();
            if (text != null) {
                text = text.replaceAll("\\s+", " ");
                text = text.replaceAll("\0", "");
            }
            out.println(String.format("%d\t%s\t%s\t%s", status.getId(), status.getScreenname(),
                    status.getCreatedAt(), text));
        }
        cnt++;
        if (cnt % 10000 == 0 && cmdline.hasOption(VERBOSE_OPTION)) {
            LOG.info(cnt + " statuses read");
        }
    }
    stream.close();
    LOG.info(String.format("Total of %s statuses read.", cnt));
}

From source file:de.akquinet.android.rindirect.Main.java

/**
 * Main method.//from w  ww . j a va2  s .  c  om
 * This methods defines the arguments, parse them and launch the R indirection
 * generation.
 * @param args the arguments.
 * @throws ParseException
 * @throws IOException
 */
public static void main(String[] args) throws ParseException, Exception {
    LOGGER.setLevel(Level.WARNING);

    Options options = new Options();

    options.addOption("P", "package", true, "destination package (mandatory)")
            .addOption("R", "classname", true, "generated java file [R]")
            .addOption("D", "destination", true, "the root of the destination [src]")
            .addOption("I", "input", true, "R file [searched in the 'gen' folder]")
            .addOption("V", "verbose", false, "Enable verbose mode");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    RIndirect rindirect = configure(cmd);
    rindirect.generate();
}

From source file:de.citec.csra.highlight.HighlightService.java

public static void main(String[] args)
        throws InitializeException, RSBException, InterruptedException, ParseException {

    Options opts = new Options();
    opts.addOption("scope", true, "RSB scope for highlight targets.\nDefault: '" + scope + "'");
    opts.addOption("server", true, "RSB server for configuration, e.g., tokens.\nDefault: '" + cfg + "'");
    opts.addOption("help", false, "Print this help and exit");

    String footer = null;//from w w  w .  j  a v  a2s  .  com
    //      String footer = "\nThe following sub-scopes are registered automatically:\n"
    //            + "\n.../preset for color presets:\n" + Arrays.toString(ColorConfig.values())
    //            + "\n.../color for color values:\n" + "HSV (comma separated)"
    //            + "\n.../power for power states:\n" + Arrays.toString(PowerState.State.values())
    //            + "\n.../history for history commands:\n" + Arrays.toString(ColorHistory.values());

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(opts, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("csra-highlight-service [OPTION...]", "where OPTION includes:", opts, footer);
        System.exit(0);
    }

    if (System.getenv().containsKey(SCOPEVAR)) {
        scope = System.getenv(SCOPEVAR);
    }

    String s = cmd.getOptionValue("scope");
    if (s != null) {
        scope = s;
    }
    scope = scope.replaceAll("/$", "");

    String c = cmd.getOptionValue("cfg");
    if (c != null) {
        cfg = c;
    }
    cfg = cfg.replaceAll("/$", "");

    Defaults.loadDefaults();
    ExecutorService exec = Executors.newFixedThreadPool(2);

    exec.submit(() -> {
        try {
            ConfigServer cfgServer = new ConfigServer(cfg);
            cfgServer.execute();
        } catch (RSBException ex) {
            LOG.log(Level.SEVERE, "Config server failed", ex);
        }
    });

    exec.submit(() -> {
        try {
            TaskServer server = new TaskServer(scope, new HighlightTaskHandler());
            server.execute();
        } catch (RSBException | InterruptedException ex) {
            LOG.log(Level.SEVERE, "Task server failed", ex);
        }
    });

}

From source file:de.ncoder.studipsync.Starter.java

public static void main(String[] args) throws Exception {
    boolean displayHelp = false;
    CommandLineParser parser = new DefaultParser();
    try {/* w w w  .  jav a  2s .co  m*/
        CommandLine cmd = parser.parse(OPTIONS, args);
        if (cmd.hasOption(OPTION_HELP)) {
            displayHelp = true;
            return;
        }

        Syncer syncer = createSyncer(cmd);
        StorageLog storeLog = new StorageLog();
        syncer.getStorage().registerListener(storeLog);
        try {
            log.info("Started " + getImplementationTitle() + " " + getImplementationVersion());
            syncer.sync();
            log.info(storeLog.getStatusMessage(syncer.getStorage().getRoot()));
            log.info("Finished");
        } finally {
            syncer.close();
        }
    } catch (ParseException e) {
        System.out.println("Illegal arguments passed. " + e.getMessage());
        displayHelp = true;
    } finally {
        if (displayHelp) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("studip-sync", OPTIONS);
        }
    }
    //TODO AWT Event Queue blocks termination with modality level 1
    System.exit(0);
}

From source file:edu.usc.pgroup.floe.client.commands.SwitchAlternate.java

/**
 * Entry point for Scale command./*from w w w.  j  av a 2  s  .c om*/
 * @param args command line arguments sent by the floe.py script.
 */
public static void main(final String[] args) {

    Options options = new Options();

    Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Application Name").create("app");

    Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Pellet Name").create("pellet");

    Option alternateOption = OptionBuilder.withArgName("alternate").hasArg().withType(new String())
            .withDescription("The new alternate to switch to.").create("alternate");

    options.addOption(appOption);
    options.addOption(pelletNameOption);
    options.addOption(alternateOption);

    CommandLineParser parser = new BasicParser();
    CommandLine line;

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

    } catch (ParseException e) {
        LOGGER.error("Invalid command: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("scale options", options);
        return;
    }

    String app = line.getOptionValue("app");
    String pellet = line.getOptionValue("pellet");
    String alternate = line.getOptionValue("alternate");

    LOGGER.info("Application: {}", app);
    LOGGER.info("Pellet: {}", pellet);
    LOGGER.info("alternate: {}", alternate);

    try {

        FloeClient.getInstance().getClient().switchAlternate(app, pellet, alternate);
    } catch (TException e) {
        LOGGER.error("Error while connecting to the coordinator: {}", e);
    }
}

From source file:net.mitnet.tools.pdf.book.openoffice.ui.cli.OpenOfficeReportBuilderCLI.java

public static void main(String[] arguments) throws Exception {

    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);
    CommandLineHelper commandLineHelper = new CommandLineHelper(commandLine);

    if (!commandLineHelper.hasOption(CliOptions.OPTION_INPUT_TEMPLATE_FILE)) {
        System.err.println("Must specify " + CliOptions.OPTION_INPUT_TEMPLATE_FILE.getDescription());
        showHelp();/*from  w  ww . ja  v a 2 s . com*/
    }
    File sourceTemplateFile = commandLineHelper.getOptionValueAsFile(CliOptions.OPTION_INPUT_TEMPLATE_FILE);

    if (!commandLineHelper.hasOption(CliOptions.OPTION_INPUT_DATA_FILE)) {
        System.err.println("Must specify " + CliOptions.OPTION_INPUT_DATA_FILE.getDescription());
        showHelp();
    }
    File sourceDataFile = commandLineHelper.getOptionValueAsFile(CliOptions.OPTION_INPUT_DATA_FILE);

    if (!commandLineHelper.hasOption(CliOptions.OPTION_OUTPUT_REPORT_FILE)) {
        System.err.println("Must specify " + CliOptions.OPTION_OUTPUT_REPORT_FILE.getDescription());
        showHelp();
    }
    File outputReportFile = commandLineHelper.getOptionValueAsFile(CliOptions.OPTION_OUTPUT_REPORT_FILE);

    boolean verbose = false;
    if (commandLineHelper.hasOption(CliOptions.OPTION_VERBOSE)) {
        verbose = true;
    }

    try {
        System.out.println("Source template file is " + sourceTemplateFile);
        System.out.println("Source data file is " + sourceDataFile);
        System.out.println("Output report file is " + outputReportFile);
        System.out.println("Building report ...");
        // ProgressMonitor progressMonitor = new ConsoleProgressMonitor();
        OpenOfficeReportBuilder reportBuilder = new OpenOfficeReportBuilder();
        reportBuilder.buildReport(sourceTemplateFile, sourceDataFile, outputReportFile);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.err.println("Error building report: " + e.getMessage());
        System.exit(SystemExitValues.EXIT_CODE_ERROR);
    }
    System.out.println("Finished converting files.");
}

From source file:de.l3s.content.mapred.WikipediaPagesBz2InputStream.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("gzipped XML dump file")
            .create(INPUT_OPTION));//from www. j av  a 2  s.com
    options.addOption(OptionBuilder.withArgName("lang").hasArg().withDescription("output location")
            .create(LANGUAGE_OPTION));

    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_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(WikipediaPagesBz2InputStream.class.getCanonicalName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String path = cmdline.getOptionValue(INPUT_OPTION);
    String lang = cmdline.hasOption(LANGUAGE_OPTION) ? cmdline.getOptionValue(LANGUAGE_OPTION) : "en";
    WikipediaPage p = WikipediaPageFactory.createWikipediaPage(lang);

    WikipediaPagesBz2InputStream stream = new WikipediaPagesBz2InputStream(path);
    while (stream.readNext(p)) {
        System.out.println(p.getTitle() + "\t" + p.getDocid());
    }
}

From source file:edu.ifpb.pos.restletclient.CommandLineApp.java

public static void main(String[] args) {
    try {// www . j a  v a2s.c  o  m
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(getOp(), args);
        execute(line);
    } catch (ParseException ex) {
        System.out.println("ERROR: " + ex.getMessage());
    } catch (IOException ex) {
        Logger.getLogger(CommandLineApp.class.getName()).log(Level.SEVERE, null, ex);
    }

}