List of usage examples for org.apache.commons.cli Options addOption
public Options addOption(Option opt)
From source file:it.iit.genomics.cru.genomics.misc.apps.Vcf2tabApp.java
public static void main(String[] args) throws IOException, ParseException { Options options = new Options(); Option helpOpt = new Option("help", "print this message."); options.addOption(helpOpt); Option option1 = new Option("f", "filename", true, "VCF file to load"); option1.setRequired(true);/*from w ww .j a v a 2 s. c o m*/ options.addOption(option1); option1 = new Option("o", "outputfile", true, "outputfilene"); option1.setRequired(true); options.addOption(option1); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { // parse the command line arguments cmd = parser.parse(options, args, true); } catch (ParseException exp) { displayUsage("vcf2tab", options); System.exit(1); } if (cmd.hasOption("help")) { displayUsage("vcf2tab", options); System.exit(0); } String filename = cmd.getOptionValue("f"); String outputfilename = cmd.getOptionValue("o"); Vcf2tab loader = new Vcf2tab(); loader.file2tab(filename, outputfilename); //(args[0]); }
From source file:edu.scripps.fl.pubchem.app.AssayDownloader.java
public static void main(String[] args) throws Exception { CommandLineHandler clh = new CommandLineHandler() { public void configureOptions(Options options) { options.addOption(OptionBuilder.withLongOpt("data_url").withType("").withValueSeparator('=') .hasArg().create()); options.addOption(//from w w w .j a v a 2 s. co m OptionBuilder.withLongOpt("days").withType(0).withValueSeparator('=').hasArg().create()); options.addOption(OptionBuilder.withLongOpt("mlpcn").withType(false).create()); options.addOption(OptionBuilder.withLongOpt("notInDb").withType(false).create()); } }; args = clh.handle(args); String data_url = clh.getCommandLine().getOptionValue("data_url"); if (null == data_url) data_url = "ftp://ftp.ncbi.nlm.nih.gov/pubchem/Bioassay/CSV/"; // data_url = "file:///C:/Home/temp/PubChemFTP/"; AssayDownloader main = new AssayDownloader(); main.dataUrl = new URL(data_url); if (clh.getCommandLine().hasOption("days")) main.days = Integer.parseInt(clh.getCommandLine().getOptionValue("days")); if (clh.getCommandLine().hasOption("mlpcn")) main.mlpcn = true; if (clh.getCommandLine().hasOption("notInDb")) main.notInDb = true; if (args.length == 0) main.process(); else { Long[] list = (Long[]) ConvertUtils.convert(args, Long[].class); List<Long> l = (List<Long>) Arrays.asList(list); log.info("AID to process: " + l); main.process(new HashSet<Long>(Arrays.asList(list))); } }
From source file:com.github.sdnwiselab.sdnwise.mote.standalone.Loader.java
/** * @param args the command line arguments *//* ww w. jav a 2s. com*/ public static void main(final String[] args) { Options options = new Options(); options.addOption(Option.builder("n").argName("net").hasArg().required().desc("Network ID of the node") .numberOfArgs(1).build()); options.addOption(Option.builder("a").argName("address").hasArg().required() .desc("Address of the node <0-65535>").numberOfArgs(1).build()); options.addOption(Option.builder("p").argName("port").hasArg().required().desc("Listening UDP port") .numberOfArgs(1).build()); options.addOption(Option.builder("t").argName("filename").hasArg().required() .desc("Use given file for neighbors discovery").numberOfArgs(1).build()); options.addOption(Option.builder("c").argName("ip:port").hasArg() .desc("IP address and TCP port of the controller. (SINK ONLY)").numberOfArgs(1).build()); options.addOption(Option.builder("sp").argName("port").hasArg() .desc("Port number of the switch. (SINK ONLY)").numberOfArgs(1).build()); options.addOption(Option.builder("sm").argName("mac").hasArg() .desc("MAC address of the switch. Example: <00:00:00:00:00:00>." + " (SINK ONLY)").numberOfArgs(1) .build()); options.addOption(Option.builder("sd").argName("dpid").hasArg().desc("DPID of the switch (SINK ONLY)") .numberOfArgs(1).build()); options.addOption(Option.builder("l").argName("level").hasArg() .desc("Use given log level. Values: SEVERE, WARNING, INFO, " + "CONFIG, FINE, FINER, FINEST.") .numberOfArgs(1).optionalArg(true).build()); // create the parser CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, args); Thread th; byte cmdNet = (byte) Integer.parseInt(line.getOptionValue("n")); NodeAddress cmdAddress = new NodeAddress(Integer.parseInt(line.getOptionValue("a"))); int cmdPort = Integer.parseInt(line.getOptionValue("p")); String cmdTopo = line.getOptionValue("t"); String cmdLevel; if (!line.hasOption("l")) { cmdLevel = "SEVERE"; } else { cmdLevel = line.getOptionValue("l"); } if (line.hasOption("c")) { if (!line.hasOption("sd")) { throw new ParseException("-sd option missing"); } if (!line.hasOption("sp")) { throw new ParseException("-sp option missing"); } if (!line.hasOption("sm")) { throw new ParseException("-sm option missing"); } String cmdSDpid = line.getOptionValue("sd"); String cmdSMac = line.getOptionValue("sm"); long cmdSPort = Long.parseLong(line.getOptionValue("sp")); String[] ipport = line.getOptionValue("c").split(":"); th = new Thread(new Sink(cmdNet, cmdAddress, cmdPort, new InetSocketAddress(ipport[0], Integer.parseInt(ipport[1])), cmdTopo, cmdLevel, cmdSDpid, cmdSMac, cmdSPort)); } else { th = new Thread(new Mote(cmdNet, cmdAddress, cmdPort, cmdTopo, cmdLevel)); } th.start(); th.join(); } catch (InterruptedException | ParseException ex) { System.out.println("Parsing failed. Reason: " + ex.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sdn-wise-data -n id -a address -p port" + " -t filename [-l level] [-sd dpid -sm mac -sp port]", options); } }
From source file:be.redlab.maven.yamlprops.create.YamlConvertCli.java
public static void main(String... args) throws IOException { CommandLineParser parser = new DefaultParser(); Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); options.addOption(Option.builder("s").argName("source").desc("the source folder or file to convert") .longOpt("source").hasArg(true).build()); options.addOption(Option.builder("t").argName("target").desc("the target file to store in") .longOpt("target").hasArg(true).build()); options.addOption(Option.builder("h").desc("print help").build()); try {//ww w . j a v a 2s. c om CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { formatter.printHelp("converter", options); } File source = new File(cmd.getOptionValue("s", System.getProperty("user.dir"))); String name = source.getName(); if (source.isDirectory()) { PropertiesToYamlConverter yamlConverter = new PropertiesToYamlConverter(); String[] ext = { "properties" }; Iterator<File> fileIterator = FileUtils.iterateFiles(source, ext, true); while (fileIterator.hasNext()) { File next = fileIterator.next(); System.out.println(next); String s = StringUtils.removeStart(next.getParentFile().getPath(), source.getPath()); System.out.println(s); String f = StringUtils.split(s, IOUtils.DIR_SEPARATOR)[0]; System.out.println("key = " + f); Properties p = new Properties(); try { p.load(new FileReader(next)); yamlConverter.addProperties(f, p); } catch (IOException e) { e.printStackTrace(); } } FileWriter fileWriter = new FileWriter( new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml")); yamlConverter.writeYaml(fileWriter); fileWriter.close(); } else { Properties p = new Properties(); p.load(new FileReader(source)); FileWriter fileWriter = new FileWriter( new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml")); new PropertiesToYamlConverter().addProperties(name, p).writeYaml(fileWriter); fileWriter.close(); } } catch (ParseException e) { e.printStackTrace(); formatter.printHelp("converter", options); } }
From source file:cc.twittertools.search.api.SearchStatusesThrift.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(HELP_OPTION, "show help")); options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION)); options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION)); options.addOption(//from ww w . ja v a 2s . co m OptionBuilder.withArgName("string").hasArg().withDescription("query id").create(QID_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("maxid").create(MAX_ID_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION)); options.addOption(new Option(VERBOSE_OPTION, "print out complete document")); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(SearchStatusesThrift.class.getName(), options); System.exit(-1); } String qid = cmdline.hasOption(QID_OPTION) ? cmdline.getOptionValue(QID_OPTION) : DEFAULT_QID; String query = cmdline.hasOption(QUERY_OPTION) ? cmdline.getOptionValue(QUERY_OPTION) : DEFAULT_Q; String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG; long maxId = cmdline.hasOption(MAX_ID_OPTION) ? Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION)) : DEFAULT_MAX_ID; int numResults = cmdline.hasOption(NUM_RESULTS_OPTION) ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)) : DEFAULT_NUM_RESULTS; boolean verbose = cmdline.hasOption(VERBOSE_OPTION); String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null; String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null; TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION), Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token); System.err.println("qid: " + qid); System.err.println("q: " + query); System.err.println("max_id: " + maxId); System.err.println("num_results: " + numResults); PrintStream out = new PrintStream(System.out, true, "UTF-8"); List<TResult> results = client.search(query, maxId, numResults); int i = 1; for (TResult result : results) { out.println(String.format("%s Q0 %d %d %f %s", qid, result.id, i, result.rsv, runtag)); if (verbose) { System.out.println("# " + result.toString().replaceAll("[\\n\\r]+", " ")); } i++; } out.close(); }
From source file:cc.twittertools.search.api.TrecSearchThriftServer.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(HELP_OPTION, "show help")); options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION)); options.addOption(// w w w.ja v a 2s .c o m OptionBuilder.withArgName("index").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg() .withDescription("max number of threads in thread pool").create(MAX_THREADS_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("file containing access tokens").create(CREDENTIALS_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(TrecSearchThriftServer.class.getName(), options); System.exit(-1); } int port = cmdline.hasOption(PORT_OPTION) ? Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)) : DEFAULT_PORT; int maxThreads = cmdline.hasOption(MAX_THREADS_OPTION) ? Integer.parseInt(cmdline.getOptionValue(MAX_THREADS_OPTION)) : DEFAULT_MAX_THREADS; File index = new File(cmdline.getOptionValue(INDEX_OPTION)); Map<String, String> credentials = null; if (cmdline.hasOption(CREDENTIALS_OPTION)) { credentials = Maps.newHashMap(); File cfile = new File(cmdline.getOptionValue(CREDENTIALS_OPTION)); if (!cfile.exists()) { System.err.println("Error: " + cfile + " does not exist!"); System.exit(-1); } for (String s : Files.readLines(cfile, Charsets.UTF_8)) { try { String[] arr = s.split(":"); credentials.put(arr[0], arr[1]); } catch (Exception e) { // Catch any exceptions from parsing file contain access tokens System.err.println("Error reading access tokens from " + cfile + "!"); System.exit(-1); } } } if (!index.exists()) { System.err.println("Error: " + index + " does not exist!"); System.exit(-1); } TServerSocket serverSocket = new TServerSocket(port); TrecSearch.Processor<TrecSearch.Iface> searchProcessor = new TrecSearch.Processor<TrecSearch.Iface>( new TrecSearchHandler(index, credentials)); TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverSocket); serverArgs.maxWorkerThreads(maxThreads); TServer thriftServer = new TThreadPoolServer( serverArgs.processor(searchProcessor).protocolFactory(new TBinaryProtocol.Factory())); thriftServer.serve(); }
From source file:com.rabbitmq.examples.FileConsumer.java
public static void main(String[] args) { Options options = new Options(); options.addOption(new Option("h", "uri", true, "AMQP URI")); options.addOption(new Option("q", "queue", true, "queue name")); options.addOption(new Option("t", "type", true, "exchange type")); options.addOption(new Option("e", "exchange", true, "exchange name")); options.addOption(new Option("k", "routing-key", true, "routing key")); options.addOption(new Option("d", "directory", true, "output directory")); CommandLineParser parser = new GnuParser(); try {//from w w w. ja v a 2s . c o m CommandLine cmd = parser.parse(options, args); String uri = strArg(cmd, 'h', "amqp://localhost"); String requestedQueueName = strArg(cmd, 'q', ""); String exchangeType = strArg(cmd, 't', "direct"); String exchange = strArg(cmd, 'e', null); String routingKey = strArg(cmd, 'k', null); String outputDirName = strArg(cmd, 'd', "."); File outputDir = new File(outputDirName); if (!outputDir.exists() || !outputDir.isDirectory()) { System.err.println("Output directory must exist, and must be a directory."); System.exit(2); } ConnectionFactory connFactory = new ConnectionFactory(); connFactory.setUri(uri); Connection conn = connFactory.newConnection(); final Channel ch = conn.createChannel(); String queueName = (requestedQueueName.equals("") ? ch.queueDeclare() : ch.queueDeclare(requestedQueueName, false, false, false, null)).getQueue(); if (exchange != null || routingKey != null) { if (exchange == null) { System.err.println("Please supply exchange name to bind to (-e)"); System.exit(2); } if (routingKey == null) { System.err.println("Please supply routing key pattern to bind to (-k)"); System.exit(2); } ch.exchangeDeclare(exchange, exchangeType); ch.queueBind(queueName, exchange, routingKey); } QueueingConsumer consumer = new QueueingConsumer(ch); ch.basicConsume(queueName, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); Map<String, Object> headers = delivery.getProperties().getHeaders(); byte[] body = delivery.getBody(); Object headerFilenameO = headers.get("filename"); String headerFilename = (headerFilenameO == null) ? UUID.randomUUID().toString() : headerFilenameO.toString(); File givenName = new File(headerFilename); if (givenName.getName().equals("")) { System.out.println("Skipping file with empty name: " + givenName); } else { File f = new File(outputDir, givenName.getName()); System.out.print("Writing " + f + " ..."); FileOutputStream o = new FileOutputStream(f); o.write(body); o.close(); System.out.println(" done."); } ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } catch (Exception ex) { System.err.println("Main thread caught exception: " + ex); ex.printStackTrace(); System.exit(1); } }
From source file:com.hortonworks.registries.storage.tool.shell.ShellMigrationInitializer.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH) .desc("Root directory of script path").build()); options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH) .desc("Config file path").build()); options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.MIGRATE.toString()) .desc("Execute schema migration from last check point").build()); options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.INFO.toString()) .desc("Show the status of the schema migration compared to the target database").build()); options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.VALIDATE.toString()) .desc("Validate the target database changes with the migration scripts").build()); options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.REPAIR.toString()).desc( "Repairs the SCRIPT_CHANGE_LOG by removing failed migrations and correcting checksum of existing migration script") .build());/*from w ww . j a v a 2 s. co m*/ CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) { usage(options); System.exit(1); } boolean isShellMigrationOptionSpecified = false; ShellMigrationOption shellMigrationOptionSpecified = null; for (ShellMigrationOption shellMigrationOption : ShellMigrationOption.values()) { if (commandLine.hasOption(shellMigrationOption.toString())) { if (isShellMigrationOptionSpecified) { System.out.println( "Only one operation can be execute at once, please select one of ',migrate', 'validate', 'info', 'repair'."); System.exit(1); } isShellMigrationOptionSpecified = true; shellMigrationOptionSpecified = shellMigrationOption; } } if (!isShellMigrationOptionSpecified) { System.out.println( "One of the option 'migrate', 'validate', 'info', 'repair' must be specified to execute."); System.exit(1); } String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH); String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH); StorageProviderConfiguration storageProperties; try { Map<String, Object> conf = Utils.readConfig(confFilePath); StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader(); storageProperties = confReader.readStorageConfig(conf); } catch (IOException e) { System.err.println("Error occurred while reading config file: " + confFilePath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } ShellMigrationHelper schemaMigrationHelper = new ShellMigrationHelper( ShellFlywayFactory.get(storageProperties, scriptRootPath)); try { schemaMigrationHelper.execute(shellMigrationOptionSpecified); System.out.println(String.format("\"%s\" option successful", shellMigrationOptionSpecified.toString())); } catch (Exception e) { System.err.println(String.format("\"%s\" option failed : %s", shellMigrationOptionSpecified.toString(), e.getMessage())); System.exit(1); } }
From source file:cloudlens.cli.Main.java
public static void main(String[] args) throws Exception { final CommandLineParser optionParser = new DefaultParser(); final HelpFormatter formatter = new HelpFormatter(); final Option lens = Option.builder("r").longOpt("run").hasArg().argName("lens file").desc("Lens file.") .required(true).build();//www .j av a2s . c o m final Option log = Option.builder("l").longOpt("log").hasArg().argName("log file").desc("Log file.") .build(); final Option jsonpath = Option.builder().longOpt("jsonpath").hasArg().argName("path") .desc("Path to logs in a json object.").build(); final Option js = Option.builder().longOpt("js").hasArg().argName("js file").desc("Load JS file.").build(); final Option format = Option.builder("f").longOpt("format").hasArg() .desc("Choose log format (text or json).").build(); final Option streaming = Option.builder().longOpt("stream").desc("Streaming mode.").build(); final Option history = Option.builder().longOpt("history").desc("Store history.").build(); final Options options = new Options(); options.addOption(log); options.addOption(lens); options.addOption(format); options.addOption(jsonpath); options.addOption(js); options.addOption(streaming); options.addOption(history); try { final CommandLine cmd = optionParser.parse(options, args); final String jsonPath = cmd.getOptionValue("jsonpath"); final String[] jsFiles = cmd.getOptionValues("js"); final String[] lensFiles = cmd.getOptionValues("run"); final String[] logFiles = cmd.getOptionValues("log"); final String source = cmd.getOptionValue("format"); final boolean stream = cmd.hasOption("stream") || !cmd.hasOption("log"); final boolean withHistory = cmd.hasOption("history") || !stream; final CL cl = new CL(System.out, System.err, stream, withHistory); try { final InputStream input = (cmd.hasOption("log")) ? FileReader.readFiles(logFiles) : System.in; if (source == null) { cl.source(input); } else { switch (source) { case "text": cl.source(input); break; case "json": cl.json(input, jsonPath); break; default: input.close(); throw new CLException("Unsupported format: " + source); } } for (final String jsFile : FileReader.fullPaths(jsFiles)) { cl.engine.eval("CL.loadjs('file://" + jsFile + "')"); } final List<ASTElement> top = ASTBuilder.parseFiles(lensFiles); cl.launch(top); } catch (final CLException | ASTException e) { cl.errWriter.println(e.getMessage()); } finally { cl.outWriter.flush(); cl.errWriter.flush(); } } catch (final ParseException e) { System.err.println(e.getMessage()); formatter.printHelp("cloudlens", options); } }
From source file:com.runwaysdk.system.metadata.MetadataPatcher.java
@SuppressWarnings("static-access") public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("vendor").hasArg() .withDescription("Database vendor [" + POSTGRESQL + "]").isRequired().create("d")); options.addOption(OptionBuilder.withArgName("username").hasArg().withDescription("Database username") .isRequired().create("u")); options.addOption(OptionBuilder.withArgName("password").hasArg().withDescription("Database password") .isRequired().create("p")); options.addOption(/*from www.j av a2 s. co m*/ OptionBuilder.withArgName("url").hasArg().withDescription("Database URL").isRequired().create("l")); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); MetadataPatcher patcher = new MetadataPatcher(); patcher.setDbms(cmd.getOptionValue("d")); patcher.setUserid(cmd.getOptionValue("u")); patcher.setPassword(cmd.getOptionValue("p")); patcher.setUrl(cmd.getOptionValue("l")); patcher.run(); } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); } catch (RuntimeException exp) { System.err.println("Patching failed. Reason: " + exp.getMessage()); } }