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:CountandraServer.java

public static void main(String args[]) {

    try {// ww  w  .  j  a v a 2s.  c  om
        System.out.println(args[0]);

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

        if (line.hasOption("cassandrahostip")) {
            CountandraUtils.setCassandraHostIp(line.getOptionValue("cassandrahostip"));
            if (line.hasOption("consistencylevel")) {
                if (line.hasOption("replicationfactor")) {

                    CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"),
                            line.getOptionValue("consistencylevel"));
                    CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"),
                            line.getOptionValue("replicationfactor"));

                } else {

                    CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"),
                            line.getOptionValue("consistencylevel"));
                    CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"));

                }
            }

            else { // no consistency level -- assumed to be ONE
                if (line.hasOption("replicationfactor")) {

                    CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"));
                    CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"),
                            line.getOptionValue("replicationfactor"));

                } else {

                    CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"));
                    CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"));

                }
            }
        } else {
            CassandraStorage.setGlobalParams(cassandraServerForClient);
            CassandraDB.setGlobalParams(cassandraServerForClient);
        }

        if (line.hasOption("s")) {
            System.out.println("Starting Cassandra");
            // cassandra server
            CassandraUtils.startupCassandraServer();

        }
        if (line.hasOption("i")) {
            System.out.print("Checking if Cassandra is initialized");
            CassandraDB csdb = new CassandraDB();
            while (!csdb.isCassandraUp()) {
                System.out.print(".");
            }
            System.out.println(".");
            System.out.println("Initializing Basic structures");
            CountandraUtils.initBasicDataStructures();
            System.out.println("Initialized Basic structures");

        }

        if (line.hasOption("h")) {

            if (line.hasOption("httpserverport")) {
                httpPort = Integer.parseInt(line.getOptionValue("httpserverport"));
            }
            NettyUtils.startupNettyServer(httpPort);
            System.out.println("Started Http Server");
        }

        if (line.hasOption("k")) {

            KafkaUtils.startupKafkaConsumer();
            System.out.println("Started Kafka Consumer");
        }

        // Unit Tests
        if (line.hasOption("t")) {
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            org.junit.runner.JUnitCore.main(CountandraTestCases.class.getName());
        }

    } catch (IOException ioe) {
        System.out.println(ioe);
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.mvdb.etl.actions.FetchConfigValue.java

/**
 * @param args//from w  w w . jav a2s  .c o  m
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    String customerName = null;
    String valueName = null;
    String outputFileName = null;

    ActionUtils.setUpInitFileProperty();

    final CommandLineParser cmdLinePosixParser = new PosixParser();
    final Options posixOptions = constructPosixOptions();
    CommandLine commandLine;
    try {
        commandLine = cmdLinePosixParser.parse(posixOptions, args);
        if (commandLine.hasOption("customer")) {
            customerName = commandLine.getOptionValue("customer");
        }
        if (commandLine.hasOption("name")) {
            valueName = commandLine.getOptionValue("name");
        }
        if (commandLine.hasOption("outputFile")) {
            outputFileName = commandLine.getOptionValue("outputFile");
        }

        System.out.println("customerName:" + customerName);
        System.out.println("valueName:" + valueName);
        System.out.println("outputFileName:" + outputFileName);

    } catch (ParseException parseException) // checked exception
    {
        System.err.println(
                "Encountered exception while parsing using PosixParser:\n" + parseException.getMessage());
    }

    if (customerName == null) {
        System.err.println("Could not find customerName. Aborting...");
        System.exit(1);
    }

    if (valueName == null) {
        System.err.println("Could not find valueName. Aborting...");
        System.exit(1);
    }

    if (outputFileName == null) {
        System.err.println("Could not find outputFileName. Aborting...");
        System.exit(1);
    }

    String value = ActionUtils.getConfigurationValue(customerName, valueName);
    FileUtils.writeStringToFile(new File(outputFileName), value);

}

From source file:com.svds.genericconsumer.main.GenericConsumerGroup.java

/**
 * Given command-line arguments, create GenericConsumerGroup
 * /*from  w  w w.  j a  va  2 s. c o  m*/
 * @param args  command-line arguments to parse
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    LOG.info("HELLO from main");

    Options options = new Options();
    options.addOption(OptionBuilder.isRequired().withLongOpt(ZOOKEEPER).withDescription("Zookeeper servers")
            .hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(GROUPID).withDescription("Kafka group id").hasArg()
            .create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(TOPICNAME).withDescription("Kafka topic name")
            .hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(THREADS).withType(Number.class)
            .withDescription("Number of threads").hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(CONSUMERCLASS)
            .withDescription("Consumer Class from processing topic name").hasArg().create());

    options.addOption(OptionBuilder.withLongOpt(PARAMETERS)
            .withDescription("Parameters needed for the consumer Class if needed").hasArgs()
            .withValueSeparator(',').create());

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        LOG.error(e.getMessage(), e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("GenericConsumerGroup.main", options);
        throw new IOException(e);
    }

    try {
        GenericConsumerGroup consumerGroupExample = new GenericConsumerGroup();
        consumerGroupExample.doWork(cmd);
    } catch (ParseException ex) {
        LOG.error("Error parsing command-line args");
        throw new IOException(ex);
    }
}

