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:cc.wikitools.lucene.FindWikipediaArticleId.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(/*from   ww  w.j  a  v  a 2s .co m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("article title").create(TITLE_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(TITLE_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(FindWikipediaArticleId.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 title = cmdline.getOptionValue(TITLE_OPTION);

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

    WikipediaSearcher searcher = new WikipediaSearcher(indexLocation);
    int id = searcher.getArticleId(title);

    out.println(title + ": id = " + id);

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

From source file:com.dopsun.msg4j.tools.CodeGen.java

/**
 * @param args//from   w ww. j  a va 2s  . c om
 * @throws IOException
 * @throws MalformedURLException
 * @throws ParseException
 */
public static void main(String[] args) throws MalformedURLException, IOException, ParseException {
    Options options = new Options();
    options.addOption("o", "out", true, "Output file");
    options.addOption("s", "src", true, "Source file");
    options.addOption("l", "lang", true, "Language");

    CommandLineParser cmdParser = new DefaultParser();
    CommandLine cmd = cmdParser.parse(options, args);

    String lang = cmd.getOptionValue("lang", "Java");
    String srcFile = cmd.getOptionValue("src");
    String outFile = cmd.getOptionValue("out");

    YamlModelSource modelSource = YamlModelSource.load(new File(srcFile).toURI().toURL());
    YamlModelParser parser = YamlModelParser.create();
    ModelInfo modelInfo = parser.parse(modelSource);

    String codeText = null;
    if (lang.equals("Java")) {
        codeText = Generator.JAVA.generate(modelInfo);
    } else {
        throw new UnsupportedOperationException("Unrecognized lang: " + lang);
    }

    if (outFile != null) {
        File file = new File(outFile);
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();

        Files.append(codeText, new File(outFile), Charsets.UTF_8);
    } else {
        System.out.println(codeText);
    }
}

From source file:com.palmercox.rustcryptotester.App.java

public static void main(String[] args) throws Exception {
    final CommandLineParser clp = new GnuParser();
    final CommandLine cl = clp.parse(getOptions(), args);

    if (cl.hasOption("help")) {
        help();// ww w  .j  a  v a  2  s.  c o m
        return;
    }

    final String rustExec;
    if (cl.hasOption("rustexec")) {
        rustExec = cl.getOptionValue("rustexec");
    } else {
        help();
        return;
    }

    System.out.println("Starting Rust Crypto Tests:");

    boolean ok = true;

    final RustCryptRunner runner = new RustCryptRunner(new File(rustExec));
    try {
        for (final Tester t : getTesters()) {
            final Random rand = new Random(0);
            final boolean result = t.test(runner, rand);
            System.out.println("Test passed: " + result);
            ok = ok && result;
        }
    } finally {
        runner.close();
    }

    System.out.println("Done");

    if (!ok) {
        System.exit(1);
    }
}

From source file:com.linkedin.bowser.tool.REPLCommandLine.java

public static void main(String... args) throws Exception {
    Logger root = Logger.getRootLogger();

    Options options = new Options();
    options.addOption("v", "verbose", false, "verbose output");
    options.addOption("t", "threads", true, "parallel threads");
    CommandLineParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args);

    if (cmdline.hasOption("v"))
        root.setLevel(Level.DEBUG);
    else//from   ww  w  . j a  v  a2  s.  c om
        root.setLevel(Level.INFO);

    REPLCommandLine cmd = new REPLCommandLine(cmdline.hasOption("v"),
            cmdline.hasOption("t") ? Integer.parseInt(cmdline.getOptionValue("t")) : null);
    cmd.doRun();
}

From source file:com.nextdoor.bender.ValidateSchema.java

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

    /*// w  ww  . ja v a 2 s.co m
     * Parse cli arguments
     */
    Options options = new Options();
    options.addOption(Option.builder().longOpt("schema").hasArg()
            .desc("Filename to output schema to. Default: schema.json").build());
    options.addOption(Option.builder().longOpt("configs").hasArgs()
            .desc("List of config files to validate against schema.").build());
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    String schemaFilename = cmd.getOptionValue("schema", "schema.json");
    String[] configFilenames = cmd.getOptionValues("configs");

    /*
     * Validate config files against schema
     */
    boolean hasFailures = false;
    for (String configFilename : configFilenames) {
        StringBuilder sb = new StringBuilder();
        Files.lines(Paths.get(configFilename), StandardCharsets.UTF_8).forEach(p -> sb.append(p + "\n"));

        System.out.println("Attempting to validate " + configFilename);
        try {
            ObjectMapper mapper = BenderConfig.getObjectMapper(configFilename);
            mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
            BenderConfig.load(configFilename, sb.toString(), mapper, true);
            System.out.println("Valid");
            BenderConfig config = BenderConfig.load(configFilename, sb.toString());
        } catch (ConfigurationException e) {
            System.out.println("Invalid");
            e.printStackTrace();
            hasFailures = true;
        }
    }

    if (hasFailures) {
        System.exit(1);
    }
}

