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:co.cask.cdap.data.tools.CoprocessorBuildTool.java

public static void main(final String[] args) throws ParseException {

    Options options = new Options().addOption(new Option("h", "help", false, "Print this usage message."))
            .addOption(new Option("f", "force", false, "Overwrites any coprocessors that already exist."));

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);
    String[] commandArgs = commandLine.getArgs();

    // if help is an option, or if there isn't a single 'ensure' command, print usage and exit.
    if (commandLine.hasOption("h") || commandArgs.length != 1 || !"check".equalsIgnoreCase(commandArgs[0])) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(CoprocessorBuildTool.class.getName() + " check",
                "Checks that HBase coprocessors required by CDAP are loaded onto HDFS. "
                        + "If not, the coprocessors are built and placed on HDFS.",
                options, "");
        System.exit(0);/* w  ww.  j  a  va 2  s .  c  om*/
    }

    boolean overwrite = commandLine.hasOption("f");

    CConfiguration cConf = CConfiguration.create();
    Configuration hConf = HBaseConfiguration.create();

    Injector injector = Guice.createInjector(new ConfigModule(cConf, hConf),
            // for LocationFactory
            new PrivateModule() {
                @Override
                protected void configure() {
                    bind(FileContext.class).toProvider(FileContextProvider.class).in(Scopes.SINGLETON);
                    expose(LocationFactory.class);
                }

                @Provides
                @Singleton
                private LocationFactory providesLocationFactory(Configuration hConf, CConfiguration cConf,
                        FileContext fc) {
                    final String namespace = cConf.get(Constants.CFG_HDFS_NAMESPACE);
                    return new FileContextLocationFactory(hConf, fc, namespace);
                }
            });

    try {
        SecurityUtil.loginForMasterService(cConf);
    } catch (Exception e) {
        LOG.error("Failed to login as CDAP user", e);
        System.exit(1);
    }

    LocationFactory locationFactory = injector.getInstance(LocationFactory.class);
    HBaseTableUtil tableUtil = new HBaseTableUtilFactory(cConf).get();
    CoprocessorManager coprocessorManager = new CoprocessorManager(cConf, locationFactory, tableUtil);

    try {
        Location location = coprocessorManager.ensureCoprocessorExists(overwrite);
        LOG.info("coprocessor exists at {}.", location);
    } catch (IOException e) {
        LOG.error("Unable to build and upload coprocessor jars.", e);
        System.exit(1);
    }
}

From source file:de.dknapps.pswgendesktop.main.PswGenDesktop.java

/**
 * Hier werden die Kommandozeilenparameter analysiert und die Anwendung gestartet.
 *///from w w  w.  j  a va 2  s.c o  m
public static void main(String[] args) throws IOException {
    Options options = new Options();
    Option help = new Option("help", "print this message");
    @SuppressWarnings("static-access")
    Option services = OptionBuilder.withArgName("file").hasArg()
            .withDescription("use given file to store services").create("services");
    @SuppressWarnings("static-access")
    Option upgrade = OptionBuilder.withArgName("passphrase").hasArg()
            .withDescription("converts and re-encrypts services to new format if not too old")
            .create("upgrade");
    options.addOption(help);
    options.addOption(services);
    options.addOption(upgrade);
    CommandLineParser parser = new GnuParser(); // GnuParser => mehrbuchstabige Optionen
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage()); // line bleibt null, dann kommt die Hilfe
    }
    if (line == null || line.hasOption("help")) { // Hilfe ausgeben => nur das tun
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("pswgen", options);
    } else if (line.hasOption("upgrade")) { // Datei umformatieren => nur das tun
        String servicesFilename = line.getOptionValue("services", CoreConstants.SERVICES_FILENAME);
        String passphrase = line.getOptionValue("upgrade");
        PswGenCtl ctl = new PswGenCtl(servicesFilename);
        ctl.upgradeServiceInfoList(passphrase);
    } else {
        String servicesFilename = line.getOptionValue("services", CoreConstants.SERVICES_FILENAME);
        PswGenCtl ctl = new PswGenCtl(servicesFilename);
        ctl.start(); // Anwendung starten, PswGenCtl terminiert die VM
    }
}

From source file:com.osrdata.etltoolbox.fileloader.Main.java

