下面列出了怎么用org.apache.commons.cli.GnuParser的API类实例代码及写法,或者点击链接到github查看源代码。
private void handleNetezzaImportExtraArgs(ImportJobContext context)
throws ParseException {
SqoopOptions opts = context.getOptions();
Configuration conf = opts.getConf();
String[] extraArgs = opts.getExtraArgs();
conf.setBoolean(NETEZZA_DATASLICE_ALIGNED_ACCESS_OPT, false);
if (extraArgs != null && extraArgs.length > 0
&& ConfigurationHelper.getConfNumMaps(conf) > 1) {
RelatedOptions netezzaOpts = getNetezzaExtraOpts();
CommandLine cmdLine = new GnuParser().parse(netezzaOpts, extraArgs, true);
if (cmdLine.hasOption(NETEZZA_DATASLICE_ALIGNED_ACCESS_LONG_ARG)) {
conf.setBoolean(NETEZZA_DATASLICE_ALIGNED_ACCESS_OPT, true);
context.setInputFormat(NetezzaDataDrivenDBInputFormat.class);
}
}
}
public static void main(String[] argv) throws Exception {
CommandLine cliParser = new GnuParser().parse(opts, argv);
if (cliParser.hasOption("put")) {
String path = cliParser.getOptionValue("put");
if (path != null && path.length() > 0) {
if (cliParser.hasOption(ENTITY_DATA_TYPE)) {
putTimelineDataInJSONFile(path, ENTITY_DATA_TYPE);
return;
} else if (cliParser.hasOption(DOMAIN_DATA_TYPE)) {
putTimelineDataInJSONFile(path, DOMAIN_DATA_TYPE);
return;
}
}
}
printUsage();
}
public MyOptions(String[] args) {
seed = System.nanoTime();
try {
Options opts = buildOptions();
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(opts, args, true);
processOptions(line, opts);
validateOptions();
}
catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println("Try \"--help\" option for details.");
setStopProceed();
}
}
private void processSQS(String [] args) throws Exception {
GnuParser parser = new GnuParser();
Options options = new Options();
CommandLine cmdline = parser.parse(options, args);
SQS_CMD cmd = SQS_CMD.valueOf(cmdline.getArgs()[0].toUpperCase());
AlertJanitor janitor = new AlertJanitor();
janitor.initalize(PathUtil.S3N, new Configuration());
String queue = janitor.resolveQueueUrl(cmdline.getArgs()[1]);
switch(cmd) {
case LOG:
janitor.writeLogs(queue, new Path(cmdline.getArgs()[2]));
break;
case PURGE:
janitor.clearAll(queue);
break;
default:
usage();
}
}
public MyOptions(String[] args) {
seed = System.nanoTime();
try {
Options opts = buildOptions();
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(opts, args, true);
processOptions(line, opts);
validateOptions();
}
catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println("Try \"--help\" option for details.");
setStopProceed();
}
}
public MyOptions(String[] args) {
seed = System.nanoTime();
try {
Options opts = buildOptions();
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(opts, args, true);
processOptions(line, opts);
validateOptions();
}
catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println("Try \"--help\" option for details.");
setStopProceed();
}
}
public JackrabbitMain(final String[] args) throws ParseException {
options.addOption("?", "help", false, "print this message");
options.addOption("n", "notice", false, "print copyright notices");
options.addOption("l", "license", false, "print license information");
options.addOption("q", "quiet", false, "disable console output");
options.addOption("d", "debug", false, "enable debug logging");
options.addOption("h", "host", true, "IP address of the HTTP server");
options.addOption("p", "port", true, "TCP port of the HTTP server (8080)");
options.addOption("f", "file", true, "location of this jar file");
options.addOption("r", "repo", true, "repository directory (jackrabbit)");
options.addOption("c", "conf", true, "repository configuration file");
command = new GnuParser().parse(options, args);
}
public static void main(String[] argv) throws Exception {
CommandLine cliParser = new GnuParser().parse(opts, argv);
if (cliParser.hasOption("put")) {
String path = cliParser.getOptionValue("put");
if (path != null && path.length() > 0) {
if (cliParser.hasOption(ENTITY_DATA_TYPE)) {
putTimelineDataInJSONFile(path, ENTITY_DATA_TYPE);
return;
} else if (cliParser.hasOption(DOMAIN_DATA_TYPE)) {
putTimelineDataInJSONFile(path, DOMAIN_DATA_TYPE);
return;
}
}
}
printUsage();
}
/** Attempts to parse options for given command, printing usage under failure */
private static CommandLine parseOptions(String[] args, Options options, String cmdStr) {
CommandLineParser cliParser = new GnuParser();
CommandLine cmd = null;
try {
cmd = cliParser.parse(options, args);
} catch (ParseException pe) {
LOG.error("CommandLineClient: failed to parse command-line options: " + pe.toString());
printUsage(options, cmdStr);
System.exit(1);
}
boolean ret = checkOptionArgsNumber(cmd.getOptions());
if (!ret) {
printUsage(options, cmdStr);
System.exit(1);
}
return cmd;
}
public MyOptions(String[] args) {
seed = System.nanoTime();
try {
Options opts = buildOptions();
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(opts, args, true);
processOptions(line, opts);
validateOptions();
}
catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println("Try \"--help\" option for details.");
setStopProceed();
}
}
public MyOptions(String[] args) {
seed = System.nanoTime();
try {
Options opts = buildOptions();
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(opts, args, true);
processOptions(line, opts);
validateOptions();
}
catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println("Try \"--help\" option for details.");
setStopProceed();
}
}
public MyOptions(String[] args) {
seed = System.nanoTime();
try {
Options opts = buildOptions();
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(opts, args, true);
processOptions(line, opts);
validateOptions();
}
catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println("Try \"--help\" option for details.");
setStopProceed();
}
}
protected CommandLine parseArgs(CliContext context, String[] stringArgs) {
GnuParser parser = new GnuParser();
CommandLine args;
Options options = getOptions();
Io io = context.getIo();
try {
args = parser.parse(options, stringArgs);
} catch (ParseException e) {
logger.warn("Invalid command line arguments.", e);
io.errorln("Invalid command line arguments.");
io.errorln(e.getMessage());
return null;
}
if (args.hasOption("h")) {
printHelp(context);
return null;
}
return args;
}
public MyOptions(String[] args) {
seed = System.nanoTime();
try {
Options opts = buildOptions();
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(opts, args, true);
processOptions(line, opts);
validateOptions();
}
catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println("Try \"--help\" option for details.");
setStopProceed();
}
}
public static void main(String[] args) throws Exception {
App myServer = new App();
CommandLineParser parser = new GnuParser();
Options options = getAvaliableCommandLineOptions();
System.out
.println(new Date()
+ " Usage: java -classpath ... com.yahoo.dba.tools.myperfserver.App -f config_file_path -j jettyhome "
+ "-p port -c webcontextroot -k workingDir -l logpath -w war_file");
readOptionsFromCommandLine(args, parser, options, myServer);
System.setProperty("logPath", myServer.getLogDirectoryPath());
PID_FILE = myServer.getWarFile().substring(0,
myServer.getWarFile().indexOf('.'))
+ ".pid";
checksRunningOfAnotherServerInstance();
//for https, we have to use https for jQuery
System.setProperty("url_protocl", myServer.useHttps?"https":"http");
runServer(myServer);
}
private static CommandLine parseArgs(String[] args) throws ParseException {
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("file")
.withDescription("sequence file to read")
.hasArg()
.withArgName("<sequence_file_name>")
.withType(String.class)
.create("f"));
options.addOption("o", "print_offsets_only", false, "whether to print only offsets " +
"ignoring the message payload");
CommandLineParser parser = new GnuParser();
return parser.parse(options, args);
}
/**
* Parse command line options
*
* @param args Command line args
* @return Whether init successful and run should be invoked
* @throws ParseException
* @throws IOException
*/
public boolean init(String[] args) throws ParseException, IOException {
Options opts = new Options();
opts.addOption(JOYConstants.APP_ATTEMPT_ID, true,
"App Attempt ID. Not to be used unless for testing purposes");
opts.addOption(JOYConstants.SHELL_SCRIPT, true,
"Environment for shell script. Specified as env_key=env_val pairs");
opts.addOption(JOYConstants.CONTAINER_MEMORY, true,
"Amount of memory in MB to be requested to run the shell command");
opts.addOption(JOYConstants.CONTAINER_VCORES, true,
"Amount of virtual cores to be requested to run the shell command");
opts.addOption(JOYConstants.NUM_CONTAINERS, true,
"No. of containers on which the shell command needs to be executed");
opts.addOption(JOYConstants.PRIORITY, true, "Application Priority. Default 0");
opts.addOption(JOYConstants.DEBUG, false, "Dump out debug information");
opts.addOption(JOYConstants.HELP, false, "Print usage");
if (args.length == 0) {
printUsage(opts);
throw new IllegalArgumentException(
"No args specified for application master to initialize");
}
try {
CommandLine cliParser = new GnuParser().parse(opts, args);
JstormYarnUtils.checkAndSetMasterOptions(cliParser, jstormMasterContext, this.conf);
} catch (Exception e) {
LOG.error(e);
}
return true;
}
public static CommandLine processCommandLineArgs(String[] cliArgs) throws Exception {
CommandLineParser cliParser = new GnuParser();
Options cliOptions = constructCommandLineOptions();
try {
return cliParser.parse(cliOptions, cliArgs);
} catch (ParseException pe) {
logger.error("fail to parse command-line options. cliArgs: " + Arrays.toString(cliArgs), pe);
printUsage(cliOptions);
System.exit(1);
}
return null;
}
public CommandLine process(String[] argv) {
try {
return new GnuParser().parse(options, argv);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addOption(OPTION_METADATA);
options.addOption(OPTION_SQL);
CommandLineParser parser = new GnuParser();
CommandLine commandLine = parser.parse(options, args);
KylinConfig config = KylinConfig.createInstanceFromUri(commandLine.getOptionValue(OPTION_METADATA.getOpt()));
String sql = commandLine.getOptionValue(OPTION_SQL.getOpt());
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = QueryConnection.getConnection(null);
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
int n = 0;
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
n++;
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.println(n + " - " + meta.getColumnLabel(i) + ":\t" + rs.getObject(i));
}
}
} finally {
DBUtils.closeQuietly(rs);
DBUtils.closeQuietly(stmt);
DBUtils.closeQuietly(conn);
}
}
public static Configuration configure(String[] args, Configuration conf, Logger log) throws ParseException {
log.info("Searching for metrics.xml on classpath.");
URL cpConfig = Thread.currentThread().getContextClassLoader().getResource("metrics.xml");
if (cpConfig == null) {
log.error("No configuration file specified nor runtime args supplied- exiting.");
System.exit(1);
} else {
log.info("Using conf file located at " + cpConfig);
conf.addResource(cpConfig);
}
MetricsOptions mOpts = new MetricsOptions();
CommandLine cl = new GnuParser().parse(mOpts, args);
// add the file config options first
String confFiles = cl.getOptionValue("conf", "");
if (confFiles != null && !confFiles.isEmpty()) {
for (String confFile : confFiles.split(",")) {
if (!confFile.isEmpty()) {
log.trace("Adding " + confFile + " to configurations resource base.");
conf.addResource(confFile);
}
}
}
// now get the runtime overrides
for (Option opt : cl.getOptions()) {
// Ensure we don't try to set a null value (option-only) because this will
// cause an NPE out of Configuration/Hashtable
conf.set(MetricsConfig.MTX + opt.getOpt(), null == opt.getValue() ? "" : opt.getValue());
}
return conf;
}
public static CommandLine processCommandLineArgs(String[] cliArgs) throws Exception {
CommandLineParser cliParser = new GnuParser();
Options cliOptions = constructCommandLineOptions();
try {
return cliParser.parse(cliOptions, cliArgs);
} catch (ParseException pe) {
System.err.println("CommandLineClient: failed to parse command-line options: "
+ pe.toString());
printUsage(cliOptions);
System.exit(1);
}
return null;
}
public static int run( final String[] args ) throws IOException{
CommandLine cl;
try{
CommandLineParser clParser = new GnuParser();
cl = clParser.parse( createOptions( args ) , args );
}catch( ParseException e ){
printHelp( args );
throw new IOException( e );
}
if( cl.hasOption( "help" ) ){
printHelp( args );
return 0;
}
String input = cl.getOptionValue( "input" , null );
String format = cl.getOptionValue( "format" , null );
String schema = cl.getOptionValue( "schema" , null );
String output = cl.getOptionValue( "output" , null );
InputStream in = FileUtil.fopen( input );
IStreamReader reader = StreamReaderFactory.create( in , format , schema );
OutputStream out = FileUtil.create( output );
MDSRecordWriter writer = new MDSRecordWriter( out );
while( reader.hasNext() ){
writer.addParserRow( reader.next() );
}
writer.close();
return 0;
}
public static int run( final String[] args ) throws IOException{
CommandLine cl;
try{
CommandLineParser clParser = new GnuParser();
cl = clParser.parse( createOptions( args ) , args );
}catch( ParseException e ){
printHelp( args );
throw new IOException( e );
}
if( cl.hasOption( "help" ) ){
printHelp( args );
return 0;
}
String input = cl.getOptionValue( "input" , null );
String output = cl.getOptionValue( "output" , null );
Configuration config = new Configuration();
ArrowFileReader arrowReader = new ArrowFileReader( new FileInputStream( input ).getChannel() , new RootAllocator( Integer.MAX_VALUE ) );
OutputStream out = FileUtil.create( output );
MDSWriter writer = new MDSWriter( out , config );
List<ArrowBlock> blockList = arrowReader.getRecordBlocks();
for( ArrowBlock block : blockList ){
VectorSchemaRoot root = arrowReader.getVectorSchemaRoot();
arrowReader.loadRecordBatch(block);
List<FieldVector> fieldVectorList = root.getFieldVectors();
Spread spread = ArrowSpreadUtil.toSpread( root.getRowCount() , fieldVectorList );
writer.append( spread );
}
arrowReader.close();
writer.close();
return 0;
}
private CommandLine parseCommandLineOptions(String[] args) {
if (args.length == 0) {
printUsage();
}
CommandLineParser parser = new GnuParser();
CommandLine commandLine = null;
try {
commandLine = parser.parse(OPTIONS, args);
} catch (ParseException e) {
System.err.println("Could not parse command line options. " + e.getMessage());
printUsage();
}
return commandLine;
}
private void handleNetezzaExtraArgs(SqoopOptions opts)
throws ParseException {
Configuration conf = opts.getConf();
String[] extraArgs = opts.getExtraArgs();
RelatedOptions netezzaOpts = getNetezzaExtraOpts();
CommandLine cmdLine = new GnuParser().parse(netezzaOpts, extraArgs, true);
if (cmdLine.hasOption(NETEZZA_ERROR_THRESHOLD_LONG_ARG)) {
int threshold = Integer.parseInt(cmdLine
.getOptionValue(NETEZZA_ERROR_THRESHOLD_LONG_ARG));
conf.setInt(NETEZZA_ERROR_THRESHOLD_OPT, threshold);
}
if (cmdLine.hasOption(NETEZZA_LOG_DIR_LONG_ARG)) {
String dir = cmdLine.getOptionValue(NETEZZA_LOG_DIR_LONG_ARG);
conf.set(NETEZZA_LOG_DIR_OPT, dir);
}
conf.setBoolean(NETEZZA_CTRL_CHARS_OPT,
cmdLine.hasOption(NETEZZA_CTRL_CHARS_LONG_ARG));
conf.setBoolean(NETEZZA_TRUNC_STRING_OPT,
cmdLine.hasOption(NETEZZA_TRUNC_STRING_LONG_ARG));
conf.setBoolean(NETEZZA_CRIN_STRING_OPT,
cmdLine.hasOption(NETEZZA_CRIN_STRING_LONG_ARG));
conf.setBoolean(NETEZZA_IGNORE_ZERO_OPT,
cmdLine.hasOption(NETEZZA_IGNORE_ZERO_LONG_ARG));
// Always true for Netezza direct mode access
conf.setBoolean(NETEZZA_DATASLICE_ALIGNED_ACCESS_OPT, true);
}
/**
* Runs the ScoreUpdater tool.
*/
public int run(String[] args)
throws Exception {
Options options = new Options();
Option helpOpts = OptionBuilder.withArgName("help").withDescription(
"show this help message").create("help");
Option crawlDbOpts = OptionBuilder.withArgName("crawldb").hasArg().withDescription(
"the crawldb to use").create("crawldb");
Option webGraphOpts = OptionBuilder.withArgName("webgraphdb").hasArg().withDescription(
"the webgraphdb to use").create("webgraphdb");
options.addOption(helpOpts);
options.addOption(crawlDbOpts);
options.addOption(webGraphOpts);
CommandLineParser parser = new GnuParser();
try {
CommandLine line = parser.parse(options, args);
if (line.hasOption("help") || !line.hasOption("webgraphdb")
|| !line.hasOption("crawldb")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("ScoreUpdater", options);
return -1;
}
String crawlDb = line.getOptionValue("crawldb");
String webGraphDb = line.getOptionValue("webgraphdb");
update(new Path(crawlDb), new Path(webGraphDb));
return 0;
}
catch (Exception e) {
LOG.error("ScoreUpdater: " + StringUtils.stringifyException(e));
return -1;
}
}
/**
* Parse extra arguments.
*
* @param args Extra arguments array
* @throws ParseException
*/
private 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 parsed arguments
applyExtraArguments(cmdLine);
}
private CommandLine parseArgs(Options opts, String[] args) throws ParseException {
if (args.length == 0) {
throw new IllegalArgumentException("No args specified for " + name + " to initialize");
}
return new GnuParser().parse(opts, args);
}
private static CommandLine parseArgs(String[] args) throws ParseException {
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("topic")
.withDescription("kafka topic name")
.hasArg()
.withArgName("<topic>")
.withType(String.class)
.create("t"));
options.addOption(OptionBuilder.withLongOpt("start_offset")
.withDescription("offset identifying the first set of files to check")
.hasArg()
.withArgName("<offset>")
.withType(Long.class)
.create("s"));
options.addOption(OptionBuilder.withLongOpt("end_offset")
.withDescription("offset identifying the last set of files to check")
.hasArg()
.withArgName("<offset>")
.withType(Long.class)
.create("e"));
options.addOption(OptionBuilder.withLongOpt("messages")
.withDescription("expected number of messages")
.hasArg()
.withArgName("<num_messages>")
.withType(Number.class)
.create("m"));
options.addOption("q", "sequence_offsets", false, "whether to verify that offsets " +
"increase sequentially. Requires loading all offsets in a snapshot " +
"to memory so use cautiously");
CommandLineParser parser = new GnuParser();
return parser.parse(options, args);
}