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.kaaprotech.satu.util.CmdLineUtil.java

public static CommanndLineValues parseCommanndLineArgs(String[] args) {
    final CommandLine commandLine;
    try {//from   w  ww .j a  v a  2 s . com
        final CommandLineParser parser = new GnuParser();
        commandLine = parser.parse(getOptions(), args);
    } catch (ParseException e) {
        System.err.println("Satu: Failed to parse command line arguments: " + e.getMessage());
        throw new RuntimeException(e);
    }

    final String[] in = commandLine.getOptionValues(IN);
    final String out = commandLine.getOptionValue(OUT);
    final boolean json = commandLine.hasOption(JSON);
    return new CommanndLineValuesImpl(in, out, json);
}

From source file:com.rabbitmq.examples.MulticastMain.java

private static List<?> lstArg(CommandLine cmd, char opt) {
    String[] vals = cmd.getOptionValues('f');
    if (vals == null) {
        vals = new String[] {};
    }/* www.  jav  a2 s  . c  om*/
    return Arrays.asList(vals);
}

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

/** Extract the account names
 *  @param  commandLine Command Line object (org.apache.commons.cli.CommandLine)
 *  @return ArrayList containing the account names specified on the command line (-a or -L)
 *//*ww  w.j  a v a 2 s.  co m*/
static ArrayList<String> getAccounts(CommandLine commandLine) {
    ArrayList<String> accounts = new ArrayList<String>();
    String[] values = commandLine.getOptionValues("a");
    String filename = commandLine.getOptionValue("L");

    /* Start off with any account specified with `-a' */
    if (values != null) {
        for (String u : commandLine.getOptionValues("a")) {
            accounts.add(u);
        }
    }

    /* Other accounts may be read from a list file specified with -L 
       Each line of input will contain one account name
     */
    if (filename != null) {
        BufferedReader br;
        if (filename == "-") {
            br = new BufferedReader(new InputStreamReader(System.in));
        } else {
            try {
                br = new BufferedReader(new FileReader(filename));
            } catch (FileNotFoundException e) {
                br = null;
                System.err.println("File not found: " + filename);
            }
        }

        if (br != null) {
            String s;
            do {
                try {
                    s = br.readLine();
                } catch (IOException e) {
                    s = null;
                }

                if (s != null) {
                    accounts.add(s);
                }
            } while (s != null);

            try {
                br.close();
            } catch (IOException e) {
            }
        }
    }

    return accounts;
}

From source file:com.linkedin.cubert.ScriptExecutor.java

/**
 * Properties are collected in the following order--
 * <p/>//from   w  w w  .  j  a va 2  s .  c  o m
 * 1. Azkaban (or other) executor params
 * 2. properties passed through -f argument (for multiple order in CLI order)
 * 3. properties passed as -D arguments directly on CLI
 *
 * @param cmdLine
 * @param executorProps
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
private static Properties getProperties(CommandLine cmdLine, Properties executorProps)
        throws URISyntaxException, IOException {
    Properties props = new Properties();

    // 1. Substitute executor params
    if (executorProps != null) {
        props.putAll(extractCubertParams(executorProps));
    }

    // 2. -f properties
    String[] propFiles = cmdLine.getOptionValues("f");
    if (propFiles != null && propFiles.length > 0) {
        for (String propFile : propFiles) {
            URI uri = new URI(propFile);
            boolean isHDFS = (uri.getScheme() != null) && uri.getScheme().equalsIgnoreCase("hdfs");
            String path = uri.getPath();
            if (isHDFS) {
                props.load(new BufferedReader(
                        new InputStreamReader(FileSystem.get(new JobConf()).open(new Path(path)))));
            } else {
                props.load(new BufferedReader(new FileReader(path)));
            }
        }
    }

    // 3. -D properties
    if (cmdLine.getOptionProperties("D").size() > 0) {
        props.putAll(cmdLine.getOptionProperties("D"));
    }
    return props;
}

From source file:io.werval.cli.DamnSmallDevShell.java

private static Set<File> prepareSourcesRoots(boolean debug, CommandLine cmd) {
    String[] sourcesPaths = cmd.hasOption('s') ? cmd.getOptionValues('s')
            : new String[] { "src" + separator + "main" + separator + "java",
                    "src" + separator + "main" + separator + "resources" };
    Set<File> sourcesRoots = new LinkedHashSet<>();
    for (String sourceRoot : sourcesPaths) {
        sourcesRoots.add(new File(sourceRoot));
    }/*from  w  ww  .j  a v a2  s  .  c o m*/
    if (debug) {
        System.out.println("Sources roots are: " + sourcesRoots);
    }
    return sourcesRoots;
}

From source file:ch.zhaw.iamp.rct.App.java

