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

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

Introduction

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

Prototype

public boolean hasOption(char opt) 

Source Link

Document

Query to see if an option has been set.

Usage

From source file:edu.uga.cs.fluxbuster.FluxbusterCLI.java

/**
 * The main method.//from w w  w.  j a v a 2  s.co m
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    GnuParser parser = new GnuParser();
    Options opts = FluxbusterCLI.initializeOptions();
    CommandLine cli;
    try {
        cli = parser.parse(opts, args);

        if (cli.hasOption('?')) {
            throw new ParseException(null);
        }

        if (validateDate(cli.getOptionValue('d')) && validateDate(cli.getOptionValue('e'))) {

            if (log.isInfoEnabled()) {
                StringBuffer arginfo = new StringBuffer("\n");
                arginfo.append("generate-clusters: " + cli.hasOption('g') + "\n");
                arginfo.append("calc-features: " + cli.hasOption('f') + "\n");
                arginfo.append("calc-similarity: " + cli.hasOption('s') + "\n");
                arginfo.append("classify-clusters: " + cli.hasOption('c') + "\n");
                arginfo.append("start-date: " + cli.getOptionValue('d') + "\n");
                arginfo.append("end-date: " + cli.getOptionValue('e') + "\n");
                log.info(arginfo.toString());
            }

            try {
                boolean clus = true, feat = true, simil = true, clas = true;
                if (cli.hasOption('g') || cli.hasOption('f') || cli.hasOption('s') || cli.hasOption('c')) {
                    if (!cli.hasOption('g')) {
                        clus = false;
                    }
                    if (!cli.hasOption('f')) {
                        feat = false;
                    }
                    if (!cli.hasOption('s')) {
                        simil = false;
                    }
                    if (!cli.hasOption('c')) {
                        clas = false;
                    }
                }

                DBInterfaceFactory.init();
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
                Date logdate = df.parse(cli.getOptionValue('d'));
                long startTime = logdate.getTime() / 1000;
                long endTime = df.parse(cli.getOptionValue('e')).getTime() / 1000;

                if (clus) {
                    ClusterGenerator cg = new ClusterGenerator();
                    List<DomainCluster> clusters = cg.generateClusters(startTime, endTime, true);
                    cg.storeClusters(clusters, logdate);
                }
                if (feat) {
                    FeatureCalculator calc = new FeatureCalculator();
                    calc.updateFeatures(logdate);
                }
                if (simil) {
                    ClusterSimilarityCalculator calc2 = new ClusterSimilarityCalculator();
                    calc2.updateClusterSimilarities(logdate);
                }
                if (clas) {
                    Classifier calc3 = new Classifier();
                    calc3.updateClusterClasses(logdate, 30);
                }
            } catch (Exception e) {
                if (log.isFatalEnabled()) {
                    log.fatal("", e);
                }
            } finally {
                DBInterfaceFactory.shutdown();
            }
        } else {
            throw new ParseException(null);
        }
    } catch (ParseException e1) {
        PrintWriter writer = new PrintWriter(System.out);
        HelpFormatter usageFormatter = new HelpFormatter();
        usageFormatter.printHelp(writer, 80, "fluxbuster", "If none of the options g, f, s, c are specified "
                + "then the program will execute as if all of them "
                + "have been specified.  Otherwise, the program will " + "only execute the options specified.",
                opts, 0, 2, "");
        writer.close();
    }
}

From source file:com.artistech.tuio.mouse.MouseDriver.java

/**
 * Main: can take a port value as an argument.
 *
 * @param args//w ww .  ja  va2  s  .c  o m
 */
