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:gov.llnl.lc.smt.command.file.SmtFile.java

/**
 * Parse the command line options here.  If any of these need to be persistent
 * then they need to be "put" into the config map.  Otherwise the command line
 * options need to set "command" flags or variables, which will potentially be
 * used later, typically the "doCommand()".
 *
 * @see gov.llnl.lc.smt.command.SmtCommand#parseCommands(java.util.Map, org.apache.commons.cli.CommandLine)
 *
 * @param config//from   w  w w  .ja va  2  s  .c  o m
 * @param line
 * @return
 ***********************************************************/

@Override
public boolean parseCommands(Map<String, String> config, CommandLine line) {
    // set the command and sub-command
    config.put(SmtProperty.SMT_COMMAND.getName(), this.getClass().getName());

    // parse (only) the command specific options (see init() )

    // the command needs a filename as an argument
    saveCommandArgs(line.getArgs(), config);

    // only one of these will work at a time.  Since the INFO command is parsed
    // second, it will always take precedence if both are specified on the command
    // line.  (Subcommand and Values are over written).
    SmtProperty sp = SmtProperty.SMT_FILE_TYPE;
    if (line.hasOption(sp.getName())) {
        config.put(SmtProperty.SMT_SUBCOMMAND.getName(), sp.getName());
        config.put(sp.getName(), line.getOptionValue(sp.getName()));
    }

    sp = SmtProperty.SMT_FILE_INFO;
    if (line.hasOption(sp.getName())) {
        config.put(SmtProperty.SMT_SUBCOMMAND.getName(), sp.getName());
        config.put(sp.getName(), line.getOptionValue(sp.getName()));
    }

    sp = SmtProperty.SMT_FILE_COMPRESS;
    if (line.hasOption(sp.getName())) {
        // exactly two arguments, first must be #, second is output filename
        config.put(SmtProperty.SMT_SUBCOMMAND.getName(), sp.getName());
        saveCompressionArgs(line.getOptionValues(sp.getName()), config);
    }

    sp = SmtProperty.SMT_CONCAT_HISTORY;
    if (line.hasOption(sp.getName())) {
        config.put(SmtProperty.SMT_SUBCOMMAND.getName(), sp.getName());
        saveConcatinationArgs(line.getOptionValues(sp.getName()), config);
    }

    sp = SmtProperty.SMT_FILE_FILTER;
    if (line.hasOption(sp.getName())) {
        // must be two arguments, first is filter filename,  final is output filename

        config.put(sp.getName(), line.getOptionValue(sp.getName()));
        config.put(SmtProperty.SMT_SUBCOMMAND.getName(), sp.getName());
        saveFilterArgs(line.getOptionValues(sp.getName()), config);
    }

    sp = SmtProperty.SMT_FILE_EXTRACT;
    if (line.hasOption(sp.getName())) {
        // must be two or three arguments, should be one or two timestamps, final is output filename

        config.put(SmtProperty.SMT_SUBCOMMAND.getName(), sp.getName());
        saveExtractionArgs(line.getOptionValues(sp.getName()), config);
    }

    sp = SmtProperty.SMT_LIST_TIMESTAMP;
    if (line.hasOption(sp.getName())) {
        config.put(sp.getName(), sp.getName());
    }
    return true;
}

From source file:cmd.ArgumentHandler.java

/**
 * Parses the options in the command line arguments and returns an array of
 * strings corresponding to the filenames given as arguments only
 *
 * @param args/*from  ww w .  ja  v a 2s .  c o  m*/
 * @throws org.apache.commons.cli.ParseException
 */
