当前位置: 首页>>代码示例>>Java>>正文


Java CommandLine.getOptionValues方法代码示例

本文整理汇总了Java中org.apache.commons.cli.CommandLine.getOptionValues方法的典型用法代码示例。如果您正苦于以下问题:Java CommandLine.getOptionValues方法的具体用法?Java CommandLine.getOptionValues怎么用?Java CommandLine.getOptionValues使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.commons.cli.CommandLine的用法示例。


在下文中一共展示了CommandLine.getOptionValues方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: handle

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
@Override
public boolean handle(@NotNull MessageReceivedEvent event, String command, @NotNull String matchedText) throws
        RateLimitException, DiscordException, MissingPermissionsException {

    if (HELLO_COMMAND.mainCommand().equalsIgnoreCase(command)) {
        try {
            CommandLine cmd = HELLO_COMMAND.parse(matchedText);

            if (HELLO_COMMAND.showHelpIfPresent(event.getClient(), event.getMessage().getChannel(), cmd)) {
                return true;
            }

            boolean isMention = cmd.hasOption("m");
            String[] to = cmd.getOptionValues("m");

            sendHelloWorld(event, isMention, to);

        } catch (ParseException e) {
            logger.info("Parsing failed", e);
            EventUtils.sendIncorrectUsageMessage(event.getClient(), event.getMessage().getChannel(), HELLO_COMMAND.mainCommand(), e.getMessage());
        }
        return true;
    }
    return false;
}
 
开发者ID:ViniciusArnhold,项目名称:ProjectAltaria,代码行数:26,代码来源:SimpleCommandHandler.java

