Example usage for org.apache.commons.cli CommandLine getOptions

List of usage examples for org.apache.commons.cli CommandLine getOptions

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getOptions.

Prototype

public Option[] getOptions() 

Source Link

Document

Returns an array of the processed Option s.

Usage

From source file:com.aleggeup.util.App.java

public static void main(final String[] args) {
    final CommandLineParser parser = new PosixParser();
    final Options options = buildOptions();

    File sourceFile = null;/*from  w w w .ja v a2s  .c  o  m*/
    File targetFile = null;

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

        if (commandLine.getOptions().length == 0 || commandLine.hasOption('h')) {
            printHelp(options);
            System.exit(0);
        }

        if (commandLine.hasOption('s')) {
            sourceFile = new File(commandLine.getOptionValue('s')).getCanonicalFile();
        }

        if (commandLine.hasOption('t')) {
            targetFile = new File(commandLine.getOptionValue('t')).getCanonicalFile();
        }

    } catch (final ParseException e) {
        printHelp(options);
        System.exit(-1);
    } catch (final IOException e) {
        e.printStackTrace();
    }

}

From source file:it.polimi.tower4clouds.rules.batch.BatchTool.java

public static void main(String[] args) {
    Options options = buildOptions();/*  w ww.  jav a 2 s  . com*/
    CommandLineParser parser = new BasicParser();
    HelpFormatter formatter = new HelpFormatter();
    FileInputStream inputFile = null;
    try {
        // parse the command line arguments
        CommandLine cmd = parser.parse(options, args);
        if (cmd.getOptions().length != 1) {
            System.err.println("Parsing failed: Reason: one and only one option is required");
            formatter.printHelp("qos-models", options);
        } else if (cmd.hasOption("h")) {
            formatter.printHelp("qos-models", options);
        } else if (cmd.hasOption("v")) {
            String file = cmd.getOptionValue("v");
            inputFile = new FileInputStream(file);
            MonitoringRules rules = XMLHelper.deserialize(inputFile, MonitoringRules.class);
            RulesValidator validator = new RulesValidator();
            Set<Problem> problems = validator.validateAllRules(rules);
            printResult(problems);
        } else if (cmd.hasOption("c")) {
            String file = cmd.getOptionValue("c");
            inputFile = new FileInputStream(file);
            Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class);
            QoSValidator validator = new QoSValidator();
            Set<Problem> problems = validator.validateAllConstraints(constraints);
            printResult(problems);
        } else if (cmd.hasOption("r")) {
            String file = cmd.getOptionValue("r");
            inputFile = new FileInputStream(file);
            Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class);
            MonitoringRuleFactory factory = new MonitoringRuleFactory();
            MonitoringRules rules = factory.makeRulesFromQoSConstraints(constraints);
            XMLHelper.serialize(rules, System.out);
        }
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
        formatter.printHelp("qos-models", options);
    } catch (FileNotFoundException e) {
        System.err.println("Could not locate input file: " + e.getMessage());
    } catch (JAXBException | SAXException e) {
        System.err.println("Input file could not be parsed: ");
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println("Unknown error: ");
        e.printStackTrace();
    } finally {
        if (inputFile != null) {
            try {
                inputFile.close();
            } catch (IOException e) {
            }
        }
    }
}

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);/*w w  w .  jav  a  2  s  .  c om*/
    }
    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.notifier.desktop.Main.java