@SuppressWarnings("static-access")
public void parseCommandLineOptions(String[] args) throws ParseException {

    options = new Options();

    options.addOption("h", "help", false, "Help page for command usage");

    options.addOption("s", false, "SubStructure detection");

    options.addOption("a", false, "Add Hydrogen");

    options.addOption("x", false, "Match Atom Type");

    options.addOption("r", false, "Remove Hydrogen");

    options.addOption("z", false, "Ring matching");

    options.addOption("b", false, "Match Bond types (Single, Double etc)");

    options.addOption(
            OptionBuilder.hasArg().withDescription("Query filename").withArgName("filepath").create("q"));

    options.addOption(
            OptionBuilder.hasArg().withDescription("Target filename").withArgName("filepath").create("t"));

    options.addOption(OptionBuilder.hasArg().withDescription("Add suffix to the files").withArgName("suffix")
            .create("S"));

    options.addOption("g", false, "create png of the mapping");

    options.addOption(OptionBuilder.hasArg().withDescription("Dimension of the image in pixels")
            .withArgName("WIDTHxHEIGHT").create("d"));

    options.addOption("m", false, "Report all Mappings");

    String filterDescr = "Default: 0, Stereo: 1, " + "Stereo+Fragment: 2, Stereo+Fragment+Energy: 3";
    options.addOption(OptionBuilder.hasArg().withDescription(filterDescr).withArgName("number").create("f"));

    options.addOption("A", false, "Appends output to existing files, else creates new files");

    options.addOption(OptionBuilder.withDescription("Do N-way MCS on the target SD file").create("N"));

    options.addOption(OptionBuilder.hasArg().withDescription("Query type (MOL, SMI, etc)").withArgName("type")
            .create("Q"));

    options.addOption(OptionBuilder.hasArg().withDescription("Target type (MOL, SMI, SMIF, etc)")
            .withArgName("type").create("T"));

    options.addOption(OptionBuilder.hasArg().withDescription("Output the substructure to a file")
            .withArgName("filename").create("o"));

    options.addOption(
            OptionBuilder.hasArg().withDescription("Output type (SMI, MOL)").withArgName("type").create("O"));

    options.addOption(OptionBuilder.hasOptionalArgs(2).withValueSeparator().withDescription("Image options")
            .withArgName("option=value").create("I"));

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

    if (line.hasOption('Q')) {
        queryType = line.getOptionValue("Q");
    } //else {
    //            queryType = "MOL";
    //        } //XXX default type?

    if (line.hasOption('T')) {
        targetType = line.getOptionValue("T");
    } else {
        targetType = "MOL";
    }

    if (line.hasOption('a')) {
        this.setApplyHAdding(true);
    }

    if (line.hasOption('r')) {
        this.setApplyHRemoval(true);
    }

    if (line.hasOption('m')) {
        this.setAllMapping(true);
    }

    if (line.hasOption('s')) {
        this.setSubstructureMode(true);
    }

    if (line.hasOption('g')) {
        this.setImage(true);
    }

    if (line.hasOption('b')) {
        this.setMatchBondType(true);
    }

    if (line.hasOption('z')) {
        this.setMatchRingType(true);
    }

    if (line.hasOption('x')) {
        this.setMatchAtomType(true);
    }

    remainingArgs = line.getArgs();

    if (line.hasOption('h') || line.getOptions().length == 0) {
        //            System.out.println("Hello");
        helpRequested = true;
    }

    if (line.hasOption('S')) {
        String[] suffix_reader = line.getOptionValues('S');
        if (suffix_reader.length < 1) {
            System.out.println("Suffix required!");
            helpRequested = true;
        }
        setSuffix(suffix_reader[0]);
        setApplySuffix(true);
    }

    if (line.hasOption('f')) {
        String[] filters = line.getOptionValues('f');
        if (filters.length < 1) {
            System.out.println("Chemical filter required (Ranges: 0 to 3)!");
            helpRequested = true;
        }
        setChemFilter((int) new Integer(filters[0]));
    }

    if (line.hasOption('q')) {
        queryFilepath = line.getOptionValue('q');
    }

    if (line.hasOption('t')) {
        targetFilepath = line.getOptionValue('t');
    }

    if (line.hasOption("A")) {
        this.setAppendMode(true);
    }

    if (line.hasOption("N")) {
        setNMCS(true);
    }

    if (line.hasOption("o")) {
        outputSubgraph = true;
        outputFilepath = line.getOptionValue("o");
    }

    if (line.hasOption("O")) {
        outputFiletype = line.getOptionValue("O");
    } else {
        outputFiletype = "MOL";
    }

    if (line.hasOption("d")) {
        String dimensionString = line.getOptionValue("d");
        if (dimensionString.contains("x")) {
            String[] parts = dimensionString.split("x");
            try {
                setImageWidth(Integer.parseInt(parts[0]));
                setImageHeight(Integer.parseInt(parts[1]));
                System.out.println("set image dim to " + getImageWidth() + "x" + getImageHeight());
            } catch (NumberFormatException nfe) {
                throw new ParseException("Malformed dimension string " + dimensionString);
            }
        } else {
            throw new ParseException("Malformed dimension string " + dimensionString);
        }
    }

    if (line.hasOption("I")) {
        imageProperties = line.getOptionProperties("I");
        if (imageProperties.isEmpty()) {
            // used just "-I" by itself
            isImageOptionHelp = true;
        }
    }
}

