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: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");
    }/*from   w ww .j  av  a 2  s  . c  o  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();
    }
}

From source file:com.twitter.heron.ckptmgr.CheckpointManager.java

public static void main(String[] args) throws IOException, ParseException, CheckpointManagerException {
    Options options = constructOptions();
    Options helpOptions = constructHelpOptions();
    CommandLineParser parser = new DefaultParser();
    // parse the help options first.
    CommandLine cmd = parser.parse(helpOptions, args, true);

    if (cmd.hasOption("h")) {
        usage(options);//from  ww  w . j  a v  a 2 s .  c o m
        return;
    }

    try {
        // Now parse the required options
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        usage(options);
        throw new RuntimeException("Error parsing command line options ", e);
    }

    String topologyName = cmd.getOptionValue("topologyname");
    String topologyId = cmd.getOptionValue("topologyid");
    String ckptmgrId = cmd.getOptionValue("ckptmgrid");
    int port = Integer.parseInt(cmd.getOptionValue("ckptmgrport"));
    String stateConfigFilename = cmd.getOptionValue("ckptmgrconfig");
    String heronInternalConfig = cmd.getOptionValue("heroninternalconfig");
    SystemConfig systemConfig = SystemConfig.newBuilder(true).putAll(heronInternalConfig, true).build();
    CheckpointManagerConfig ckptmgrConfig = CheckpointManagerConfig.newBuilder(true)
            .putAll(stateConfigFilename, true).build();

    // Add the SystemConfig into SingletonRegistry
    SingletonRegistry.INSTANCE.registerSingleton(SystemConfig.HERON_SYSTEM_CONFIG, systemConfig);

    // Init the logging setting and redirect the stdout and stderr to logging
    // For now we just set the logging level as INFO; later we may accept an argument to set it.
    Level loggingLevel = Level.INFO;
    String loggingDir = systemConfig.getHeronLoggingDirectory();

    // Log to file and TMaster
    LoggingHelper.loggerInit(loggingLevel, true);
    LoggingHelper.addLoggingHandler(LoggingHelper.getFileHandler(ckptmgrId, loggingDir, true,
            systemConfig.getHeronLoggingMaximumSize(), systemConfig.getHeronLoggingMaximumFiles()));
    LoggingHelper.addLoggingHandler(new ErrorReportLoggingHandler());

    // Start the actual things
    LOG.info(String.format(
            "Starting topology %s with topologyId %s with " + "Checkpoint Manager Id %s, Port: %d.",
            topologyName, topologyId, ckptmgrId, port));

    LOG.info("System Config: " + systemConfig);

    CheckpointManager checkpointManager = new CheckpointManager(topologyName, topologyId, ckptmgrId,
            CHECKPOINT_MANAGER_HOST, port, systemConfig, ckptmgrConfig);
    checkpointManager.startAndLoop();

    LOG.info("Loops terminated. Exiting.");
}

From source file:me.preilly.SimplePush.java

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

    /* Parse command line arguments */
    Options opt = new Options();
    opt.addOption("d", false, "Debug");
    opt.addOption("e", true, "Environment to run in");
    opt.addOption("h", false, "Print help for this application");

    BasicParser parser = new BasicParser();
    CommandLine cl = parser.parse(opt, args);
    boolean err = false;

    if (cl.hasOption("e")) {
        environmentKey = cl.getOptionValue("e");
    }//from   w ww.  ja v a2  s.c  o  m

    if (err || cl.hasOption("h")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar SimplePush.jar -c cookie [-d -p -e [-f filename]]", opt);
        System.exit(0);
    }

    ConfigFactory factory = ConfigFactory.getInstance();
    PropertiesConfiguration config = factory.getConfigProperties(environmentKey, propertiesFileName);
    Globals.getInstance(config);

    certName = config.getString(Const.CERT_NAME);
    certPass = config.getString(Const.CERT_PASSWORD);

    SimplePush obj = new SimplePush();
    obj.pushMessage();
}