private static void handleArguments(String[] args) {
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine;

    try {// www.  j a v  a2s  . c  o m
        commandLine = parser.parse(cliOptions, args);
    } catch (ParseException ex) {
        System.out.println("The arguments could not be understood: " + ex.getMessage());
        printCliHelp();
        return;
    }

    if (commandLine.hasOption("g")) {
        System.out.println("The generation grammar is not implemented yet.");
        return;
    }

    if (commandLine.hasOption("w")) {
        String[] optionValues = commandLine.getOptionValues("w");
        Weights.calculateWeights(optionValues[0], optionValues[1], optionValues[2], 1000);
        return;
    }

    if (commandLine.getOptions() != null && commandLine.getOptions().length > 0) {
        System.out.println("The arguments could not be understood.\n");
        printCliHelp();
        return;
    }

    controller.showMainWindow();
}

From source file:com.act.biointerpretation.l2expansion.L2FilteringDriver.java

private static L2PredictionCorpus runDbLookups(CommandLine cl, L2PredictionCorpus predictionCorpus,
        Options opts) throws IOException {

    if (cl.hasOption(OPTION_DB_LOOKUP)) {

        if (cl.hasOption(OPTION_LOOKUP_TYPES)) {

            LOGGER.info("Instantiating mongoDB.");
            MongoDB mongoDB = new MongoDB("localhost", 27017, cl.getOptionValue(OPTION_DB_LOOKUP));

            String[] lookupOptions = cl.getOptionValues(OPTION_LOOKUP_TYPES);
            Set<String> lookupSet = new HashSet<>();
            for (String option : lookupOptions) {
                if (!option.equals(LOOKUP_CHEMICALS) && !option.equals(LOOKUP_REACTIONS)) {
                    LOGGER.error("Invalid lookup option supplied: %s", option);
                    HELP_FORMATTER.printHelp(L2FilteringDriver.class.getCanonicalName(), HELP_MESSAGE, opts,
                            null, true);
                    System.exit(1);
                }/*from   w  w w . j av  a2s  . c o m*/
                lookupSet.add(option);
            }

            if (lookupSet.contains(LOOKUP_CHEMICALS)) {
                LOGGER.info("Looking up chemicals in DB.");
                predictionCorpus = predictionCorpus.applyTransformation(new ChemicalsTransformer(mongoDB));
            }
            if (lookupSet.contains(LOOKUP_REACTIONS)) {
                LOGGER.info("Looking up reactions in DB.");
                predictionCorpus = predictionCorpus.applyTransformation(new ReactionsTransformer(mongoDB));
            }

        } else {
            LOGGER.warn("Mongo DB instantiated but lookup option not selected.");
        }
    }
    return predictionCorpus;
}

From source file:com.flipkart.fdp.migration.distcp.core.MirrorDistCPDriver.java

@SuppressWarnings("static-access")
public static DCMConfig getParams(String[] args) throws Exception {

    Options options = new Options();

    options.addOption("p", true, "properties filename from the classpath");
    options.addOption("P", true, "external properties filename");
    options.addOption("D", true, "JVM and Hadoop Configuration Override");
    options.addOption("V", true, "Custom runtime config variables");
    options.addOption("J", true, "properties as JSON String");
    options.addOption("libjars", true, "JVM and Hadoop Configuration Override");

    options.addOption(OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value for given property").create("D"));

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

    String path = null;// w  ww . jav a  2 s  .c om
    if (cmd.hasOption('p')) {
        path = cmd.getOptionValue('p');
    } else if (cmd.hasOption('P')) {
        path = cmd.getOptionValue('P');
    }
    HashMap<String, String> varMap = new HashMap<String, String>();
    if (cmd.hasOption('V')) {
        String runtimeVars[] = cmd.getOptionValues('V');
        for (String var : runtimeVars) {
            String kv[] = var.split("=");
            varMap.put("#" + kv[0], kv[1]);
        }
    }
    if (cmd.hasOption('J')) {
        String configString = cmd.getOptionValue('J');
        Gson gson = new Gson();
        return gson.fromJson(configString, DCMConfig.class);
    }

    if (path == null || !new File(path).exists()) {
        throw new Exception("Unable to load Config File...");
    }
    String configString = MirrorUtils.getFileAsString(path);

    if (varMap.size() > 0) {

        for (Entry<String, String> kv : varMap.entrySet()) {
            System.out.println("Custom Config Replacer: " + kv.getKey() + ", with: " + kv.getValue());
            configString = configString.replace(kv.getKey(), kv.getValue());
        }
    }
    Gson gson = new Gson();
    return gson.fromJson(configString, DCMConfig.class);
}

From source file:com.ibm.ie.tachyon.fuse.TachyonFuse.java

/**
 * Parses CLI options//ww w.ja va 2s . c  o m
 * @param args CLI args
 * @return Tachyon-FUSE configuration options
 */
private static TachyonFuseOptions parseOptions(String[] args) {
    final Options opts = new Options();
    final Option mntPoint = Option.builder("m").hasArg().required(false).longOpt("mount-point")
            .desc("Path where tachyon-fuse should be mounted.").build();

    final Option tachyonAddress = Option.builder("t").hasArg().required(false).longOpt("tachyon-master")
            .desc("URI of the Tachyon Master (e.g. tachyon://localhost:19998/").build();

    final Option tachyonRoot = Option.builder("r").hasArg().required(false).longOpt("tachyon-root")
            .desc("Path within tachyon that will be the root of the mount (e.g., /users/foo)").build();

    final Option help = Option.builder("h").required(false).desc("Print this help").build();

    final Option debug = Option.builder("d").required(false).longOpt("debug").desc("Enable FUSE debug output")
            .build();

    final Option fuseOption = Option.builder("o").valueSeparator(',').required(false).hasArgs()
            .desc("FUSE mount options").build();

    opts.addOption(mntPoint);
    opts.addOption(tachyonAddress);
    opts.addOption(tachyonRoot);
    opts.addOption(help);
    opts.addOption(debug);
    opts.addOption(fuseOption);

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

        if (cli.hasOption("h")) {
            final HelpFormatter fmt = new HelpFormatter();
            fmt.printHelp(TachyonFuse.class.getName(), opts);
            return null;
        }

        String m = cli.getOptionValue("m");
        String t = cli.getOptionValue("t");
        String r = cli.getOptionValue("r");
        boolean d = cli.hasOption("d");

        List<String> fuseOpts;
        if (cli.hasOption("o")) {
            String[] fopts = cli.getOptionValues("o");
            fuseOpts = new ArrayList<>(fopts.length);
            // keep the -o
            for (int i = 0; i < fopts.length; i++) {
                fuseOpts.add("-o" + fopts[i]);
            }
        } else {
            fuseOpts = Collections.emptyList();
        }

        if (m == null) {
            LOG.info("Mounting on default {}", TachyonFuse.DEFAULT_MOUNT_POINT);
            m = TachyonFuse.DEFAULT_MOUNT_POINT;
        }

        if (t == null) {
            LOG.info("Using default master address {}", TachyonFuse.DEFAULT_MASTER_ADDR);
            t = TachyonFuse.DEFAULT_MASTER_ADDR;
        }

        if (r == null) {
            LOG.info("Using default tachyon root {}", TachyonFuse.DEFAULT_ROOT);
            r = TachyonFuse.DEFAULT_ROOT;
        }

        return new TachyonFuseOptions(m, t, r, d, fuseOpts);
    } catch (ParseException e) {
        System.err.println("Error while parsing CLI: " + e.getMessage());
        final HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp(TachyonFuse.class.getName(), opts);
        return null;
    }

}

