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

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

Introduction

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

Prototype

public String getOptionValue(char opt) 

Source Link

Document

Retrieve the argument, if any, of this option.

Usage

From source file:com.floragunn.searchguard.tools.Hasher.java

public static void main(final String[] args) {

    final Options options = new Options();
    final HelpFormatter formatter = new HelpFormatter();
    options.addOption(//from w  w  w.  j ava  2  s  . c  o  m
            Option.builder("p").argName("password").hasArg().desc("Cleartext password to hash").build());
    options.addOption(Option.builder("env").argName("name environment variable").hasArg()
            .desc("name environment variable to read password from").build());

    final CommandLineParser parser = new DefaultParser();
    try {
        final CommandLine line = parser.parse(options, args);

        if (line.hasOption("p")) {
            System.out.println(hash(line.getOptionValue("p").getBytes("UTF-8")));
        } else if (line.hasOption("env")) {
            final String pwd = System.getenv(line.getOptionValue("env"));
            if (pwd == null || pwd.isEmpty()) {
                throw new Exception("No environment variable '" + line.getOptionValue("env") + "' set");
            }
            System.out.println(hash(pwd.getBytes("UTF-8")));
        } else {
            final Console console = System.console();
            if (console == null) {
                throw new Exception("Cannot allocate a console");
            }
            final char[] passwd = console.readPassword("[%s]", "Password:");
            System.out.println(hash(new String(passwd).getBytes("UTF-8")));
        }
    } catch (final Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("hasher.sh", options, true);
        System.exit(-1);
    }
}

From source file:com.twitter.bazel.checkstyle.PythonCheckstyle.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file")
            .desc("bazel extra action protobuf file").build());
    options.addOption(Option.builder("p").required(true).hasArg().longOpt("pylint_file")
            .desc("Executable pylint file to invoke").build());

    try {/*from   w  ww.  j a v a2s .  c  o  m*/
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        String extraActionFile = line.getOptionValue("f");
        String pylintFile = line.getOptionValue("p");

        Collection<String> sourceFiles = getSourceFiles(extraActionFile);
        if (sourceFiles.size() == 0) {
            LOG.info("No python files found by checkstyle");
            return;
        }

        LOG.info(sourceFiles.size() + " python files found by checkstyle");

        // Create and run the command
        List<String> commandBuilder = new ArrayList<>();
        commandBuilder.add(pylintFile);
        commandBuilder.addAll(sourceFiles);
        runLinter(commandBuilder);

    } catch (ParseException exp) {
        LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage()));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + CLASSNAME, options);
    }
}

From source file:com.yahoo.athenz.example.zms.tls.client.ZMSTLSClient.java