示例2: find

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
@Override
public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) {
    if(input.getOptionValues(action.name()).length == 2) {
        switch(action) {
            case download:
                return new DownloadTransferItemFinder().find(input, action, remote);
            case upload:
            case synchronize:
                return new UploadTransferItemFinder().find(input, action, remote);
        }
    }
    else {
        switch(action) {
            case upload:
            case synchronize:
                return Collections.emptySet();
        }
    }
    // Relative to current working directory using prefix finder.
    return Collections.singleton(
            new TransferItem(remote, LocalFactory.get(prefixer.normalize(remote.getName())))
    );
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:24,代码来源:SingleTransferItemFinder.java

示例3: main

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
/**
 * Main method for invocation from the command line. Handles parsing of command line options.
 */
public static void main(String[] args) throws BuildStepException, IOException {
  addCliOptions(CLI_OPTIONS);
  CommandLine cmd = parse(args);
  String[] jdkMappings = cmd.getOptionValues("j");
  String[] serverMappings = cmd.getOptionValues("s");
  String compatImage = cmd.getOptionValue("c");
  String mavenImage = cmd.getOptionValue("m");
  String gradleImage = cmd.getOptionValue("g");
  boolean disableSourceBuild = cmd.hasOption("n");

  Injector injector = Guice.createInjector(
      new RootModule(mergeSettingsWithDefaults(jdkMappings, serverMappings),
          compatImage == null ? DEFAULT_COMPAT_RUNTIME_IMAGE : compatImage,
          mavenImage == null ? DEFAULT_MAVEN_DOCKER_IMAGE : mavenImage,
          gradleImage == null ? DEFAULT_GRADLE_DOCKER_IMAGE : gradleImage,
          disableSourceBuild, getAppYamlOverrideSettings(cmd)));

  // Perform dependency injection and run the application
  Path workspaceDir = Paths.get(System.getProperty("user.dir"));
  injector.getInstance(BuildPipelineConfigurator.class).generateDockerResources(workspaceDir);
}
 
开发者ID:GoogleCloudPlatform,项目名称:runtime-builder-java,代码行数:25,代码来源:Application.java

示例4: areInputFilesValid

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
private static boolean areInputFilesValid(CommandLine commandLine, ValidatedArgs validatedArgs) {
    validatedArgs.inputFiles = new LinkedList<>();
    if (commandLine.hasOption(CommandLineOptions.INPUT_FILES)) {
        String[] inputFileStrings = commandLine.getOptionValues(CommandLineOptions.INPUT_FILES);
        for (String inputFileStr : inputFileStrings) {
            // TODO: if no path separator is in the inputFile String, assume current directory as path and append it
            File input = new File(inputFileStr);
            if ((!input.exists()) || (!input.canRead())) {
                System.out.println("Input file: " + inputFileStr + " does not exist or cannot be read!");
                return false;
            } else {
                validatedArgs.inputFiles.add(input);
            }
        }
        return true;
    }
    return false;
}
 
开发者ID:rmcnew,项目名称:LiquidFortressPacketAnalyzer,代码行数:19,代码来源:CommandLineValidator.java

示例5: processGeneralOptions

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
/**
 * Modify configuration according user-specified generic options
 * @param conf Configuration to be modified
 * @param line User-specified generic options
 */
private void processGeneralOptions(Configuration conf,
    CommandLine line) throws IOException {
  if (line.hasOption("fs")) {
    FileSystem.setDefaultUri(conf, line.getOptionValue("fs"));
  }

  if (line.hasOption("jt")) {
    String optionValue = line.getOptionValue("jt");
    if (optionValue.equalsIgnoreCase("local")) {
      conf.set("mapreduce.framework.name", optionValue);
    }

    conf.set("yarn.resourcemanager.address", optionValue, 
        "from -jt command line option");
  }
  if (line.hasOption("conf")) {
    String[] values = line.getOptionValues("conf");
    for(String value : values) {
      conf.addResource(new Path(value));
    }
  }

  if (line.hasOption('D')) {
    String[] property = line.getOptionValues('D');
    for(String prop : property) {
      String[] keyval = prop.split("=", 2);
      if (keyval.length == 2) {
        conf.set(keyval[0], keyval[1], "from command line");
      }
    }
  }

  if (line.hasOption("libjars")) {
    conf.set("tmpjars", 
             validateFiles(line.getOptionValue("libjars"), conf),
             "from -libjars command line option");
    //setting libjars in client classpath
    URL[] libjars = getLibJars(conf);
    if(libjars!=null && libjars.length>0) {
      conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader()));
      Thread.currentThread().setContextClassLoader(
          new URLClassLoader(libjars, 
              Thread.currentThread().getContextClassLoader()));
    }
  }
  if (line.hasOption("files")) {
    conf.set("tmpfiles", 
             validateFiles(line.getOptionValue("files"), conf),
             "from -files command line option");
  }
  if (line.hasOption("archives")) {
    conf.set("tmparchives", 
              validateFiles(line.getOptionValue("archives"), conf),
              "from -archives command line option");
  }
  conf.setBoolean("mapreduce.client.genericoptionsparser.used", true);
  
  // tokensFile
  if(line.hasOption("tokenCacheFile")) {
    String fileName = line.getOptionValue("tokenCacheFile");
    // check if the local file exists
    FileSystem localFs = FileSystem.getLocal(conf);
    Path p = localFs.makeQualified(new Path(fileName));
    if (!localFs.exists(p)) {
        throw new FileNotFoundException("File "+fileName+" does not exist.");
    }
    if(LOG.isDebugEnabled()) {
      LOG.debug("setting conf tokensFile: " + fileName);
    }
    UserGroupInformation.getCurrentUser().addCredentials(
        Credentials.readTokenStorageFile(p, conf));
    conf.set("mapreduce.job.credentials.binary", p.toString(),
             "from -tokenCacheFile command line option");

  }
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:82,代码来源:GenericOptionsParser.java

示例6: testDefaultSettingsMatchJavaYaml

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
/**
 * A check that the default settings are not outdated compared to what is in java.yaml.
 */