From source file:com.esri.geoportal.base.metadata.MetadataCLI.java

/**
        /*from   www .java 2 s  . c  o  m*/
 * <h1>run the javascript Evaluators.js scripts</h1>
 * from command line for testing.
 *
 * <div> java com.esri.geoportal.base.metadata.MetadataCLI -md={XMLFile_fullpath}
 *</div>
 *
 * <p><b>Note:</b> This only produces the basic JSON elements seen in the
 * elastic search json document. Other steps, such as itemID are found in {@link com.esri.geoportal.lib.elastic.request.PublishMetadataRequest#prePublish(ElasticContext, AccessUtil, AppResponse, MetadataDocument)} </p>
 *
 *<p><b>Note:</b> mainly tested in JetBrains Intellij</p>
 *  <p><b>Note:</b> mvn command line call is in contrib</p>
 *
 * @author David Valentine
 *
 */
public static void main(String[] args) {
    Option help = Option.builder("h").required(false).longOpt("help").desc("HELP").build();

    //        Option metadataJsDir =
    //                Option.builder("js")
    //                        .required(true)
    //                        .hasArg()
    //                        .longOpt("jsdir")
    //                        .desc("Base metadata javascript directory")
    //                      //  .type(File.class)  // test if this is a directory
    //                        .build();
    ;
    /* not needed.
    js read from classpath,
    metadata/js/Evaluator.js
    required to be on classpath.
    TODO: test if this works in/on a jar, if not might need to test if
    running in a jar, and set appropriate resource location
     */
    Option metadataFile = Option.builder("md").required(true).hasArg().longOpt("metdatafile")
            .desc("Metadata File")
            // .type(File.class)
            .build();
    ;

    Option verbose = Option.builder("v").required(false)

            .longOpt("verboase").build();
    ;

    Options options = new Options();
    options.addOption(help);
    //options.addOption(metadataJsDir);
    options.addOption(metadataFile);
    ;
    options.addOption(verbose);
    ;
    // create the parser
    CommandLineParser parser = new DefaultParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        Boolean v = line.hasOption("v");

        String mds = line.getOptionValue("md");
        File md = new File(mds);

        if (!md.isFile())
            System.err.println("Md Metadata must be a file");

        testScriptEvaluator(md, v);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    } catch (Exception ex) {
        System.err.println("Metadata Evaluation Failed.  Reason: " + ex.getMessage());
    }

}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoCreator.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/* w  w  w.j av a  2s  .c o  m*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));

        String outputDir = commandLine.getOptionValue(OUT);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        EmbeddedCDOServer server = new EmbeddedCDOServer(outputDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            transaction.getRootResource().getContents().clear();
            LOG.log(Level.INFO, "Start moving elements");
            transaction.getRootResource().getContents().addAll(sourceResource.getContents());
            LOG.log(Level.INFO, "End moving elements");
            LOG.log(Level.INFO, "Commiting");
            transaction.commit();
            LOG.log(Level.INFO, "Commit done");
            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:is.merkor.statistics.cli.Main.java

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

    CommandLineParser parser = new GnuParser();
    try {/*from  w  w  w. j  av a2s .  c  o m*/
        MerkorCommandLineOptions.createOptions();
        processCommandLine(parser.parse(MerkorCommandLineOptions.options, args));
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
    }
}

From source file:net.mybox.mybox.ServerSetup.java

/**
 * Handle command line arguments/*from  w ww  . ja va 2 s  .  co  m*/
 * @param args
 */
public static void main(String[] args) {

    Options options = new Options();
    options.addOption("a", "apphome", true, "application home directory");
    options.addOption("h", "help", false, "show help screen");
    options.addOption("V", "version", false, "print the Mybox version");

    CommandLineParser line = new GnuParser();
    CommandLine cmd = null;

    try {
        cmd = line.parse(options, args);
    } catch (Exception exp) {
        System.err.println(exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Server.class.getName(), options);
        return;
    }

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Server.class.getName(), options);
        return;
    }

    if (cmd.hasOption("V")) {
        Server.printMessage("version " + Common.appVersion);
        return;
    }

    if (cmd.hasOption("a")) {
        String appHomeDir = cmd.getOptionValue("a");
        try {
            Common.updatePaths(appHomeDir);
        } catch (FileNotFoundException e) {
            Server.printErrorExit(e.getMessage());
        }

        Server.updatePaths();
    }

    ServerSetup setup = new ServerSetup();
}

From source file:com.continuuity.loom.runtime.DummyProvisioner.java