From source file:com.zimbra.cs.util.ProxyConfOverride.java

public static void overrideDefaultVars(CommandLine cl) {
    String[] overrides = cl.getOptionValues('c');

    if (overrides != null) {
        for (String o : overrides) {
            mLog.debug("Processing config override " + o);
            int e = o.indexOf("=");
            if (e <= 0) {
                mLog.info("Ignoring config override " + o + " because it is not of the form name=value");
            } else {
                String k = o.substring(0, e);
                String v = o.substring(e + 1);

                if (mVars.containsKey(k)) {
                    mLog.info("Overriding config variable " + k + " with " + v);
                    mVars.put(k, v);//from w w w. ja v a2  s.c  o  m
                } else {
                    mLog.info("Ignoring non-existent config variable " + k);
                }
            }
        }
    }
}

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

/**
 * Parse command line options/*from   w w  w.  ja va2 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("help")) {
        printUsage();
        return false;
    }

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

    }

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

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

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

    appMasterJar = cliParser.getOptionValue("jar");

    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_script")) {
        shellScriptPath = cliParser.getOptionValue("shell_script");
    }
    if (cliParser.hasOption("shell_args")) {
        shellArgs = cliParser.getOptionValue("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"));
    numContainers = Integer.parseInt(cliParser.getOptionValue("num_containers", "1"));

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

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

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

    return true;
}

From source file:com.github.houbie.lesscss.LesscCommandLineParser.java

private void setOptions(CommandLine cmd) throws ParseException {
    options = new Options();

    options.setDependenciesOnly(cmd.hasOption(DEPENDS_OPTION));
    options.setIeCompat(!cmd.hasOption(NO_IE_COMPAT_OPTION));
    options.setJavascriptEnabled(!cmd.hasOption(NO_JS_OPTION));
    options.setLint(cmd.hasOption(LINT_OPTION));
    options.setSilent(cmd.hasOption(SILENT_OPTION));
    options.setStrictImports(cmd.hasOption(STRICT_IMPORTS_OPTION));
    options.setCompress(cmd.hasOption(COMPRESS_OPTION));
    options.setSourceMap(cmd.hasOption(SOURCE_MAP_OPTION));
    options.setSourceMapRootpath(cmd.getOptionValue(SOURCE_MAP__ROOTPATH_OPTION));
    options.setSourceMapBasepath(cmd.getOptionValue(SOURCE_MAP__BASEPATH_OPTION));
    options.setSourceMapLessInline(cmd.hasOption(SOURCE_MAP_LESS_INLINE_OPTION));
    options.setSourceMapMapInline(cmd.hasOption(SOURCE_MAP_MAP_INLINE_OPTION));
    options.setSourceMapURL(cmd.getOptionValue(SOURCE_MAP_URL_OPTION));
    if (options.isSourceMap() && !options.isSourceMapMapInline()) {
        String sourceMapFileName = cmd.getOptionValue(SOURCE_MAP_OPTION);
        if (sourceMapFileName == null) {
            if (destination == null) {
                throw new ParseException(
                        "The sourcemap option only has an optional filename if the css filename is given");
            }//  www .ja  va  2s .  co m
            sourceMapFile = new File(getDestination().getParentFile(), getDestination().getName() + ".map");
        } else {
            sourceMapFile = new File(sourceMapFileName);
        }
    }

    options.setRootpath(cmd.getOptionValue(ROOT_PATH_OPTION));
    options.setRelativeUrls(cmd.hasOption(RELATIVE_URLS_OPTION));
    options.setStrictMath(cmd.hasOption(STRICT_MATH_OPTION));
    options.setStrictUnits(cmd.hasOption(STRICT_UNITS_OPTION));
    options.setGlobalVars(getValuesMap(cmd.getOptionValues(GLOBAL_VAR_OPTION)));
    options.setModifyVars(getValuesMap(cmd.getOptionValues(MODIFY_VAR_OPTION)));
    options.setMinify(cmd.hasOption(YUI_COMPRESS_OPTION));

    //deprecated options
    if (cmd.hasOption(OPTIMIZATION_LEVEL_OPTION)) {
        options.setOptimizationLevel(((Long) cmd.getParsedOptionValue(OPTIMIZATION_LEVEL_OPTION)).intValue());
    }
    if (cmd.hasOption(LINE_NUMBERS_OPTION)) {
        options.setDumpLineNumbers(
                Options.LineNumbersOutput.fromOptionString(cmd.getOptionValue(LINE_NUMBERS_OPTION)));
    }
}

From source file:com.github.dakusui.symfonion.CLI.java

public void analyze(CommandLine cmd) throws CLIException {
    if (cmd.hasOption('O')) {
        String optionName = "O";
        this.midiouts = initializeMidiPorts(cmd, optionName);
    }/*from  w  ww.  j  a v a 2  s. c o  m*/
    if (cmd.hasOption('I')) {
        String optionName = "I";
        this.midiins = initializeMidiPorts(cmd, optionName);
    }
    if (cmd.hasOption('o')) {
        String sinkFilename = getSingleOptionValue(cmd, "o");
        if (sinkFilename == null) {
            String msg = composeErrMsg("Output filename is required by this option.", "o", null);
            throw new CLIException(msg);
        }
        this.sink = new File(sinkFilename);
    }
    if (cmd.hasOption("V") || cmd.hasOption("version")) {
        this.mode = Mode.VERSION;
    } else if (cmd.hasOption("h") || cmd.hasOption("help")) {
        this.mode = Mode.HELP;
    } else if (cmd.hasOption("l") || cmd.hasOption("list")) {
        this.mode = Mode.LIST;
    } else if (cmd.hasOption("p") || cmd.hasOption("play")) {
        this.mode = Mode.PLAY;
        String sourceFilename = getSingleOptionValue(cmd, "p");
        if (sourceFilename == null) {
            String msg = composeErrMsg("Input filename is required by this option.", "p", null);
            throw new CLIException(msg);
        }
        this.source = new File(sourceFilename);
    } else if (cmd.hasOption("c") || cmd.hasOption("compile")) {
        this.mode = Mode.COMPILE;
        String sourceFilename = getSingleOptionValue(cmd, "c");
        if (sourceFilename == null) {
            String msg = composeErrMsg("Input filename is required by this option.", "c", null);
            throw new CLIException(msg);
        }
        this.source = new File(sourceFilename);
    } else if (cmd.hasOption("r") || cmd.hasOption("route")) {
        this.mode = Mode.ROUTE;
        Properties props = cmd.getOptionProperties("r");
        if (props.size() != 1) {
            String msg = composeErrMsg("Route information is not given or specified multiple times.", "r",
                    "route");
            throw new CLIException(msg);
        }

        this.route = new Route(cmd.getOptionValues('r')[0], cmd.getOptionValues('r')[1]);
    } else {
        @SuppressWarnings("unchecked")
        List<String> leftovers = cmd.getArgList();
        if (leftovers.size() == 0) {
            this.mode = Mode.HELP;
        } else if (leftovers.size() == 1) {
            this.mode = Mode.PLAY;
            this.source = new File(leftovers.get(0));
        } else {
            String msg = composeErrMsg(
                    String.format("Unrecognized arguments:%s", leftovers.subList(2, leftovers.size())), "-",
                    null);
            throw new CLIException(msg);
        }
    }
}