@Test
public void testDefaultSettingsMatchJavaYaml()
    throws URISyntaxException, IOException, ParseException {
  Path path = Paths.get("../java.yaml");

  ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

  JavaYaml javaYaml = mapper.readValue(path.toFile(), JavaYaml.class);

  String[] args = ((ArrayList<String>) javaYaml.getSteps()[0].get("args")).toArray(new String[0]);

  Options options = new Options();

  Application.addCliOptions(options);

  CommandLine cmd = new DefaultParser().parse(options, args);

  String[] jdkMappings = cmd.getOptionValues("j");
  String[] serverMappings = cmd.getOptionValues("s");

  assertTrue(Arrays.equals(jdkMappings, Application.DEFAULT_JDK_MAPPINGS));
  assertTrue(Arrays.equals(serverMappings, Application.DEFAULT_SERVER_MAPPINGS));

  String compatImage = cmd.getOptionValue("c");
  String mavenImage = cmd.getOptionValue("m");
  String gradleImage = cmd.getOptionValue("g");

  assertEquals(compatImage, Application.DEFAULT_COMPAT_RUNTIME_IMAGE);
  assertEquals(mavenImage, Application.DEFAULT_MAVEN_DOCKER_IMAGE);
  assertEquals(gradleImage, Application.DEFAULT_GRADLE_DOCKER_IMAGE);
}
 
开发者ID:GoogleCloudPlatform,项目名称:runtime-builder-java,代码行数:35,代码来源:RootModuleTest.java

示例7: parse

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
public SpydraArgument parse(String[] args) throws IOException {
  DefaultParser parser = new DefaultParser();
  CommandLine cmdLine;

  cmdLine = CliHelper.tryParse(parser, options, args);

  SpydraArgument spydraArgument = new SpydraArgument();
  if (cmdLine.hasOption(CliConsts.SPYDRA_JSON_OPTION_NAME)) {
    String[] files = cmdLine.getOptionValues(CliConsts.SPYDRA_JSON_OPTION_NAME);
    for (String file : files) {
      spydraArgument = SpydraArgument.merge(spydraArgument,
          JsonHelper.objectMapper().readValue(new File(file), SpydraArgument.class));
    }
  }

  if (cmdLine.hasOption(CliConsts.JAR_OPTION_NAME)) {
    spydraArgument.getSubmit().getOptions().put(SpydraArgument.OPTION_JAR,
        cmdLine.getOptionValue(CliConsts.JAR_OPTION_NAME));
  }

  if (cmdLine.hasOption(CliConsts.CLIENT_ID_OPTION_NAME)) {
    spydraArgument.setClientId(cmdLine.getOptionValue(CliConsts.CLIENT_ID_OPTION_NAME));
  }

  if (cmdLine.hasOption(CliConsts.JARS_OPTION_NAME)) {
    spydraArgument.getSubmit().getOptions().put(SpydraArgument.OPTION_JARS,
        StringUtils.join(cmdLine.getOptionValues(CliConsts.JARS_OPTION_NAME), ","));
  }

  if (cmdLine.hasOption(CliConsts.JOBNAME_OPTION_NAME)) {
    spydraArgument.getSubmit().getOptions().put(SpydraArgument.OPTION_JOB_ID,
        sanitizeJobId(cmdLine.getOptionValue(CliConsts.JOBNAME_OPTION_NAME)));
  }

  if (spydraArgument.jobType.isPresent()) {
    spydraArgument.setJobType(spydraArgument.getJobType().toLowerCase());
  }

  if (cmdLine.hasOption(SpydraArgument.OPTION_DRYRUN)) {
    spydraArgument.setDryRun(true);
  }

  List<String> jobArgs = new LinkedList<>(cmdLine.getArgList());
  if (jobArgs.size() > 0) {
    spydraArgument.getSubmit().setJobArgs(jobArgs);
  }

  return spydraArgument;
}
 
开发者ID:spotify,项目名称:spydra,代码行数:50,代码来源:SubmissionCliParser.java

示例8: parseOptions

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
/**
 * Parses the introduced arguments to a map from ArgsOptions to String[] of introduced values.
 * 
 * @param options Prepared options.
 * @param args Introduced arguments.
 * @return Map from ArgsOptions to String[] of introduced values.
 * @throws ParseException If an error occurs parsing any of the options or the introduced
 *         arguments do not fit any of them.
 */