public static void main(String args[]) {
    int tuio_port = 3333;

    Options options = new Options();
    options.addOption("t", "tuio-port", true, "TUIO Port to listen on. (Default = 3333)");
    options.addOption("h", "help", false, "Show this message.");
    HelpFormatter formatter = new HelpFormatter();

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

        if (cmd.hasOption("help")) {
            formatter.printHelp("tuio-mouse-driver", options);
            return;
        } else {
            if (cmd.hasOption("t") || cmd.hasOption("tuio-port")) {
                tuio_port = Integer.parseInt(cmd.getOptionValue("t"));
            }
        }
    } catch (ParseException | NumberFormatException ex) {
        System.err.println("Error Processing Command Options:");
        formatter.printHelp("tuio-mouse-driver", options);
        return;
    }

    try {
        MouseDriver mouse = new MouseDriver();
        TuioClient client = new TuioClient(tuio_port);

        logger.info(
                MessageFormat.format("Listening to TUIO message at port: {0}", Integer.toString(tuio_port)));
        client.addTuioListener(mouse);
        client.connect();
    } catch (AWTException e) {
        logger.fatal(null, e);
    }
}

From source file:com.buddycloud.channeldirectory.cli.Main.java

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

    JsonElement rootElement = new JsonParser().parse(new FileReader(QUERIES_FILE));
    JsonArray rootArray = rootElement.getAsJsonArray();

    Map<String, Query> queries = new HashMap<String, Query>();

    for (int i = 0; i < rootArray.size(); i++) {
        JsonObject queryElement = rootArray.get(i).getAsJsonObject();
        String queryName = queryElement.get("name").getAsString();
        String type = queryElement.get("type").getAsString();

        Query query = null;/*ww  w  .j  a v  a  2 s.  c o  m*/

        if (type.equals("solr")) {
            query = new QueryToSolr(queryElement.get("agg").getAsString(),
                    queryElement.get("core").getAsString(), queryElement.get("q").getAsString());
        } else if (type.equals("dbms")) {
            query = new QueryToDBMS(queryElement.get("q").getAsString());
        }

        queries.put(queryName, query);
    }

    LinkedList<String> queriesNames = new LinkedList<String>(queries.keySet());
    Collections.sort(queriesNames);

    Options options = new Options();
    options.addOption(OptionBuilder.isRequired(true).withLongOpt("query").hasArg(true)
            .withDescription("The name of the query. Possible queries are: " + queriesNames).create('q'));

    options.addOption(OptionBuilder.isRequired(false).withLongOpt("args").hasArg(true)
            .withDescription("Arguments for the query").create('a'));

    options.addOption(new Option("?", "help", false, "Print this message"));

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        printHelpAndExit(options);
    }

    if (cmd.hasOption("help")) {
        printHelpAndExit(options);
    }

    String queryName = cmd.getOptionValue("q");
    String argsCmd = cmd.getOptionValue("a");

    Properties configuration = ConfigurationUtils.loadConfiguration();

    Query query = queries.get(queryName);
    if (query == null) {
        printHelpAndExit(options);
    }

    System.out.println(query.exec(argsCmd, configuration));

}

From source file:dk.alexandra.fresco.demo.DistanceDemo.java

