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:net.lldp.checksims.ChecksimsCommandLine.java

/**
 * Parse flags which require submissions to be built.
 *
 * TODO unit tests//from  w w  w . j a v  a 2s  . c  o  m
 *
 * @param cli Parse CLI options
 * @param baseConfig Base configuration to work off
 * @return Modified baseConfig with submissions (and possibly common code and archive submissions) changed
 * @throws ChecksimsException Thrown on bad argument
 * @throws IOException Thrown on error building submissions
 */
static ChecksimsConfig parseFileFlags(CommandLine cli, ChecksimsConfig baseConfig)
        throws ChecksimsException, IOException {
    checkNotNull(cli);
    checkNotNull(baseConfig);

    ChecksimsConfig toReturn = new ChecksimsConfig(baseConfig);

    // Get glob match pattern
    // Default to *
    String globPattern = cli.getOptionValue("g", "*");

    // Check if we are recursively building
    boolean recursive = cli.hasOption("r");

    // Check if we are retaining empty submissions
    boolean retainEmpty = cli.hasOption("e");

    // Get submission directories
    if (!cli.hasOption("s")) {
        throw new ChecksimsException("Must provide at least one submission directory!");
    }

    String[] submissionDirsString = cli.getOptionValues("s");

    // Make a Set<File> from those submission directories
    // Map to absolute file, to ensure no dups
    Set<File> submissionDirs = Arrays.stream(submissionDirsString).map(File::new).map(File::getAbsoluteFile)
            .collect(Collectors.toSet());

    if (submissionDirs.isEmpty()) {
        throw new ChecksimsException("Must provide at least one submission directory!");
    }

    // Generate submissions
    Set<Submission> submissions = getSubmissions(submissionDirs, globPattern, recursive, retainEmpty);

    logs.debug("Generated " + submissions.size() + " submissions to process.");

    if (submissions.isEmpty()) {
        throw new ChecksimsException("Could build any submissions to operate on!");
    }

    toReturn = toReturn.setSubmissions(submissions);

    // Check if we need to perform common code removal
    if (cli.hasOption("c")) {
        // Get the directory containing the common code
        String commonCodeDirString = cli.getOptionValue("c");

        List<SubmissionPreprocessor> procs = new ArrayList<>(toReturn.getPreprocessors());
        try {
            procs.add(getCommonCodeRemoval(commonCodeDirString, submissionDirs, globPattern));
        } catch (IOException | ChecksimsException e) {
            logs.debug(e.getMessage());
        }
        toReturn = toReturn.setPreprocessors(procs);
    }

    // Check if we need to add archive directories
    if (cli.hasOption("archive")) {
        String[] archiveDirsString = cli.getOptionValues("archive");

        // Convert them into a set of files, again using getAbsoluteFile
        Set<File> archiveDirs = Arrays.stream(archiveDirsString).map(File::new).map(File::getAbsoluteFile)
                .collect(Collectors.toSet());

        archiveDirs = extractTurninFiles(archiveDirs);

        // Ensure that none of them are also submission directories
        for (File archiveDir : archiveDirs) {
            if (submissionDirs.contains(archiveDir)) {
                throw new ChecksimsException("Directory is both an archive directory and submission directory: "
                        + archiveDir.getAbsolutePath());
            }
        }

        // Get set of archive submissions
        Set<Submission> archiveSubmissions = getSubmissions(archiveDirs, globPattern, recursive, retainEmpty);

        logs.debug("Generated " + archiveSubmissions.size() + " archive submissions to process");

        if (archiveSubmissions.isEmpty()) {
            logs.warn("Did not find any archive submissions to test with!");
        }

        toReturn = toReturn.setArchiveSubmissions(archiveSubmissions);
    }

    return toReturn;
}

From source file:com.hp.mqm.clt.CliParser.java

