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.soteradefense.dga.DGACommandLineUtil.java

public static DGAConfiguration parseCommandLine(String[] args, Options options) throws ParseException {
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        printUsageAndExit(options);/*  w w  w  .  j  a  va2 s.c o m*/
    }

    DGAConfiguration dgaConf = new DGAConfiguration();

    if (cmd.hasOption("q")) {
        dgaConf.setGiraphProperty("-q", "");
    }

    if (cmd.hasOption("w")) {
        dgaConf.setGiraphProperty("-w", cmd.getOptionValue("w"));
    }

    if (cmd.hasOption("yj")) {
        dgaConf.setGiraphProperty("-yj", cmd.getOptionValue("yj"));
    }

    if (cmd.hasOption("yh")) {
        dgaConf.setGiraphProperty("-yh", cmd.getOptionValue("yh"));
    }

    if (cmd.hasOption("ca")) {
        String[] customArguments = cmd.getOptionValues("ca");
        for (String customArgument : customArguments) {
            int indexOfEquals = customArgument.indexOf("=");
            if (indexOfEquals == -1)
                throw new ParseException(
                        "The custom argument " + customArgument + " does not follow the form -ca key=value");
            String key = customArgument.substring(0, indexOfEquals);
            String value = customArgument.substring(indexOfEquals + 1);
            if (characterMap.containsKey(value)) {
                value = String.valueOf(characterMap.get(value));
            }
            dgaConf.setCustomProperty(key, value);
        }
    }

    if (cmd.hasOption("D")) {
        String[] systemProperty = cmd.getOptionValues("D");
        for (String sysProp : systemProperty) {
            int indexOfEquals = sysProp.indexOf("=");
            if (indexOfEquals == -1)
                throw new ParseException(
                        "The systemProperty " + sysProp + " does not follow the form -D key=value");
            String key = sysProp.substring(0, indexOfEquals);
            String value = sysProp.substring(indexOfEquals + 1);
            dgaConf.setSystemProperty(key, value);
        }
    }

    return dgaConf;
}

From source file:boa.compiler.BoaCompiler.java

public static void parseOnly(final String[] args) throws IOException {
    final CommandLine cl = processParseCommandLineOptions(args);
    if (cl == null)
        return;//from w  w w . j  av  a  2 s  .  co  m
    final ArrayList<File> inputFiles = BoaCompiler.inputFiles;

    // find custom libs to load
    final List<URL> libs = new ArrayList<URL>();
    if (cl.hasOption('l'))
        for (final String lib : cl.getOptionValues('l'))
            libs.add(new File(lib).toURI().toURL());

    SymbolTable.initialize(libs);

    final int maxVisitors;
    if (cl.hasOption('v'))
        maxVisitors = Integer.parseInt(cl.getOptionValue('v'));
    else
        maxVisitors = Integer.MAX_VALUE;

    for (int i = 0; i < inputFiles.size(); i++) {
        final File f = inputFiles.get(i);
        try {
            final BoaLexer lexer = new BoaLexer(new ANTLRFileStream(f.getAbsolutePath()));
            lexer.removeErrorListeners();
            lexer.addErrorListener(new LexerErrorListener());

            final CommonTokenStream tokens = new CommonTokenStream(lexer);
            final BoaParser parser = new BoaParser(tokens);
            parser.removeErrorListeners();
            parser.addErrorListener(new BaseErrorListener() {
                @Override
                public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                        int charPositionInLine, String msg, RecognitionException e)
                        throws ParseCancellationException {
                    throw new ParseCancellationException(e);
                }
            });

            final BoaErrorListener parserErrorListener = new ParserErrorListener();
            final Start p = parse(tokens, parser, parserErrorListener);

            try {
                if (!parserErrorListener.hasError) {
                    new TypeCheckingVisitor().start(p, new SymbolTable());

                    final TaskClassifyingVisitor simpleVisitor = new TaskClassifyingVisitor();
                    simpleVisitor.start(p);

                    LOG.info(f.getName() + ": task complexity: "
                            + (!simpleVisitor.isComplex() ? "simple" : "complex"));
                }
            } catch (final TypeCheckException e) {
                parserErrorListener.error("typecheck", lexer, null, e.n.beginLine, e.n.beginColumn,
                        e.n2.endColumn - e.n.beginColumn + 1, e.getMessage(), e);
            }
        } catch (final Exception e) {
            System.err.print(f.getName() + ": parsing failed: ");
            e.printStackTrace();
        }
    }
}

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