/**
 * Main entry point into the application.
 * @param args command line argunemtns/*from ww w  .jav a 2  s  . c om*/
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("s", "spec", true, "Source-to-target specification file"));
    options.addOption(new Option("d", "directory", true, "Source directory to load"));
    options.addOption(new Option("f", "file", true, "File to perform operation on"));
    options.addOption(new Option("r", "replace", false, "Replace previously loaded data"));
    options.addOption(new Option("t", "trace", true, "Trace records processed at specified interval"));

    CommandLineParser parser = new BasicParser();

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

        if (line.hasOption("spec") && (line.hasOption("directory") || line.hasOption("file"))) {
            FileLoader loader = new FileLoader(line);

            loader.init();

            if (line.hasOption("file")) {
                loader.load(new File(line.getOptionValue("file")));
            } else if (line.hasOption("directory")) {
                File directory = new File(line.getOptionValue("directory"));

                if (directory.isDirectory()) {
                    File[] files = directory.listFiles();

                    for (File file : files) {
                        loader.load(file);
                    }
                } else {
                    log.fatal(directory.getAbsolutePath() + " does not appear to be a directory.");
                }
            }
        } else {
            usage();
        }
    } catch (ParseException e) {
        usage();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.fischer.thotti.core.runner.TargetURLGenerator.java

public static final void main(String[] args) {
    String accessKey = null;/*  w w w.  j av a  2 s. co m*/
    String secretKey = null;

    Options options = createCommandLineOption();

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (!line.hasOption("ak")) {
            throw new ParseException("AWS Accress Key is missing.");
        }

        if (!line.hasOption("sk")) {
            throw new ParseException("AWS Secret Key is missing.");
        }

        accessKey = line.getOptionValue("ak");
        secretKey = line.getOptionValue("sk");

    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        System.exit(1);
    }

    TargetURLGenerator generator = new TargetURLGenerator();

    generator.setAccessKey(accessKey);
    generator.setSecretKey(secretKey);

    generator.run();
}

From source file:com.xafero.vee.cmd.MainApp.java

public static void main(String[] args) {
    // Define options
    Option help = new Option("?", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    Option eval = Option.builder("e").desc("evaluate script").argName("file").longOpt("eval").hasArg().build();
    Option list = new Option("l", "list", false, "print all available languages");
    // Collect them
    Options options = new Options();
    options.addOption(help);/*from  ww w.j ava 2s. c o  m*/
    options.addOption(version);
    options.addOption(eval);
    options.addOption(list);
    // If nothing given, nothing will happen
    if (args == null || args.length < 1) {
        printHelp(options);
        return;
    }
    // Parse command line
    try {
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);
        // Work on it
        process(line, options);
    } catch (Throwable e) {
        System.err.printf("Error occurred: %n " + e.getMessage());
    }
}

From source file:edu.cuhk.hccl.cmd.AppQueryExpander.java

public static void main(String[] args) {

    try {//from w ww. j  a v  a  2s . com

        CommandLineParser parser = new BasicParser();
        Options options = createOptions();
        CommandLine line = parser.parse(options, args);

        // Get parameters
        String queryStr = line.getOptionValue('q');
        int topK = Integer.parseInt(line.getOptionValue('k'));
        String modelPath = line.getOptionValue('m');
        String queryType = line.getOptionValue('t');

        QueryExpander expander = null;
        if (queryType.equalsIgnoreCase("WordVector")) {
            // Load word vectors
            System.out.println("[INFO] Loading word vectors...");
            expander = new WordVectorExpander(modelPath);
        } else if (queryType.equalsIgnoreCase("WordNet")) {
            // Load WordNet
            System.out.println("[INFO] Loading WordNet...");
            expander = new WordNetExpander(modelPath);
        } else {
            System.out.println("Please choose a correct expander: WordNet or WordVector!");
            System.exit(-1);
        }

        // Expand query
        System.out.println("[INFO] Computing similar words...");
        List<String> terms = expander.expandQuery(queryStr, topK);

        System.out.println(String.format("\n[INFO] The top %d similar words are: ", topK));
        for (String term : terms) {
            System.out.println(term);
        }

    } catch (ParseException exp) {
        System.out.println("Error in parameters: \n" + exp.getMessage());
        System.exit(-1);

    }
}

From source file:cc.wikitools.lucene.SearchWikipedia.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(/*from w w w.  ja v  a 2s.com*/
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));

    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));
    options.addOption(new Option(TITLE_OPTION, "search title"));
    options.addOption(new Option(ARTICLE_OPTION, "search article"));

    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(QUERY_OPTION) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(QUERY_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SearchWikipedia.class.getName(), options);
        System.exit(-1);
    }

    File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION));
    if (!indexLocation.exists()) {
        System.err.println("Error: " + indexLocation + " does not exist!");
        System.exit(-1);
    }

    String queryText = cmdline.getOptionValue(QUERY_OPTION);
    int numResults = cmdline.hasOption(NUM_RESULTS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION))
            : DEFAULT_NUM_RESULTS;
    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);
    boolean searchArticle = !cmdline.hasOption(TITLE_OPTION);

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

    WikipediaSearcher searcher = new WikipediaSearcher(indexLocation);
    TopDocs rs = null;
    if (searchArticle) {
        rs = searcher.searchArticle(queryText, numResults);
    } else {
        rs = searcher.searchTitle(queryText, numResults);
    }

    int i = 1;
    for (ScoreDoc scoreDoc : rs.scoreDocs) {
        Document hit = searcher.doc(scoreDoc.doc);

        out.println(String.format("%d. %s (wiki id = %s, lucene id = %d) %f", i,
                hit.getField(IndexField.TITLE.name).stringValue(),
                hit.getField(IndexField.ID.name).stringValue(), scoreDoc.doc, scoreDoc.score));
        if (verbose) {
            out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " "));
        }
        i++;
    }

    searcher.close();
    out.close();
}

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

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

    Options options = new Options();

    Option dirOption = OptionBuilder.withArgName("direction").hasArg().isRequired()
            .withDescription("Scale Direction.").create("dir");

    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 cntOption = OptionBuilder.withArgName("num").hasArg().withType(new String())
            .withDescription("Number of instances to scale up/down").create("cnt");

    options.addOption(dirOption);
    options.addOption(appOption);
    options.addOption(pelletNameOption);
    options.addOption(cntOption);

    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 dir = line.getOptionValue("dir");
    String app = line.getOptionValue("app");
    String pellet = line.getOptionValue("pellet");
    String cnt = line.getOptionValue("cnt");

    LOGGER.info("direction: {}", dir);
    LOGGER.info("Application: {}", app);
    LOGGER.info("Pellet: {}", pellet);
    LOGGER.info("count: {}", cnt);

    ScaleDirection direction = Enum.valueOf(ScaleDirection.class, dir);
    int count = Integer.parseInt(cnt);
    try {
        FloeClient.getInstance().getClient().scale(direction, app, pellet, count);
    } catch (TException e) {
        LOGGER.error("Error while connecting to the coordinator: {}", e);
    }
}