From source file:net.anthonypoon.ngram.rollingregression.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("a", "action", true, "Action");
    options.addOption("i", "input", true, "input");
    options.addOption("o", "output", true, "output");
    //options.addOption("f", "format", true, "Format");
    options.addOption("u", "upbound", true, "Year up bound");
    options.addOption("l", "lowbound", true, "Year low bound");
    options.addOption("r", "range", true, "Range");
    options.addOption("T", "threshold", true, "Threshold - min count for regression");
    options.addOption("p", "positive-only", false, "Write positive slope only"); // default faluse
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    Configuration conf = new Configuration();
    if (cmd.hasOption("range")) {
        conf.set("range", cmd.getOptionValue("range"));
    }/*from  www . j  a va 2 s  .  com*/
    if (cmd.hasOption("upbound")) {
        conf.set("upbound", cmd.getOptionValue("upbound"));
    } else {
        conf.set("upbound", "9999");
    }
    if (cmd.hasOption("lowbound")) {
        conf.set("lowbound", cmd.getOptionValue("lowbound"));
    } else {
        conf.set("lowbound", "0");
    }
    if (cmd.hasOption("threshold")) {
        conf.set("threshold", cmd.getOptionValue("threshold"));
    }
    if (cmd.hasOption("positive-only")) {
        conf.set("positive-only", "true");
    }
    Job job = Job.getInstance(conf);
    /**
    if (cmd.hasOption("format")) {
    switch (cmd.getOptionValue("format")) {
        case "compressed":
            job.setInputFormatClass(SequenceFileAsTextInputFormat.class);
            break;
        case "text":
            job.setInputFormatClass(KeyValueTextInputFormat.class);
            break;
    }
            
    }**/
    job.setJarByClass(Main.class);
    switch (cmd.getOptionValue("action")) {
    case "get-regression":
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        for (String inputPath : cmd.getOptionValue("input").split(",")) {
            MultipleInputs.addInputPath(job, new Path(inputPath), KeyValueTextInputFormat.class,
                    RollingRegressionMapper.class);
        }
        job.setReducerClass(RollingRegressionReducer.class);
        break;
    default:
        throw new IllegalArgumentException("Missing action");
    }

    String timestamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());

    //FileInputFormat.setInputPaths(job, new Path(cmd.getOptionValue("input")));
    FileOutputFormat.setOutputPath(job, new Path(cmd.getOptionValue("output") + "/" + timestamp));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
    /**
    double[] nazismBaseLine = {3, 12, 12, 18, 233, 239, 386, 333, 593, 1244, 1925, 3013, 3120, 3215, 3002, 3355, 2130, 1828, 1406, 1751, 1433, 1033, 881, 1330, 1029, 760, 1288, 1013, 1014};
    InputStream inStream = Main.class.getResourceAsStream("/1g-matrix.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
    String line = "";
    Map<String, Double> result = new HashMap();
    while ((line = br.readLine()) != null) {
    String[] strArray = line.split("\t");
    double[] compareArray = new double[nazismBaseLine.length];
    for (int i = 0; i < nazismBaseLine.length; i ++) {
        compareArray[i] = Double.valueOf(strArray[i + 24]);
    }
    result.put(strArray[0], new PearsonsCorrelation().correlation(nazismBaseLine, compareArray));
    }
    List<Map.Entry<String, Double>> toBeSorted = new ArrayList();
    for (Map.Entry pair : result.entrySet()) {
    toBeSorted.add(pair);
    }
    Collections.sort(toBeSorted, new Comparator<Map.Entry<String, Double>>(){
    @Override
    public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
        return o2.getValue().compareTo(o1.getValue());
    }
    });
    for (Map.Entry<String, Double> pair : toBeSorted) {
    if (!Double.isNaN(pair.getValue())) {
        System.out.println(pair.getKey() + "\t" + pair.getValue());
    }
    }**/
}

From source file:com.trendmicro.hdfs.webdav.tool.Get.java