public static void main(final String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "host", true, "Loom server to connect to");
    options.addOption("p", "port", true, "Loom server port to connect to");
    options.addOption("c", "concurrency", true, "default concurrent threads");
    options.addOption("f", "failurePercent", true, "% of the time a provisioner should fail its task");
    options.addOption("o", "once", false, "whether or not only one task should be taken before exiting");
    options.addOption("d", "taskDuration", true, "number of milliseconds it should take to finish a task");
    options.addOption("s", "sleepMs", true,
            "number of milliseconds a thread will sleep before taking another task");
    options.addOption("n", "numTasks", true,
            "number of tasks to try and take from the queue.  Default is infinite.");
    options.addOption("t", "tenant", true, "tenant id to use.");

    try {//from   www  . j  ava  2  s  .c o  m
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);
        host = cmd.hasOption('h') ? cmd.getOptionValue('h') : "localhost";
        port = cmd.hasOption('p') ? Integer.valueOf(cmd.getOptionValue('p')) : 55054;
        concurrency = cmd.hasOption('c') ? Integer.valueOf(cmd.getOptionValue('c')) : 5;
        failurePercent = cmd.hasOption('f') ? Integer.valueOf(cmd.getOptionValue('f')) : 0;
        runOnce = cmd.hasOption('o');
        taskMs = cmd.hasOption('d') ? Long.valueOf(cmd.getOptionValue('d')) : 1000;
        sleepMs = cmd.hasOption('s') ? Long.valueOf(cmd.getOptionValue('s')) : 1000;
        numTasks = cmd.hasOption('n') ? Integer.valueOf(cmd.getOptionValue('n')) : -1;
        tenant = cmd.hasOption('t') ? cmd.getOptionValue('t') : "loom";
    } catch (ParseException e) {
        LOG.error("exception parsing input arguments.", e);
        return;
    }
    if (concurrency < 1) {
        LOG.error("invalid concurrency level {}.", concurrency);
        return;
    }

    if (runOnce) {
        new Provisioner("dummy-0", tenant, host, port, failurePercent, taskMs, sleepMs, 1).runOnce();
    } else {
        LOG.info(String.format(
                "running with %d threads, connecting to %s:%d using tenant %s, with a failure rate of"
                        + "%d percent, task time of %d ms, and sleep time of %d ms between fetches",
                concurrency, host, port, tenant, failurePercent, taskMs, sleepMs));
        pool = Executors.newFixedThreadPool(concurrency);

        try {
            int tasksPerProvisioner = numTasks >= 0 ? numTasks / concurrency : -1;
            int extra = numTasks < 0 ? 0 : numTasks % concurrency;
            pool.execute(new Provisioner("dummy-0", tenant, host, port, failurePercent, taskMs, sleepMs,
                    tasksPerProvisioner + extra));
            for (int i = 1; i < concurrency; i++) {
                pool.execute(new Provisioner("dummy-" + i, tenant, host, port, failurePercent, taskMs, sleepMs,
                        tasksPerProvisioner));
            }
        } catch (Exception e) {
            LOG.error("Caught exception, shutting down now.", e);
            pool.shutdownNow();
        }
        pool.shutdown();
    }
}

From source file:com.google.endpoints.examples.bookstore.BookstoreClient.java

public static void main(String[] args) throws Exception {
    Options options = createOptions();/*from   ww w  .  jav  a  2  s .co m*/
    CommandLineParser parser = new DefaultParser();
    CommandLine params;
    try {
        params = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Invalid command line: " + e.getMessage());
        printUsage(options);
        return;
    }

    String address = params.getOptionValue("bookstore", DEFAULT_ADDRESS);
    String apiKey = params.getOptionValue("api_key");
    String authToken = params.getOptionValue("auth_token");
    String operation = params.getOptionValue("operation", "list");

    // Create gRPC stub.
    BookstoreGrpc.BookstoreBlockingStub bookstore = createBookstoreStub(address, apiKey, authToken);

    if ("list".equals(operation)) {
        listShelves(bookstore);
    } else if ("create".equals(operation)) {
        createShelf(bookstore);
    } else if ("enumerate".equals(operation)) {
        enumerate(bookstore);
    }
}

From source file:edu.gslis.ts.DumpThriftData.java

public static void main(String[] args) {
    try {/*from   w w w . j a v a2 s  . co m*/
        // Get the commandline options
        Options options = createOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        String in = cmd.getOptionValue("i");
        String sentenceParser = cmd.getOptionValue("p");
        String query = cmd.getOptionValue("q");
        String externalCollection = cmd.getOptionValue("e");

        // Get background statistics
        CollectionStats bgstats = new IndexBackedCollectionStats();
        bgstats.setStatSource(externalCollection);

        // Set query
        GQuery gquery = new GQuery();
        gquery.setText(query);
        gquery.setFeatureVector(new FeatureVector(query, null));

        // Setup the filter
        DumpThriftData f = new DumpThriftData();

        if (in != null) {
            File infile = new File(in);
            if (infile.isDirectory()) {
                for (File file : infile.listFiles()) {
                    if (file.isDirectory()) {
                        for (File filefile : file.listFiles()) {
                            System.err.println(filefile.getAbsolutePath());
                            f.filter(filefile, sentenceParser, gquery, bgstats);
                        }
                    } else {
                        System.err.println(file.getAbsolutePath());
                        f.filter(file, sentenceParser, gquery, bgstats);
                    }
                }
            } else
                System.err.println(infile.getAbsolutePath());
            f.filter(infile, sentenceParser, gquery, bgstats);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}