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.benasmussen.tools.testeditor.ExtractorCLI.java

public static void main(String[] args) throws Exception {
    HelpFormatter formatter = new HelpFormatter();

    // cli options
    Options options = new Options();
    options.addOption(CMD_OPT_INPUT, true, "Input file");
    // options.addOption(CMD_OPT_OUTPUT, true, "Output file");

    try {/*from www.  ja va  2  s. co  m*/

        // evaluate command line options
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(CMD_OPT_INPUT)) {
            // option value
            String optionValue = cmd.getOptionValue(CMD_OPT_INPUT);

            // input file
            File inputFile = new File(optionValue);

            // id extractor
            IdExtractor idExtractor = new IdExtractor(inputFile);
            Vector<Vector> data = idExtractor.parse();

            // // TODO implement output folder
            // if (cmd.hasOption(CMD_OPT_OUTPUT))
            // {
            // // file output
            // throw new Exception("Not implemented");
            // }
            // else
            // {
            // console output
            System.out.println("Id;Value");
            for (Vector vector : data) {
                StringBuilder sb = new StringBuilder();
                if (vector.size() >= 1) {
                    sb.append(vector.get(0));
                }
                sb.append(";");
                if (vector.size() >= 2) {
                    sb.append(vector.get(1));
                }
                System.out.println(sb.toString());
            }
            // }
        } else {
            throw new IllegalArgumentException();
        }

    } catch (ParseException e) {
        formatter.printHelp("ExtractorCLI", options);
    } catch (IllegalArgumentException e) {
        formatter.printHelp("ExtractorCLI", options);
    }
}

From source file:fr.tpt.atlanalyser.tests.TestOldAGTExpPost2Pre.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {

    // URL resource = Thread.currentThread().getContextClassLoader()
    // .getResource("OldAGTExp");
    // System.out.println(resource.toString());
    // File f = new File(resource.getPath());
    // System.out.println(f.toString());
    // System.out.println(f.isDirectory());
    // System.exit(0);

    Options options = new Options();
    options.addOption(/*from w  w w.ja  va  2  s.c o m*/
            OptionBuilder.hasArg().withArgName("N").withDescription("Number of parallel jobs").create("j"));
    options.addOption(OptionBuilder.withDescription("Display help").create("h"));

    CommandLineParser parser = new BasicParser();
    int jobs = 1;
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            new HelpFormatter().printHelp(TestOldAGTExpPost2Pre.class.getSimpleName(), options);
            System.exit(0);
        }

        if (cmd.hasOption("j")) {
            jobs = Integer.parseInt(cmd.getOptionValue("j"));
        }
    } catch (Exception e) {
        System.out.println("Incorrect command line arguments");
        new HelpFormatter().printHelp(TestOldAGTExpPost2Pre.class.getSimpleName(), options);
        System.exit(1);
    }

    new TestOldAGTExpPost2Pre(models().iterator().next()[0], jobs).testPost2Pre();
}

From source file:com.dobrunov.zktreeutil.zkTreeUtilMain.java

public static void main(String[] args) {
    Options options = initOptions();//from w ww  . j a  v  a  2 s  .  co m
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        usage(options);
    }
    Job job = buildJob(options, cmd);
    if (job != null) {
        job.go();
    }
}

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

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

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

    if (cmdline.hasOption(ID_OPTION)) {
        int id = Integer.parseInt(cmdline.getOptionValue(ID_OPTION));
        Document doc = searcher.getArticle(id);

        if (doc == null) {
            System.err.print("id " + id + " doesn't exist!\n");
        } else {
            out.println(doc.getField(IndexField.TEXT.name).stringValue());
        }
    } else {
        String title = cmdline.getOptionValue(TITLE_OPTION);
        Document doc = searcher.getArticle(title);

        if (doc == null) {
            System.err.print("article \"" + title + "\" doesn't exist!\n");
        } else {
            out.println(doc.getField(IndexField.TEXT.name).stringValue());
        }
    }

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

From source file:com.asual.lesscss.LessEngineCli.java