private boolean isTagFormatValid(CommandLine cmd, String option) {
    String[] tags = cmd.getOptionValues(option);
    if (tags == null) {
        return true;
    }//from   ww  w  .  jav  a 2  s .  c  o m
    // CODE REVIEW, Johnny, 19Oct2015 - consult with Mirek with regards to localization, this is very probably
    // good for this release, but I can imagine it will have to be relaxed once we for example start to support
    // languages like French (and all their funny characters)
    Pattern pattern = Pattern.compile("^\\w+:\\w+$");
    for (String tag : tags) {
        if (!pattern.matcher(tag).matches()) {
            System.out.println("Tag and field tag arguments must be in TYPE:VALUE format: " + tag);
            return false;
        }
    }
    return true;
}

From source file:VOConfig.java

/**
 * Set configuration by parsed commandline options.
 *
 * @param cmd parsed commandline options
 *//*from   www. j  ava2s.c  o m*/
public void setCmd(CommandLine cmd) {
    if (cmd.hasOption("repository")) {
        this.repository = cmd.getOptionValue("repository");
    }

    if (cmd.hasOption("backup")) {
        this.backup = cmd.getOptionValue("backup");
    }

    if (cmd.hasOption("exclude")) {
        this.exclude = new ArrayList<>();
        this.exclude.addAll(Arrays.asList(cmd.getOptionValues("exclude")));
    }

    if (cmd.hasOption("exclude-dir")) {
        this.excludedir = new ArrayList<>();
        this.excludedir.addAll(Arrays.asList(cmd.getOptionValues("exclude-dir")));
    }

    if (CollectionUtils.isNotEmpty(cmd.getArgList())) {
        //noinspection unchecked
        this.paths = new ArrayList<String>(cmd.getArgList());
    }
}

From source file:com.facebook.presto.accumulo.tools.TimestampCheckTask.java

@Override
public int run(AccumuloConfig config, CommandLine cmd) throws Exception {
    this.setConfig(config);
    if (cmd.hasOption(AUTHORIZATIONS_OPT)) {
        this.setAuthorizations(new Authorizations(cmd.getOptionValues(AUTHORIZATIONS_OPT)));
    }/*from   w  ww  . j  ava  2  s .  co  m*/

    this.setSchema(cmd.getOptionValue(SCHEMA_OPT));
    this.setTableName(cmd.getOptionValue(TABLE_OPT));
    this.setStart(cmd.getOptionValue(START_OPT));
    this.setEnd(cmd.getOptionValue(END_OPT));
    this.setColumn(cmd.getOptionValue(COLUMN_OPT));

    return this.exec();
}

From source file:de.uni_koblenz.jgralab.utilities.csv2tg.Csv2Tg.java

protected void getOptions(String[] args) throws GraphIOException {
    CommandLine comLine = processCommandLineOptions(args);
    assert comLine != null;

    setSchema(comLine.getOptionValue(CLI_OPTION_SCHEMA));
    setCsvFiles(comLine.getOptionValues(CLI_OPTION_CSV_FILES));
    setOutputFile(comLine.getOptionValue(CLI_OPTION_OUTPUT_FILE));
}

From source file:com.rockagen.commons.util.CLITest.java

@Test
@Ignore//from   w  w  w. j  a  va  2s .  c o  m
public void testCLI() {

    // create the Options
    Options options = new Options();
    options.addOption("h", "help", false, "print help for the command.");
    options.addOption("v", "verbose", false, "verbose");
    OptionBuilder.withArgName("property=value");
    OptionBuilder.hasArgs(2);
    OptionBuilder.withLongOpt("desc");
    OptionBuilder.withValueSeparator();
    OptionBuilder.withDescription("use value for given property");
    options.addOption(OptionBuilder.create("D"));

    OptionBuilder.withArgName("file1,file2...");
    OptionBuilder.hasArgs();
    OptionBuilder.withLongOpt("input");
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withDescription("file name");
    options.addOption(OptionBuilder.create("i"));

    String formatstr = "CLITest [-h/--help][-v/--verbose]..";
    try {
        String[] args = { "CLITest", "--help", "-v", "-s", "--desc", "name=value", "--input", "file1", "file2",
                "file3" };
        // parse the command line arguments
        CommandLine line = CmdUtil.parse(options, args);

        if (line.hasOption("h")) {
            CmdUtil.printHelp(formatstr, "weclome usa", options,
                    "If you hava some quesion,please mail to agen@rockagen.com");
        }
        if (line.hasOption("v")) {
            System.out.println("VERSION 0.0.1");
        }
        if (line.hasOption("D")) {
            System.out.println("hey,guys,you input " + ArrayUtil.toString(line.getOptionValues("D")));
        }
        if (line.hasOption("i")) {
            System.out.println("hey,guys,you input " + ArrayUtil.toString(line.getOptionValues("i")));
        } else {
            CmdUtil.printHelp(formatstr, options);
        }
    } catch (ParseException exp) {
        CmdUtil.printHelp(formatstr, options);
        System.err.println();
        System.err.println(exp.getMessage());
    }

}