From source file:com.google.oacurl.options.LoginOptions.java

@Override
public CommandLine parse(String[] args) throws ParseException {
    CommandLine line = super.parse(args);

    parameters = new ArrayList<Parameter>();

    serviceProviderFileName = line.getOptionValue("service-provider");
    consumerFileName = line.getOptionValue("consumer");
    consumerKey = line.getOptionValue("consumer-key");
    consumerSecret = line.getOptionValue("consumer-secret");
    browser = line.getOptionValue("browser");

    // backward compatibility for --icon-url
    if (line.hasOption("icon-url")) {
        parameters.add(new Parameter("iconUrl", line.getOptionValue("icon-url")));
    } else if (line.hasOption("buzz")) {
        parameters.add(new Parameter("iconUrl", "http://www.gstatic.com/codesite/ph/images/defaultlogo.png"));
    }/*from  www .j  av  a2  s  . co  m*/

    noserver = line.hasOption("noserver");
    nobrowser = line.hasOption("nobrowser");
    buzz = line.hasOption("buzz");
    blogger = line.hasOption("blogger");
    latitude = line.hasOption("latitude");
    demo = line.hasOption("demo");
    wirelog = line.hasOption("wirelog");
    host = line.getOptionValue("host", "localhost");
    callback = line.getOptionValue("callback", null);

    version = OAuthVersion.V1;

    if (line.hasOption("scope")) {
        StringBuilder scopeBuilder = new StringBuilder();
        // Google separates scopes with spaces, Windows Live with commas. Since
        // WL scopes are already short, we use space as the separate in order to
        // support the SCOPE_MAP expansion of Google scope URLs.
        for (String oneScope : line.getOptionValue("scope").split(" ")) {
            if (SCOPE_MAP.containsKey(oneScope)) {
                oneScope = SCOPE_MAP.get(oneScope);
            }

            if (scopeBuilder.length() > 0) {
                scopeBuilder.append(" ");
            }
            scopeBuilder.append(oneScope);
        }

        scope = scopeBuilder.toString();
    } else if (isBuzz()) {
        StringBuilder scopeBuilder = new StringBuilder();
        scopeBuilder.append(SCOPE_MAP.get("BUZZ"));
        scopeBuilder.append(" ");
        scopeBuilder.append(SCOPE_MAP.get("PHOTOS"));
        scope = scopeBuilder.toString();
    } else if (isBlogger()) {
        scope = SCOPE_MAP.get("BLOGGER");
    } else if (isLatitude()) {
        scope = SCOPE_MAP.get("LATITUDE");
        version = OAuthVersion.V2;
    }

    String[] parameterArray = line.getOptionValues("param");
    if (parameterArray != null) {
        for (String param : parameterArray) {
            String[] paramBits = param.split("=", 2);
            parameters.add(new OAuth.Parameter(paramBits[0].trim(), paramBits[1].trim()));
        }
    }

    if (line.hasOption("2")) {
        version = OAuthVersion.V2;
    } else if (line.hasOption("wrap")) {
        version = OAuthVersion.WRAP;
    } else if (line.hasOption("1")) {
        version = OAuthVersion.V1;
    }

    return line;
}