public static void main(String[] args) {
    Options options = createCommandLineOptions();
    try {//  www.  ja  va  2s. c om
        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:com.evolveum.midpoint.tools.ninja.Main.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(help);/*from   ww w. j  a  va  2s. c o m*/
    options.addOption(validate);
    options.addOption(create);
    options.addOption(importOp);
    options.addOption(schemaOp);
    options.addOption(exportOp);
    options.addOption(driver);
    options.addOption(url);
    options.addOption(username);
    options.addOption(password);
    options.addOption(Password);
    options.addOption(keyStore);
    options.addOption(trans);
    options.addOption(outputFormat);
    options.addOption(outputDirectory);
    options.addOption(input);

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(options, args);
        if (line.getOptions().length == 0 || line.hasOption(help.getOpt())) {
            printHelp(options);
            return;
        }

        //repository validation, if proper option is present
        boolean valid = validate(line, options);
        //import DDL, if proper option is present
        if (line.hasOption(create.getOpt())) {
            ImportDDL ddl = new ImportDDL(createDDLConfig(line));
            if (!ddl.execute()) {
                System.out.println("DLL import was unsuccessful, skipping other steps.");
                return;
            }

            //repository validation after DDL import, if proper option is present
            valid = validate(line, options);
        }

        //import objects, only if repository validation didn't fail (in case it was tested)
        if (valid && line.hasOption(importOp.getOpt())) {
            String path = line.getOptionValue(importOp.getOpt());
            boolean validateSchema = line.hasOption(schemaOp.getOpt());
            ImportObjects objects = new ImportObjects(path, validateSchema);
            objects.execute();
        }

        if (valid && line.hasOption(exportOp.getOpt())) {
            String path = line.getOptionValue(exportOp.getOpt());
            ExportObjects objects = new ExportObjects(path);
            objects.execute();
        }

        if (line.hasOption(keyStore.getOpt())) {
            KeyStoreDumper keyStoreDumper = new KeyStoreDumper();
            keyStoreDumper.execute();
        }

        if (line.hasOption(trans.getOpt())) {
            if (!checkCommand(line)) {
                return;
            }
            FileTransformer transformer = new FileTransformer();
            configureTransformer(transformer, line);
            transformer.execute();
        }
    } catch (ParseException ex) {
        System.out.println("Error: " + ex.getMessage());
        printHelp(options);
    } catch (Exception ex) {
        System.out.println("Exception occurred, reason: " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:com.cyberway.issue.io.Arc2Warc.java

/**
 * Command-line interface to Arc2Warc./*from www  . ja  v a 2  s .c om*/
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    options.addOption(new Option("f", "force", false, "Force overwrite of target file."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();

    // If no args, print help.
    if (cmdlineArgs.size() <= 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    boolean force = false;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'f':
            force = true;
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    // If no args, print help.
    if (cmdlineArgs.size() != 2) {
        usage(formatter, options, 0);
    }
    (new Arc2Warc()).transform(new File(cmdlineArgs.get(0).toString()), new File(cmdlineArgs.get(1).toString()),
            force);
}

From source file:edu.indiana.d2i.htrc.corpus.analysis.LDAAnalysisDriver.java

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

    GenericOptionsParser parser = new GenericOptionsParser(new Configuration(), args);

    CommandLine commandLine = parser.getCommandLine();

    Option[] options = commandLine.getOptions();

    /**//from   w w w  .  j  ava  2  s.  c o  m
     * appArgs[0] = <path/to/input/directory> (where sequence files reside)
     * appArgs[1] = <path/to/output/directory/prefix> (where LDA state file
     * should go) appArgs[2] = <path/local/property/file>
     * 
     * Note: the passed in <path/to/output/directory/prefix> is only a
     * prefix, we automatically append the iteration number suffix
     */
    String[] appArgs = parser.getRemainingArgs();

    // load property file
    Properties prop = new Properties();
    prop.load(new FileInputStream(appArgs[2]));

    int maxIterationNum = Integer.parseInt(
            prop.getProperty(Constants.LDA_ANALYSIS_MAX_ITER, Constants.LDA_ANALYSIS_DEFAULT_MAX_ITER));

    int iterationCount = 0;

    /**
     * in the first iteration (iteration 0), there is no LDA state
     */
    String[] arguments = generateArgs(options, new String[0], appArgs[0],
            appArgs[1] + "-iter-" + iterationCount);

    /**
     * iterate until convergence or maximum iteration number reached
     */
    while (true) {

        int exitCode = ToolRunner.run(new LDAAnalysisDriver(), arguments);

        System.out.println(String.format("LDA analysis finished iteration %d, with exitCode = %d",
                iterationCount, exitCode));

        /**
         * LDA state is the output (sequence file) from current iteration
         * and is used to initialize the words-topics table and
         * topics-documents table for the next iteration
         */
        String ldaStateFilePath = appArgs[1] + "-iter-" + iterationCount + File.separator + "part-r-00000";

        /**
         * load LDA state to check whether it is converged
         */
        if (isAnalysisConverged(ldaStateFilePath)) {
            System.out.println(String.format("LDA analysis converged at iteration %d", iterationCount));
            break;
        }

        if ((iterationCount + 1) >= maxIterationNum) {
            System.out.println(String.format(
                    "LDA analysis reached the maximum iteration number %d, going to stop", maxIterationNum));
            break;
        }

        String[] otherOps = { "-D", "user.args.lda.state.filepath=" + ldaStateFilePath };

        /**
         * generate arguments for the next iteration and increase iteration
         * count
         */
        arguments = generateArgs(options, otherOps, appArgs[0], appArgs[1] + "-iter-" + ++iterationCount);
    }

}

From source file:com.medsavant.mailer.Mail.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new GnuParser();
    Options ops = getOptions();/*  w  w w  .j  a  va2 s.  c om*/
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(ops, args);

        // print help
        if (line.hasOption('h') || line.getOptions().length == 0) {
            printHelp();
            return;
        }

        // parse args

        String email = null;
        String emailPass = null;
        String mailingList = null;
        String subject = null;
        String htmlFile = null;

        for (Option o : line.getOptions()) {
            switch (o.getOpt().charAt(0)) {
            case 's':
                subject = o.getValue();
                break;
            case 'e':
                htmlFile = o.getValue();
                break;
            case 'u':
                email = o.getValue();
                break;
            case 'p':
                emailPass = o.getValue();
                break;
            case 'l':
                mailingList = o.getValue();
                break;
            }
        }

        setMailCredentials(email, emailPass, host, port);

        String text = readFileIntoString(new File(htmlFile));

        sendEmail(mailingList, subject, text);

    } catch (org.apache.commons.cli.ParseException exp) {

        printHelp();
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }
}

From source file:com.cyberway.issue.io.Warc2Arc.java

/**
 * Command-line interface to Arc2Warc.//from ww  w  .  j  av  a2  s .  c  o m
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    options.addOption(new Option("f", "force", false, "Force overwrite of target file."));
    options.addOption(
            new Option("p", "prefix", true, "Prefix to use on created ARC files, else uses default."));
    options.addOption(
            new Option("s", "suffix", true, "Suffix to use on created ARC files, else uses default."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();

    // If no args, print help.
    if (cmdlineArgs.size() < 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    boolean force = false;
    String prefix = "WARC2ARC";
    String suffix = null;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'f':
            force = true;
            break;

        case 'p':
            prefix = cmdlineOptions[i].getValue();
            break;

        case 's':
            suffix = cmdlineOptions[i].getValue();
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    // If no args, print help.
    if (cmdlineArgs.size() != 2) {
        usage(formatter, options, 0);
    }
    (new Warc2Arc()).transform(new File(cmdlineArgs.get(0).toString()), new File(cmdlineArgs.get(1).toString()),
            prefix, suffix, force);
}

From source file:com.uber.stream.kafka.mirrormaker.controller.ControllerStarter.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    cmd = parser.parse(ControllerConf.constructControllerOptions(), args);
    if (cmd.getOptions().length == 0 || cmd.hasOption("help")) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("OptionsTip", ControllerConf.constructControllerOptions());
        System.exit(0);//  w  w  w.  j  a v a  2 s. c  om
    }
    final ControllerStarter controllerStarter = ControllerStarter.init(cmd);

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

    try {
        controllerStarter.start();
    } catch (Exception e) {
        LOGGER.error("Cannot start Helix Mirror Maker Controller: ", e);
    }
}