下面列出了怎么用org.apache.commons.cli.CommandLine的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
// namespace
String namespace = commandLine.getOptionValue('s').trim();
// key name
String key = commandLine.getOptionValue('k').trim();
// key name
String value = commandLine.getOptionValue('v').trim();
defaultMQAdminExt.start();
defaultMQAdminExt.createAndUpdateKvConfig(namespace, key, value);
System.out.printf("create or update kv config to namespace success.%n");
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
private static void runCommand(CommandLine cmd) throws Exception {
boolean verbose = Boolean.parseBoolean(cmd.getOptionValue(VERBOSE_OPTION, Boolean.toString(false)));
File file = new File(cmd.getOptionValue(FILE_OPTION));
if (file.exists()) {
try {
Port port = new Port(Integer.parseInt(cmd.getOptionValue(PORT_OPTION)));
String host = cmd.getOptionValue(HOST_OPTION, "localhost");
String shabang = cmd.getOptionValue(SHABANG_OPTION, null);
RunScript runner = new RunScript(file, port, host, shabang, verbose);
runner.run();
} catch (NumberFormatException e) {
System.out.println("Port must be numeric");
System.exit(PORT_NOT_A_NUMBER);
}
} else {
System.out.println("Script not found");
System.exit(FILE_NOT_FOUND);
}
}
public static void main(String[] args) throws IOException {
CommandLine parsedArgs = BaseOption.parseOptions(args);
File configPath = null;
if (!NO_CONFIG.isSet(parsedArgs)) {
configPath = BaseOption.checkedConfigPath(parsedArgs);
}
ContentConfig config = ContentConfig.load(configPath);
ShoppingContent.Builder builder = createStandardBuilder(parsedArgs, config);
ShoppingContent content = createService(builder);
ShoppingContent sandbox = createSandboxContentService(builder);
retrieveConfiguration(content, config);
try {
new DatafeedsWorkflow(content, sandbox, config).execute();
} catch (GoogleJsonResponseException e) {
checkGoogleJsonResponseException(e);
}
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
final String topic = commandLine.getOptionValue('t').trim();
final String key = commandLine.getOptionValue('k').trim();
this.queryByKey(defaultMQAdminExt, topic, key);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
@Override
public void run(CommandLine line, ToolRunningContext context) throws Exception {
try (OfflineApplication app = new RemoteOfflineApplicationImpl()) {
Map<String, OfflineWorkflowStatus> statuses = app.listWorkflows();
Table table = new Table(4, BorderStyle.CLASSIC_WIDE);
table.addCell("ID");
table.addCell("Running");
table.addCell("Step");
table.addCell("Time");
for (Map.Entry<String, OfflineWorkflowStatus> entry : statuses.entrySet()) {
String workflowId = entry.getKey();
OfflineWorkflowStatus status = entry.getValue();
Duration remaining = null;
if (status.getStartTime() != null) {
remaining = Duration.millis(status.getStartParameters().getDuration() * 60 * 1000)
.minus(new Duration(status.getStartTime(), DateTime.now()));
}
table.addCell(workflowId);
table.addCell(Boolean.toString(status.isRunning()));
table.addCell(status.getStep() != null ? status.getStep().toString() : "");
table.addCell(remaining != null ? PeriodFormat.getDefault().print(remaining.toPeriod()) : "");
}
context.getOutputStream().println(table.render());
}
}
@Override
public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
String topic = commandLine.getOptionValue('t').trim();
try {
defaultMQAdminExt.start();
Set<String> clusters = defaultMQAdminExt.getTopicClusterList(topic);
for (String value : clusters) {
System.out.printf("%s%n", value);
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
@Test
public void testCorrectSettingOfMaxSlots() throws Exception {
String[] params =
new String[] {"-ys", "3"};
FlinkYarnSessionCli yarnCLI = createFlinkYarnSessionCliWithJmAndTmTotalMemory(2048);
final CommandLine commandLine = yarnCLI.parseCommandLineOptions(params, true);
final Configuration executorConfig = yarnCLI.applyCommandLineOptionsToConfiguration(commandLine);
final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
final ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(executorConfig);
// each task manager has 3 slots but the parallelism is 7. Thus the slots should be increased.
assertEquals(3, clusterSpecification.getSlotsPerTaskManager());
}
@Test
public void testInvalidConfig() {
try {
String[] arguments = {};
CommandLine line = new PosixParser().parse(CliFrontend.getJobManagerAddressOption(new Options()), arguments, false);
TestingCliFrontend frontend = new TestingCliFrontend(CliFrontendTestUtils.getInvalidConfigDir());
assertTrue(frontend.getJobManagerAddress(line) == null);
}
catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
fail("Program caused an exception: " + e.getMessage());
}
}
@Override
public Configuration applyCommandLineOptionsToConfiguration(CommandLine commandLine) throws FlinkException {
final Configuration resultingConfiguration = new Configuration(configuration);
resultingConfiguration.setString(DeploymentOptions.TARGET, RemoteExecutor.NAME);
if (commandLine.hasOption(addressOption.getOpt())) {
String addressWithPort = commandLine.getOptionValue(addressOption.getOpt());
InetSocketAddress jobManagerAddress = NetUtils.parseHostPortAddress(addressWithPort);
setJobManagerAddressInConfig(resultingConfiguration, jobManagerAddress);
}
if (commandLine.hasOption(zookeeperNamespaceOption.getOpt())) {
String zkNamespace = commandLine.getOptionValue(zookeeperNamespaceOption.getOpt());
resultingConfiguration.setString(HighAvailabilityOptions.HA_CLUSTER_ID, zkNamespace);
}
return resultingConfiguration;
}
public static void main(@NotNull final String[] args) throws ParseException, SQLException
{
final Options options = new Options();
CopyNumberAnalyser.addCmdLineArgs(options);
final CommandLineParser parser = new DefaultParser();
final CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption(LOG_DEBUG))
{
Configurator.setRootLevel(Level.DEBUG);
}
String outputDir = formOutputPath(cmd.getOptionValue(DATA_OUTPUT_DIR));
final DatabaseAccess dbAccess = cmd.hasOption(DB_URL) ? databaseAccess(cmd) : null;
CopyNumberAnalyser cnAnalyser = new CopyNumberAnalyser(outputDir, dbAccess);
cnAnalyser.loadConfig(cmd);
cnAnalyser.runAnalysis();
cnAnalyser.close();
LNX_LOGGER.info("CN analysis complete");
}
@SuppressWarnings("static-access")
private static CommandLine parse(String[] otherArgs, Writer out) {
Options options = new Options();
options.addOption(OptionBuilder.withArgName("startwith").hasArg().withDescription("The value to start with.")
.create("s"));
options.addOption(OptionBuilder.withArgName("size").hasArg().withDescription("The number of terms to return.")
.create("n"));
options.addOption(OptionBuilder.withDescription("Get the frequency of each term.").create("F"));
CommandLineParser parser = new PosixParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, otherArgs);
} catch (ParseException e) {
HelpFormatter formatter = new HelpFormatter();
PrintWriter pw = new PrintWriter(out, true);
formatter.printHelp(pw, HelpFormatter.DEFAULT_WIDTH, "terms", null, options, HelpFormatter.DEFAULT_LEFT_PAD,
HelpFormatter.DEFAULT_DESC_PAD, null, false);
return null;
}
return cmd;
}
private String encodeDynamicProperties(final CommandLine cmd) {
final Properties properties = cmd.getOptionProperties(dynamicproperties.getOpt());
final String[] dynamicProperties = properties.stringPropertyNames().stream()
.flatMap(
(String key) -> {
final String value = properties.getProperty(key);
LOG.info("Dynamic Property set: {}={}", key, GlobalConfiguration.isSensitive(key) ? GlobalConfiguration.HIDDEN_CONTENT : value);
if (value != null) {
return Stream.of(key + dynamicproperties.getValueSeparator() + value);
} else {
return Stream.empty();
}
})
.toArray(String[]::new);
return StringUtils.join(dynamicProperties, YARN_DYNAMIC_PROPERTIES_SEPARATOR);
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
// namespace
String namespace = commandLine.getOptionValue('s').trim();
// key name
String key = commandLine.getOptionValue('k').trim();
// key name
String value = commandLine.getOptionValue('v').trim();
defaultMQAdminExt.start();
defaultMQAdminExt.createAndUpdateKvConfig(namespace, key, value);
System.out.printf("create or update kv config to namespace success.%n");
return;
} catch (Exception e) {
e.printStackTrace();
} finally {
defaultMQAdminExt.shutdown();
}
}
@Override
public void run(CommandLine line, ToolRunningContext context) throws Exception {
String inputFile = line.getOptionValue(INPUT_FILE);
String outputFormat = line.getOptionValue(OUTPUT_FORMAT);
String outputFile = line.getOptionValue(OUTPUT_FILE);
Exporter exporter = Exporters.getExporter(outputFormat);
if (exporter == null) {
throw new PowsyblException("Target format " + outputFormat + " not supported");
}
Properties inputParams = readProperties(line, ConversionToolUtils.OptionType.IMPORT, context);
Network network = Importers.loadNetwork(context.getFileSystem().getPath(inputFile), context.getShortTimeExecutionComputationManager(), createImportConfig(), inputParams);
Properties outputParams = readProperties(line, ConversionToolUtils.OptionType.EXPORT, context);
DataSource ds2 = Exporters.createDataSource(context.getFileSystem().getPath(outputFile), new DefaultDataSourceObserver() {
@Override
public void opened(String streamName) {
context.getOutputStream().println("Generating file " + streamName + "...");
}
});
exporter.export(network, outputParams, ds2);
}
public static Optional<Integer> getOptionalIntegerArg(CommandLine cmdline, String arg) throws IllegalArgumentException {
try {
if (cmdline.hasOption(arg)) {
return Optional.of(Integer.parseInt(cmdline.getOptionValue(arg)));
} else {
return Optional.absent();
}
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(arg + " is not a number");
}
}
public static CommandLine parse(Options options, String[] args, boolean stopAtNonOptions) throws CliArgsException {
final DefaultParser parser = new DefaultParser();
try {
return parser.parse(options, args, stopAtNonOptions);
} catch (ParseException e) {
throw new CliArgsException(e.getMessage());
}
}
@Override
public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
long printInterval = 1;
boolean enableInterval = commandLine.hasOption('i');
if (enableInterval) {
printInterval = Long.parseLong(commandLine.getOptionValue('i')) * 1000;
}
try {
defaultMQAdminExt.start();
long i = 0;
do {
if (i++ > 0) {
Thread.sleep(printInterval);
}
if (commandLine.hasOption('m')) {
this.printClusterMoreStats(defaultMQAdminExt);
} else {
this.printClusterBaseInfo(defaultMQAdminExt);
}
}
while (enableInterval);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
/**
* Gets the custom command-line for the arguments.
* @param commandLine The input to the command-line.
* @return custom command-line which is active (may only be one at a time)
*/
public CustomCommandLine<?> getActiveCustomCommandLine(CommandLine commandLine) {
for (CustomCommandLine<?> cli : customCommandLines) {
if (cli.isActive(commandLine)) {
return cli;
}
}
throw new IllegalStateException("No command-line ran.");
}
/**
* Apply Apache Commons CLI PosixParser to command-line arguments.
*
* @param commandLineArguments
* Command-line arguments to be processed with Posix-style parser.
*/
private static CommandLine usePosixParser(final String[] commandLineArguments) {
final CommandLineParser cmdLinePosixParser = new DefaultParser();
final Options posixOptions = constructPosixOptions();
try {
return cmdLinePosixParser.parse(posixOptions, commandLineArguments);
} catch (ParseException parseException) {
System.err
.println("Encountered exception while parsing using PosixParser:\n" + parseException.getMessage());
}
return null;
}
/**
* Parse extra arguments.
*
* @param args Extra arguments array
* @throws ParseException
*/
void parseExtraArgs(String[] args) throws ParseException {
// No-op when no extra arguments are present
if (args == null || args.length == 0) {
return;
}
// We do not need extended abilities of SqoopParser, so we're using
// Gnu parser instead.
CommandLineParser parser = new GnuParser();
CommandLine cmdLine = parser.parse(getExtraOptions(), args, true);
// Apply extra options
if (cmdLine.hasOption(SCHEMA)) {
String schemaName = cmdLine.getOptionValue(SCHEMA);
LOG.info("We will use schema " + schemaName);
this.schema = schemaName;
}
// Apply table hints
if (cmdLine.hasOption(TABLE_HINTS)) {
String hints = cmdLine.getOptionValue(TABLE_HINTS);
LOG.info("Sqoop will use following table hints for data transfer: "
+ hints);
this.tableHints = hints;
}
identityInserts = cmdLine.hasOption(IDENTITY_INSERT);
}
@Override
public StandaloneClusterDescriptor createClusterDescriptor(
CommandLine commandLine) throws FlinkException {
final Configuration effectiveConfiguration = applyCommandLineOptionsToConfiguration(commandLine);
return new StandaloneClusterDescriptor(effectiveConfiguration);
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
GetBrokerConfigCommand cmd = new GetBrokerConfigCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
public static Optional<Boolean> getOptionalBooleanArg(CommandLine cmdline, String arg) {
if (cmdline.hasOption(arg)) {
return Optional.of(true);
} else {
return Optional.absent();
}
}
/**
* Given a command line, check for the required options and return an IRI to be used as the
* OntologyIRI for the output ontology.
*
* @param line the command line to use
* @return the IRI for the output ontology, or null
*/
public static IRI getOutputIRI(CommandLine line) {
String outputIRIString = getOptionalValue(line, "output-iri");
IRI outputIRI = null;
if (outputIRIString != null) {
outputIRI = IRI.create(outputIRIString);
}
return outputIRI;
}
/**
* Read and convert the bounding box from CLI args
* @param line
* @return
*/
private Hyperrectangle getBoundingBoxFromArgs(final CommandLine line) {
final String bbox = line.getOptionValue(CLIParameter.BOUNDING_BOX);
final Optional<Hyperrectangle> resultBox = HyperrectangleHelper.parseBBox(bbox);
if(! resultBox.isPresent()) {
System.err.println("Invalid bounding box: " + bbox);
System.exit(-1);
}
return resultBox.get();
}
@Ignore
@Test
public void testExecute() throws SubCommandException {
ProducerConnectionSubCommand cmd = new ProducerConnectionSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-g default-producer-group", "-t unit-test"};
final CommandLine commandLine =
ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
cmd.execute(commandLine, options, null);
}
private Object getOptionValueFromCmdLine(Option option, CommandLine cmd) {
Object optionValue = null;
if(!option.hasArg()) {
if(cmd.hasOption(option.getLongOpt())) {
optionValue = true;
}
}
else {
optionValue = cmd.getOptionValue(option.getLongOpt());
}
return optionValue;
}
public static CommandLine parseArgs(Options options, String[] args) {
CommandLine commandLineArgs;
try {
// parse the command line arguments
commandLineArgs = parser.parse(options, args, false);
} catch (ParseException pe) {
throw new RuntimeException("Parsing failed for command option:", pe);
}
return commandLineArgs;
}
public static void main(String[] args) throws Exception {
Options opts = new Options();
for (Option.Builder b : OPTION_BUILDERS) {
opts.addOption(b.build());
}
CommandLine cl = null;
try {
CommandLineParser parser = new DefaultParser();
cl = parser.parse(opts, args);
} catch (ParseException e) {
System.err.format("Argument parsing failed: %s\n", e.getMessage());
HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
System.exit(1);
}
if (cl.hasOption("help")) {
HELP_FORMATTER.printHelp(ReactionDesalter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
return;
}
NoSQLAPI api = new NoSQLAPI(cl.getOptionValue(OPTION_READ_DB), cl.getOptionValue(OPTION_READ_DB));
MechanisticValidator validator = new MechanisticValidator(api);
validator.init();
Map<Integer, List<Ero>> results = validator.validateOneReaction(Long.parseLong(cl.getOptionValue(OPTION_RXN_ID)));
if (results == null) {
System.out.format("ERROR: validation results are null.\n");
} else if (results.size() == 0) {
System.out.format("No matching EROs were found for the specified reaction.\n");
} else {
for (Map.Entry<Integer, List<Ero>> entry : results.entrySet()) {
List<String> eroIds = entry.getValue().stream().map(x -> x.getId().toString()).collect(Collectors.toList());
System.out.format("%d: %s\n", entry.getKey(), StringUtils.join(eroIds, ", "));
}
}
}
@Override
protected void parseCommandLine(CommandLine cmdline) throws ParseException {
super.parseCommandLine(cmdline);
if (!cmdline.hasOption("s")) {
throw new ParseException("No stream to set ACL");
}
stream = cmdline.getOptionValue("s");
}