public static void main(String[] args) {
    CmdLineUtil cmdUtil = new CmdLineUtil();
    SCEConfiguration sceConf = null;//ww  w . j  a  v a2 s.  c om
    int x, y;
    x = y = 0;
    try {
        cmdUtil.addOption(Option.builder("x").desc("The integer x coordinate of this party. "
                + "Note only party 1 and 2 should supply this input.").hasArg().build());
        cmdUtil.addOption(Option.builder("y").desc(
                "The integer y coordinate of this party. " + "Note only party 1 and 2 should supply this input")
                .hasArg().build());
        CommandLine cmd = cmdUtil.parse(args);
        sceConf = cmdUtil.getSCEConfiguration();

        if (sceConf.getMyId() == 1 || sceConf.getMyId() == 2) {
            if (!cmd.hasOption("x") || !cmd.hasOption("y")) {
                throw new ParseException("Party 1 and 2 must submit input");
            } else {
                x = Integer.parseInt(cmd.getOptionValue("x"));
                y = Integer.parseInt(cmd.getOptionValue("y"));
            }
        } else {
            if (cmd.hasOption("x") || cmd.hasOption("y"))
                throw new ParseException("Only party 1 and 2 should submit input");
        }

    } catch (ParseException | IllegalArgumentException e) {
        System.out.println("Error: " + e);
        System.out.println();
        cmdUtil.displayHelp();
        System.exit(-1);
    }
    DistanceDemo distDemo = new DistanceDemo(sceConf.getMyId(), x, y);
    SCE sce = SCEFactory.getSCEFromConfiguration(sceConf);
    try {
        sce.runApplication(distDemo);
    } catch (Exception e) {
        System.out.println("Error while doing MPC: " + e.getMessage());
        e.printStackTrace();
        System.exit(-1);
    }
    double dist = distDemo.distance.getValue().doubleValue();
    dist = Math.sqrt(dist);
    System.out.println("Distance between party 1 and 2 is " + dist);
}

From source file:com.siemens.sw360.UtilsEntryPoint.java

