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

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

Introduction

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

Prototype

public String[] getOptionValues(char opt) 

Source Link

Document

Retrieves the array of values, if any, of an option.

Usage

From source file:com.trsst.Command.java

public int doPost(Client client, CommandLine commands, LinkedList<String> arguments, PrintStream out,
        InputStream in) {//from  w ww.  ja  va 2  s . c o m

    String id = null;

    if (arguments.size() == 0 && commands.getArgList().size() == 0) {
        printPostUsage();
        return 127; // "command not found"
    }

    if (arguments.size() > 0) {
        id = arguments.removeFirst();
        System.err.println("Obtaining keys for feed id: " + id);
    } else {
        System.err.println("Generating new feed id... ");
    }

    // read input text
    String subject = commands.getOptionValue("s");
    String verb = commands.getOptionValue("v");
    String base = commands.getOptionValue("b");
    String body = commands.getOptionValue("c");
    String name = commands.getOptionValue("n");
    String email = commands.getOptionValue("m");
    String uri = commands.getOptionValue("uri");
    String title = commands.getOptionValue("t");
    String subtitle = commands.getOptionValue("subtitle");
    String icon = commands.getOptionValue("i");
    if (icon == null && commands.hasOption("i")) {
        icon = "-";
    }
    String logo = commands.getOptionValue("l");
    if (logo == null && commands.hasOption("l")) {
        logo = "-";
    }
    String attach = commands.getOptionValue("a");
    if (attach == null && commands.hasOption("a")) {
        attach = "-";
    }
    String[] recipients = commands.getOptionValues("e");
    String[] mentions = commands.getOptionValues("r");
    String[] tags = commands.getOptionValues("g");
    String url = commands.getOptionValue("u");
    String vanity = commands.getOptionValue("vanity");

    // obtain password
    char[] password = null;
    String pass = commands.getOptionValue("p");
    if (pass != null) {
        password = pass.toCharArray();
    } else {
        try {
            Console console = System.console();
            if (console != null) {
                password = console.readPassword("Password: ");
            } else {
                log.info("No console detected for password input.");
            }
        } catch (Throwable t) {
            log.error("Unexpected error while reading password", t);
        }
    }
    if (password == null) {
        log.error("Password is required to post.");
        return 127; // "command not found"
    }
    if (password.length < 6) {
        System.err.println("Password must be at least six characters in length.");
        return 127; // "command not found"
    }

    // obtain keys
    KeyPair signingKeys = null;
    KeyPair encryptionKeys = null;
    String keyPath = commands.getOptionValue("k");

    // if id was not specified from the command line
    if (id == null) {

        // if password was not specified from command line
        if (pass == null) {
            try {
                // verify password
                char[] verify = null;
                Console console = System.console();
                if (console != null) {
                    verify = console.readPassword("Re-type Password: ");
                } else {
                    log.info("No console detected for password verification.");
                }
                if (verify == null || verify.length != password.length) {
                    System.err.println("Passwords do not match.");
                    return 127; // "command not found"
                }
                for (int i = 0; i < verify.length; i++) {
                    if (verify[i] != password[i]) {
                        System.err.println("Passwords do not match.");
                        return 127; // "command not found"
                    }
                    verify[i] = 0;
                }
            } catch (Throwable t) {
                log.error("Unexpected error while verifying password: " + t.getMessage(), t);
            }
        }

        // create new account
        if (base == null) {
            // default to trsst hub
            base = "https://home.trsst.com/feed";
        }

        // generate vanity id if required
        if (vanity != null) {
            System.err.println("Searching for vanity feed id prefix: " + vanity);
            switch (vanity.length()) {
            case 0:
            case 1:
                break;
            case 2:
                System.err.println("This may take several minutes.");
                break;
            case 3:
                System.err.println("This may take several hours.");
                break;
            case 4:
                System.err.println("This may take several days.");
                break;
            case 5:
                System.err.println("This may take several months.");
                break;
            default:
                System.err.println("This may take several years.");
                break;
            }
            System.err.println("Started: " + new Date());
            System.err.println("^C to exit");
        }
        do {
            signingKeys = Common.generateSigningKeyPair();
            id = Common.toFeedId(signingKeys.getPublic());
        } while (vanity != null && !id.startsWith(vanity));
        if (vanity != null) {
            System.err.println("Finished: " + new Date());
        }

        encryptionKeys = Common.generateEncryptionKeyPair();
        System.err.println("New feed id created: " + id);

        File keyFile;
        if (keyPath != null) {
            keyFile = new File(keyPath, id + Common.KEY_EXTENSION);
        } else {
            keyFile = new File(Common.getClientRoot(), id + Common.KEY_EXTENSION);
        }

        // persist to keystore
        writeSigningKeyPair(signingKeys, id, keyFile, password);
        writeEncryptionKeyPair(encryptionKeys, id, keyFile, password);

    } else {

        File keyFile;
        if (keyPath != null) {
            keyFile = new File(Common.getClientRoot(), keyPath);
        } else {
            keyFile = new File(Common.getClientRoot(), id + Common.KEY_EXTENSION);
        }

        if (keyFile.exists()) {
            System.err.println("Using existing account id: " + id);

        } else {
            System.err.println("Cannot locate keys for account id: " + id);
            return 78; // "configuration error"
        }

        signingKeys = readSigningKeyPair(id, keyFile, password);
        if (signingKeys != null) {
            encryptionKeys = readEncryptionKeyPair(id, keyFile, password);
            if (encryptionKeys == null) {
                encryptionKeys = signingKeys;
            }
        }
    }

    // clear password chars
    for (int i = 0; i < password.length; i++) {
        password[i] = 0;
    }
    if (signingKeys == null) {
        System.err.println("Could not obtain keys for signing.");
        return 73; // "can't create output error"
    }

    String[] recipientIds = null;
    if (recipients != null) {
        LinkedList<String> keys = new LinkedList<String>();
        for (int i = 0; i < recipients.length; i++) {
            if ("-".equals(recipients[i])) {
                // "-" is shorthand for encrypt for mentioned ids
                if (mentions != null) {
                    for (String mention : mentions) {
                        if (Common.isFeedId(mention)) {
                            keys.add(mention);
                        }
                    }
                }
            } else if (Common.isFeedId(recipients[i])) {
                keys.add(recipients[i]);
            } else {
                log.warn("Could not parse recipient id: " + recipients[i]);
            }
        }
        recipientIds = keys.toArray(new String[0]);
    }

    // handle binary attachment
    String mimetype = null;
    byte[] attachment = null;
    if (attach != null) {
        InputStream input = null;
        try {
            if ("-".equals(attach)) {
                input = new BufferedInputStream(in);
            } else {
                File file = new File(attach);
                input = new BufferedInputStream(new FileInputStream(file));
                System.err.println("Attaching: " + file.getCanonicalPath());
            }
            attachment = Common.readFully(input);
            mimetype = new Tika().detect(attachment);
            System.err.println("Detected type: " + mimetype);
        } catch (Throwable t) {
            log.error("Could not read attachment: " + attach, t);
            return 73; // "can't create output error"
        } finally {
            try {
                input.close();
            } catch (IOException ioe) {
                // suppress any futher error on closing
            }
        }
    }

    Object result;
    try {
        EntryOptions options = new EntryOptions();
        options.setStatus(subject);
        options.setVerb(verb);
        if (mentions != null) {
            options.setMentions(mentions);
        }
        if (tags != null) {
            options.setTags(tags);
        }
        options.setBody(body);
        if (attachment != null) {
            options.addContentData(attachment, mimetype);
        } else if (url != null) {
            options.setContentUrl(url);
        }
        FeedOptions feedOptions = new FeedOptions();
        feedOptions.setAuthorEmail(email);
        feedOptions.setAuthorName(name);
        feedOptions.setAuthorUri(uri);
        feedOptions.setTitle(title);
        feedOptions.setSubtitle(subtitle);
        feedOptions.setBase(base);
        if (icon != null) {
            if ("-".equals(icon)) {
                feedOptions.setAsIcon(true);
            } else {
                feedOptions.setIconURL(icon);
            }
        }
        if (logo != null) {
            if ("-".equals(logo)) {
                feedOptions.setAsLogo(true);
            } else {
                feedOptions.setLogoURL(logo);
            }
        }
        if (recipientIds != null) {
            EntryOptions publicEntry = new EntryOptions().setStatus("Encrypted content").setVerb("encrypt");
            // TODO: add duplicate mentions to outside of envelope
            options.encryptFor(recipientIds, publicEntry);
        }
        result = client.post(signingKeys, encryptionKeys, options, feedOptions);
    } catch (IllegalArgumentException e) {
        log.error("Invalid request: " + id + " : " + e.getMessage(), e);
        return 76; // "remote error"
    } catch (IOException e) {
        log.error("Error connecting to service for id: " + id, e);
        return 76; // "remote error"
    } catch (org.apache.abdera.security.SecurityException e) {
        log.error("Error generating signatures for id: " + id, e);
        return 73; // "can't create output error"
    } catch (Exception e) {
        log.error("General security error for id: " + id, e);
        return 74; // "general io error"
    }

    if (result != null) {
        if (format) {
            out.println(Common.formatXML(result.toString()));
        } else {
            out.println(result.toString());
        }
    }

    return 0; // "OK"
}