From source file:com.zimbra.cs.redolog.util.PlaybackUtil.java

private static Params initParams(CommandLine cl) throws ServiceException, IOException {
    Params params = new Params();
    params.help = cl.hasOption(OPT_HELP);
    if (params.help)
        return params;

    params.stopOnError = cl.hasOption(OPT_STOP_ON_ERROR);

    if (cl.hasOption(OPT_FROM_TIME)) {
        String timeStr = cl.getOptionValue(OPT_FROM_TIME);
        Date time = SoapCLI.parseDatetime(timeStr);
        if (time != null) {
            params.fromTime = time.getTime();
            SimpleDateFormat f = new SimpleDateFormat(SoapCLI.CANONICAL_DATETIME_FORMAT);
            String tstamp = f.format(time);
            System.out.printf("Using from-time of %s\n", tstamp);
        } else {/*from w  w w .j av a 2 s.c  o m*/
            System.err.printf("Invalid timestamp \"%s\" specified for --%s option\n", timeStr, OPT_FROM_TIME);
            System.err.println();
            System.err.print(SoapCLI.getAllowedDatetimeFormatsHelp());
            System.exit(1);
        }
    }
    if (cl.hasOption(OPT_FROM_SEQ)) {
        params.fromSeq = Long.parseLong(cl.getOptionValue(OPT_FROM_SEQ));
        System.out.printf("Using from-sequence of %d\n", params.fromSeq);
    }
    if (cl.hasOption(OPT_TO_TIME)) {
        String timeStr = cl.getOptionValue(OPT_TO_TIME);
        Date time = SoapCLI.parseDatetime(timeStr);
        if (time != null) {
            params.toTime = time.getTime();
            SimpleDateFormat f = new SimpleDateFormat(SoapCLI.CANONICAL_DATETIME_FORMAT);
            String tstamp = f.format(time);
            System.out.printf("Using to-time of %s\n", tstamp);
        } else {
            System.err.printf("Invalid timestamp \"%s\" specified for --%s option\n", timeStr, OPT_TO_TIME);
            System.err.println();
            System.err.print(SoapCLI.getAllowedDatetimeFormatsHelp());
            System.exit(1);
        }
    }
    if (cl.hasOption(OPT_TO_SEQ)) {
        params.toSeq = Long.parseLong(cl.getOptionValue(OPT_TO_SEQ));
        System.out.printf("Using to-sequence of %d\n", params.toSeq);
    }
    if (params.fromSeq > params.toSeq) {
        System.err.println("Error: fromSeq greater than toSeq");
        System.exit(1);
    }
    if (params.fromTime > params.toTime) {
        System.err.println("Error: fromTime later than toTime");
        System.exit(1);
    }

    if (cl.hasOption(OPT_MAILBOX_ID)) {
        params.mboxId = Integer.parseInt(cl.getOptionValue(OPT_MAILBOX_ID));
        System.out.printf("Replaying operations for mailbox %d only\n", params.mboxId);
    } else {
        System.out.println("Replaying operations for all mailboxes");
    }

    if (cl.hasOption(OPT_THREADS))
        params.threads = Integer.parseInt(cl.getOptionValue(OPT_THREADS));
    System.out.printf("Using %d redo player threads\n", params.threads);
    if (cl.hasOption(OPT_QUEUE_CAPACITY))
        params.queueCapacity = Integer.parseInt(cl.getOptionValue(OPT_QUEUE_CAPACITY));
    System.out.printf("Using %d as queue capacity for each redo player thread\n", params.queueCapacity);

    List<File> logList = new ArrayList<File>();
    if (cl.hasOption(OPT_LOGFILES)) {
        String[] fnames = cl.getOptionValues(OPT_LOGFILES);
        params.logfiles = new File[fnames.length];
        for (int i = 0; i < fnames.length; i++) {
            File f = new File(fnames[i]);
            if (f.exists())
                logList.add(f);
            else
                throw new FileNotFoundException("No such file: " + f.getAbsolutePath());
        }
    } else {
        // By default, use /opt/zimbra/redolog/archive/*, then /opt/zimbra/redolog/redo.log,
        // ordered by log sequence.
        Provisioning prov = Provisioning.getInstance();
        Server server = prov.getLocalServer();
        String archiveDirPath = Config
                .getPathRelativeToZimbraHome(
                        server.getAttr(Provisioning.A_zimbraRedoLogArchiveDir, "redolog/archive"))
                .getAbsolutePath();
        String redoLogPath = Config
                .getPathRelativeToZimbraHome(
                        server.getAttr(Provisioning.A_zimbraRedoLogLogPath, "redolog/redo.log"))
                .getAbsolutePath();

        File archiveDir = new File(archiveDirPath);
        if (archiveDir.exists()) {
            File[] archiveLogs = RolloverManager.getArchiveLogs(archiveDir, params.fromSeq, params.toSeq);
            for (File f : archiveLogs) {
                logList.add(f);
            }
        }
        File redoLog = new File(redoLogPath);
        if (redoLog.exists()) {
            FileLogReader logReader = new FileLogReader(redoLog);
            long seq = logReader.getHeader().getSequence();
            if (params.fromSeq <= seq && seq <= params.toSeq)
                logList.add(redoLog);
        }
    }
    // Filter out logs based on from/to times.
    for (Iterator<File> iter = logList.iterator(); iter.hasNext();) {
        File f = iter.next();
        FileHeader hdr = (new FileLogReader(f)).getHeader();
        if (hdr.getFirstOpTstamp() > params.toTime
                || (hdr.getLastOpTstamp() < params.fromTime && !hdr.getOpen())) {
            // log is outside the time range
            iter.remove();
            System.out.printf("Redolog %s has no operation in the requested time range\n", f.getName());
        }
    }
    params.logfiles = new File[logList.size()];
    params.logfiles = logList.toArray(params.logfiles);
    System.out.printf("%d redolog files to play back\n", params.logfiles.length);

    return params;
}