public static void main(String[] args) throws MalformedURLException {
    CommandLine cmd;

    try {//from   w w w  .  j  a  v a  2  s.  co  m
        cmd = parseArgs(args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printHelp();
        return;
    }

    String[] leftArgs = cmd.getArgs();

    if (cmd.hasOption(OPTION_HELP)) {
        printHelp();
        return;
    }

    if (cmd.hasOption(OPTION_DOWNLOAD)) {
        runRemoteAttachmentDownloader(leftArgs);
    } else {
        printHelp();
    }
}

From source file:edu.ksu.cis.indus.staticanalyses.concurrency.DeadlockAnalysisCLI.java

/**
 * The entry point to this class./*from   w ww.j a v a  2s.co m*/
 * 
 * @param args command line arguments.
 * @throws RuntimeException when escape information and side-effect information calculation fails.
 */
public static void main(final String[] args) {
    final Options _options = new Options();
    Option _option = new Option("h", "help", false, "Display message.");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("p", "soot-classpath", false, "Prepend this to soot class path.");
    _option.setArgs(1);
    _option.setArgName("classpath");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("S", "scope", true, "The scope that should be analyzed.");
    _option.setArgs(1);
    _option.setArgName("scope");
    _option.setRequired(false);
    _options.addOption(_option);

    final CommandLineParser _parser = new GnuParser();

    try {
        final CommandLine _cl = _parser.parse(_options, args);

        if (_cl.hasOption("h")) {
            final String _cmdLineSyn = "java " + DeadlockAnalysisCLI.class.getName()
                    + " <options> <classnames>";
            (new HelpFormatter()).printHelp(_cmdLineSyn, _options);
            System.exit(1);
        }

        if (_cl.getArgList().isEmpty()) {
            throw new MissingArgumentException("Please specify atleast one class.");
        }

        final DeadlockAnalysisCLI _cli = new DeadlockAnalysisCLI();

        if (_cl.hasOption('p')) {
            _cli.addToSootClassPath(_cl.getOptionValue('p'));
        }

        if (_cl.hasOption('S')) {
            _cli.setScopeSpecFile(_cl.getOptionValue('S'));
        }
        _cli.setClassNames(_cl.getArgList());
        _cli.<ITokens>execute();
    } catch (final ParseException _e) {
        LOGGER.error("Error while parsing command line.", _e);
        System.out.println("Error while parsing command line." + _e);
        final String _cmdLineSyn = "java " + DeadlockAnalysisCLI.class.getName() + " <options> <classnames>";
        (new HelpFormatter()).printHelp(_cmdLineSyn, "Options are:", _options, "");
    } catch (final Throwable _e) {
        LOGGER.error("Beyond our control. May day! May day!", _e);
        throw new RuntimeException(_e);
    }
}

From source file:com.vmware.photon.controller.common.auth.AuthOIDCRegistrar.java

public static int main(String[] args) {
    Options options = new Options();
    options.addOption(USERNAME_ARG, true, "Lightwave user name");
    options.addOption(PASSWORD_ARG, true, "Password");
    options.addOption(TARGET_ARG, true, "Registration Hostname or IPAddress"); // Possible
                                                                               // load-balancer
                                                                               // address
    options.addOption(MANAGEMENT_UI_REG_FILE_ARG, true, "Management UI Registration Path");
    options.addOption(SWAGGER_UI_REG_FILE_ARG, true, "Swagger UI Registration Path");
    options.addOption(HELP_ARG, false, "Help");

    try {/*w ww .  j  a  v a2 s .  c  om*/
        String username = null;
        String password = null;
        String registrationAddress = null;
        String mgmtUiRegPath = null;
        String swaggerUiRegPath = null;

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

        if (cmd.hasOption(HELP_ARG)) {
            showUsage(options);
            return 0;
        }

        if (cmd.hasOption(USERNAME_ARG)) {
            username = cmd.getOptionValue(USERNAME_ARG);
        }

        if (cmd.hasOption(PASSWORD_ARG)) {
            password = cmd.getOptionValue(PASSWORD_ARG);
        }

        if (cmd.hasOption(TARGET_ARG)) {
            registrationAddress = cmd.getOptionValue(TARGET_ARG);
        }

        if (cmd.hasOption(MANAGEMENT_UI_REG_FILE_ARG)) {
            mgmtUiRegPath = cmd.getOptionValue(MANAGEMENT_UI_REG_FILE_ARG);
        }

        if (cmd.hasOption(SWAGGER_UI_REG_FILE_ARG)) {
            swaggerUiRegPath = cmd.getOptionValue(SWAGGER_UI_REG_FILE_ARG);
        }

        if (username == null || username.trim().isEmpty()) {
            throw new UsageException("Error: username is not specified");
        }

        if (password == null) {
            char[] passwd = System.console().readPassword("Password:");
            password = new String(passwd);
        }

        DomainInfo domainInfo = DomainInfo.build();

        AuthOIDCRegistrar registrar = new AuthOIDCRegistrar(domainInfo);

        registrar.register(registrationAddress, username, password, mgmtUiRegPath, swaggerUiRegPath);

        return 0;
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        return ERROR_PARSE_EXCEPTION;
    } catch (UsageException e) {
        System.err.println(e.getMessage());
        showUsage(options);
        return ERROR_USAGE_EXCEPTION;
    } catch (AuthException e) {
        System.err.println(e.getMessage());
        return ERROR_AUTH_EXCEPTION;
    }
}

From source file:de.binfalse.jatter.App.java

/**
 * Run jatter's main.//ww w  . j a  v  a  2 s. c  o m
 *
 * @param args
 *          the arguments
 * @throws Exception
 *           the exception
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();

    Option conf = new Option("c", "config", true, "config file path");
    conf.setRequired(false);
    options.addOption(conf);

    Option t = new Option("t", "template", false, "show a config template");
    t.setRequired(false);
    options.addOption(t);

    Option v = new Option("v", "verbose", false, "print information messages");
    v.setRequired(false);
    options.addOption(v);

    Option d = new Option("d", "debug", false, "print debugging messages incl stack traces");
    d.setRequired(false);
    options.addOption(d);

    Option h = new Option("h", "help", false, "show help");
    h.setRequired(false);
    options.addOption(h);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h"))
            throw new RuntimeException("showing the help page");
    } catch (Exception e) {
        help(options, e.getMessage());
        return;
    }

    if (cmd.hasOption("t")) {
        System.out.println();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                App.class.getClassLoader().getResourceAsStream("config.properties.template")));
        while (br.ready())
            System.out.println(br.readLine());
        br.close();
        System.exit(0);
    }

    if (cmd.hasOption("v"))
        LOGGER.setMinLevel(LOGGER.INFO);

    if (cmd.hasOption("d")) {
        LOGGER.setMinLevel(LOGGER.DEBUG);
        LOGGER.setLogStackTrace(true);
    }

    if (!cmd.hasOption("c"))
        help(options, "a config file is required for running jatter");

    startJatter(cmd.getOptionValue("c"));
}

From source file:jlite.cli.JobSubmit.java

public static void main(String[] args) {
    System.out.println(); // extra line
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();//ww  w  .  java 2  s . c  om
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;

    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
            System.out.println(); // extra line
            System.exit(0);
        } else {
            if (line.hasOption("xml")) {
                System.out.println("<output>");
            }
            String[] remArgs = line.getArgs();
            if (remArgs.length == 1) {
                run(remArgs[0], line);
            } else if (remArgs.length == 0) {
                throw new MissingArgumentException("Missing required argument: <jdl_file>");
            } else {
                throw new UnrecognizedOptionException("Unrecognized extra arguments");
            }
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage() + "\n");
        helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
        System.out.println(); // extra line
        System.exit(-1);
    } catch (Exception e) {
        if (line.hasOption("xml")) {
            System.out.println("<error>" + e.getMessage() + "</error>");
        } else {
            System.err.println(e.getMessage());
        }
    } finally {
        if (line.hasOption("xml")) {
            System.out.println("</output>");
        }
    }
    System.out.println(); // extra line
}

From source file:com.simple.sftpfetch.App.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Options options = getOptions();// w w w  . ja v  a 2  s.  com

    List<String> requiredProperties = asList("c");

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption("h")) {
            printUsage(options);
            System.exit(0);
        }

        for (String opt : requiredProperties) {
            if (!commandLine.hasOption(opt)) {
                System.err.println("The option: " + opt + " is required.");
                printUsage(options);
                System.exit(1);
            }
        }

        Pattern pattern;
        if (commandLine.hasOption("p")) {
            pattern = Pattern.compile(commandLine.getOptionValue("p"));
        } else {
            pattern = MATCH_EVERYTHING;
        }

        String filename = commandLine.getOptionValue("c");
        Properties properties = new Properties();
        try {
            InputStream stream = new FileInputStream(new File(filename));
            properties.load(stream);
        } catch (IOException ioe) {
            System.err.println("Unable to read properties from: " + filename);
            System.exit(2);
        }

        String routingKey = "";
        if (commandLine.hasOption("r")) {
            routingKey = commandLine.getOptionValue("r");
        } else if (properties.containsKey("rabbit.routingkey")) {
            routingKey = properties.getProperty("rabbit.routingkey");
        }

        int daysToFetch;
        if (commandLine.hasOption("d")) {
            daysToFetch = Integer.valueOf(commandLine.getOptionValue("d"));
        } else {
            daysToFetch = Integer.valueOf(properties.getProperty(FETCH_DAYS));
        }

        FileDecrypter decrypter = null;
        if (properties.containsKey("decryption.key.path")) {
            decrypter = new PGPFileDecrypter(new File(properties.getProperty("decryption.key.path")));
        } else {
            decrypter = new NoopDecrypter();
        }

        SftpClient sftpClient = new SftpClient(new JSch(), new SftpConnectionInfo(properties));
        try {
            App app = new App(sftpClient, s3FromProperties(properties),
                    new RabbitClient(new ConnectionFactory(), new RabbitConnectionInfo(properties)), decrypter,
                    System.out);
            app.run(routingKey, daysToFetch, pattern, commandLine.hasOption("n"), commandLine.hasOption("o"));
        } finally {
            sftpClient.close();
        }
        System.exit(0);
    } catch (UnrecognizedOptionException uoe) {
        System.err.println(uoe.getMessage());
        printUsage(options);
        System.exit(10);
    }
}