private static URL[] prepareRuntimeClasspath(boolean debug, Set<File> sourcesRoots, CommandLine cmd)
        throws MalformedURLException {
    List<URL> classpathList = new ArrayList<>();
    // First, current classpath
    classpathList.addAll(ClassLoaders.urlsOf(DamnSmallDevShell.class.getClassLoader()));
    // Then add command line provided
    if (cmd.hasOption('c')) {
        for (String url : cmd.getOptionValues('c')) {
            classpathList.add(new URL(url));
        }/*from w ww. java  2s. c o  m*/
    }
    // Append Application sources
    for (File sourceRoot : sourcesRoots) {
        classpathList.add(sourceRoot.toURI().toURL());
    }
    URL[] runtimeClasspath = classpathList.toArray(new URL[classpathList.size()]);
    if (debug) {
        System.out.println("Runtime Classpath is: " + classpathList);
    }
    return runtimeClasspath;
}

From source file:com.alibaba.jstorm.yarn.utils.JstormYarnUtils.java

public static void setShellEnv(CommandLine cliParser, MasterContext jstormContext) {
    if (cliParser.hasOption(JOYConstants.SHELL_ENV)) {
        String envs[] = cliParser.getOptionValues(JOYConstants.SHELL_ENV);
        for (String env : envs) {
            env = env.trim();//  w w w  . java2 s.  c o m
            int index = env.indexOf(JOYConstants.EQUAL);
            if (index == -1) {
                jstormContext.getShellEnv().put(env, JOYConstants.EMPTY);
                continue;
            }
            String key = env.substring(0, index);
            String val = JOYConstants.EMPTY;
            if (index < (env.length() - 1)) {
                val = env.substring(index + 1);
            }
            jstormContext.getShellEnv().put(key, val);
        }
    }
}

From source file:net.skyebook.zerocollada.ZeroCollada.java

private static void doRequestedAction(File file, CommandLine cmd) throws IOException, JDOMException {
    // what is the operation?
    if (cmd.hasOption(ZCOpts.transform)) {
        // Do a transform that brings us as close to zero as possible
        Document dom = createDocument(file);

        ClosestToOriginTransformer ct = new ClosestToOriginTransformer(dom, cmd.hasOption(ZCOpts.includeX),
                cmd.hasOption(ZCOpts.includeY), cmd.hasOption(ZCOpts.includeZ));
        file = removeOldXYZTag(file);/*from ww  w  .j  a  v a 2s.com*/
        ct.writeColladaToFile(newFilename(file, ct));
        // recollect the resources
        ct = null;
        dom = null;
        System.gc();
    } else if (cmd.hasOption(ZCOpts.translate)) {
        cmd.getOptionValues(ZCOpts.translate);
        //System.out.println("Args: " + cmd.getOptionValues(ZCOpts.translate).length);
        if (cmd.getOptionValues(ZCOpts.translate).length == 0) {
            showHelp();
        } else {
            Translation translation = new Translation(createDocument(file));
            for (int i = 0; i < cmd.getOptionValues(ZCOpts.translate).length; i++) {
                String arg = cmd.getOptionValues(ZCOpts.translate)[i];
                if (arg.equals("zerowithname")) {
                    translation.zeroTranslation(cmd.getOptionValues(ZCOpts.translate)[i + 1]);
                } else if (arg.equals("zerowithoutname")) {
                    translation.zeroAllTranslationsExcept(cmd.getOptionValues(ZCOpts.translate)[i + 1]);
                }
            }
            translation.writeColladaToFile(newFilename(file, translation));
        }
    }
}

From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java

/**
 * Outputs the results based on the command line parameters.
 *
 * @param cmdLine the parsed command line parameters
 * @param bestKeywords the optimized set of keywords
 * @throws KeywordOptimizerException in case there is no output file specified
 *//*from   w  w w .j  ava 2s.  c  o  m*/
private static void output(CommandLine cmdLine, KeywordCollection bestKeywords)
        throws KeywordOptimizerException {
    if (!cmdLine.hasOption("o")) {
        outputCsv(cmdLine, bestKeywords);
    } else {
        for (String mode : cmdLine.getOptionValues("o")) {
            if ("CONSOLE".equalsIgnoreCase(mode)) {
                outputConsole(bestKeywords);
            } else if ("CSV".equalsIgnoreCase(mode)) {
                outputCsv(cmdLine, bestKeywords);
            } else {
                throw new KeywordOptimizerException("Output mode '" + mode + "' is not supported");
            }
        }
    }
}

From source file:ai.grakn.graql.GraqlShell.java