From source file:gov.llnl.lc.smt.command.privileged.SmtPrivileged.java

private boolean savePortIdentification(String cName, Map<String, String> config, CommandLine line) {
    if (line.hasOption(cName)) {
        // there should be a guid or lid, followed by a port number
        String[] args = line.getOptionValues(cName);
        if (args.length != 2) {
            // log an error, and exit
            System.err.println("command requires a two arguments");
            return false;
        }//from  w  ww. j  av  a2  s.c om
        // save the nodeid and port number
        config.put(NODE_ID, args[0]);
        config.put(PORT_ID, args[1]);

        config.put(SmtProperty.SMT_SUBCOMMAND.getName(), cName);
        return true;
    }
    return false;
}

From source file:kieker.tools.logReplayer.FilesystemLogReplayerStarter.java

@Override
protected boolean readPropertiesFromCommandLine(final CommandLine commandLine) {
    boolean retVal = true;

    // 0.) monitoring properties
    this.monitoringConfigurationFile = commandLine.getOptionValue(CMD_OPT_NAME_MONITORING_CONFIGURATION);

    // 1.) init inputDirs
    this.inputDirs = commandLine.getOptionValues(CMD_OPT_NAME_INPUTDIRS);
    if (this.inputDirs == null) {
        LOG.error("No input directory configured");
        retVal = false;/*from   www . j a  v  a 2s.  co m*/
    }

    // 2.) init keepOriginalLoggingTimestamps
    final String keepOriginalLoggingTimestampsOptValStr = commandLine
            .getOptionValue(CMD_OPT_NAME_KEEPORIGINALLOGGINGTIMESTAMPS, "true");
    if (!("true".equals(keepOriginalLoggingTimestampsOptValStr)
            || "false".equals(keepOriginalLoggingTimestampsOptValStr))) {
        LOG.error("Invalid value for option " + CMD_OPT_NAME_KEEPORIGINALLOGGINGTIMESTAMPS + ": '"
                + keepOriginalLoggingTimestampsOptValStr + "'");
        retVal = false;
    }
    this.keepOriginalLoggingTimestamps = "true".equals(keepOriginalLoggingTimestampsOptValStr);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Keeping original logging timestamps: "
                + (this.keepOriginalLoggingTimestamps ? "true" : "false")); // NOCS
    }
    // 3.) init realtimeMode
    final String realtimeOptValStr = commandLine.getOptionValue(CMD_OPT_NAME_REALTIME, "false");
    if (!("true".equals(realtimeOptValStr) || "false".equals(realtimeOptValStr))) {
        LOG.error("Invalid value for option " + CMD_OPT_NAME_REALTIME + ": '" + realtimeOptValStr + "'");
        retVal = false;
    }
    this.realtimeMode = "true".equals(realtimeOptValStr);

    // 4.) init numRealtimeWorkerThreads
    final String numRealtimeWorkerThreadsStr = commandLine.getOptionValue(CMD_OPT_NAME_NUM_REALTIME_WORKERS,
            "1");
    try {
        this.numRealtimeWorkerThreads = Integer.parseInt(numRealtimeWorkerThreadsStr);
    } catch (final NumberFormatException ex) {
        LOG.error("Invalid value for option " + CMD_OPT_NAME_NUM_REALTIME_WORKERS + ": '"
                + numRealtimeWorkerThreadsStr + "'");
        LOG.error("NumberFormatException: ", ex);
        retVal = false;
    }
    if (this.numRealtimeWorkerThreads < 1) {
        LOG.error("Option value for " + CMD_OPT_NAME_NUM_REALTIME_WORKERS + " must be >= 1; found "
                + this.numRealtimeWorkerThreads);
        LOG.error("Invalid specification of " + CMD_OPT_NAME_NUM_REALTIME_WORKERS + ":"
                + this.numRealtimeWorkerThreads);
        retVal = false;
    }

    // 5.) init realtimeAccelerationFactor
    final String realtimeAccelerationFactorStr = commandLine
            .getOptionValue(CMD_OPT_NAME_REALTIME_ACCELERATION_FACTOR, "1");
    try {
        this.realtimeAccelerationFactor = Double.parseDouble(realtimeAccelerationFactorStr);
    } catch (final NumberFormatException ex) {
        LOG.error("Invalid value for option " + CMD_OPT_NAME_REALTIME_ACCELERATION_FACTOR + ": '"
                + numRealtimeWorkerThreadsStr + "'");
        LOG.error("NumberFormatException: ", ex);
        retVal = false;
    }
    if (this.numRealtimeWorkerThreads <= 0) {
        LOG.error("Option value for " + CMD_OPT_NAME_REALTIME_ACCELERATION_FACTOR + " must be > 0; found "
                + this.realtimeAccelerationFactor);
        LOG.error("Invalid specification of " + CMD_OPT_NAME_REALTIME_ACCELERATION_FACTOR + ":"
                + this.realtimeAccelerationFactor);
        retVal = false;
    }

    // 6.) init ignoreRecordsBefore/After
    final DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_PATTERN, Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    try {
        final String ignoreRecordsBeforeTimestampString = commandLine
                .getOptionValue(CMD_OPT_NAME_IGNORERECORDSBEFOREDATE, null);
        final String ignoreRecordsAfterTimestampString = commandLine
                .getOptionValue(CMD_OPT_NAME_IGNORERECORDSAFTERDATE, null);
        if (ignoreRecordsBeforeTimestampString != null) {
            final Date ignoreBeforeDate = dateFormat.parse(ignoreRecordsBeforeTimestampString);
            this.ignoreRecordsBeforeTimestamp = ignoreBeforeDate.getTime() * (1000 * 1000);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Ignoring records before " + dateFormat.format(ignoreBeforeDate) + " ("
                        + this.ignoreRecordsBeforeTimestamp + ")");
            }
        }
        if (ignoreRecordsAfterTimestampString != null) {
            final Date ignoreAfterDate = dateFormat.parse(ignoreRecordsAfterTimestampString);
            this.ignoreRecordsAfterTimestamp = ignoreAfterDate.getTime() * (1000 * 1000);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Ignoring records after " + dateFormat.format(ignoreAfterDate) + " ("
                        + this.ignoreRecordsAfterTimestamp + ")");
            }
        }
    } catch (final java.text.ParseException ex) {
        final String erorMsg = "Error parsing date/time string. Please use the following pattern: "
                + DATE_FORMAT_PATTERN_CMD_USAGE_HELP;
        LOG.error(erorMsg, ex);
        return false;
    }

    // log configuration
    if (retVal && LOG.isDebugEnabled()) {
        LOG.debug("inputDirs: "
                + FilesystemLogReplayerStarter.fromStringArrayToDeliminedString(this.inputDirs, ';'));
        LOG.debug("Replaying in " + (this.realtimeMode ? "" : "non-") + "realtime mode"); // NOCS
        if (this.realtimeMode) {
            LOG.debug("Using " + this.numRealtimeWorkerThreads + " realtime worker thread"
                    + (this.numRealtimeWorkerThreads > 1 ? "s" : "")); // NOCS
        }
    }

    return retVal;
}