From source file:com.netcrest.pado.tools.pado.PadoShell.java

private void parseArgs(String args[]) {
    Options options = new Options();

    Option opt = OptionBuilder.create("dir");
    opt.setArgs(1);//from   w  ww . java  2s  .  c o  m
    opt.setOptionalArg(true);
    options.addOption(opt);

    opt = OptionBuilder.create("i");
    opt.setArgs(1);
    opt.setOptionalArg(true);
    options.addOption(opt);

    opt = OptionBuilder.create("e");
    opt.setArgs(Option.UNLIMITED_VALUES);
    opt.setOptionalArg(true);
    options.addOption(opt);

    opt = OptionBuilder.create("f");
    opt.setArgs(1);
    opt.setOptionalArg(true);
    options.addOption(opt);

    opt = OptionBuilder.create("jar");
    opt.setArgs(1);
    opt.setOptionalArg(true);
    options.addOption(opt);

    opt = OptionBuilder.create("l");
    opt.setArgs(1);
    opt.setOptionalArg(true);
    options.addOption(opt);

    opt = OptionBuilder.create("a");
    opt.setArgs(1);
    opt.setOptionalArg(true);
    options.addOption(opt);

    opt = OptionBuilder.create("u");
    opt.setArgs(1);
    opt.setOptionalArg(true);
    options.addOption(opt);

    opt = OptionBuilder.create("p");
    opt.setArgs(1);
    opt.setOptionalArg(true);
    options.addOption(opt);

    // domain
    opt = OptionBuilder.create("d");
    opt.setArgs(1);
    opt.setOptionalArg(true);
    options.addOption(opt);

    // history
    opt = OptionBuilder.create("h");
    opt.setArgs(1);
    opt.setOptionalArg(true);
    options.addOption(opt);

    // editor (vi or emacs) - default vi
    opt = OptionBuilder.create("o");
    opt.setArgs(1);
    opt.setOptionalArg(true);
    options.addOption(opt);

    options.addOption("n", false, "");
    options.addOption("v", false, "");
    options.addOption("?", false, "");

    CommandLine commandLine = null;
    try {
        commandLine = cliParseCommandLine(options, args);
    } catch (Exception e) {
        Logger.error(e);
    }

    if (commandLine == null || commandLine.hasOption('?')) {
        usage();
        exit(0);
    }

    if (commandLine.hasOption('v')) {
        PadoVersion padoVersion = new PadoVersion();
        println("v" + padoVersion.getVersion());
        exit(0);
    }

    if (commandLine.hasOption("dir") && commandLine.getOptionValue("dir") != null) {
        //         jarDirectoryPath = commandLine.getOptionValue("dir");
        // ignore dir. dir is handled by the shell script.
    }

    if (commandLine.hasOption("i") && commandLine.getOptionValue("i") != null) {
        inputFilePath = commandLine.getOptionValue("i");
    }

    if (commandLine.hasOption("e") && commandLine.getOptionValue("e") != null) {
        inputCommands = commandLine.getOptionValues("e");
    }
    if (commandLine.hasOption("f") && commandLine.getOptionValue("f") != null) {
        scriptFilePath = commandLine.getOptionValue("f");
    }

    if (commandLine.hasOption("jar") && commandLine.getOptionValue("jar") != null) {
        jarPaths = commandLine.getOptionValue("jar");
    }

    if (commandLine.hasOption("h") && commandLine.getOptionValue("h") != null) {
        historyFileName = commandLine.getOptionValue("h");
    }

    if (commandLine.hasOption("o") && commandLine.getOptionValue("o") != null) {
        editorName = commandLine.getOptionValue("o");
        // Only vi and emacs supported. Default to vi if a bad name.
        if (editorName.equalsIgnoreCase("vi") == false && editorName.equalsIgnoreCase("emacs")) {
            editorName = "vi";
        }
    }

    locators = commandLine.getOptionValue("l");
    appId = commandLine.getOptionValue("a");
    user = commandLine.getOptionValue("u");
    String pw = commandLine.getOptionValue("p");
    if (pw != null) {
        password = pw.toCharArray();
    }

    ignorePadoRcFile = commandLine.hasOption("n");

    if (commandLine.hasOption("h")) {
        setHistoryPerSession(Boolean.TRUE);
    }

    interactiveMode = scriptFilePath == null && inputCommands == null;

    if (interactiveMode) {
        println();
        println(PadoShellLogo.getPadoLogo());
        println(PadoShellLogo.getCopyrights());
        println();
    }

    envProperties.putAll(System.getenv());
}

From source file:com.sogou.dockeronyarn.client.DockerClient.java

/**
 * Parse command line options/* w  w  w.  jav a  2  s.  c  om*/
 * @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(DockerClient.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("appname", "DistributedShell");
    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"));

    container_retry = Integer.parseInt(cliParser.getOptionValue("container_retry", "3"));

    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_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;
}