public static void main(String[] args) throws LessException, URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(LessOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(LessOptions.COMPRESS_OPTION, false, "Flag that enables compressed CSS output.");
    cmdOptions.addOption(LessOptions.CSS_OPTION, false, "Flag that enables compilation of .css files.");
    cmdOptions.addOption(LessOptions.LESS_OPTION, true, "Path to a custom less.js for Rhino version.");
    try {/*from w w  w  .  j a v  a  2  s  .c o m*/
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        LessOptions options = new LessOptions();
        if (cmdLine.hasOption(LessOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(LessOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(LessOptions.COMPRESS_OPTION)) {
            options.setCompress(true);
        }
        if (cmdLine.hasOption(LessOptions.CSS_OPTION)) {
            options.setCss(true);
        }
        if (cmdLine.hasOption(LessOptions.LESS_OPTION)) {
            options.setLess(new File(cmdLine.getOptionValue(LessOptions.LESS_OPTION)).toURI().toURL());
        }
        LessEngine engine = new LessEngine(options);
        if (System.in.available() != 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            String src = sw.toString();
            if (!src.isEmpty()) {
                System.out.println(engine.compile(src, null, options.isCompress()));
                System.exit(0);
            }
        }
        String[] files = cmdLine.getArgs();
        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0]), options.isCompress()));
            System.exit(0);
        }
        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]), options.isCompress());
            System.exit(0);
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }
    String[] paths = LessEngine.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
            .split(File.separator);
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar " + paths[paths.length - 1] + " input [output] [options]", cmdOptions);
    System.exit(1);
}

From source file:com.uber.stream.kafka.mirrormaker.manager.ManagerStarter.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(ManagerConf.constructManagerOptions(), args);
    if (cmd.getOptions().length == 0 || cmd.hasOption("help")) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("OptionsTip", ManagerConf.constructManagerOptions());
        System.exit(0);/*from w  ww .j  a v a  2 s  . co  m*/
    }
    final ManagerStarter managerStarter = ManagerStarter.init(cmd);

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

    try {
        managerStarter.start();
    } catch (Exception e) {
        LOGGER.error("Cannot start uReplicator-Manager: ", e);
    }
}

