下面列出了org.apache.commons.cli.CommandLineParser#parse ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static CommandLine parseCommandLine(String[] args) {
Option host = new Option(BROKER_NAME, true, "kafka broker");
Option jmxPort = new Option(JMX_PORT, true, "kafka jmx port number");
jmxPort.setArgName("kafka jmx port number");
Option metric = new Option(METRICS_NAME, true, "jmx metric name");
options.addOption(jmxPort).addOption(host).addOption(metric);
if (args.length < 4) {
printUsageAndExit();
}
CommandLineParser parser = new DefaultParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException | NumberFormatException e) {
printUsageAndExit();
}
return cmd;
}
public static CommandLine parseCmdLine(final String appName, String[] args, Options options,
CommandLineParser parser) {
HelpFormatter hf = new HelpFormatter();
hf.setWidth(110);
CommandLine commandLine = null;
try {
commandLine = parser.parse(options, args);
if (commandLine.hasOption('h')) {
hf.printHelp(appName, options, true);
return null;
}
} catch (ParseException e) {
hf.printHelp(appName, options, true);
}
return commandLine;
}
public static CommandLine parseCmdLine(final String appName, String[] args, Options options,
CommandLineParser parser) {
HelpFormatter hf = new HelpFormatter();
hf.setWidth(110);
CommandLine commandLine = null;
try {
commandLine = parser.parse(options, args);
if (commandLine.hasOption('h')) {
hf.printHelp(appName, options, true);
return null;
}
} catch (ParseException e) {
hf.printHelp(appName, options, true);
}
return commandLine;
}
public Command parse(CliToolConfig.Cmd cmd, String[] args) throws Exception {
CommandLineParser parser = new DefaultParser();
CommandLine cli = parser.parse(CliToolConfig.OptionsSource.HELP.options(), args, true);
if (cli.hasOption("h")) {
return helpCmd(cmd);
}
cli = parser.parse(cmd.options(), args, cmd.isStopAtNonOption());
Terminal.Verbosity verbosity = Terminal.Verbosity.resolve(cli);
terminal.verbosity(verbosity);
return parse(cmd.name(), cli);
}
static GetAppPackageInfoCommandLineInfo getGetAppPackageInfoCommandLineInfo(String[] args) throws ParseException
{
CommandLineParser parser = new PosixParser();
GetAppPackageInfoCommandLineInfo result = new GetAppPackageInfoCommandLineInfo();
CommandLine line = parser.parse(GET_APP_PACKAGE_INFO_OPTIONS, args);
result.provideDescription = line.hasOption("withDescription");
return result;
}
public static void main(String[] args) throws ParseException {
// first load the configurations from command line and config files
Options options = new Options();
options.addOption("para", true, "Workers");
CommandLineParser commandLineParser = new DefaultParser();
CommandLine cmd = commandLineParser.parse(options, args);
Config config = ResourceAllocator.loadConfig(new HashMap<>());
int para = Integer.parseInt(cmd.getOptionValue("para"));
// build JobConfig
JobConfig jobConfig = new JobConfig();
jobConfig.put("para", Integer.toString(para));
submitJob(config, para, jobConfig, HelloTSet.class.getName());
}
/**
* Starts the service.
* @param args Expects the port: -p PORT
* @throws Exception If cannot start service.
*/
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addRequiredOption("p", "port", true, "Port to listen to.");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
// If port string is not valid, it will throw an exception.
int port = Integer.parseInt(cmd.getOptionValue("port"));
DaprApplication.start(port);
}
@Test
public void testNoLocalInOptionsUploadFile() throws Exception {
final CommandLineParser parser = new PosixParser();
final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--upload", "rackspace://cdn.cyberduck.ch/remote"});
final Set<TransferItem> found = new SingleTransferItemFinder().find(input, TerminalAction.upload, new Path("/cdn.cyberduck.ch/remote", EnumSet.of(Path.Type.file)));
assertTrue(found.isEmpty());
}
@Test
public void testFindWildcard() throws Exception {
final CommandLineParser parser = new PosixParser();
final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--delete", "rackspace://cdn.cyberduck.ch/remote/*.txt"});
assertTrue(new DeletePathFinder().find(input, TerminalAction.delete, new Path("/remote/*.txt", EnumSet.of(Path.Type.file))).contains(
new TransferItem(new Path("/remote", EnumSet.of(Path.Type.directory)))
));
}
public static void main(final String[] args) {
// Parse the command line options
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(PubchemMeshSynonyms.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
System.exit(1);
}
if (cl.hasOption("help")) {
HELP_FORMATTER.printHelp(PubchemMeshSynonyms.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
return;
}
String serviceHostIp = cl.getOptionValue(OPTION_SERVICE_HOST, DEFAULT_SERVICE_HOST);
Integer servicePort = Integer.parseInt(cl.getOptionValue(OPTION_SERVICE_PORT, DEFAULT_SERVICE_PORT));
String queryInchi = cl.getOptionValue(OPTION_QUERY_INCHI);
PubchemMeshSynonyms pubchemMeshSynonyms = new PubchemMeshSynonyms(serviceHostIp, servicePort);
String cid = pubchemMeshSynonyms.fetchCIDFromInchi(queryInchi);
if (cid != null) {
Map<PubchemSynonymType, Set<String>> pubchemSynonyms = pubchemMeshSynonyms.fetchPubchemSynonymsFromCID(cid);
LOGGER.info("Resulting Pubchem synonyms for %s are: %s", queryInchi, pubchemSynonyms);
Map<MeshTermType, Set<String>> meshTerms = pubchemMeshSynonyms.fetchMeshTermsFromCID(cid);
LOGGER.info("Resulting MeSH term s for %s are: %s", queryInchi, meshTerms);
} else {
LOGGER.info("No PubChem compound ID was found for the input InChI.");
}
}
/**
* Usage: KafkaWriter \
* --zookeeper zookeeper001:2181/cluster1 --topic kafka_test \
* --message "this is a test message"
*/
private static CommandLine parseCommandLine(String[] args) {
Option zookeeper = new Option(ZOOKEEPER, true, "zookeeper connection string");
Option topic = new Option(TOPIC, true, "action report topic name");
Option message = new Option(MESSAGE, true, "messags that writes to kafka");
options.addOption(zookeeper).addOption(topic).addOption(message);
if (args.length < 6) {
printUsageAndExit();
}
CommandLineParser parser = new DefaultParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException | NumberFormatException e) {
printUsageAndExit();
}
return cmd;
}
@Test
public void testDynamicProperties() throws Exception {
FlinkYarnSessionCli cli = new FlinkYarnSessionCli(
new Configuration(),
tmp.getRoot().getAbsolutePath(),
"",
"",
false);
Options options = new Options();
cli.addGeneralOptions(options);
cli.addRunOptions(options);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, new String[]{"run", "-j", "fake.jar", "-n", "15",
"-D", "akka.ask.timeout=5 min", "-D", "env.java.opts=-DappName=foobar"});
AbstractYarnClusterDescriptor flinkYarnDescriptor = cli.createClusterDescriptor(cmd);
Assert.assertNotNull(flinkYarnDescriptor);
Map<String, String> dynProperties =
FlinkYarnSessionCli.getDynamicProperties(flinkYarnDescriptor.getDynamicPropertiesEncoded());
assertEquals(2, dynProperties.size());
assertEquals("5 min", dynProperties.get("akka.ask.timeout"));
assertEquals("-DappName=foobar", dynProperties.get("env.java.opts"));
}
/**
* This is the main method of this app.
* @param args The port to listen on.
* @throws Exception An Exception.
*/
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addRequiredOption("p", "port", true, "Port to listen to.");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
// If port string is not valid, it will throw an exception.
int port = Integer.parseInt(cmd.getOptionValue("port"));
final GrpcHelloWorldDaprService service = new GrpcHelloWorldDaprService();
service.start(port);
service.awaitTermination();
}
@SuppressWarnings( "static-access" )
private static void parseAndRunCommand( String[] args ) throws Exception {
options = new Options();
options.addOption( OptionBuilder.withLongOpt( "stop" ).withDescription( BaseMessages.getString( PKG,
"HopServer.ParamDescription.stop" ) ).hasArg( false ).isRequired( false ).create( 's' ) );
options.addOption( OptionBuilder.withLongOpt( "userName" ).withDescription( BaseMessages.getString( PKG,
"HopServer.ParamDescription.userName" ) ).hasArg( true ).isRequired( false ).create( 'u' ) );
options.addOption( OptionBuilder.withLongOpt( "password" ).withDescription( BaseMessages.getString( PKG,
"HopServer.ParamDescription.password" ) ).hasArg( true ).isRequired( false ).create( 'p' ) );
options.addOption( OptionBuilder.withLongOpt( "help" ).withDescription( BaseMessages.getString( PKG,
"HopServer.ParamDescription.help" ) ).create( 'h' ) );
CommandLineParser parser = new BasicParser();
CommandLine cmd = parser.parse( options, args );
if ( cmd.hasOption( 'h' ) ) {
displayHelpAndAbort();
}
String[] arguments = cmd.getArgs();
boolean usingConfigFile = false;
// Load from an xml file that describes the complete configuration...
//
HopServerConfig config = null;
if ( arguments.length == 1 && !Utils.isEmpty( arguments[ 0 ] ) ) {
if ( cmd.hasOption( 's' ) ) {
throw new HopServerCommandException( BaseMessages.getString( PKG, "HopServer.Error.illegalStop" ) );
}
usingConfigFile = true;
FileObject file = HopVfs.getFileObject( arguments[ 0 ] );
Document document = XmlHandler.loadXmlFile( file );
setHopEnvironment(); // Must stand up server now to allow decryption of password
Node configNode = XmlHandler.getSubNode( document, HopServerConfig.XML_TAG );
config = new HopServerConfig( new LogChannel( "Hop server config" ), configNode );
if ( config.getAutoSequence() != null ) {
config.readAutoSequences();
}
config.setFilename( arguments[ 0 ] );
}
if ( arguments.length == 2 && !Utils.isEmpty( arguments[ 0 ] ) && !Utils.isEmpty( arguments[ 1 ] ) ) {
String hostname = arguments[ 0 ];
String port = arguments[ 1 ];
if ( cmd.hasOption( 's' ) ) {
String user = cmd.getOptionValue( 'u' );
String password = cmd.getOptionValue( 'p' );
shutdown( hostname, port, user, password );
System.exit( 0 );
}
org.apache.hop.server.HopServer hopServer = new org.apache.hop.server.HopServer( hostname + ":" + port, hostname, port, null, null );
config = new HopServerConfig();
config.setHopServer( hopServer );
}
// Nothing configured: show the usage
//
if ( config == null ) {
displayHelpAndAbort();
}
if ( !usingConfigFile ) {
setHopEnvironment();
}
runHopServer( config );
}
@SuppressWarnings("unchecked")
public int resolve(String[] args) {
Options resolveOption = new Options();
CommandLineParser parser = new GnuParser();
try {
CommandLine line = parser.parse(resolveOption, args);
List<String> argsList = line.getArgList();
if (argsList.size() != 2) {
return usageError("resolve requires exactly one path argument",
RESOLVE_USAGE);
}
if (!validatePath(argsList.get(1))) {
return -1;
}
try {
ServiceRecord record = registry.resolve(argsList.get(1));
for (Endpoint endpoint : record.external) {
sysout.println(" Endpoint(ProtocolType="
+ endpoint.protocolType + ", Api="
+ endpoint.api + ");"
+ " Addresses(AddressType="
+ endpoint.addressType + ") are: ");
for (Map<String, String> address : endpoint.addresses) {
sysout.println("[ ");
for (Map.Entry<String, String> entry : address.entrySet()) {
sysout.print("\t" + entry.getKey()
+ ":" + entry.getValue());
}
sysout.println("\n]");
}
sysout.println();
}
return 0;
} catch (Exception e) {
syserr.println(analyzeException("resolve", e, argsList));
}
return -1;
} catch (ParseException exp) {
return usageError("Invalid syntax " + exp, RESOLVE_USAGE);
}
}
public static void main(String[] args) throws Exception {
org.apache.commons.cli.Options opts = new org.apache.commons.cli.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(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
System.exit(1);
}
if (cl.hasOption("help")) {
HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
return;
}
File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));
if (!rocksDBFile.isDirectory()) {
System.err.format("Index directory does not exist or is not a directory at '%s'", rocksDBFile.getAbsolutePath());
HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
System.exit(1);
}
List<String> compoundIds = null;
if (cl.hasOption(OPTION_PUBCHEM_COMPOUND_ID)) {
compoundIds = Collections.singletonList(cl.getOptionValue(OPTION_PUBCHEM_COMPOUND_ID));
} else if (cl.hasOption(OPTION_IDS_FILE)) {
File idsFile = new File(cl.getOptionValue(OPTION_IDS_FILE));
if (!idsFile.exists()) {
System.err.format("Cannot find Pubchem CIDs file at %s", idsFile.getAbsolutePath());
HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
System.exit(1);
}
compoundIds = getCIDsFromFile(idsFile);
if (compoundIds.size() == 0) {
System.err.format("Found zero Pubchem CIDs to process in file at '%s', exiting", idsFile.getAbsolutePath());
HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
System.exit(1);
}
} else {
System.err.format("Must specify one of '%s' or '%s'; index is too big to print all synonyms.",
OPTION_PUBCHEM_COMPOUND_ID, OPTION_IDS_FILE);
HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
System.exit(1);
}
// Run a quick check to warn users of malformed ids.
compoundIds.forEach(x -> {
if (!PC_CID_PATTERN.matcher(x).matches()) { // Use matches() for complete matching.
LOGGER.warn("Specified compound id does not match expected format: %s", x);
}
});
LOGGER.info("Opening DB and searching for %d Pubchem CIDs", compoundIds.size());
Pair<RocksDB, Map<PubchemTTLMerger.COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles = null;
Map<String, PubchemSynonyms> results = new LinkedHashMap<>(compoundIds.size());
try {
dbAndHandles = PubchemTTLMerger.openExistingRocksDB(rocksDBFile);
RocksDB db = dbAndHandles.getLeft();
ColumnFamilyHandle cidToSynonymsCfh =
dbAndHandles.getRight().get(PubchemTTLMerger.COLUMN_FAMILIES.CID_TO_SYNONYMS);
for (String cid : compoundIds) {
PubchemSynonyms synonyms = null;
byte[] val = db.get(cidToSynonymsCfh, cid.getBytes(UTF8));
if (val != null) {
ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(val));
// We're relying on our use of a one-value-type per index model here so we can skip the instanceof check.
synonyms = (PubchemSynonyms) oi.readObject();
} else {
LOGGER.warn("No synonyms available for compound id '%s'", cid);
}
results.put(cid, synonyms);
}
} finally {
if (dbAndHandles != null) {
dbAndHandles.getLeft().close();
}
}
try (OutputStream outputStream =
cl.hasOption(OPTION_OUTPUT) ? new FileOutputStream(cl.getOptionValue(OPTION_OUTPUT)) : System.out) {
OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(outputStream, results);
new OutputStreamWriter(outputStream).append('\n');
}
LOGGER.info("Done searching for Pubchem synonyms");
}
public static void main(String[] args) throws IOException {
CommandLineParser parser = new DefaultParser();
// create the Options
Options options = new Options();
options.addOption(Option.builder("f")
.required(true).hasArg()
.longOpt("extra_action_file")
.desc("bazel extra action protobuf file")
.build());
options.addOption(Option.builder("p")
.required(true).hasArg()
.longOpt("pylint_file")
.desc("Executable pylint file to invoke")
.build());
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
String extraActionFile = line.getOptionValue("f");
String pylintFile = line.getOptionValue("p");
Collection<String> sourceFiles = getSourceFiles(extraActionFile);
if (sourceFiles.size() == 0) {
LOG.info("No python files found by checkstyle");
return;
}
LOG.info(sourceFiles.size() + " python files found by checkstyle");
// Create and run the command
List<String> commandBuilder = new ArrayList<>();
commandBuilder.add(pylintFile);
commandBuilder.add("--rcfile=" + PYLINT_RCFILE);
commandBuilder.add("--reports=n");
commandBuilder.add("--disable=I");
commandBuilder.addAll(sourceFiles);
runLinter(commandBuilder);
} catch (ParseException exp) {
LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage()));
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java " + CLASSNAME, options);
}
}
public static void main(String[] args) throws ParseException {
// first load the configurations from command line and config files
Config config = ResourceAllocator.loadConfig(new HashMap<>());
// build JobConfig
HashMap<String, Object> configurations = new HashMap<>();
configurations.put(SchedulerContext.THREADS_PER_WORKER, 1);
Options options = new Options();
options.addOption(CDFConstants.ARGS_PARALLELISM_VALUE, true, "2");
options.addOption(CDFConstants.ARGS_WORKERS, true, "2");
@SuppressWarnings("deprecation")
CommandLineParser commandLineParser = new DefaultParser();
CommandLine commandLine = commandLineParser.parse(options, args);
int instances = Integer.parseInt(commandLine.getOptionValue(CDFConstants.ARGS_WORKERS));
int parallelismValue =
Integer.parseInt(commandLine.getOptionValue(CDFConstants.ARGS_PARALLELISM_VALUE));
configurations.put(CDFConstants.ARGS_WORKERS, Integer.toString(instances));
configurations.put(CDFConstants.ARGS_PARALLELISM_VALUE, Integer.toString(parallelismValue));
// build JobConfig
JobConfig jobConfig = new JobConfig();
jobConfig.putAll(configurations);
config = Config.newBuilder().putAll(config)
.put(SchedulerContext.DRIVER_CLASS, null).build();
Twister2Job twister2Job;
twister2Job = Twister2Job.newBuilder()
.setJobName(HelloExample.class.getName())
.setWorkerClass(CDFWWorker.class)
.setDriverClass(TwoDataFlowsDriver.class.getName())
.addComputeResource(1, 512, instances)
.setConfig(jobConfig)
.build();
// now submit the job
Twister2Submitter.submitJob(twister2Job, config);
}
private static CommandLine parseCommandLineArgs(Options options, String[] args) throws ParseException {
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
return cmd;
}
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(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
System.exit(1);
}
if (cl.hasOption("help")) {
HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
return;
}
// Not enough memory available? We're gonna need a bigger heap.
long maxMemory = Runtime.getRuntime().maxMemory();
if (maxMemory < 1 << 34) { // 16GB
String msg = StringUtils.join(
String.format("You have run this class with a maximum heap size of less than 16GB (%d to be exact). ",
maxMemory),
"There is no way this process will complete with that much space available. ",
"Crank up your heap allocation with -Xmx and try again."
, "");
throw new RuntimeException(msg);
}
File inputFile = new File(cl.getOptionValue(OPTION_SCAN_FILE));
if (!inputFile.exists()) {
System.err.format("Cannot find input scan file at %s\n", inputFile.getAbsolutePath());
HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
System.exit(1);
}
File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));
if (rocksDBFile.exists()) {
System.err.format("Index file at %s already exists--remove and retry\n", rocksDBFile.getAbsolutePath());
HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
System.exit(1);
}
List<Double> targetMZs = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(cl.getOptionValue(OPTION_TARGET_MASSES)))) {
String line;
while ((line = reader.readLine()) != null) {
targetMZs.add(Double.valueOf(line));
}
}
TraceIndexExtractor extractor = new TraceIndexExtractor();
extractor.processScan(targetMZs, inputFile, rocksDBFile);
}