List of usage examples for org.apache.commons.cli CommandLine getOptionValues
public String[] getOptionValues(char opt)
From source file:com.springrts.springls.CmdLineArgs.java
/** * Processes all command line arguments in 'args'. * Raises an exception in case of errors. * @return whether to exit the application after this method *//*from w w w.j ava 2 s . c om*/ private static boolean apply(Configuration configuration, CommandLineParser parser, Options options, String[] args) throws ParseException { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Server.getApplicationName(), options); return true; } if (cmd.hasOption("port")) { String portStr = cmd.getOptionValue("port"); int port = Integer.parseInt(portStr); if ((port < 1) || (port > 65535)) { throw new ParseException("Invalid port specified: " + portStr); } configuration.setProperty(ServerConfiguration.PORT, port); } if (cmd.hasOption("database")) { configuration.setProperty(ServerConfiguration.USE_DATABASE, true); } else if (cmd.hasOption("file-storage")) { configuration.setProperty(ServerConfiguration.USE_DATABASE, false); } else { configuration.setProperty(ServerConfiguration.LAN_MODE, true); } if (cmd.hasOption("statistics")) { configuration.setProperty(ServerConfiguration.STATISTICS_STORE, true); } if (cmd.hasOption("nat-port")) { String portStr = cmd.getOptionValue("port"); int port = Integer.parseInt(portStr); if ((port < 1) || (port > 65535)) { throw new ParseException("Invalid NAT traversal port" + " specified: " + portStr); } configuration.setProperty(ServerConfiguration.NAT_PORT, port); } if (cmd.hasOption("log-main")) { configuration.setProperty(ServerConfiguration.CHANNELS_LOG_REGEX, "^main$"); } if (cmd.hasOption("lan-admin")) { String[] usernamePassword = cmd.getOptionValues("lan-admin"); if (usernamePassword.length < 1) { throw new MissingArgumentException("LAN admin user name is missing"); } String username = usernamePassword[0]; String password = (usernamePassword.length > 1) ? usernamePassword[0] : ServerConfiguration.getDefaults().getString(ServerConfiguration.LAN_ADMIN_PASSWORD); String error = Account.isOldUsernameValid(username); if (error != null) { throw new ParseException("LAN admin user name is not valid: " + error); } error = Account.isPasswordValid(password); if (error != null) { throw new ParseException("LAN admin password is not valid: " + error); } configuration.setProperty(ServerConfiguration.LAN_ADMIN_USERNAME, username); configuration.setProperty(ServerConfiguration.LAN_ADMIN_PASSWORD, password); } if (cmd.hasOption("load-args")) { File argsFile = new File(cmd.getOptionValue("load-args")); Reader inF = null; BufferedReader in = null; try { try { inF = new FileReader(argsFile); in = new BufferedReader(inF); String line; List<String> argsList = new LinkedList<String>(); while ((line = in.readLine()) != null) { String[] argsLine = line.split("[ \t]+"); argsList.addAll(Arrays.asList(argsLine)); } String[] args2 = argsList.toArray(new String[argsList.size()]); apply(configuration, parser, options, args2); } finally { if (in != null) { in.close(); } else if (inF != null) { inF.close(); } } } catch (Exception ex) { throw new ParseException("invalid load-args argument: " + ex.getMessage()); } } if (cmd.hasOption("spring-version")) { String version = cmd.getOptionValue("spring-version"); configuration.setProperty(ServerConfiguration.ENGINE_VERSION, version); } return false; }
From source file:fr.ens.biologie.genomique.eoulsan.actions.CreateDesignAction.java
@Override public void action(final List<String> arguments) { final Options options = makeOptions(); final CommandLineParser parser = new GnuParser(); String filename = "design.txt"; int argsOptions = 0; boolean pairedEndMode = false; final List<String> sampleSheetPaths = new ArrayList<>(); String samplesProjectName = null; boolean symlinks = false; int formatVersion = DEFAULT_DESIGN_FORMAT; try {//from w w w . ja va 2s .c o m // parse the command line arguments final CommandLine line = parser.parse(options, arguments.toArray(new String[arguments.size()]), true); // Pair-end option if (line.hasOption("paired-end")) { pairedEndMode = true; argsOptions += 1; } // Help option if (line.hasOption("help")) { help(options); } // Output option if (line.hasOption("o")) { filename = line.getOptionValue("o"); argsOptions += 2; } // Casava design option if (line.hasOption("s")) { String[] sampleSheets = line.getOptionValues("s"); sampleSheetPaths.addAll(Arrays.asList(sampleSheets)); argsOptions += sampleSheets.length * 2; } // Casava project option if (line.hasOption("n")) { samplesProjectName = line.getOptionValue("n"); argsOptions += 2; } // Symbolic links option if (line.hasOption("symlinks")) { symlinks = true; argsOptions++; } // Eoulsan design format version option if (line.hasOption("f")) { try { formatVersion = Integer.parseInt(line.getOptionValue("f").trim()); } catch (NumberFormatException e) { Common.errorExit(e, "Invalid Eoulsan design format version: " + e.getMessage()); } argsOptions += 2; } } catch (ParseException e) { Common.errorExit(e, "Error while parsing command line arguments: " + e.getMessage()); } // Write log entries Main.getInstance().flushLog(); Design design = null; final DataFile designFile = new DataFile(filename); try { final List<String> newArgs = arguments.subList(argsOptions, arguments.size()); final DesignBuilder db = new DesignBuilder(); // Add all the files of a Casava design if Casava design path is defined for (String sampleSheetPath : sampleSheetPaths) { db.addBcl2FastqSamplesheetProject(new File(sampleSheetPath), samplesProjectName); } // Add files in the command line db.addFiles(newArgs); design = db.getDesign(pairedEndMode); if (symlinks) { DesignUtils.replaceLocalPathBySymlinks(design, designFile.getParent()); } } catch (EoulsanException | IOException e) { Common.errorExit(e, "Error: " + e.getMessage()); } if (design.getSamples().isEmpty()) { Common.showErrorMessageAndExit( "Error: Nothing to create, no file found.\n" + " Use the -h option to get more information.\n" + "usage: " + Globals.APP_NAME_LOWER_CASE + " createdesign files"); } try { if (designFile.exists()) { throw new IOException("Output design file " + designFile + " already exists"); } final DesignWriter dw; switch (formatVersion) { case 1: dw = new Eoulsan1DesignWriter(designFile.create()); break; case 2: dw = new Eoulsan2DesignWriter(designFile.create()); break; default: Common.showErrorMessageAndExit("Unknown Eoulsan design format version: " + formatVersion); return; } dw.write(design); } catch (IOException e) { Common.errorExit(e, "File not found: " + e.getMessage()); } }
From source file:fr.inrialpes.exmo.align.cli.ExtGroupEval.java
public void run(String[] args) throws Exception { try {//from www. j ava 2 s. c o m CommandLine line = parseCommandLine(args); if (line == null) return; // --help // Here deal with command specific arguments if (line.hasOption('f')) format = line.getOptionValue('f'); if (line.hasOption('r')) reference = line.getOptionValue('r'); //if ( line.hasOption( 's' ) ) dominant = line.getOptionValue( 's' ); if (line.hasOption('t')) type = line.getOptionValue('t'); if (line.hasOption('c')) color = line.getOptionValue('c', "lightblue"); if (line.hasOption('l')) { listAlgo = line.getOptionValues('l'); size = listAlgo.length; } if (line.hasOption('w')) ontoDir = line.getOptionValue('w'); } catch (ParseException exp) { logger.error(exp.getMessage()); usage(); System.exit(-1); } print(iterateDirectories()); }
From source file:dumptspacket.Main.java
public void start(String[] args) throws org.apache.commons.cli.ParseException { final String fileName; final Long limit; final Set<Integer> pids; System.out.println("args : " + dumpArgs(args)); final Option fileNameOption = Option.builder("f").required().longOpt("filename").desc("ts??") .hasArg().type(String.class).build(); final Option limitOption = Option.builder("l").required(false).longOpt("limit") .desc("??(???????EOF??)").hasArg() .type(Long.class).build(); final Option pidsOption = Option.builder("p").required().longOpt("pids") .desc("pid(?16?)").type(String.class).hasArgs().build(); Options opts = new Options(); opts.addOption(fileNameOption);/*from w w w . ja v a2 s. co m*/ opts.addOption(limitOption); opts.addOption(pidsOption); CommandLineParser parser = new DefaultParser(); CommandLine cl; HelpFormatter help = new HelpFormatter(); try { // parse options cl = parser.parse(opts, args); // handle interface option. fileName = cl.getOptionValue(fileNameOption.getOpt()); if (fileName == null) { throw new ParseException("????????"); } // handlet destination option. Long xl = null; try { xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt())); } catch (NumberFormatException e) { xl = null; } finally { limit = xl; } Set<Integer> x = new HashSet<>(); List<String> ls = new ArrayList<>(); ls.addAll(Arrays.asList(cl.getOptionValues(pidsOption.getOpt()))); for (String s : ls) { try { x.add(Integer.parseUnsignedInt(s, 16)); } catch (NumberFormatException e) { throw new ParseException(e.getMessage()); } } pids = Collections.unmodifiableSet(x); System.out.println("Starting application..."); System.out.println("filename : " + fileName); System.out.println("limit : " + limit); System.out.println("pids : " + dumpSet(pids)); // your code TsReader reader; if (limit == null) { reader = new TsReader(new File(fileName), pids); } else { reader = new TsReader(new File(fileName), pids, limit); } Map<Integer, List<TsPacketParcel>> ret = reader.getPackets(); try { for (Integer pid : ret.keySet()) { FileWriter writer = new FileWriter(fileName + "_" + Integer.toHexString(pid) + ".txt"); for (TsPacketParcel par : ret.get(pid)) { String text = Hex.encodeHexString(par.getPacket().getData()); writer.write(text + "\n"); } writer.flush(); writer.close(); } } catch (IOException ex) { LOG.fatal("", ex); } } catch (ParseException e) { // print usage. help.printHelp("My Java Application", opts); throw e; } catch (FileNotFoundException ex) { LOG.fatal("", ex); } }
From source file:com.emc.ecs.EcsBufferedWriter.java
protected static WriterTask createTask(CommandLine line) throws Exception { WriterTask task;//w w w. j a va 2 s .co m // Special check for version if (line.hasOption(VERSION_OPTION)) { //System.out.println(versionLine()); System.out.println("JMC 1.0"); System.exit(0); } //LogManager.getRootLogger().setLevel(Level.INFO); //this.l4j. //LogManager.getRootLogger().addAppender(new FileAppender()); // check required options boolean status = true; if (line.hasOption(ENDPOINT_OPTION) == false) { status = false; System.out.println("Missing endpoint option"); } if (line.hasOption(ACCESS_KEY_OPTION) == false) { status = false; System.out.println("Missing access key option"); } if (line.hasOption(SECRET_KEY_OPTION) == false) { status = false; System.out.println("Missing secret key option"); } if (line.hasOption(BUCKET_OPTION) == false) { status = false; System.out.println("Missing bucket option"); } if (line.hasOption(KEY_OPTION) == false) { status = false; System.out.println("Missing key/file option"); } if (line.getArgs().length == 0) { status = false; //JMC tailbuf is undocumented because that last partially filled buffer doesn't //flush if it's just hanging around waiting System.out.println("Missing initial command option (write|append|tail)"); } if (status == false) { help(); System.exit(1); } String command = line.getArgs()[0]; // parse endpoint string String[] endpointStrings = line.getOptionValues(ENDPOINT_OPTION); //////////////////////////////////// /* Protocol protocol = Protocol.HTTPS; int port = -1; List<Vdc> vdcList = new ArrayList<Vdc>(); for (String endpointString : endpointStrings) { URI endpoint = new URI(endpointString); // check for just a host if (endpointString.matches("^[a-zA-Z0-9.-]*$")) endpoint = new URI(null, endpointString, null, null); // get protocol if (endpoint.getScheme() != null) protocol = Protocol.valueOf(endpoint.getScheme().toUpperCase()); // get port port = endpoint.getPort(); vdcList.add(new Vdc(endpoint.getHost())); } // create S3 config S3Config s3Config = new S3Config(protocol, vdcList.toArray(new Vdc[vdcList.size()])).withPort(port); s3Config.withIdentity(line.getOptionValue(ACCESS_KEY_OPTION)).withSecretKey(line.getOptionValue(SECRET_KEY_OPTION)); //s3Config.setProperty(S3Config.PROPERTY_DISABLE_HEALTH_CHECK, true); */ /////// S3Config s3Config = new S3Config(new URI(endpointStrings[0])); s3Config.withIdentity(line.getOptionValue(ACCESS_KEY_OPTION)) .withSecretKey(line.getOptionValue(SECRET_KEY_OPTION)); if (line.hasOption(NAMESPACE_OPTION) == true) { String ns = new String(line.getOptionValue(NAMESPACE_OPTION)); System.err.println("Creating s3Config with namespace: " + ns); s3Config.withNamespace(ns); } l4j.debug(s3Config); S3Client s3Client = new S3JerseyClient(s3Config); String bucket = line.getOptionValue(BUCKET_OPTION); // figure out file/key name String key = line.getOptionValue(KEY_OPTION); System.err.println("executing command: " + command); //if stream to ecs if (WRITE_COMMAND.equals(command)) { System.err.println("Found matching write command"); StreamToEcs ste = new StreamToEcs(s3Client, bucket, key, StreamToEcs.DOWRITE); task = new WriterTask(ste); } else if (APPEND_COMMAND.equals(command)) { System.err.println("Found matching append command"); StreamToEcs ste = new StreamToEcs(s3Client, bucket, key, StreamToEcs.DOAPPEND); task = new WriterTask(ste); } //else if tail from ecs else if (TAILBYTE_COMMAND.equals(command)) { System.err.println("Found matching tail command"); TailFromEcs tfe = new TailFromEcs(s3Client, bucket, key, TailFromEcs.TAILBYTE); task = new WriterTask(tfe); } else if (TAIL_COMMAND.equals(command)) { System.err.println("Found matching tailbuf command"); TailFromEcs tfe = new TailFromEcs(s3Client, bucket, key, TailFromEcs.TAIL); if (line.hasOption(BYTES_FROM_END_OPTION) == true) { Long bytesFromEnd = new Long(line.getOptionValue(BYTES_FROM_END_OPTION)); tfe.bytesFromEnd = bytesFromEnd.longValue(); System.err.println("tailing " + bytesFromEnd + " bytes from EOF"); } task = new WriterTask(tfe); } //else... not sure else { throw new RuntimeException("unrecognized command word"); } return (task); }
From source file:gov.llnl.lc.smt.command.SubnetMonitorTool.java
/** * Describe the method here/*from w w w. j a v a2 s.c o m*/ * * @see gov.llnl.lc.smt.command.SmtCommandInterface#parseCommands(java.util.Map, org.apache.commons.cli.CommandLine) * * @param config * @param line * @return ***********************************************************/ @Override public boolean parseCommands(Map<String, String> config, CommandLine line) { boolean status = true; // set the command and sub-command (always do this) config.put(SmtProperty.SMT_COMMAND.getName(), this.getClass().getName()); // everything is considered an argument that is not part of the subcommand // the first subcommand wins saveCommandArgs(line.getArgs(), config); for (SmtCommandType s : SmtCommandType.SMT_COMMON_CMDS) { if (line.hasOption(s.getName())) { config.put(SmtProperty.SMT_SUBCOMMAND.getName(), s.getName()); config.put(s.getName(), line.getOptionValue(s.getName())); saveCommandArgs(line.getOptionValues(s.getName()), config); break; } } return status; }
From source file:com.teradata.benchto.generator.HiveTypesGenerator.java
@Override public int run(String[] args) throws Exception { Options options = new Options(); options.addOption(//from w ww .j a v a 2 s . c om Option.builder("format").required().hasArg().desc("file format (orc, parquet or text)").build()); options.addOption(Option.builder("type").required().hasArg().desc( "hive type to be generated (bigint, int, boolean, double, binary, date, timestamp, string, decimal or varchar)") .build()); options.addOption(Option.builder("rows").required().hasArg().desc("total row count").build()); options.addOption(Option.builder("mappers").required().hasArg().desc("total mappers count").build()); options.addOption(Option.builder("path").hasArg() .desc("base path for generating files, default is: /benchmarks/benchto/types").build()); options.addOption(Option.builder("regex").numberOfArgs(3) .desc("generate varchars from regex pattern, arguments are: pattern, min length, max length") .build()); CommandLine line; String format; String hiveType; long numberOfRows; long numberOfFiles; String basePath; Optional<String> regexPattern = Optional.absent(); Optional<Integer> regexMinLength = Optional.absent(); Optional<Integer> regexMaxLength = Optional.absent(); try { line = new DefaultParser().parse(options, args); format = line.getOptionValue("format"); hiveType = line.getOptionValue("type"); numberOfRows = parseLong(line.getOptionValue("rows")); numberOfFiles = parseLong(line.getOptionValue("mappers")); basePath = line.getOptionValue("path", "/benchmarks/benchto/types"); if (line.hasOption("regex")) { String[] values = line.getOptionValues("regex"); regexPattern = Optional.of(values[0]); regexMinLength = Optional.of(parseInt(values[1])); regexMaxLength = Optional.of(parseInt(values[2])); } } catch (Exception e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("benchto-generator", options); throw e; } String jobName = format("GenerateData-%s-%s-%d", format, hiveType, numberOfRows); Path outputDir = new Path(format("%s/%s-%s/%d", basePath, format, hiveType, numberOfRows)); Class<? extends OutputFormat> outputFormatClass = getOutputFormatClass(format); LOG.info("Generating " + numberOfRows + " " + hiveType + "s, directory: " + outputDir + ", number of files: " + numberOfFiles); Configuration configuration = new Configuration(); configuration.set(FORMAT_PROPERTY_NAME, format); configuration.set(HIVE_TYPE_PROPERTY_NAME, hiveType); configuration.setLong(NUM_ROWS_PROPERTY_NAME, numberOfRows); configuration.setLong(NUM_MAPS, numberOfFiles); if (regexPattern.isPresent()) { configuration.set(REGEX_PATTERN, regexPattern.get()); configuration.setInt(REGEX_MIN_LENGTH, regexMinLength.get()); configuration.setInt(REGEX_MAX_LENGTH, regexMaxLength.get()); } Job generatorJob = Job.getInstance(configuration, jobName); FileOutputFormat.setOutputPath(generatorJob, outputDir); ParquetOutputFormat.setWriteSupportClass(generatorJob, DataWritableWriteSupport.class); generatorJob.setJarByClass(HiveTypesGenerator.class); generatorJob.setMapperClass(HiveTypesMapper.class); generatorJob.setNumReduceTasks(0); generatorJob.setOutputKeyClass(NullWritable.class); generatorJob.setOutputValueClass(Writable.class); generatorJob.setInputFormatClass(CounterInputFormat.class); generatorJob.setOutputFormatClass(outputFormatClass); return generatorJob.waitForCompletion(true) ? 0 : 1; }
From source file:com.yahoo.yqlplus.engine.tools.YQLPlusRun.java
@SuppressWarnings("unchecked") public int run(CommandLine command) throws Exception { String script = null;//w ww . j a va 2s .com String filename = null; if (command.hasOption("command")) { script = command.getOptionValue("command"); filename = "<command line>"; } List<String> scriptAndArgs = (List<String>) command.getArgList(); if (filename == null && scriptAndArgs.size() < 1) { System.err.println("No script specified."); return -1; } else if (script == null) { filename = scriptAndArgs.get(0); Path scriptPath = Paths.get(filename); if (!Files.isRegularFile(scriptPath)) { System.err.println(scriptPath + " is not a file."); return -1; } script = Charsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(scriptPath))).toString(); } List<String> paths = Lists.newArrayList(); if (command.hasOption("path")) { paths.addAll(Arrays.asList(command.getOptionValues("path"))); } // TODO: this isn't going to be very interesting without some sources Injector injector = Guice.createInjector(new JavaEngineModule()); YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class); CompiledProgram program = compiler.compile(script); if (command.hasOption("source")) { program.dump(System.out); return 0; } // TODO: read command line arguments to pass to program ExecutorService outputThreads = Executors.newSingleThreadExecutor(); ProgramResult result = program.run(Maps.<String, Object>newHashMap(), true); for (String name : result.getResultNames()) { final ListenableFuture<YQLResultSet> future = result.getResult(name); future.addListener(new Runnable() { @Override public void run() { try { YQLResultSet resultSet = future.get(); System.out.println(new String((byte[]) resultSet.getResult())); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }, outputThreads); } Future<TraceRequest> done = result.getEnd(); try { done.get(10000L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException | TimeoutException e) { e.printStackTrace(); } outputThreads.awaitTermination(1L, TimeUnit.SECONDS); return 0; }
From source file:fr.inrialpes.exmo.align.cli.WGroupEval.java
public void run(String[] args) throws Exception { try {//from ww w . j av a 2 s .c o m CommandLine line = parseCommandLine(args); if (line == null) return; // --help // Here deal with command specific arguments if (line.hasOption('f')) format = line.getOptionValue('f'); if (line.hasOption('r')) reference = line.getOptionValue('r'); if (line.hasOption('s')) dominant = line.getOptionValue('s'); if (line.hasOption('t')) type = line.getOptionValue('t'); if (line.hasOption('c')) color = line.getOptionValue('c', "lightblue"); if (line.hasOption('l')) { listAlgo = line.getOptionValues('l'); size = listAlgo.length; } if (line.hasOption('w')) ontoDir = line.getOptionValue('w'); } catch (ParseException exp) { logger.error(exp.getMessage()); usage(); System.exit(-1); } print(iterateDirectories()); }
From source file:co.turnus.analysis.bottlenecks.AlgorithmicBottlenecksCliLauncher.java
private static Configuration parseCommandLine(CommandLine cmd) throws ParseException { Configuration config = new BaseConfiguration(); StringBuffer s = new StringBuffer(); config.setProperty(VERBOSE, cmd.hasOption("v")); if (!cmd.hasOption("t")) { s.append("Trace project directory not specified. "); } else {/*from ww w .j a v a 2 s . c om*/ String fileName = cmd.getOptionValue("t", ""); File file = new File(fileName); if (file == null || !file.exists()) { s.append("Trace project does not exists. "); } else { config.setProperty(TRACE_PROJECT, fileName); } } if (!cmd.hasOption("w")) { s.append("Profiling weights file not specified. "); } else { String fileName = cmd.getOptionValue("w", ""); File file = new File(fileName); if (file == null || !file.exists()) { s.append("Profiling weights file does not exists. "); } else { config.setProperty(PROFILING_WEIGHTS, fileName); } } if (!cmd.hasOption("o")) { s.append("Output directory not specified. "); } else { String fileName = cmd.getOptionValue("o", ""); File file = new File(fileName); if (file == null || !file.exists()) { s.append("Output directory does not exists. "); } else { config.setProperty(OUTPUT_PATH, fileName); } } if (cmd.hasOption("xls")) { String fileName = cmd.getOptionValue("xls", ""); if (fileName == null || fileName.isEmpty()) { s.append("XLS file name is not correct. "); } else { config.setProperty(XLS, fileName); } } if (cmd.hasOption("i")) { config.setProperty(IMPACT_ANALYSIS_RUN, true); String[] values = cmd.getOptionValues("i"); if (values.length < 3) { s.append("No enought parameters for the impact analysis. "); } else { try { int intValue = Integer.parseInt(values[0]); config.setProperty(IMPACT_ANALYSIS_ACTIONS, intValue); } catch (Exception e) { s.append("The number of actions for the impact analysis should be an integer value. "); } try { int intValue = Integer.parseInt(values[1]); config.setProperty(IMPACT_ANALYSIS_POINTS, intValue); } catch (Exception e) { s.append("The number of points for the impact analysis should be an integer value. "); } String value = values[2]; if (value.equals("a")) { config.setProperty(IMPACT_ANALYSIS_ACTORLEVEL, true); } else if (value.equals("c")) { config.setProperty(IMPACT_ANALYSIS_ACTORLEVEL, false); } else { s.append("The impact analysis granularity is not correct. "); } } } else { config.setProperty(IMPACT_ANALYSIS_RUN, false); } String error = s.toString(); if (!error.isEmpty()) { throw new ParseException(error); } return config; }