private static Map<ArgsOptions, String[]> parseOptions(
        Options options,
        String[] args)
        throws ParseException {

    CommandLine cmd = new DefaultParser().parse(options, args);
    Map<ArgsOptions, String[]> parsedOptions = new HashMap<>(ArgsOptions.values().length);

    for (ArgsOptions argsOption : ArgsOptions.values()) {

        if (cmd.hasOption(argsOption.longOption)) {

            String[] optionValues = cmd.getOptionValues(argsOption.longOption);
            if (optionValues == null) {
                optionValues = new String[0];
            }

            if (argsOption.minArgs > 0 && optionValues.length == 0) {
                throw new ParseException(String.format(
                        "Missing %s for option: %s.",
                        argsOption.maxArgs < 0 || argsOption.maxArgs > 1
                                ? "arguments" : "argument",
                        argsOption.display()));
            }

            if (argsOption.maxArgs == 0 && optionValues.length > 0) {
                throw new ParseException(String.format(
                        "Option %s takes no arguments.",
                        argsOption.display()));
            }

            if (argsOption.minArgs > 0 && optionValues.length < argsOption.minArgs) {
                throw new ParseException(String.format(
                        "Too few arguments for option: %s.",
                        argsOption.display()));
            }

            if (argsOption.maxArgs > 0 && optionValues.length > argsOption.maxArgs) {
                throw new ParseException(String.format(
                        "Too many arguments for option: %s.",
                        argsOption.display()));
            }

            parsedOptions.put(argsOption, optionValues);

        } else {

            if (argsOption.required) {
                throw new ParseException(String.format(
                        "Missing required option: %s.",
                        argsOption.display()));
            }

        }

    }

    return parsedOptions;

}
 
开发者ID:s3curitybug,项目名称:similarity-uniform-fuzzy-hash,代码行数:70,代码来源:Main.java