From source file:alluxio.fuse.AlluxioFuse.java

/**
 * Parses CLI options.//from   ww  w  . ja  v  a2s. c om
 *
 * @param args CLI args
 * @return Alluxio-FUSE configuration options
 */
private static AlluxioFuseOptions parseOptions(String[] args) {
    final Options opts = new Options();
    final Option mntPoint = Option.builder("m").hasArg().required(false).longOpt("mount-point")
            .desc("Desired local mount point for alluxio-fuse.").build();

    final Option alluxioRoot = Option.builder("r").hasArg().required(false).longOpt("alluxio-root")
            .desc("Path within alluxio that will be used as the root of the FUSE mount "
                    + "(e.g., /users/foo; defaults to /)")
            .build();

    final Option help = Option.builder("h").required(false).desc("Print this help").build();

    final Option fuseOption = Option.builder("o").valueSeparator(',').required(false).hasArgs()
            .desc("FUSE mount options").build();

    opts.addOption(mntPoint);
    opts.addOption(alluxioRoot);
    opts.addOption(help);
    opts.addOption(fuseOption);

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

        if (cli.hasOption("h")) {
            final HelpFormatter fmt = new HelpFormatter();
            fmt.printHelp(AlluxioFuse.class.getName(), opts);
            return null;
        }

        String mntPointValue = cli.getOptionValue("m");
        String alluxioRootValue = cli.getOptionValue("r");

        List<String> fuseOpts = new ArrayList<>();
        boolean noUserMaxWrite = true;
        if (cli.hasOption("o")) {
            String[] fopts = cli.getOptionValues("o");
            // keep the -o
            for (final String fopt : fopts) {
                fuseOpts.add("-o" + fopt);
                if (noUserMaxWrite && fopt.startsWith("max_write")) {
                    noUserMaxWrite = false;
                }
            }
        }
        // check if the user has specified his own max_write, otherwise get it
        // from conf
        if (noUserMaxWrite) {
            final long maxWrite = Configuration.getLong(PropertyKey.FUSE_MAXWRITE_BYTES);
            fuseOpts.add(String.format("-omax_write=%d", maxWrite));
        }

        if (mntPointValue == null) {
            mntPointValue = Configuration.get(PropertyKey.FUSE_MOUNT_DEFAULT);
            LOG.info("Mounting on default {}", mntPointValue);
        }

        if (alluxioRootValue == null) {
            alluxioRootValue = Configuration.get(PropertyKey.FUSE_FS_ROOT);
            LOG.info("Using default alluxio root {}", alluxioRootValue);
        }

        final boolean fuseDebug = Configuration.getBoolean(PropertyKey.FUSE_DEBUG_ENABLED);

        return new AlluxioFuseOptions(mntPointValue, alluxioRootValue, fuseDebug, fuseOpts);
    } catch (ParseException e) {
        System.err.println("Error while parsing CLI: " + e.getMessage());
        final HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp(AlluxioFuse.class.getName(), opts);
        return null;
    }
}