public static void runShell(String[] args, String version, String historyFilename, GraqlClient client) {

    Options options = new Options();
    options.addOption("k", "keyspace", true, "keyspace of the graph");
    options.addOption("e", "execute", true, "query to execute");
    options.addOption("f", "file", true, "graql file path to execute");
    options.addOption("r", "uri", true, "uri to factory to engine");
    options.addOption("b", "batch", true, "graql file path to batch load");
    options.addOption("s", "size", true, "the size of the batches (must be used with -b)");
    options.addOption("a", "active", true, "the number of active tasks (must be used with -b)");
    options.addOption("o", "output", true, "output format for results");
    options.addOption("u", "user", true, "username to sign in");
    options.addOption("p", "pass", true, "password to sign in");
    options.addOption("i", "implicit", false, "show implicit types");
    options.addOption("n", "infer", false, "perform inference on results");
    options.addOption("m", "materialise", false, "materialise inferred results");
    options.addOption("h", "help", false, "print usage message");
    options.addOption("v", "version", false, "print version");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;

    try {//from w  ww .  j  a  va 2 s  .  c  o  m
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        return;
    }

    Optional<List<String>> queries = Optional.ofNullable(cmd.getOptionValue("e")).map(Lists::newArrayList);
    String[] filePaths = cmd.getOptionValues("f");

    // Print usage message if requested or if invalid arguments provided
    if (cmd.hasOption("h") || !cmd.getArgList().isEmpty()) {
        printUsage(options, null);
        return;
    }

    if (cmd.hasOption("v")) {
        System.out.println(version);
        return;
    }

    String keyspace = cmd.getOptionValue("k", DEFAULT_KEYSPACE);
    String uriString = cmd.getOptionValue("r", DEFAULT_URI);
    String outputFormat = cmd.getOptionValue("o", DEFAULT_OUTPUT_FORMAT);
    Optional<String> username = Optional.ofNullable(cmd.getOptionValue("u"));
    Optional<String> password = Optional.ofNullable(cmd.getOptionValue("p"));

    boolean showImplicitTypes = cmd.hasOption("i");
    boolean infer = cmd.hasOption("n");
    boolean materialise = cmd.hasOption("m");

    if (cmd.hasOption("b")) {
        try {
            Optional<Integer> activeTasks = Optional.empty();
            Optional<Integer> batchSize = Optional.empty();
            if (cmd.hasOption("a")) {
                activeTasks = Optional.of(Integer.parseInt(cmd.getOptionValue("a")));
            }
            if (cmd.hasOption("s")) {
                batchSize = Optional.of(Integer.parseInt(cmd.getOptionValue("s")));
            }
            try {
                sendBatchRequest(client.loaderClient(keyspace, uriString), cmd.getOptionValue("b"), activeTasks,
                        batchSize);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (NumberFormatException e) {
            printUsage(options, "Cannot cast argument to an integer " + e.getMessage());
        }
        return;
    } else if (cmd.hasOption("a") || cmd.hasOption("s")) {
        printUsage(options, "The active or size option has been specified without batch.");
        return;
    }

    try {
        if (filePaths != null) {
            queries = Optional.of(loadQueries(filePaths));
        }

        URI uri = new URI("ws://" + uriString + REMOTE_SHELL_URI);

        new GraqlShell(historyFilename, keyspace, username, password, client, uri, queries, outputFormat,
                showImplicitTypes, infer, materialise);
    } catch (java.net.ConnectException e) {
        System.err.println(ErrorMessage.COULD_NOT_CONNECT.getMessage());
    } catch (Throwable e) {
        System.err.println(getFullStackTrace(e));
    }
}

From source file:exm.stc.ui.Main.java

private static Args processArgs(String[] args) {
    Options opts = initOptions();//w w w  .j a v  a2 s . c  o m

    CommandLine cmd = null;
    try {
        CommandLineParser parser = new GnuParser();
        cmd = parser.parse(opts, args);
    } catch (ParseException ex) {
        // Use Apache CLI-provided messages
        System.err.println(ex.getMessage());
        usage(opts);
        System.exit(1);
        return null;
    }

    boolean updateOutput = cmd.hasOption(UPDATE_FLAG);

    if (cmd.hasOption(INCLUDE_FLAG)) {
        for (String dir : cmd.getOptionValues(INCLUDE_FLAG)) {
            Settings.addModulePath(dir);
        }
    }

    Properties swiftProgramArgs = cmd.getOptionProperties(SWIFT_PROG_ARG_FLAG);

    String preprocMacros[];
    if (cmd.hasOption(PREPROC_MACRO_FLAG)) {
        preprocMacros = cmd.getOptionValues(PREPROC_MACRO_FLAG);
    } else {
        preprocMacros = new String[0];
    }

    String[] remainingArgs = cmd.getArgs();
    if (remainingArgs.length < 1 || remainingArgs.length > 2) {
        System.out.println(
                "Expected input file and optional output file, but got " + remainingArgs.length + " arguments");
        usage(opts);
        System.exit(ExitCode.ERROR_COMMAND.code());
    }

    String input = remainingArgs[0];
    String output = null;
    if (remainingArgs.length == 2) {
        output = remainingArgs[1];
    }
    Args result = new Args(input, output, updateOutput, swiftProgramArgs, Arrays.asList(preprocMacros));
    recordArgValues(result);
    return result;
}

From source file:com.gNova.circularFP.Fingerprinter.java

private static void parseCommandLine(String... args) {
    CommandLineParser parser = new PosixParser();
    Options options = defineCommandLineOptions();
    try {/*  w  ww.j  ava 2 s  . com*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("help"))
            usage(null, options);
        if (!cmd.hasOption("in"))
            usage("In file required", options);

        infile = cmd.getOptionValue("in", ".sdf");
        outfile = cmd.getOptionValue("out", ".sdf");
        format = cmd.getOptionValue("format", "hex");
        type = cmd.getOptionValue("type", "atomic");
        smaFile = cmd.getOptionValue("functionDefinition");

        countType = CFPCountType.NOCount;
        if (cmd.hasOption("count"))
            countType = CFPCountType.valueOf(cmd.getOptionValue("count"));

        if (cmd.hasOption("verbose"))
            Fingerprinter.verbose = true;

        String[] lvlStr = cmd.getOptionValues("level");
        if (lvlStr != null) {
            levels = new int[lvlStr.length];
            for (int i = 0; i < lvlStr.length; i++)
                levels[i] = Integer.parseInt(lvlStr[i]);
        }

        nbits = Integer.parseInt(cmd.getOptionValue("nbits", "256"));
    } catch (Exception exp) {
        String msg = "Parsing failed: " + exp.getMessage();
        usage(msg, options);
    }
    validateOptions(options);
}

From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java

/**
 * Creates the seed generator based on the command line options.
 *
 * @param cmdLine the parsed command line parameters
 * @param context holding shared objects during the optimization process
 * @return a {@link SeedGenerator} object
 * @throws KeywordOptimizerException in case of an error constructing the seed generator
 *///  w w w.  jav a2 s  . c om
private static SeedGenerator getSeedGenerator(CommandLine cmdLine, OptimizationContext context)
        throws KeywordOptimizerException {
    Option seedOption = getOnlySeedOption(cmdLine);

    if ("sk".equals(seedOption.getOpt())) {
        String[] keywords = cmdLine.getOptionValues("sk");

        SimpleSeedGenerator seedGenerator = new SimpleSeedGenerator();
        for (String keyword : keywords) {
            log("Using seed keyword: " + keyword);
            seedGenerator.addKeyword(keyword);
        }

        return seedGenerator;
    } else if ("skf".equals(seedOption.getOpt())) {
        List<String> keywords = loadFromFile(cmdLine.getOptionValue("skf"));

        SimpleSeedGenerator seedGenerator = new SimpleSeedGenerator();
        for (String keyword : keywords) {
            log("Using seed keyword: " + keyword);
            seedGenerator.addKeyword(keyword);
        }

        return seedGenerator;
    } else if ("st".equals(seedOption.getOpt())) {
        String[] keywords = cmdLine.getOptionValues("st");

        TisSearchTermsSeedGenerator seedGenerator = new TisSearchTermsSeedGenerator(context, null);
        for (String keyword : keywords) {
            log("Using seed search term: " + keyword);
            seedGenerator.addSearchTerm(keyword);
        }

        return seedGenerator;
    } else if ("stf".equals(seedOption.getOpt())) {
        List<String> terms = loadFromFile(cmdLine.getOptionValue("skf"));

        TisSearchTermsSeedGenerator seedGenerator = new TisSearchTermsSeedGenerator(context, null);
        for (String term : terms) {
            log("Using seed serach term: " + term);
            seedGenerator.addSearchTerm(term);
        }

        return seedGenerator;
    } else if ("su".equals(seedOption.getOpt())) {
        String[] urls = cmdLine.getOptionValues("su");

        TisUrlSeedGenerator seedGenerator = new TisUrlSeedGenerator(context, null);
        for (String url : urls) {
            log("Using seed url: " + url);
            seedGenerator.addUrl(url);
        }

        return seedGenerator;
    } else if ("suf".equals(seedOption.getOpt())) {
        List<String> urls = loadFromFile(cmdLine.getOptionValue("suf"));

        TisUrlSeedGenerator seedGenerator = new TisUrlSeedGenerator(context, null);
        for (String url : urls) {
            log("Using seed url: " + url);
            seedGenerator.addUrl(url);
        }

        return seedGenerator;
    } else if ("sc".equals(seedOption.getOpt())) {
        int category = Integer.parseInt(seedOption.getValue());
        log("Using seed category: " + category);
        TisCategorySeedGenerator seedGenerator = new TisCategorySeedGenerator(context, category, null);
        return seedGenerator;
    }

    throw new KeywordOptimizerException("Seed option " + seedOption.getOpt() + " is not supported yet");
}