示例9: run

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
@Override
public int run(String[] args) throws Exception {

  Options opts = new Options();
  opts.addOption(HELP_CMD, false, "Displays help for all commands.");
  opts.addOption(STATUS_CMD, true, "Prints the status report of the node.");
  opts.addOption(LIST_CMD, false, "List all running nodes. " +
      "Supports optional use of -states to filter nodes " +
      "based on node state, all -all to list all nodes.");
  Option nodeStateOpt = new Option(NODE_STATE_CMD, true,
      "Works with -list to filter nodes based on input comma-separated list of node states.");
  nodeStateOpt.setValueSeparator(',');
  nodeStateOpt.setArgs(Option.UNLIMITED_VALUES);
  nodeStateOpt.setArgName("States");
  opts.addOption(nodeStateOpt);
  Option allOpt = new Option(NODE_ALL, false,
      "Works with -list to list all nodes.");
  opts.addOption(allOpt);
  opts.getOption(STATUS_CMD).setArgName("NodeId");

  int exitCode = -1;
  CommandLine cliParser = null;
  try {
    cliParser = new GnuParser().parse(opts, args);
  } catch (MissingArgumentException ex) {
    sysout.println("Missing argument for options");
    printUsage(opts);
    return exitCode;
  }

  if (cliParser.hasOption("status")) {
    if (args.length != 2) {
      printUsage(opts);
      return exitCode;
    }
    printNodeStatus(cliParser.getOptionValue("status"));
  } else if (cliParser.hasOption("list")) {
    Set<NodeState> nodeStates = new HashSet<NodeState>();
    if (cliParser.hasOption(NODE_ALL)) {
      for (NodeState state : NodeState.values()) {
        nodeStates.add(state);
      }
    } else if (cliParser.hasOption(NODE_STATE_CMD)) {
      String[] types = cliParser.getOptionValues(NODE_STATE_CMD);
      if (types != null) {
        for (String type : types) {
          if (!type.trim().isEmpty()) {
            nodeStates.add(NodeState.valueOf(
                org.apache.hadoop.util.StringUtils.toUpperCase(type.trim())));
          }
        }
      }
    } else {
      nodeStates.add(NodeState.RUNNING);
    }
    listClusterNodes(nodeStates);
  } else if (cliParser.hasOption(HELP_CMD)) {
    printUsage(opts);
    return 0;
  } else {
    syserr.println("Invalid Command Usage : ");
    printUsage(opts);
  }
  return 0;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:66,代码来源:NodeCLI.java

示例10: getVals

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
private static String[] getVals(CommandLine command, String option) {
  return command.getOptionValues(option);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:4,代码来源:OptionsParser.java

示例11: main

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
/**
 * The main method.
 *
 * @param args
 *            the arguments
 * @throws ParseException
 *             the parse exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void main(final String args[]) throws ParseException, IOException {

    // Parse CLI options
    final Options options = getCmdOptions();
    final CommandLine cmd = parseCmdOptions(options, args);

    if (cmd == null || cmd.hasOption("h")) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("metarecsys", options);
        System.exit(0);
    }

    final Path runsFolder = Paths.get(cmd.getOptionValue(RUN_OPTION));
    final Path outputFolder = Paths.get(cmd.getOptionValue(OUT_OPTION));
    final int maxRank = Integer.parseInt(cmd.getOptionValue(MAX_OPTION, DEFAULT_MAX_RANK));

    // Build metarecsys algorithms
    final List<RankAggregation> algs = Arrays.stream(cmd.getOptionValues(ALG_OPTION))
            .map(name -> RankAggregation.build(name, maxRank)).collect(Collectors.toList());

    // For each normalisation algorithm
    for (final String norm : cmd.getOptionValues(NORM_OPTION)) {

        // Read runs by fold
        final ConcurrentMap<Integer, List<RunFile>> runsByFold = RunFile.readRuns(runsFolder,
                maxRank, NormalisationAlgorithm.build(norm));

        // For each metarecsys algorithm
        for (final RankAggregation alg : algs) {

            // For each fold
            runsByFold.forEach((fold, runs) -> {
                alg.computeAllCombinations(fold, runs, outputFolder);
            });

        }

    }

    RankAggregation.finishPool();
    Logger.getGlobal().info("Finished!");

}
 
开发者ID:dvalcarce,项目名称:metarecsys,代码行数:54,代码来源:MetaRecSys.java

示例12: run

import org.apache.commons.cli.CommandLine; //导入方法依赖的package包/类
@Override
public void run(CommandLine theCommandLine) throws Exception {
	FhirContext ctx = getSpecVersionContext(theCommandLine);

	String targetServer = theCommandLine.getOptionValue("t");
	if (isBlank(targetServer)) {
		throw new ParseException("No target server (-t) specified");
	} else if (targetServer.startsWith("http") == false && targetServer.startsWith("file") == false) {
		throw new ParseException("Invalid target server specified, must begin with 'http' or 'file'");
	}

	String termUrl = theCommandLine.getOptionValue("u");
	if (isBlank(termUrl)) {
		throw new ParseException("No URL provided");
	}
	
	String[] datafile = theCommandLine.getOptionValues("d");
	if (datafile == null || datafile.length == 0) {
		throw new ParseException("No data file provided");
	}
	
	String bearerToken = theCommandLine.getOptionValue("b");

	IGenericClient client = super.newClient(ctx, targetServer);
	IBaseParameters inputParameters;
	if (ctx.getVersion().getVersion() == FhirVersionEnum.DSTU2_HL7ORG) {
		Parameters p = new Parameters();
		p.addParameter().setName("url").setValue(new UriType(termUrl));
		for (String next : datafile) {
			p.addParameter().setName("localfile").setValue(new StringType(next));
		}
		inputParameters = p;
	} else {
		throw new ParseException("This command does not support FHIR version " + ctx.getVersion().getVersion());
	}
	/*
	if (isNotBlank(bearerToken)) {
		client.registerInterceptor(new BearerTokenAuthInterceptor(bearerToken));
	}

	if (theCommandLine.hasOption('v')) {
		client.registerInterceptor(new LoggingInterceptor(true));
	}
	*/
	ourLog.info("Beginning upload - This may take a while...");
	IBaseParameters response = client
		.operation()
		.onServer()
		.named("upload-external-code-system")
		.withParameters(inputParameters)
		.execute();

	ourLog.info("Upload complete!");
	ourLog.info("Response:\n{}", ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(response));
}
 
开发者ID:nhsconnect,项目名称:careconnect-reference-implementation,代码行数:56,代码来源:UploadTerminologyCommand.java


注:本文中的org.apache.commons.cli.CommandLine.getOptionValues方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。