From source file:hisqisnoten.HisqisNoten.java

public static void main(String[] args) {
    options = new Options();
    options.addOption("h", "help", false, "this help");
    options.addOption("u", "user", true, "username for hisqis");
    options.addOption("p", "pass", true, "password for hisqis");
    options.addOption("c", "console", false, "console mode instead of gui mode");

    CommandLineParser parser = new PosixParser();

    try {//from   ww w.j  a v  a2 s  .c o  m
        CommandLine cmdline = parser.parse(options, args);

        if (cmdline.hasOption("help")) {
            printHelp();
            System.exit(0);
        }

        if (cmdline.getArgList().size() != 0) {
            System.err.println("Please use the new commandline options.");
            System.out.println();

            printHelp();
            System.exit(1);
        }

        HisqisSettings settings = null;
        HisqisSettings.genConfigPath();

        for (File configpath : HisqisSettings.configpath) {
            if (configpath.exists() && configpath.canRead()) {
                settings = HisqisSettingsReader.loadDocument(configpath);

                if (settings != null) {
                    break;
                }
            }
        }

        if (settings == null) {
            settings = new HisqisSettings();
        }

        String user = cmdline.getOptionValue("user", null);
        String pass = cmdline.getOptionValue("pass", null);

        if (user != null) {
            settings.username = user;
        }
        if (pass != null) {
            settings.password = pass;
        }

        if (cmdline.hasOption("console")) {
            new HisqisConsole(settings);
        } else {
            new HisqisGUI(settings);
        }
    } catch (ParseException e) {
        printHelp();
    }
}

From source file:com.act.biointerpretation.l2expansion.L2RenderingDriver.java

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

    // Build command line parser.
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from   w  w w . j  av a2  s . co m*/
    }

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

    // Print help.
    if (cl.hasOption(OPTION_HELP)) {
        HELP_FORMATTER.printHelp(L2RenderingDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    // Set up input corpus file.
    File corpusFile = new File(cl.getOptionValue(OPTION_CORPUS_PATH));
    if (!corpusFile.exists()) {
        LOGGER.error("Input corpus file does not exist");
        return;
    }
    //Set up output directory.
    File outputDirectory = new File(cl.getOptionValue(OPTION_OUTPUT_DIRECTORY));
    if (outputDirectory.exists() && !outputDirectory.isDirectory()) {
        LOGGER.error("Can't render corpus: supplied image directory is an existing non-directory file.");
        return;
    }
    outputDirectory.mkdir();

    LOGGER.info("Reading in corpus from file.");
    L2PredictionCorpus predictionCorpus = L2PredictionCorpus.readPredictionsFromJsonFile(corpusFile);
    LOGGER.info("Finished reading in corpus with %d predictions", predictionCorpus.getCorpus().size());

    // Set image format options
    String format = cl.getOptionValue(OPTION_IMAGE_FORMAT, DEFAULT_IMAGE_FORMAT);
    Integer width = Integer.parseInt(cl.getOptionValue(OPTION_IMAGE_WIDTH, DEFAULT_IMAGE_WIDTH));
    Integer height = Integer.parseInt(cl.getOptionValue(OPTION_IMAGE_HEIGHT, DEFAULT_IMAGE_HEIGHT));

    // Render the corpus.
    LOGGER.info("Drawing images for each prediction in corpus.");
    ReactionRenderer reactionRenderer = new ReactionRenderer(format, width, height);
    PredictionCorpusRenderer renderer = new PredictionCorpusRenderer(reactionRenderer);
    renderer.renderCorpus(predictionCorpus, outputDirectory);

    LOGGER.info("L2RenderingDriver complete!");
}