From source file:com.netflix.Aegisthus.java

@Override
public int run(String[] args) throws Exception {
    Job job = new Job(getConf());

    job.setJarByClass(Aegisthus.class);
    CommandLine cl = getOptions(args);
    if (cl == null) {
        return 1;
    }/*  ww w.j av  a  2 s .com*/
    job.setInputFormatClass(AegisthusInputFormat.class);
    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(Text.class);
    job.setOutputFormatClass(TextOutputFormat.class);
    job.setMapperClass(CassMapper.class);
    job.setReducerClass(CassReducer.class);
    List<Path> paths = Lists.newArrayList();
    if (cl.hasOption(OPT_INPUT)) {
        for (String input : cl.getOptionValues(OPT_INPUT)) {
            paths.add(new Path(input));
        }
    }
    if (cl.hasOption(OPT_INPUTDIR)) {
        paths.addAll(getDataFiles(job.getConfiguration(), cl.getOptionValue(OPT_INPUTDIR)));
    }
    TextInputFormat.setInputPaths(job, paths.toArray(new Path[0]));
    TextOutputFormat.setOutputPath(job, new Path(cl.getOptionValue(OPT_OUTPUT)));

    job.submit();
    System.out.println(job.getJobID());
    System.out.println(job.getTrackingURL());
    boolean success = job.waitForCompletion(true);
    return success ? 0 : 1;
}