public static void main(String[] args) throws Exception {
    // Process command line 

    Options options = new Options();
    options.addOption("d", "debug", false, "Enable debug logging");

    CommandLine cmd = null;
    try {//from   w w w  . j  ava  2s  . c  o m
        cmd = new PosixParser().parse(options, args);
    } catch (ParseException e) {
        printUsageAndExit(options, -1);
    }
    boolean debug = cmd.hasOption('d');
    args = cmd.getArgs();
    if (args.length < 1) {
        printUsageAndExit(options, -1);
    }

    // Do the fetch

    AuthenticatedURL.Token token = new AuthenticatedURL.Token();
    AuthenticatedURL url = new AuthenticatedURL();
    HttpURLConnection conn = url.openConnection(new URL(args[0]), token);
    if (debug) {
        System.out.println("Token value: " + token);
        System.out.println("Status code: " + conn.getResponseCode() + " " + conn.getResponseMessage());
    }
    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
        reader.close();
    }
    System.out.println();
}

From source file:com.example.bigquery.QuerySample.java

/** Prompts the user for the required parameters to perform a query. */
public static void main(final String[] args)
        throws IOException, InterruptedException, TimeoutException, ParseException {
    Options options = new Options();

    // Use an OptionsGroup to choose which sample to run.
    OptionGroup samples = new OptionGroup();
    samples.addOption(Option.builder().longOpt("runSimpleQuery").build());
    samples.addOption(Option.builder().longOpt("runStandardSqlQuery").build());
    samples.addOption(Option.builder().longOpt("runPermanentTableQuery").build());
    samples.addOption(Option.builder().longOpt("runUncachedQuery").build());
    samples.addOption(Option.builder().longOpt("runBatchQuery").build());
    samples.isRequired();//from  w w w .  j a v  a 2  s  .  com
    options.addOptionGroup(samples);

    options.addOption(Option.builder().longOpt("query").hasArg().required().build());
    options.addOption(Option.builder().longOpt("destDataset").hasArg().build());
    options.addOption(Option.builder().longOpt("destTable").hasArg().build());
    options.addOption(Option.builder().longOpt("allowLargeResults").build());

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

    String query = cmd.getOptionValue("query");
    if (cmd.hasOption("runSimpleQuery")) {
        runSimpleQuery(query);
    } else if (cmd.hasOption("runStandardSqlQuery")) {
        runStandardSqlQuery(query);
    } else if (cmd.hasOption("runPermanentTableQuery")) {
        String destDataset = cmd.getOptionValue("destDataset");
        String destTable = cmd.getOptionValue("destTable");
        boolean allowLargeResults = cmd.hasOption("allowLargeResults");
        runQueryPermanentTable(query, destDataset, destTable, allowLargeResults);
    } else if (cmd.hasOption("runUncachedQuery")) {
        runUncachedQuery(query);
    } else if (cmd.hasOption("runBatchQuery")) {
        runBatchQuery(query);
    }
}

From source file:de.peregrinus.autocopyreport.AutoCopyReport.java

public static void main(String[] args) {
    SongInfo si;/*from   w  ww .  j av  a2s.c  o  m*/

    String openlpPath = "";
    String crPath = "";
    String crDataPath = "";
    String crPassword = "";

    System.out.println("AutoCopyReport v.1.00.00");
    System.out.println("(c) 2014 Volksmission Freudenstadt");
    System.out.println("Author: Christoph Fischer <christoph.fischer@volksmission.de>");
    //System.out.println("Available under the General Public License (GPL) v2");
    System.out.println();

    // get options
    Options options = new Options();
    options.addOption("h", "help", false, "display a list of available options");
    options.addOption(OptionBuilder.withLongOpt("openlp-path").withDescription("path to OpenLP data directory")
            .hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("copyreport-path")
            .withDescription("path to the CopyReport program directory").hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("copyreport-data-path")
            .withDescription("path to the CopyReport data directory").hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("password")
            .withDescription("internal password for the CopyReport database").hasArg().withArgName("PASSWORD")
            .create());

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

        // validate that block-size has been set
        if (line.hasOption("help")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("AutoCopyReport", options);
            System.exit(0);
        } else {
            if (line.hasOption("openlp-path")) {
                openlpPath = line.getOptionValue("openlp-path") + "/songs/songs.sqlite";
                System.out.println("OpenLP data path: " + openlpPath);
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your OpenLP data folder by using the --openlp-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("copyreport-path")) {
                crPath = line.getOptionValue("copyreport-path");
                System.out.println("Copyreport application database: " + crPath + "/ccldata.h2.db");
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your CopyReport program folder by using the --copyreport-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("copyreport-data-path")) {
                crDataPath = line.getOptionValue("copyreport-data-path");
                System.out.println("Copyreport user database: " + crDataPath + "/userdata.h2.db");
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your CopyReport data folder by using the --copyreport-data-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("password")) {
                crPassword = line.getOptionValue("password");
            } else {
                System.out.println(
                        "ERROR: Please supply the internal password for the CopyReport database by using the --password parameter.");
                System.exit(0);
            }
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
        System.exit(0);
    }

    SongDatabaseConnector sdb = new SongDatabaseConnector(openlpPath);
    SongRepository cdb = new SongRepository(crPath + "/ccldata", "sa", crPassword);

    CopyReport rpt = new CopyReport(crDataPath + "/userdata", "sa", crPassword);
    //rpt.createPeriod("2014");

    List<Song> songs = sdb.findLicensedSongs();
    for (Song song : songs) {
        System.out.println(song.title + ": " + song.ccliNumber);
        if (song.ccliNumber.matches("-?\\d+(\\.\\d+)?")) {
            si = cdb.findById(song.ccliNumber);
            if (si != null)
                rpt.reportSong(si);
        } else {
            System.out.println("Format error: '" + song.ccliNumber + "' is not numeric.");
        }
    }

    // wrap up: close the databases
    cdb.close();
    rpt.close();
    sdb.close();

}