From source file:com.sr.eb.compiler.Main.java

public static void main(String[] args) throws Throwable {
    try {//from  w  w w  . j a  va2  s . c  o m
        Options options = new Options();

        options.addOption("v", "verbose", false, "Enables verbose compiler output.");
        options.addOption("ee", "easterEgg", false, "Enables compiler easter eggs, DO NOT USE!");

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

        if (cmd.getArgs().length > 0) {
            int start = -1;
            while (true) {
                start++;
                if (options.getOption(cmd.getArgs()[start]) == null)
                    break;
            }

            String[] sourceFiles = Arrays.copyOfRange(cmd.getArgs(), start, cmd.getArgs().length);

            // TODO
        } else {
            System.out.println("Expected source files, got none!");
            System.out.println("Usage: ebc [options] <source files>");
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    /* ----- Testing ----- */
    Lexer lexer = Lexer.newInstance();
    Parser parser = Parser.newInstance();

    try (InputStream in = new FileInputStream("test.eb")) {
        lexer.reset(Utils.readAll(in));
    }

    List<Token> tokens = lexer.tokenize();
    parser.reset(tokens);
    SyntaxTree t = parser.parse();

    ASTPrettyPrinter.print(t);
}

From source file:cc.twittertools.index.ExtractTweetidsFromIndex.java

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

    options.addOption(//from   w w  w.java 2  s .  c  o  m
            OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_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(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractTweetidsFromIndex.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);
    }

    IndexReader reader = DirectoryReader.open(FSDirectory.open(indexLocation));
    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    for (int i = 0; i < reader.maxDoc(); i++) {
        Document doc = reader.document(i);
        out.println(doc.getField(StatusField.ID.name).stringValue() + "\t"
                + doc.getField(StatusField.SCREEN_NAME.name).stringValue());
    }
    out.close();
    reader.close();
}

From source file:com.ovea.tajin.server.ContainerRunner.java

public static void main(String... args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine line = parser.parse(options, args);

    if (line.hasOption("help") || !line.hasOption(Properties.CONTAINER.getName())) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ContainerRunner.class.getSimpleName(), options);
        return;/*from  w w  w  . ja v a 2  s. co m*/
    }

    // Set default values
    // And override by system properties. This way, we can start ContainerRunner with specific options such as -DjettyConf=.. -DjettyEnv=...
    ContainerConfiguration settings = ContainerConfiguration.from(System.getProperties());
    // Then parse command line
    for (Option option : line.getOptions()) {
        settings.set(Properties.from(option.getOpt()), line.getOptionValue(option.getOpt()));
    }
    Container container = settings.buildContainer(line.getOptionValue(Properties.CONTAINER.getName()));
    container.start();
}

From source file:com.linkedin.python.importer.ImporterCLI.java

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

    Options options = createOptions();/*from  w w w. j ava 2  s .c  o m*/

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

    if (line.hasOption("quite")) {
        Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        root.setLevel(Level.WARN);
    }

    final File repoPath = new File(line.getOptionValue("repo"));
    final DependencySubstitution replacements = new DependencySubstitution(buildSubstitutionMap(line));

    repoPath.mkdirs();

    if (!repoPath.exists() || !repoPath.isDirectory()) {
        throw new RuntimeException(
                "Unable to continue, " + repoPath.getAbsolutePath() + " does not exist, or is not a directory");
    }

    for (String dependency : line.getArgList()) {
        new DependencyDownloader(dependency, repoPath, replacements).download();
    }

    logger.info("Execution Finished!");
}

From source file:StompMessageConsumer.java

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

    Options options = new Options();
    options.addOption("h", true, "Host to connect to");
    options.addOption("p", true, "Port to connect to");
    options.addOption("u", true, "User name");
    options.addOption("P", true, "Password");

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

    String host = "192.168.1.7";
    String port = "61613";
    String user = "guest";
    String pass = "P@ssword1";

    if (cmd.hasOption("h")) {
        host = cmd.getOptionValue("h");
    }/*w  ww .j  a  v a 2  s  .co m*/
    if (cmd.hasOption("p")) {
        port = cmd.getOptionValue("p");
    }
    if (cmd.hasOption("u")) {
        user = cmd.getOptionValue("u");
    }
    if (cmd.hasOption("P")) {
        pass = cmd.getOptionValue("P");
    }

    try {
        StompConnection connection = new StompConnection();

        connection.open(host, Integer.parseInt(port));
        connection.connect(user, pass);
        //      connection.open("orange.cloudtroopers.ro", 61613);
        //      connection.connect("system", "manager");

        connection.subscribe("jms.queue.memberRegistration", Subscribe.AckModeValues.CLIENT);
        connection.subscribe(StompMessagePublisher.MEMBER_REGISTRATION_JMS_DESTINATION,
                Subscribe.AckModeValues.CLIENT);

        connection.begin("tx2");
        StompFrame message = connection.receive();
        System.out.println(message.getBody());
        connection.ack(message, "tx2");
        connection.commit("tx2");

        connection.disconnect();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}