From source file:lu.uni.adtool.tools.Clo.java

/**
 * Class used to parse command line options. Returns true if GUI window should
 * be shown/* w  w  w.j  a va 2 s. c  o  m*/
 */
public boolean parse(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
            return false;
        } else if (cmd.hasOption("v")) {
            version();
            return false;
        } else if (cmd.hasOption("o")) {
            this.toOpen = cmd.getOptionValues("o");
            if (this.toOpen != null && this.toOpen.length == 0) {
                this.toOpen = null;
            }
        }
        if (cmd.hasOption("i") && cmd.hasOption("x") || cmd.hasOption("i") && cmd.hasOption("d")
                && (cmd.getOptionValue("d", "0").equals("?") || cmd.getOptionValue("d", "0").equals("q"))) {
            ImportExport exporter = new ImportExport();
            if (cmd.hasOption("D")) {
                exporter.setNoDerivedValues(true);
            }
            if (cmd.hasOption("m")) {
                exporter.setMarkEditable(true);
            }
            if (cmd.hasOption("r")) {
                String r = cmd.getOptionValue("r");
                try {
                    int x = Integer.parseInt(r);
                    if (x > 0) {
                        exporter.setExportRanking(x);
                    } else {
                        System.err.println(Options.getMsg("clo.wrongrank"));
                    }
                } catch (NumberFormatException e) {
                    System.err.println(Options.getMsg("clo.wrongrank"));
                }
            }
            if (cmd.hasOption("L")) {
                exporter.setNoLabels(true);
            }
            if (cmd.hasOption("C")) {
                exporter.setNoComputedValues(true);
            }
            if (cmd.hasOption("s")) {
                String size = cmd.getOptionValue("s");
                int index = size.indexOf('x');
                if (index > 0) {
                    try {
                        int x = Integer.parseInt(size.substring(0, index));
                        int y = Integer.parseInt(size.substring(index + 1));
                        exporter.setViewPortSize(new Dimension(x, y));
                    } catch (NumberFormatException e) {
                        System.err.println(Options.getMsg("clo.wrongsize"));
                    }
                }
            }
            if (cmd.hasOption("d")) {
                String[] domainIds = cmd.getOptionValues("d");

                if (domainIds != null) {
                    // if (domainId == "?" || domainId=="q") {
                    // System.out.println(new Integer(exporter.countDomains(fileName)));
                    // return false;
                    // }
                    exporter.setExportDomainStr(domainIds);
                }
            }
            String fileName = cmd.getOptionValue("i");
            if (fileName != null && exporter.doImport(fileName)) {
                fileName = cmd.getOptionValue("x");
                if (fileName != null) {
                    exporter.doExport(fileName);
                }
            }
            return toOpen != null;
        }
        if (cmd.getOptions().length > 0) {
            System.err.println(Options.getMsg("clo.wrongCombination") + ".");
            help();
            return false;
        }
    } catch (ParseException e) {
        System.err.println(Options.getMsg("clo.parseError") + ": " + e.toString());
        help();
        return false;
    }
    return true;
}