From source file:com.liferay.jenkins.tools.JenkinsStatus.java

private void processArgs(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();

    Options options = new Options();

    options.addOption("m", "dry-run", false, "Does not fetch remote resources");
    options.addOption("c", "building", true, "Filter build by build state");
    options.addOption("d", "debug", false, "Set logging level to debug");
    options.addOption("f", "file", true, "Path to Jenkins servers list");
    options.addOption("h", "aliases", true, "Path to aliases file");
    options.addOption("i", "info", false, "Set logging level to info");
    options.addOption("n", "name", true, "Filter job by exact name");
    options.addOption("r", "result", true, "Filter build by result");
    options.addOption("u", "user", true, "Username used in authentication");

    options.addOption(Option.builder().longOpt("list-jobs").desc("List matching jobs").build());
    options.addOption(Option.builder().longOpt("name-contains").hasArg()
            .desc("Filter job by name containing specified string").build());
    options.addOption(Option.builder().longOpt("name-regex").hasArg()
            .desc("Filter job by name matching specified regular expression").build());
    options.addOption(Option.builder("p").longOpt("parameters").hasArgs().desc("Filter build by parameters")
            .valueSeparator(',').build());
    options.addOption(// w ww .j ava 2s  .c  o m
            Option.builder("b").longOpt("before").hasArgs().desc("Filter build before specified time").build());
    options.addOption(
            Option.builder("a").longOpt("after").hasArgs().desc("Filter builds after specified time").build());
    options.addOption(Option.builder("s").longOpt("between").hasArgs()
            .desc("Filter builds between two specified UNIX timestamps").build());
    options.addOption(Option.builder("e").longOpt("equals").hasArgs()
            .desc("Filter builds with specific duration").build());
    options.addOption(
            Option.builder("l").longOpt("less").hasArgs().desc("Filter builds less than the duration").build());
    options.addOption(Option.builder("g").longOpt("greater").hasArgs()
            .desc("Filter builds greater than the duration").build());
    options.addOption(Option.builder().longOpt("console-contains").hasArgs()
            .desc("Filter build by matching console text").build());

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

    if (line.hasOption("dry-run")) {
        dryRun = true;
    }

    if (line.hasOption("list-jobs")) {
        listJobs = true;
    }

    if (line.hasOption("info")) {
        Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(Level.INFO);

        showBuildInfo = true;
    }

    if (line.hasOption("debug")) {
        Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(Level.DEBUG);

        showBuildInfo = true;
    }

    if (line.hasOption("file")) {
        logger.debug("Loading file {}", line.getOptionValue("f"));

        serversListFile = new File(line.getOptionValue("f"));
    }

    if (line.hasOption("aliases")) {
        logger.debug("Loading file {}", line.getOptionValue("h"));

        aliasesFile = new File(line.getOptionValue("h"));
    }

    if (line.hasOption("user")) {
        Console console = System.console();

        if (console == null) {
            throw new IllegalStateException("Unable to get Console instance");
        }

        String username = line.getOptionValue("u");
        String password = new String(console.readPassword("Enter password for " + username + " :"));

        if (aliasesFile.isFile()) {
            jsonGetter = new RemoteJsonGetter(username, password, REQUEST_TIMEOUT, aliasesFile);
        } else {
            jsonGetter = new RemoteJsonGetter(username, password, REQUEST_TIMEOUT);
        }
    } else if (aliasesFile.isFile()) {
        jsonGetter = new LocalJsonGetter(REQUEST_TIMEOUT, aliasesFile);
    }

    if (line.hasOption("name")) {
        jobMatchers.add(new NameEqualsMatcher(line.getOptionValue("name")));
    }

    if (line.hasOption("name-contains")) {
        jobMatchers.add(new NameContainsMatcher(line.getOptionValue("name-contains")));
    }

    if (line.hasOption("name-regex")) {
        jobMatchers.add(new NameRegexMatcher(line.getOptionValue("name-regex")));
    }

    if (line.hasOption("building")) {
        buildMatchers.add(new BuildingMatcher(line.getOptionValue("c")));
    }

    if (line.hasOption("parameters")) {
        buildMatchers.add(new ParametersMatcher(line.getOptionValues("p")));
    }

    if (line.hasOption("result")) {
        buildMatchers.add(new ResultMatcher(line.getOptionValue("r")));
    }

    if (line.hasOption("before")) {
        buildMatchers.add(new BeforeTimestampMatcher(line.getOptionValues("b")));
    }

    if (line.hasOption("after")) {
        buildMatchers.add(new AfterTimestampMatcher(line.getOptionValues("a")));
    }

    if (line.hasOption("between")) {
        buildMatchers.add(new BetweenTimestampsMatcher(line.getOptionValues("s")));
    }

    if (line.hasOption("greater")) {
        buildMatchers.add(new GreaterThanDurationMatcher(line.getOptionValues("g")));
    }

    else if (line.hasOption("less")) {
        buildMatchers.add(new LessThanDurationMatcher(line.getOptionValues("l")));
    }

    if (line.hasOption("console-contains")) {
        buildMatchers.add(new ConsoleContainsMatcher(jsonGetter, line.getOptionValues("console-contains")));
    }
}