From source file:com.commonsware.android.gcm.cmd.GCM.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Option helpOpt = new Option("h", "help", false, "print this message");
    Option apiKeyOpt = OptionBuilder.withArgName("key").hasArg().isRequired().withDescription("GCM API key")
            .withLongOpt("apiKey").create('a');
    Option deviceOpt = OptionBuilder.withArgName("regId").hasArg().isRequired()
            .withDescription("device to send to").withLongOpt("device").create('d');
    Option dataOpt = OptionBuilder.withArgName("key=value").hasArgs(2).withDescription("datum to send")
            .withValueSeparator().withLongOpt("data").create('D');

    Options options = new Options();

    options.addOption(apiKeyOpt);/* www .j a  va  2s.  c o  m*/
    options.addOption(deviceOpt);
    options.addOption(dataOpt);
    options.addOption(helpOpt);

    CommandLineParser parser = new PosixParser();

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

        if (line.hasOption('h') || !line.hasOption('a') || !line.hasOption('d')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("gcm", options, true);
        } else {
            sendMessage(line.getOptionValue('a'), Arrays.asList(line.getOptionValues('d')),
                    line.getOptionProperties("data"));
        }
    } catch (org.apache.commons.cli.MissingOptionException moe) {
        System.err.println("Invalid command syntax");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("gcm", options, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.github.jasmo.Bootstrap.java

public static void main(String[] args) {
    Options options = new Options().addOption("h", "help", false, "Print help message")
            .addOption("v", "verbose", false, "Increase verbosity")
            .addOption("c", "cfn", true,
                    "Enable 'crazy fucking names and set name length (large names == large output size)'")
            .addOption("p", "package", true, "Move obfuscated classes to this package")
            .addOption("k", "keep", true, "Don't rename this class");
    try {//from w  w w . j  a  va  2s. c  o m
        CommandLineParser clp = new DefaultParser();
        CommandLine cl = clp.parse(options, args);
        if (cl.hasOption("help")) {
            help(options);
            return;
        }
        if (cl.hasOption("verbose")) {
            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
            Configuration config = ctx.getConfiguration();
            LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
            loggerConfig.setLevel(Level.DEBUG);
            ctx.updateLoggers();
        }
        String[] keep = cl.getOptionValues("keep");
        if (cl.getArgList().size() < 2) {
            throw new ParseException("Expected at-least two arguments");
        }
        log.debug("Input: {}, Output: {}", cl.getArgList().get(0), cl.getArgList().get(1));
        Obfuscator o = new Obfuscator();
        try {
            o.supply(Paths.get(cl.getArgList().get(0)));
        } catch (Exception e) {
            log.error("An error occurred while reading the source target", e);
            return;
        }
        try {
            UniqueStringGenerator usg;
            if (cl.hasOption("cfn")) {
                int size = Integer.parseInt(cl.getOptionValue("cfn"));
                usg = new UniqueStringGenerator.Crazy(size);
            } else {
                usg = new UniqueStringGenerator.Default();
            }
            o.apply(new FullAccessFlags());
            o.apply(new ScrambleStrings());
            o.apply(new ScrambleClasses(usg, cl.getOptionValue("package", ""),
                    keep == null ? new String[0] : keep));
            o.apply(new ScrambleFields(usg));
            o.apply(new ScrambleMethods(usg));
            o.apply(new InlineAccessors());
            o.apply(new RemoveDebugInfo());
            o.apply(new ShuffleMembers());
        } catch (Exception e) {
            log.error("An error occurred while applying transform", e);
            return;
        }
        try {
            o.write(Paths.get(cl.getArgList().get(1)));
        } catch (Exception e) {
            log.error("An error occurred while writing to the destination target", e);
            return;
        }
    } catch (ParseException e) {
        log.error("Failed to parse command line arguments", e);
        help(options);
    }
}

From source file:demo.learn.shiro.tool.PasswordMatcherTool.java

/**
 * Main method.//from  ww  w.j  ava2 s.  c  o  m
 * @param args Pass in plain text password, hashed password,
 * and salt. These arguments are generated from
 * {@link PasswordEncryptionTool}.
 * @throws ParseException
 */
@SuppressWarnings("static-access")
public static void main(String[] args) throws ParseException {
    String username = "";
    String plainTextPassword = "root";
    String hashedPasswordBase64 = "ZzIkhapTVzGkhWRQqdUn2zod5npt9RJMSni8My6X+r8=";
    String saltBase64 = "BobnkcsIXcZGksA30eOySA==";
    String realmName = "";

    Option p = OptionBuilder.withArgName("password").hasArg().withDescription("plain text password")
            .isRequired(false).create('p');
    Option h = OptionBuilder.withArgName("password").hasArg().withDescription("hashed password")
            .isRequired(false).create('h');
    Option s = OptionBuilder.withArgName("salt").hasArg().withDescription("salt (Base64 encoded)")
            .isRequired(false).create('s');

    Options options = new Options();
    options.addOption(p);
    options.addOption(h);
    options.addOption(s);

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

        if (cmd.hasOption("p")) {
            plainTextPassword = cmd.getOptionValue("p");
        }
        if (cmd.hasOption("h")) {
            hashedPasswordBase64 = cmd.getOptionValue("h");
        }
        if (cmd.hasOption("s")) {
            saltBase64 = cmd.getOptionValue("s");
        }
    } catch (ParseException pe) {
        String cmdLineSyntax = "java -cp %CLASSPATH% demo.learn.shiro.tool.PasswordMatcherTool";
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options, false);
        return;
    }

    SimpleByteSource salt = new SimpleByteSource(Base64.decode(saltBase64));
    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, hashedPasswordBase64, salt,
            realmName);
    UsernamePasswordToken token = new UsernamePasswordToken(username, plainTextPassword);

    HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
    matcher.setHashIterations(S.HASH_ITER);
    matcher.setStoredCredentialsHexEncoded(false);
    matcher.setHashAlgorithmName(S.ALGORITHM_NAME);

    boolean result = matcher.doCredentialsMatch(token, info);
    System.out.println("match? " + result);

}

From source file:net.hedges.fandangled.commandline.GenericCli.java

public static void main(String[] args) {
    options = buildOptions();//from  ww  w . j a  v  a 2  s . c  o  m

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(options, args);
        verbose = line.hasOption('v');
        if (line.hasOption('h')) {
            usage();
            System.exit(0);
        }
        String template = line.getOptionValue("templates");
        String input = line.getOptionValue("input");
        String output = line.getOptionValue("output");

        String prefix = line.getOptionValue("prefix", "");
        String extension = line.getOptionValue("extension", ".txt");

        File inputFile = new File(input);
        File outputDir = new File(output);
        File templateDir = new File(template);

        checkFilesAndDirectories(inputFile, outputDir, templateDir);

        GenericCodec codec = new GenericCodec();
        codec.setTemplatePath(templateDir.getAbsolutePath());
        codec.setExtension(extension);
        codec.setPrefix(prefix);

        Interface _interface = InterfaceBuilder.parse(inputFile);

        codec.encode(_interface, outputDir);

    } catch (ParseException e) {
        System.err.print(e.getMessage() + "\n");
        usage();
    } catch (Exception e) {
        e.printStackTrace();
    }
}