public static void main(String[] args) {

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    final String resource = cmd.getOptionValue("resource").toLowerCase();
    final String action = cmd.getOptionValue("action").toLowerCase();
    final String principal = cmd.getOptionValue("principal").toLowerCase();
    final String zmsUrl = cmd.getOptionValue("zmsurl");
    final String keyPath = cmd.getOptionValue("key");
    final String certPath = cmd.getOptionValue("cert");
    final String trustStorePath = cmd.getOptionValue("trustStorePath");
    final String trustStorePassword = cmd.getOptionValue("trustStorePassword");

    // we are going to setup our service private key and
    // certificate into a ssl context that we can use with
    // our zms client

    try {//from ww  w. j ava  2  s.c  o  m
        KeyRefresher keyRefresher = Utils.generateKeyRefresher(trustStorePath, trustStorePassword, certPath,
                keyPath);
        SSLContext sslContext = Utils.buildSSLContext(keyRefresher.getKeyManagerProxy(),
                keyRefresher.getTrustManagerProxy());

        try (ZMSClient zmsClient = new ZMSClient(zmsUrl, sslContext)) {
            try {
                Access access = zmsClient.getAccess(action, resource, null, principal);
                System.out.println("Access: " + access.getGranted());
            } catch (ZMSClientException ex) {
                System.out.println("Unable to carry out access check: " + ex.getMessage());
                System.exit(2);
            }
        }
    } catch (Exception ex) {
        System.out.println("Exception: " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:com.damon.rocketmq.example.operation.Producer.java

public static void main(String[] args) throws MQClientException, InterruptedException {
    CommandLine commandLine = buildCommandline(args);
    if (commandLine != null) {
        String group = commandLine.getOptionValue('g');
        String topic = commandLine.getOptionValue('t');
        String tags = commandLine.getOptionValue('a');
        String keys = commandLine.getOptionValue('k');
        String msgCount = commandLine.getOptionValue('c');

        DefaultMQProducer producer = new DefaultMQProducer(group);
        producer.setInstanceName(Long.toString(System.currentTimeMillis()));

        producer.start();//www . ja  v a 2s  .  c o  m

        for (int i = 0; i < Integer.parseInt(msgCount); i++) {
            try {
                Message msg = new Message(topic, tags, keys,
                        ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.send(msg);
                System.out.printf("%-8d %s%n", i, sendResult);
            } catch (Exception e) {
                e.printStackTrace();
                Thread.sleep(1000);
            }
        }

        producer.shutdown();
    }
}

From source file:com.hurence.logisland.runner.SparkJobLauncher.java

/**
 * main entry point/*from w ww . j  a  va2 s.  com*/
 *
 * @param args
 */
public static void main(String[] args) {

    logger.info("starting StreamProcessingRunner");

    //////////////////////////////////////////
    // Commande lien management
    Parser parser = new GnuParser();
    Options options = new Options();

    String helpMsg = "Print this message.";
    Option help = new Option("help", helpMsg);
    options.addOption(help);

    OptionBuilder.withArgName(AGENT);
    OptionBuilder.withLongOpt("agent-quorum");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("logisland agent quorum like host1:8081,host2:8081");
    Option agent = OptionBuilder.create(AGENT);
    options.addOption(agent);

    OptionBuilder.withArgName(JOB);
    OptionBuilder.withLongOpt("job-name");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("logisland agent quorum like host1:8081,host2:8081");
    Option job = OptionBuilder.create(JOB);
    options.addOption(job);

    String logisland = "                      \n"
            + "     ????????   ?????     ??  ??\n"
            + "                    \n"
            + "             ????     ??  \n"
            + "??     ?\n"
            + "??????? ??????  ??????   ??????????????????  ????  ??????????   v0.10.0-SNAPSHOT\n\n\n";

    System.out.println(logisland);
    Optional<EngineContext> engineInstance = Optional.empty();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String agentQuorum = line.getOptionValue(AGENT);
        String jobName = line.getOptionValue(JOB);

        // instanciate engine and all the processor from the config
        engineInstance = new RestComponentFactory(agentQuorum).getEngineContext(jobName);
        assert engineInstance.isPresent();
        assert engineInstance.get().isValid();

        logger.info("starting Logisland session version {}", engineInstance.get());
    } catch (Exception e) {
        logger.error("unable to launch runner : {}", e.toString());
    }

    try {
        // start the engine
        EngineContext engineContext = engineInstance.get();
        engineInstance.get().getEngine().start(engineContext);
    } catch (Exception e) {
        logger.error("something went bad while running the job : {}", e);
        System.exit(-1);
    }

}

From source file:edu.wisc.my.portlets.dmp.tools.XmlMenuPublisherRunner.java

public static void main(String[] args) throws MalformedURLException {
    final CommandLine line = parseCommandLine(args);
    if (line == null)
        return;/*from  www. j  av a 2s  . c om*/

    final String xmlFile = line.getOptionValue(XML_FILE_OPT);
    final URL xmlFileUrl = new File(xmlFile).toURL();

    final XmlMenuPublisher publisher = new XmlMenuPublisher();
    publisher.publishMenus(xmlFileUrl);
}

From source file:net.robyf.dbpatcher.Launcher.java

public static void main(final String[] args) throws DBPatcherException { //NOSONAR
    Options options = new Options();

    Option usernameOption = new Option("u", "username", true, "Database username");
    usernameOption.setRequired(true);/* w  ww  .  j  a v  a2  s . c  o  m*/
    options.addOption(usernameOption);
    Option passwordOption = new Option("p", "password", true, "Database password");
    passwordOption.setRequired(true);
    options.addOption(passwordOption);
    Option databaseOption = new Option("d", "databaseName", true, "Database name");
    databaseOption.setRequired(true);
    options.addOption(databaseOption);
    options.addOption("r", "rollback-if-error", false, "Rolls back the entire operation in case of errors");
    options.addOption("v", "to-version", true, "Target version number");
    options.addOption("s", "simulation", false, "Simulate the operation without touching the current database");
    options.addOption("c", "character-set", true, "Character set (default value: ISO-8859-1)");

    Parameters parameters = new Parameters();
    boolean showHelp = false;
    try {
        CommandLine commandLine = new PosixParser().parse(options, args);

        parameters.setUsername(commandLine.getOptionValue("u"));
        parameters.setPassword(commandLine.getOptionValue("p"));
        parameters.setDatabaseName(commandLine.getOptionValue("d"));

        parameters.setRollbackIfError(commandLine.hasOption("r"));
        parameters.setSimulationMode(commandLine.hasOption("s"));
        if (commandLine.hasOption("v")) {
            parameters.setTargetVersion(new Long(commandLine.getOptionValue("v")));
        }
        if (commandLine.hasOption("c")) {
            parameters.setCharset(Charset.forName(commandLine.getOptionValue("c")));
        }

        if (commandLine.getArgs().length == 1) {
            parameters.setSchemaPath(commandLine.getArgs()[0]);
        } else {
            showHelp = true;
        }
    } catch (ParseException pe) {
        showHelp = true;
    }

    if (showHelp) {
        new HelpFormatter().printHelp("java -jar dbpatcher.jar" + " -u username -p password -d database_name"
                + " [options] schema_root", "Available options:", options, "");
    } else {
        DBPatcherFactory.getDBPatcher().patch(parameters);
    }
}

From source file:edu.cuhk.hccl.cmd.AppQueryExpander.java

public static void main(String[] args) {

    try {/*from  w w w  .  j  a  v a  2s. c om*/

        CommandLineParser parser = new BasicParser();
        Options options = createOptions();
        CommandLine line = parser.parse(options, args);

        // Get parameters
        String queryStr = line.getOptionValue('q');
        int topK = Integer.parseInt(line.getOptionValue('k'));
        String modelPath = line.getOptionValue('m');
        String queryType = line.getOptionValue('t');

        QueryExpander expander = null;
        if (queryType.equalsIgnoreCase("WordVector")) {
            // Load word vectors
            System.out.println("[INFO] Loading word vectors...");
            expander = new WordVectorExpander(modelPath);
        } else if (queryType.equalsIgnoreCase("WordNet")) {
            // Load WordNet
            System.out.println("[INFO] Loading WordNet...");
            expander = new WordNetExpander(modelPath);
        } else {
            System.out.println("Please choose a correct expander: WordNet or WordVector!");
            System.exit(-1);
        }

        // Expand query
        System.out.println("[INFO] Computing similar words...");
        List<String> terms = expander.expandQuery(queryStr, topK);

        System.out.println(String.format("\n[INFO] The top %d similar words are: ", topK));
        for (String term : terms) {
            System.out.println(term);
        }

    } catch (ParseException exp) {
        System.out.println("Error in parameters: \n" + exp.getMessage());
        System.exit(-1);

    }
}

From source file:edu.indiana.d2i.sloan.internal.StopVMSimulator.java

public static void main(String[] args) {
    StopVMSimulator simulator = new StopVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {/*from  ww w.jav  a  2  s  . co  m*/
        CommandLine line = simulator.parseCommandLine(parser, args);
        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // cannot stop VM when it is not running
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.RUNNING)) {
            logger.error("Cannot perform stop when VM is not running");
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_RUNNING));
        }

        // stop VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update VM status file, i.e. set state to shutdown
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.SHUTDOWN.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);

    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }

}

From source file:com.linkedin.helix.mock.storage.MockStorageProcess.java

public static void main(String[] args) throws Exception {
    String clusterName = "storage-cluster";
    String relayClusterName = "relay-cluster";
    String zkServerAddress = "localhost:2181";
    String host = "localhost";
    int port = 8900;
    if (args.length > 0) {
        CommandLine cmd = processCommandLineArgs(args);
        zkServerAddress = cmd.getOptionValue(zkServer);
        clusterName = cmd.getOptionValue(cluster);
        relayClusterName = cmd.getOptionValue(relayCluster);
        host = cmd.getOptionValue(hostAddress);
        String portString = cmd.getOptionValue(hostPort);
        port = Integer.parseInt(portString);
    }/*from   w  w  w  . j a v a  2  s.co  m*/
    // Espresso_driver.py will consume this
    System.out.println("Mock storage started");
    MockStorageProcess process = new MockStorageProcess();
    process.start(host + "_" + port, zkServerAddress, clusterName, relayClusterName);

    Thread.sleep(10000000);
}