From source file:jlite.cli.ProxyInit.java

public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();//from   w  w w  .j  ava  2 s .  co m
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            System.out.println(); // extra line
            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 > 0) {
                run(remArgs, line);
            } else {
                throw new MissingArgumentException("Missing required argument: <voms>[:<command>]");
            }
        }
    } catch (ParseException e) {
        System.err.println("\n" + 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 != null) && (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:backtype.storm.command.update_topology.java

/**
 * @param args// www  . ja v a2  s .c  o m
 */
public static void main(String[] args) {
    if (args == null || args.length < 3) {
        System.out.println("Invalid parameter");
        usage();
        return;
    }
    String topologyName = args[0];
    try {
        String[] str2 = Arrays.copyOfRange(args, 1, args.length);
        CommandLineParser parser = new GnuParser();
        Options r = buildGeneralOptions(new Options());
        CommandLine commandLine = parser.parse(r, str2, true);

        String pathConf = null;
        String pathJar = null;
        if (commandLine.hasOption("conf")) {
            pathConf = (commandLine.getOptionValues("conf"))[0];
        }
        if (commandLine.hasOption("jar")) {
            pathJar = (commandLine.getOptionValues("jar"))[0];
        }
        if (pathConf != null || pathJar != null)
            updateTopology(topologyName, pathJar, pathConf);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.picdrop.security.SecureStoreMain.java

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

    CommandLineParser cliP = new DefaultParser();

    Options ops = generateBasicOptions();
    CommandLine cli = cliP.parse(ops, args);
    HelpFormatter hlp = new HelpFormatter();

    SecureStore ss;//from   w  w w.  j  a  va  2s .c  o m
    String path = ".";

    try {
        if (cli.hasOption("help")) {
            hlp.printHelp("SecureStore", ops);
            System.exit(0);
        }

        if (cli.hasOption("keystore")) {
            path = cli.getOptionValue("keystore", ".");
        }

        if (cli.hasOption("create")) {
            ss = new SecureStore(path, false);
            ss.createKeyStore();
            System.exit(0);
        } else {
            ss = new SecureStore(path, true);
        }

        if (cli.hasOption("list")) {
            Enumeration<String> en = ss.listAlias();
            while (en.hasMoreElements()) {
                System.out.println(en.nextElement());
            }
            System.exit(0);
        }

        if (cli.hasOption("store")) {
            ss.storeValue(cli.getOptionValues("store")[0], cli.getOptionValues("store")[1]);
            ss.writeStore();
            System.exit(0);
        }

        if (cli.hasOption("clear")) {
            ss.deleteValue(cli.getOptionValue("clear"));
            ss.writeStore();
            System.exit(0);
        }
    } finally {
        hlp.printHelp("SecureStore", ops);
        System.exit(0);
    }
}