Java Code Examples for org.apache.commons.cli.CommandLine#getArgs()
The following examples show how to use
org.apache.commons.cli.CommandLine#getArgs() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StatefulFunctionsClusterConfigurationParserFactory.java From stateful-functions with Apache License 2.0 | 6 votes |
@Override public StatefulFunctionsClusterConfiguration createResult(@Nonnull CommandLine commandLine) throws FlinkParseException { final String configDir = commandLine.getOptionValue(CONFIG_DIR_OPTION.getOpt()); final Properties dynamicProperties = commandLine.getOptionProperties(DYNAMIC_PROPERTY_OPTION.getOpt()); final int restPort = getRestPort(commandLine); final String hostname = commandLine.getOptionValue(HOST_OPTION.getOpt()); final SavepointRestoreSettings savepointRestoreSettings = CliFrontendParser.createSavepointRestoreSettings(commandLine); final JobID jobId = getJobId(commandLine); return new StatefulFunctionsClusterConfiguration( configDir, dynamicProperties, commandLine.getArgs(), hostname, restPort, savepointRestoreSettings, jobId); }
Example 2
Source File: ShowMetaCommand.java From parquet-tools with Apache License 2.0 | 6 votes |
@Override public void execute(CommandLine options) throws Exception { super.execute(options); String[] args = options.getArgs(); String input = args[0]; Configuration conf = new Configuration(); ParquetMetadata metaData = ParquetFileReader.readFooter(conf, new Path(input)); PrettyPrintWriter out = PrettyPrintWriter.stdoutPrettyPrinter() .withAutoColumn() .withAutoCrop() .withWhitespaceHandler(WhiteSpaceHandler.COLLAPSE_WHITESPACE) .withColumnPadding(1) .build(); MetadataUtils.showDetails(out, metaData); out.flushColumns(); }
Example 3
Source File: DistributedLogAdmin.java From distributedlog with Apache License 2.0 | 5 votes |
@Override protected int runCmd(CommandLine cmdline) throws Exception { String[] args = cmdline.getArgs(); if (args.length <= 0) { System.err.println("No distributedlog uri specified."); printUsage(); return -1; } boolean force = cmdline.hasOption("f"); URI uri = URI.create(args[0]); // resolving the uri to see if there is another bindings in this uri. ZooKeeperClient zkc = ZooKeeperClientBuilder.newBuilder().uri(uri) .sessionTimeoutMs(10000).build(); BKDLConfig bkdlConfig; try { bkdlConfig = BKDLConfig.resolveDLConfig(zkc, uri); } catch (IOException ie) { bkdlConfig = null; } if (null == bkdlConfig) { System.out.println("No bookkeeper is bound to " + uri); return 0; } else { System.out.println("There is bookkeeper bound to " + uri + " : "); System.out.println(""); System.out.println(bkdlConfig.toString()); System.out.println(""); if (!force && !IOUtils.confirmPrompt("Do you want to unbind " + uri + " :\n")) { return 0; } } DLMetadata.unbind(uri); System.out.println("Unbound on " + uri + "."); return 0; }
Example 4
Source File: ArgsOnlyCommand.java From parquet-mr with Apache License 2.0 | 5 votes |
@Override public void execute(CommandLine options) throws Exception { String[] args = options.getArgs(); if (args.length < min) { throw new MissingArgumentException("missing required arguments"); } if (args.length > max) { throw new UnrecognizedOptionException("unknown extra argument \"" + args[max] + "\""); } }
Example 5
Source File: ServerCmd.java From james-project with Apache License 2.0 | 5 votes |
@VisibleForTesting private CmdType executeCommandLine(CommandLine commandLine, PrintStream printStream) throws Exception { String[] arguments = commandLine.getArgs(); String cmdName = arguments[0]; CmdType cmdType = CmdType.lookup(cmdName); if (cmdType == null) { throw new UnrecognizedCommandException(cmdName); } if (! cmdType.hasCorrectArguments(arguments.length)) { throw new InvalidArgumentNumberException(cmdType, arguments.length); } executeCommand(arguments, cmdType, printStream); return cmdType; }
Example 6
Source File: StopOptions.java From flink with Apache License 2.0 | 5 votes |
StopOptions(CommandLine line) { super(line); this.args = line.getArgs(); this.savepointFlag = line.hasOption(STOP_WITH_SAVEPOINT_PATH.getOpt()); this.targetDirectory = line.getOptionValue(STOP_WITH_SAVEPOINT_PATH.getOpt()); this.advanceToEndOfEventTime = line.hasOption(STOP_AND_DRAIN.getOpt()); }
Example 7
Source File: UploadTransferItemFinder.java From cyberduck with GNU General Public License v3.0 | 5 votes |
@Override public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) { final Local local = LocalFactory.get(input.getOptionValues(action.name())[1]); final Set<TransferItem> items = new HashSet<TransferItem>(); items.add(this.resolve(remote, local)); for(String arg : input.getArgs()) { items.add(this.resolve(remote, LocalFactory.get(arg))); } return items; }
Example 8
Source File: DistributedLogAdmin.java From distributedlog with Apache License 2.0 | 5 votes |
@Override protected int runCmd(CommandLine cmdline) throws Exception { String[] args = cmdline.getArgs(); if (args.length <= 0) { System.err.println("No distributedlog uri specified."); printUsage(); return -1; } boolean force = cmdline.hasOption("f"); URI uri = URI.create(args[0]); // resolving the uri to see if there is another bindings in this uri. ZooKeeperClient zkc = ZooKeeperClientBuilder.newBuilder().uri(uri) .sessionTimeoutMs(10000).build(); BKDLConfig bkdlConfig; try { bkdlConfig = BKDLConfig.resolveDLConfig(zkc, uri); } catch (IOException ie) { bkdlConfig = null; } if (null == bkdlConfig) { System.out.println("No bookkeeper is bound to " + uri); return 0; } else { System.out.println("There is bookkeeper bound to " + uri + " : "); System.out.println(""); System.out.println(bkdlConfig.toString()); System.out.println(""); if (!force && !IOUtils.confirmPrompt("Do you want to unbind " + uri + " :\n")) { return 0; } } DLMetadata.unbind(uri); System.out.println("Unbound on " + uri + "."); return 0; }
Example 9
Source File: EntrypointClusterConfigurationParserFactory.java From flink with Apache License 2.0 | 5 votes |
@Override public EntrypointClusterConfiguration createResult(@Nonnull CommandLine commandLine) { final String configDir = commandLine.getOptionValue(CONFIG_DIR_OPTION.getOpt()); final Properties dynamicProperties = commandLine.getOptionProperties(DYNAMIC_PROPERTY_OPTION.getOpt()); final String restPortStr = commandLine.getOptionValue(REST_PORT_OPTION.getOpt(), "-1"); final int restPort = Integer.parseInt(restPortStr); final String hostname = commandLine.getOptionValue(HOST_OPTION.getOpt()); return new EntrypointClusterConfiguration( configDir, dynamicProperties, commandLine.getArgs(), hostname, restPort); }
Example 10
Source File: EntrypointClusterConfigurationParserFactory.java From flink with Apache License 2.0 | 5 votes |
@Override public EntrypointClusterConfiguration createResult(@Nonnull CommandLine commandLine) { final String configDir = commandLine.getOptionValue(CONFIG_DIR_OPTION.getOpt()); final Properties dynamicProperties = commandLine.getOptionProperties(DYNAMIC_PROPERTY_OPTION.getOpt()); final String restPortStr = commandLine.getOptionValue(REST_PORT_OPTION.getOpt(), "-1"); final int restPort = Integer.parseInt(restPortStr); final String hostname = commandLine.getOptionValue(HOST_OPTION.getOpt()); return new EntrypointClusterConfiguration( configDir, dynamicProperties, commandLine.getArgs(), hostname, restPort); }
Example 11
Source File: ServerCmd.java From james-project with Apache License 2.0 | 5 votes |
@VisibleForTesting static CommandLine parseCommandLine(String[] args) throws ParseException { CommandLineParser parser = new DefaultParser(); CommandLine commandLine = parser.parse(createOptions(), args); if (commandLine.getArgs().length < 1) { throw new MissingCommandException(); } return commandLine; }
Example 12
Source File: HeadCommand.java From parquet-tools with Apache License 2.0 | 5 votes |
@Override public void execute(CommandLine options) throws Exception { super.execute(options); long num = DEFAULT; if (options.hasOption('n')) { num = Long.parseLong(options.getOptionValue('n')); } String[] args = options.getArgs(); String input = args[0]; ParquetReader<SimpleRecord> reader = null; try { PrintWriter writer = new PrintWriter(Main.out, true); reader = new ParquetReader<SimpleRecord>(new Path(input), new SimpleReadSupport()); for (SimpleRecord value = reader.read(); value != null && num-- > 0; value = reader.read()) { value.prettyPrint(writer); writer.println(); } } finally { if (reader != null) { try { reader.close(); } catch (Exception ex) { } } } }
Example 13
Source File: SavepointOptions.java From flink with Apache License 2.0 | 5 votes |
public SavepointOptions(CommandLine line) { super(line); args = line.getArgs(); dispose = line.hasOption(SAVEPOINT_DISPOSE_OPTION.getOpt()); disposeSavepointPath = line.getOptionValue(SAVEPOINT_DISPOSE_OPTION.getOpt()); jarFile = line.getOptionValue(JAR_OPTION.getOpt()); }
Example 14
Source File: DownloadExercisesCommand.java From tmc-cli with MIT License | 4 votes |
@Override public void run(CliContext context, CommandLine args) { Io io = context.getIo(); ctx = context; if (!ctx.checkIsLoggedIn(false, true)) { return; } String[] stringArgs = args.getArgs(); if (stringArgs.length == 0 || stringArgs.length > 1) { io.errorln("You must give a course name as an argument."); printUsage(ctx); return; } ctx = context; showAll = args.hasOption("a"); WorkDir workDir = ctx.getWorkDir(); if (workDir.getConfigFile() != null) { io.errorln("Can't download a course inside a course directory."); return; } String courseName = stringArgs[0]; CourseFinder finder = new CourseFinder(ctx); if (!finder.search(courseName)) { return; } Course course = finder.getCourse(); this.ctx.getAnalyticsFacade().saveAnalytics(course, "download_exercises"); List<Exercise> filtered = getFilteredExercises(course); // todo: If -c switch, use core.downloadCompletedExercises() to download user's old // submissions. Not yet implemented in tmc-core. Color color1 = ctx.getColorProperty("progressbar-left", ctx.getApp()); Color color2 = ctx.getColorProperty("progressbar-right", ctx.getApp()); CliProgressObserver progobs = new CliProgressObserver(io, color1, color2); ctx.useAccount(finder.getAccount()); if (!ctx.getSettings().getOrganization().isPresent()) { io.errorln("Failed to download exercises. Make sure you are properly logged in."); return; } CourseInfoIo.createNewCourse(course, finder.getAccount(), workDir.getWorkingDirectory()); List<Exercise> exercises = TmcUtil.downloadExercises(ctx, filtered, progobs); if (exercises == null) { io.errorln("Failed to download exercises"); CourseInfoIo.deleteConfigDirectory(course, workDir.getWorkingDirectory()); return; } printStatistics(course, filtered.size(), exercises.size()); }
Example 15
Source File: FastCopy.java From RDFS with Apache License 2.0 | 4 votes |
public static void runTool(String args[]) throws Exception { CommandLine cmd = parseCommandline(args); args = cmd.getArgs(); int threadPoolSize = (cmd.hasOption('t')) ? Integer.parseInt(cmd .getOptionValue('t')) : THREAD_POOL_SIZE; List<CopyPath> srcs = new ArrayList<CopyPath>(); String dst = parseFiles(srcs, args); Path dstPath = new Path(dst); DistributedFileSystem dstFileSys = DFSUtil.convertToDFS(dstPath .getFileSystem(defaultConf)); DistributedFileSystem srcFileSys = DFSUtil.convertToDFS(srcs.get(0) .getSrcPath().getFileSystem(defaultConf)); List<FastFileCopyRequest> requests = new ArrayList<FastFileCopyRequest>(); FastCopy fcp = new FastCopy(new Configuration(), threadPoolSize); try { for (CopyPath copyPath : srcs) { Path srcPath = copyPath.getSrcPath(); String src = srcPath.toString(); try { // Perform some error checking and path manipulation. if (!srcFileSys.exists(srcPath)) { throw new IOException("File : " + src + " does not exists on " + srcFileSys); } String destination = copyPath.getDstPath().toString(); LOG.debug("Copying : " + src + " to " + destination); requests.add(new FastFileCopyRequest(src, destination, srcFileSys, dstFileSys)); } catch (Exception e) { LOG.warn("Fast Copy failed for file : " + src, e); } } fcp.copy(requests); LOG.debug("Finished copying"); } finally { fcp.shutdown(); } }
Example 16
Source File: JMXGet.java From RDFS with Apache License 2.0 | 4 votes |
/** * main * @param args */ public static void main(String[] args) { int res = -1; // parse arguments Options opts = new Options(); CommandLine commandLine = null; try { commandLine = parseArgs(opts, args); } catch (IllegalArgumentException iae) { commandLine = null; } if (commandLine == null) { // invalid arguments err("Invalid args"); printUsage(opts); System.exit(-1); } JMXGet jm = new JMXGet(); if (commandLine.hasOption("port")) { jm.setPort(commandLine.getOptionValue("port")); } if (commandLine.hasOption("service")) { jm.setService(commandLine.getOptionValue("service")); } if (commandLine.hasOption("server")) { jm.setServer(commandLine.getOptionValue("server")); } if (commandLine.hasOption("localVM")) { // from the file /tmp/hsperfdata* jm.setLocalVMPid(commandLine.getOptionValue("localVM")); } if (commandLine.hasOption("help")) { printUsage(opts); System.exit(0); } // rest of args args = commandLine.getArgs(); try { jm.init(); if (args.length == 0) { jm.printAllValues(); } else { for (String key: args) { err("key = " + key); String val = jm.getValue(key); if (val!=null) System.out.format(JMXGet.format,key,val); } } res = 0; } catch (Exception re) { re.printStackTrace(); res = -1; } System.exit(res); }
Example 17
Source File: HAAdmin.java From hadoop with Apache License 2.0 | 4 votes |
private int failover(CommandLine cmd) throws IOException, ServiceFailedException { boolean forceFence = cmd.hasOption(FORCEFENCE); boolean forceActive = cmd.hasOption(FORCEACTIVE); int numOpts = cmd.getOptions() == null ? 0 : cmd.getOptions().length; final String[] args = cmd.getArgs(); if (numOpts > 3 || args.length != 2) { errOut.println("failover: incorrect arguments"); printUsage(errOut, "-failover"); return -1; } HAServiceTarget fromNode = resolveTarget(args[0]); HAServiceTarget toNode = resolveTarget(args[1]); // Check that auto-failover is consistently configured for both nodes. Preconditions.checkState( fromNode.isAutoFailoverEnabled() == toNode.isAutoFailoverEnabled(), "Inconsistent auto-failover configs between %s and %s!", fromNode, toNode); if (fromNode.isAutoFailoverEnabled()) { if (forceFence || forceActive) { // -forceActive doesn't make sense with auto-HA, since, if the node // is not healthy, then its ZKFC will immediately quit the election // again the next time a health check runs. // // -forceFence doesn't seem to have any real use cases with auto-HA // so it isn't implemented. errOut.println(FORCEFENCE + " and " + FORCEACTIVE + " flags not " + "supported with auto-failover enabled."); return -1; } try { return gracefulFailoverThroughZKFCs(toNode); } catch (UnsupportedOperationException e){ errOut.println("Failover command is not supported with " + "auto-failover enabled: " + e.getLocalizedMessage()); return -1; } } FailoverController fc = new FailoverController(getConf(), requestSource); try { fc.failover(fromNode, toNode, forceFence, forceActive); out.println("Failover from "+args[0]+" to "+args[1]+" successful"); } catch (FailoverFailedException ffe) { errOut.println("Failover failed: " + ffe.getLocalizedMessage()); return -1; } return 0; }
Example 18
Source File: HopServer.java From hop with Apache License 2.0 | 4 votes |
@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 ); }
Example 19
Source File: RPCCallBenchmark.java From big-c with Apache License 2.0 | 4 votes |
private void processOptions(CommandLine line, Options opts) throws ParseException { if (line.hasOption("help") || line.hasOption('?')) { HelpFormatter formatter = new HelpFormatter(); System.out.println("Protobuf IPC benchmark."); System.out.println(); formatter.printHelp(100, "java ... PBRPCBenchmark [options]", "\nSupported options:", opts, ""); return; } if (line.hasOption('s')) { serverThreads = Integer.parseInt(line.getOptionValue('s')); } if (line.hasOption('r')) { serverReaderThreads = Integer.parseInt(line.getOptionValue('r')); } if (line.hasOption('c')) { clientThreads = Integer.parseInt(line.getOptionValue('c')); } if (line.hasOption('t')) { secondsToRun = Integer.parseInt(line.getOptionValue('t')); } if (line.hasOption('m')) { msgSize = Integer.parseInt(line.getOptionValue('m')); } if (line.hasOption('p')) { port = Integer.parseInt(line.getOptionValue('p')); } if (line.hasOption('h')) { host = line.getOptionValue('h'); } if (line.hasOption('e')) { String eng = line.getOptionValue('e'); if ("protobuf".equals(eng)) { rpcEngine = ProtobufRpcEngine.class; } else if ("writable".equals(eng)) { rpcEngine = WritableRpcEngine.class; } else { throw new ParseException("invalid engine: " + eng); } } String[] remainingArgs = line.getArgs(); if (remainingArgs.length != 0) { throw new ParseException("Extra arguments: " + Joiner.on(" ").join(remainingArgs)); } }
Example 20
Source File: addedTagger.java From fnlp with GNU Lesser General Public License v3.0 | 4 votes |
/** * 训练: java -classpath fudannlp.jar edu.fudan.nlp.tag.Tagger -train template train model * 测试: java -classpath fudannlp.jar edu.fudan.nlp.tag.Tagger model test [result] * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Options opt = new Options(); opt.addOption("h", false, "Print help for this application"); opt.addOption("iter", true, "iterative num, default 50"); opt.addOption("c1", true, "parameters 1, default 1"); opt.addOption("c2", true, "parameters 2, default 0.1"); opt.addOption("train", false, "switch to training mode(Default: test model"); opt.addOption("labelwise", false, "switch to labelwise mode(Default: viterbi model"); opt.addOption("margin", false, "use hamming loss as margin threshold"); opt.addOption("interim", false, "save interim model file"); BasicParser parser = new BasicParser(); CommandLine cl; try { cl = parser.parse(opt, args); } catch (Exception e) { System.err.println("Parameters format error"); return; } if (args.length == 0 || cl.hasOption('h')) { HelpFormatter f = new HelpFormatter(); f.printHelp( "Tagger:\n" + "tagger [option] -train templet_file train_file model_file [test_file];\n" + "tagger [option] model_file test_file output_file\n", opt); return; } addedTagger tagger = new addedTagger(); tagger.iterNum = Integer.parseInt(cl.getOptionValue("iter", "50")); tagger.c1 = Float.parseFloat(cl.getOptionValue("c1", "1")); tagger.c2 = Float.parseFloat(cl.getOptionValue("c2", "0.1")); tagger.useLoss = cl.hasOption("margin"); tagger.interim = cl.hasOption("interim"); String[] arg = cl.getArgs(); if (cl.hasOption("train") && arg.length == 3) { tagger.templateFile = arg[0]; tagger.train = arg[1]; tagger.model = arg[2]; System.out.println("Training model ..."); tagger.train(); } else if (cl.hasOption("train") && arg.length == 4) { tagger.templateFile = arg[0]; tagger.train = arg[1]; tagger.model = arg[2]; tagger.testfile = arg[3]; System.out.println("Training model ..."); tagger.train(); } else if (cl.hasOption("train") && arg.length == 5) { tagger.templateFile = arg[0]; tagger.train = arg[1]; tagger.model = arg[2]; tagger.testfile = arg[3]; System.out.println("Training model ..."); tagger.train(); System.gc(); tagger.output = arg[4]; tagger.test(); } else if (arg.length == 3) { tagger.model = arg[0]; tagger.testfile = arg[1]; tagger.output = arg[2]; tagger.test(); } else if (arg.length == 2) { tagger.model = arg[0]; tagger.testfile = arg[1]; tagger.test(); } else { System.err.println("paramenters format error!"); System.err.println("Print option \"-h\" for help."); return; } System.gc(); }