From source file:de.dal33t.powerfolder.Controller.java

/**
 * Starts a config with the given command line arguments
 *
 * @param aCommandLine/*from   ww w .  j av  a 2 s .c o m*/
 *            the command line as specified by the user
 */
public void startConfig(CommandLine aCommandLine) {
    commandLine = aCommandLine;
    String[] configNames = aCommandLine.getOptionValues("c");
    String configName = configNames != null && configNames.length > 0 && StringUtils.isNotBlank(configNames[0])
            ? configNames[0]
            : null;
    if (StringUtils.isNotBlank(configName)
            && (configName.startsWith("http:") || configName.startsWith("https:"))) {
        if (configNames.length > 1) {
            configName = configNames[1];
        } else {
            configName = Constants.DEFAULT_CONFIG_FILE;
        }
    }
    startConfig(configName);
}

From source file:cn.edu.buaa.act.petuumOnYarn.Client.java

/**
 * Parse command line options//from   w w w.ja  v  a 2  s  .  c o m
 * 
 * @param args
 *            Parsed command line options
 * @return Whether the init was successful to run the client
 * @throws ParseException
 */
public boolean init(String[] args) throws ParseException {

    CommandLine cliParser = new GnuParser().parse(opts, args);

    if (args.length == 0) {
        throw new IllegalArgumentException("No args specified for client to initialize");
    }

    if (cliParser.hasOption("log_properties")) {
        String log4jPath = cliParser.getOptionValue("log_properties");
        try {
            Log4jPropertyHelper.updateLog4jConfiguration(Client.class, log4jPath);
        } catch (Exception e) {
            LOG.warn("Can not set up custom log4j properties. " + e);
        }
    }

    if (cliParser.hasOption("help")) {
        printUsage();
        return false;
    }

    if (cliParser.hasOption("debug")) {
        debugFlag = true;

    }

    if (cliParser.hasOption("keep_containers_across_application_attempts")) {
        LOG.info("keep_containers_across_application_attempts");
        keepContainers = true;
    }

    appName = cliParser.getOptionValue("app_name", "Petuum");
    startPort = Integer.parseInt(cliParser.getOptionValue("start_port", "9999"));
    amPriority = Integer.parseInt(cliParser.getOptionValue("priority", "10"));
    amQueue = cliParser.getOptionValue("queue", "default");
    amMemory = Integer.parseInt(cliParser.getOptionValue("master_memory", "500"));
    amVCores = Integer.parseInt(cliParser.getOptionValue("master_vcores", "1"));
    numNodes = Integer.parseInt(cliParser.getOptionValue("num_nodes", "1"));
    petuumHDFSPathPrefix = cliParser.getOptionValue("hdfs_path_prefix", "petuum/");

    if (amMemory < 0) {
        throw new IllegalArgumentException(
                "Invalid memory specified for application master, exiting." + " Specified memory=" + amMemory);
    }
    if (amVCores < 0) {
        throw new IllegalArgumentException("Invalid virtual cores specified for application master, exiting."
                + " Specified virtual cores=" + amVCores);
    }

    if (!cliParser.hasOption("jar")) {
        throw new IllegalArgumentException("No jar file specified for application master");
    }

    appMasterJar = cliParser.getOptionValue("jar");

    scriptPath = cliParser.getOptionValue("launch_script_path");

    if (cliParser.hasOption("shell_env")) {
        String envs[] = cliParser.getOptionValues("shell_env");
        for (String env : envs) {
            env = env.trim();
            int index = env.indexOf('=');
            if (index == -1) {
                shellEnv.put(env, "");
                continue;
            }
            String key = env.substring(0, index);
            String val = "";
            if (index < (env.length() - 1)) {
                val = env.substring(index + 1);
            }
            shellEnv.put(key, val);
        }
    }
    workerPriority = Integer.parseInt(cliParser.getOptionValue("worker_priority", "10"));

    containerMemory = Integer.parseInt(cliParser.getOptionValue("container_memory", "1000"));
    containerVirtualCores = Integer.parseInt(cliParser.getOptionValue("container_vcores", "2"));
    if (containerMemory < 0 || containerVirtualCores < 0) {
        throw new IllegalArgumentException(
                "Invalid container memory/vcores specified," + " exiting." + " Specified containerMemory="
                        + containerMemory + ", containerVirtualCores=" + containerVirtualCores);
    }

    Long.parseLong(cliParser.getOptionValue("attempt_failures_validity_interval", "-1"));

    log4jPropFile = cliParser.getOptionValue("log_properties", "");

    return true;
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.sensitivity.Evaluator.java

@Override
public void run(CommandLine commandLine) throws IOException {
    File outputFile = new File(commandLine.getOptionValue("output"));
    File inputFile = new File(commandLine.getOptionValue("input"));

    ParameterFile parameterFile = new ParameterFile(new File(commandLine.getOptionValue("parameterFile")));

    // sanity check to ensure input hasn't been modified after the output
    if (!commandLine.hasOption("force") && (outputFile.lastModified() > 0L)
            && (inputFile.lastModified() > outputFile.lastModified())) {
        throw new FrameworkException("input appears to be newer than output");
    }/*from www  .j ava 2  s.  c  om*/

    // open the resources and begin processing
    try {
        problem = ProblemFactory.getInstance().getProblem(commandLine.getOptionValue("problem"));

        try {
            input = new SampleReader(new FileReader(inputFile), parameterFile);

            try {
                if (commandLine.hasOption("metrics")) {
                    NondominatedPopulation referenceSet = null;

                    // load reference set and create the quality indicator
                    if (commandLine.hasOption("reference")) {
                        referenceSet = new NondominatedPopulation(
                                PopulationIO.readObjectives(new File(commandLine.getOptionValue("reference"))));
                    } else {
                        referenceSet = ProblemFactory.getInstance()
                                .getReferenceSet(commandLine.getOptionValue("problem"));
                    }

                    if (referenceSet == null) {
                        throw new FrameworkException("no reference set available");
                    }

                    QualityIndicator indicator = new QualityIndicator(problem, referenceSet);

                    output = new MetricFileWriter(indicator, outputFile);
                } else {
                    output = new ResultFileWriter(problem, outputFile, !commandLine.hasOption("novariables"));
                }

                // resume at the last good output
                for (int i = 0; i < output.getNumberOfEntries(); i++) {
                    if (input.hasNext()) {
                        input.next();
                    } else {
                        throw new FrameworkException("output has more entries than input");
                    }
                }

                // setup any default parameters
                Properties defaultProperties = new Properties();

                if (commandLine.hasOption("properties")) {
                    for (String property : commandLine.getOptionValues("properties")) {
                        String[] tokens = property.split("=");

                        if (tokens.length == 2) {
                            defaultProperties.setProperty(tokens[0], tokens[1]);
                        } else {
                            throw new FrameworkException("malformed property argument");
                        }
                    }
                }

                if (commandLine.hasOption("epsilon")) {
                    defaultProperties.setProperty("epsilon", commandLine.getOptionValue("epsilon"));
                }

                // seed the pseudo-random number generator
                if (commandLine.hasOption("seed")) {
                    PRNG.setSeed(Long.parseLong(commandLine.getOptionValue("seed")));
                }

                // process the remaining runs
                while (input.hasNext()) {
                    Properties properties = input.next();
                    properties.putAll(defaultProperties);

                    process(commandLine.getOptionValue("algorithm"), properties);
                }
            } finally {
                if (output != null) {
                    output.close();
                }
            }
        } finally {
            if (input != null) {
                input.close();
            }
        }
    } finally {
        if (problem != null) {
            problem.close();
        }
    }
}

From source file:com.datatorrent.stram.cli.DTCli.java

static LaunchCommandLineInfo getLaunchCommandLineInfo(String[] args) throws ParseException {
    CommandLineParser parser = new PosixParser();
    LaunchCommandLineInfo result = new LaunchCommandLineInfo();
    CommandLine line = parser.parse(LAUNCH_OPTIONS.options, args);
    result.localMode = line.hasOption(LAUNCH_OPTIONS.local.getOpt());
    result.configFile = line.getOptionValue(LAUNCH_OPTIONS.configFile.getOpt());
    result.apConfigFile = line.getOptionValue(LAUNCH_OPTIONS.apConfigFile.getOpt());
    result.ignorePom = line.hasOption(LAUNCH_OPTIONS.ignorePom.getOpt());
    String[] defs = line.getOptionValues(LAUNCH_OPTIONS.defProperty.getOpt());
    if (defs != null) {
        result.overrideProperties = new HashMap<String, String>();
        for (String def : defs) {
            int equal = def.indexOf('=');
            if (equal < 0) {
                result.overrideProperties.put(def, null);
            } else {
                result.overrideProperties.put(def.substring(0, equal), def.substring(equal + 1));
            }//from   w ww.j av a 2s. c  o  m
        }
    }
    result.libjars = line.getOptionValue(LAUNCH_OPTIONS.libjars.getOpt());
    result.archives = line.getOptionValue(LAUNCH_OPTIONS.archives.getOpt());
    result.files = line.getOptionValue(LAUNCH_OPTIONS.files.getOpt());
    result.queue = line.getOptionValue(LAUNCH_OPTIONS.queue.getOpt());
    result.args = line.getArgs();
    result.origAppId = line.getOptionValue(LAUNCH_OPTIONS.originalAppID.getOpt());
    result.exactMatch = line.hasOption("exactMatch");
    result.force = line.hasOption("force");
    return result;
}

From source file:me.haosdent.noya.Client.java

/**
 * Parse command line options//from w  w  w . j a v  a 2  s. c o m
 *
 * @param args Parsed command line options
 *
 * @return Whether the init was successful to run the client
 *
 * @throws org.apache.commons.cli.ParseException
 */
public boolean init(String[] args) throws ParseException {

    CommandLine cliParser = new GnuParser().parse(opts, args);

    if (args.length == 0) {
        throw new IllegalArgumentException("No args specified for client to initialize");
    }

    if (cliParser.hasOption("help")) {
        printUsage();
        return false;
    }

    if (cliParser.hasOption("debug")) {
        debugFlag = true;

    }

    if (cliParser.hasOption("keep_containers_across_application_attempts")) {
        LOG.info("keep_containers_across_application_attempts");
        keepContainers = true;
    }

    appName = cliParser.getOptionValue("appname", "Noya");
    amPriority = Integer.parseInt(cliParser.getOptionValue("priority", "0"));
    amQueue = cliParser.getOptionValue("queue", "default");
    amMemory = Integer.parseInt(cliParser.getOptionValue("master_memory", "10"));
    amVCores = Integer.parseInt(cliParser.getOptionValue("master_vcores", "1"));

    if (amMemory < 0) {
        throw new IllegalArgumentException(
                "Invalid memory specified for application master, exiting." + " Specified memory=" + amMemory);
    }
    if (amVCores < 0) {
        throw new IllegalArgumentException("Invalid virtual cores specified for application master, exiting."
                + " Specified virtual cores=" + amVCores);
    }

    if (!cliParser.hasOption("jar")) {
        throw new IllegalArgumentException("No jar file specified for application master");
    }

    appMasterJar = cliParser.getOptionValue("jar");

    if (!cliParser.hasOption("shell_command") && !cliParser.hasOption("shell_script")) {
        throw new IllegalArgumentException(
                "No shell command or shell script specified to be executed by application master");
    } else if (cliParser.hasOption("shell_command") && cliParser.hasOption("shell_script")) {
        throw new IllegalArgumentException(
                "Can not specify shell_command option " + "and shell_script option at the same time");
    } else if (cliParser.hasOption("shell_command")) {
        shellCommand = cliParser.getOptionValue("shell_command");
    } else {
        shellScriptPath = cliParser.getOptionValue("shell_script");
    }
    if (cliParser.hasOption("shell_args")) {
        shellArgs = cliParser.getOptionValues("shell_args");
    }
    if (cliParser.hasOption("shell_env")) {
        String envs[] = cliParser.getOptionValues("shell_env");
        for (String env : envs) {
            env = env.trim();
            int index = env.indexOf('=');
            if (index == -1) {
                shellEnv.put(env, "");
                continue;
            }
            String key = env.substring(0, index);
            String val = "";
            if (index < (env.length() - 1)) {
                val = env.substring(index + 1);
            }
            shellEnv.put(key, val);
        }
    }
    shellCmdPriority = Integer.parseInt(cliParser.getOptionValue("shell_cmd_priority", "0"));

    containerMemory = Integer.parseInt(cliParser.getOptionValue("container_memory", "10"));
    containerVirtualCores = Integer.parseInt(cliParser.getOptionValue("container_vcores", "1"));
    numContainers = Integer.parseInt(cliParser.getOptionValue("num_containers", "1"));

    if (containerMemory < 0 || containerVirtualCores < 0 || numContainers < 1) {
        throw new IllegalArgumentException("Invalid no. of containers or container memory/vcores specified,"
                + " exiting." + " Specified containerMemory=" + containerMemory + ", containerVirtualCores="
                + containerVirtualCores + ", numContainer=" + numContainers);
    }

    clientTimeout = Integer.parseInt(cliParser.getOptionValue("timeout", "600000"));

    log4jPropFile = cliParser.getOptionValue("log_properties", "");

    return true;
}

From source file:com.googlecode.japi.checker.cli.Main.java

public int run() {
    System.out.println("japi-checker-cli " + getVersion() + " - https://code.google.com/p/japi-checker/");
    System.out.println("");
    boolean reportSourceIncompatibilities = true;
    // configuring the CLI options
    Options options = new Options();
    options.addOption("bin", false,
            "check only binary compatibility (default - source and binary compatibility)");
    options.addOption("rcp", true, "reference classpath.");
    options.addOption("cp", true, "classpath.");
    options.addOption("h", "help", false, "This help message.");

    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine = null;
    try {/*from  ww  w.  ja  v a2s . co m*/
        cmdLine = parser.parse(options, args);
        if (cmdLine.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(HELP_CMDLINE, getHeader(), options, null);
            return 0;
        }
        if (cmdLine.getArgs().length != 2) {
            throw new ParseException("Missing REFERENCE_LIBRARY and/or NEW_LIBRARY.");
        }
        if (cmdLine.hasOption("bin")) {
            reportSourceIncompatibilities = false;
        }
    } catch (ParseException e) {
        System.err.println("Error parsing command line: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(HELP_CMDLINE, getHeader(), options, null);
        return -1;
    }

    // proceeding of arguments
    /*
     * List<File> referenceClasspath = new ArrayList<File>(); List<File>
     * newArtifactClasspath = new ArrayList<File>(); List<AntPatternMatcher>
     * includes = new ArrayList<AntPatternMatcher>();
     * List<AntPatternMatcher> excludes = new
     * ArrayList<AntPatternMatcher>();
     */

    String referencePath = cmdLine.getArgs()[0];
    String newPath = cmdLine.getArgs()[1];
    File reference = new File(referencePath);
    File newArtifact = new File(newPath);
    if (!reference.isDirectory() && !Utils.isArchive(reference)) {
        try {
            FileObject fo = VFS.getManager().resolveFile(referencePath);
            reference = writeToTempFile(fo);
        } catch (FileSystemException e) {
            System.err.println("Error: " + e.getMessage() + " - reference can be either a directory"
                    + ", a jar (or a zip kind of archive) file, or a URL.");
            return -1;
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
            return -1;
        }
    }
    if (!newArtifact.isDirectory() && !Utils.isArchive(newArtifact)) {
        try {
            FileObject fo = VFS.getManager().resolveFile(newPath);
            newArtifact = writeToTempFile(fo);
        } catch (FileSystemException e) {
            System.err.println("Error: " + e.getMessage() + " - new artifact can be either a directory"
                    + ", a jar (or a zip kind of archive) file or a URL.");
            return -1;
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
            return -1;
        }
    }

    BCChecker checker = new BCChecker();

    // Populating the classpaths, reference and then for tested artifact.
    if (cmdLine.hasOption("rcp")) {
        for (String filename : cmdLine.getOptionValues("rcp")) {
            checker.addToReferenceClasspath(new File(filename));
        }
    }

    if (cmdLine.hasOption("cp")) {
        for (String filename : cmdLine.getOptionValues("cp")) {
            checker.addToNewArtifactClasspath(new File(filename));
        }
    }

    // checker initialization
    CLIReporter reporter = new CLIReporter();

    // checking
    // Load rules
    List<Rule> rules = new ArrayList<Rule>();
    if (reportSourceIncompatibilities) {
        rules.add(new CheckMethodVariableArity());
    } else {
        rules.add(new AllRules());
        rules.add(new CheckMethodVariableArity());
    }
    // Running the check...
    try {
        checker.setReporter(reporter);
        checker.setRules(rules);
        checker.checkBacwardCompatibility(reference, newArtifact);
        System.out.println("Error count: " + reporter.getCount(Severity.ERROR));
        System.out.println("Warning count: " + reporter.getCount(Severity.WARNING));
        if (reporter.getCount(Severity.ERROR) > 0) {
            return -1;
        }
    } catch (IOException e) {
        System.err.println("Error: " + e.getMessage());
        return -1;
    }
    return 0;
}

From source file:com.netcrest.pado.tools.pado.command.temporal.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/* w  ww  . java 2s.  co m*/
public void run(CommandLine commandLine, String command) throws Exception {
    boolean isLucene = commandLine.hasOption("lucene");
    boolean isEnable = commandLine.hasOption("enable");
    boolean isDisable = commandLine.hasOption("disable");
    boolean isAll = commandLine.hasOption("all");
    if (isAll && (isLucene == false && isEnable == false && isDisable == false)) {
        PadoShell.printlnError(this,
                "Invalid option. '-all' only applies to '-lucene', '-enable', and '-disable'.");
        return;
    }

    List<String> argList = (List<String>) commandLine.getArgList();

    if (isLucene || isEnable || isDisable) {

        // Build Lucene indexes

        // Parse [-all [-grid <grid ID>[,...]] | [<path>...]]
        String[] gridIds = PadoShellUtil.getGridIds(this, commandLine, true);
        if (gridIds == null) {
            return;
        }
        String fullPaths[] = PadoShellUtil.getFullPaths(padoShell, commandLine);
        if (PadoShellUtil.hasError(this, padoShell, fullPaths, true)) {
            return;
        }

        if (isLucene) {
            runLucene(gridIds, fullPaths);
        } else {
            setTemporalEnabled(isEnable, gridIds, fullPaths);
        }

    } else {

        // Execute temporal command
        String path;
        if (argList.size() == 1) {
            path = padoShell.getCurrentPath();
        } else {
            path = argList.get(1);
        }
        String fullPath = padoShell.getFullPath(path);
        String gridId = SharedCache.getSharedCache().getGridId(fullPath);
        String gridPath = GridUtil.getChildPath(fullPath);

        String fullPaths[] = PadoShellUtil.getFullPaths(padoShell, commandLine);
        if (fullPaths == null) {
            fullPaths = new String[] { fullPath };
        }
        if (PadoShellUtil.hasError(this, padoShell, fullPaths, false)) {
            return;
        }

        ITemporalBiz temporalBiz = SharedCache.getSharedCache().getPado().getCatalog()
                .newInstance(ITemporalBiz.class, gridPath);
        temporalBiz.getBizContext().getGridContextClient().setGridIds(gridId);
        temporalBiz.setGridPath(gridPath);
        rawFormat = false;
        if (commandLine.hasOption("put")) {
            runPut(temporalBiz, commandLine.getOptionValues("put"));
        } else if (commandLine.hasOption("putAttachments")) {
            runPutAttachments(temporalBiz, commandLine.getOptionValues("putAttachments"));
        } else if (commandLine.hasOption("get")) {
            runGet(temporalBiz, commandLine.getOptionValues("get"));
        } else if (commandLine.hasOption("getAttachments1")) {
            runGetAttachments1(temporalBiz, commandLine.getOptionValues("getAttachments1"));
        } else if (commandLine.hasOption("getAttachments2")) {
            runGetAttachments2(temporalBiz, commandLine.getOptionValues("getAttachments2"));
        } else if (commandLine.hasOption("getAttachments3")) {
            runGetAttachments3(temporalBiz, commandLine.getOptionValues("getAttachments3"));
        } else if (commandLine.hasOption("remove")) {
            runRemove(temporalBiz, commandLine.getOptionValues("remove"));
        } else if (commandLine.hasOption("history")) {
            if (commandLine.hasOption("rawformat")) {
                rawFormat = true;
            } else {
                rawFormat = false;
            }
            runHistory(temporalBiz, commandLine.getOptionValue("history"));
        } else {
            boolean isRefresh = commandLine.hasOption("-refresh");
            IScrollableResultSet srs = temporalBiz.getEntryResultSet(System.currentTimeMillis(), null, true,
                    padoShell.getFetchSize(), isRefresh);
            srs.setFetchSize(padoShell.getFetchSize());
            ResultSetDisplay.display(srs);
        }
    }
}

From source file:com.srini.hadoopYarn.ApplicationMaster.java

/**
 * Parse command line options/*w  w  w. j ava 2 s .  c o  m*/
 *
 * @param args Command line args
 * @return Whether init successful and run should be invoked
 * @throws ParseException
 * @throws IOException
 */
public boolean init(String[] args) throws ParseException, IOException {

    Options opts = new Options();
    opts.addOption("app_attempt_id", true, "App Attempt ID. Not to be used unless for testing purposes");
    opts.addOption("shell_command", true, "Shell command to be executed by the Application Master");
    opts.addOption("shell_script", true, "Location of the shell script to be executed");
    opts.addOption("shell_args", true, "Command line args for the shell script");
    opts.addOption("shell_env", true, "Environment for shell script. Specified as env_key=env_val pairs");
    opts.addOption("container_memory", true, "Amount of memory in MB to be requested to run the shell command");
    opts.addOption("num_containers", true, "No. of containers on which the shell command needs to be executed");
    opts.addOption("priority", true, "Application Priority. Default 0");
    opts.addOption("debug", false, "Dump out debug information");

    opts.addOption("help", false, "Print usage");
    CommandLine cliParser = new GnuParser().parse(opts, args);

    if (args.length == 0) {
        printUsage(opts);
        throw new IllegalArgumentException("No args specified for application master to initialize");
    }

    if (cliParser.hasOption("help")) {
        printUsage(opts);
        return false;
    }

    if (cliParser.hasOption("debug")) {
        dumpOutDebugInfo();
    }

    Map<String, String> envs = System.getenv();

    if (!envs.containsKey(Environment.CONTAINER_ID.name())) {
        if (cliParser.hasOption("app_attempt_id")) {
            String appIdStr = cliParser.getOptionValue("app_attempt_id", "");
            appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr);
        } else {
            throw new IllegalArgumentException("Application Attempt Id not set in the environment");
        }
    } else {
        ContainerId containerId = ConverterUtils.toContainerId(envs.get(Environment.CONTAINER_ID.name()));
        appAttemptID = containerId.getApplicationAttemptId();
    }

    if (!envs.containsKey(ApplicationConstants.APP_SUBMIT_TIME_ENV)) {
        throw new RuntimeException(ApplicationConstants.APP_SUBMIT_TIME_ENV + " not set in the environment");
    }
    if (!envs.containsKey(Environment.NM_HOST.name())) {
        throw new RuntimeException(Environment.NM_HOST.name() + " not set in the environment");
    }
    if (!envs.containsKey(Environment.NM_HTTP_PORT.name())) {
        throw new RuntimeException(Environment.NM_HTTP_PORT + " not set in the environment");
    }
    if (!envs.containsKey(Environment.NM_PORT.name())) {
        throw new RuntimeException(Environment.NM_PORT.name() + " not set in the environment");
    }

    LOG.info("Application master for app" + ", appId=" + appAttemptID.getApplicationId().getId()
            + ", clustertimestamp=" + appAttemptID.getApplicationId().getClusterTimestamp() + ", attemptId="
            + appAttemptID.getAttemptId());

    if (!cliParser.hasOption("shell_command")) {
        throw new IllegalArgumentException("No shell command specified to be executed by application master");
    }
    shellCommand = cliParser.getOptionValue("shell_command");

    if (cliParser.hasOption("shell_args")) {
        shellArgs = cliParser.getOptionValue("shell_args");
    }
    if (cliParser.hasOption("shell_env")) {
        String shellEnvs[] = cliParser.getOptionValues("shell_env");
        for (String env : shellEnvs) {
            env = env.trim();
            int index = env.indexOf('=');
            if (index == -1) {
                shellEnv.put(env, "");
                continue;
            }
            String key = env.substring(0, index);
            String val = "";
            if (index < (env.length() - 1)) {
                val = env.substring(index + 1);
            }
            shellEnv.put(key, val);
        }
    }

    if (envs.containsKey(DSConstants.DISTRIBUTEDSHELLSCRIPTLOCATION)) {
        shellScriptPath = envs.get(DSConstants.DISTRIBUTEDSHELLSCRIPTLOCATION);

        if (envs.containsKey(DSConstants.DISTRIBUTEDSHELLSCRIPTTIMESTAMP)) {
            shellScriptPathTimestamp = Long.valueOf(envs.get(DSConstants.DISTRIBUTEDSHELLSCRIPTTIMESTAMP));
        }
        if (envs.containsKey(DSConstants.DISTRIBUTEDSHELLSCRIPTLEN)) {
            shellScriptPathLen = Long.valueOf(envs.get(DSConstants.DISTRIBUTEDSHELLSCRIPTLEN));
        }

        if (!shellScriptPath.isEmpty() && (shellScriptPathTimestamp <= 0 || shellScriptPathLen <= 0)) {
            LOG.error("Illegal values in env for shell script path" + ", path=" + shellScriptPath + ", len="
                    + shellScriptPathLen + ", timestamp=" + shellScriptPathTimestamp);
            throw new IllegalArgumentException("Illegal values in env for shell script path");
        }
    }

    containerMemory = Integer.parseInt(cliParser.getOptionValue("container_memory", "10"));
    numTotalContainers = Integer.parseInt(cliParser.getOptionValue("num_containers", "1"));
    if (numTotalContainers == 0) {
        throw new IllegalArgumentException("Cannot run distributed shell with no containers");
    }
    requestPriority = Integer.parseInt(cliParser.getOptionValue("priority", "0"));

    return true;
}