List of usage examples for org.apache.commons.cli CommandLineParser parse
CommandLine parse(Options options, String[] arguments) throws ParseException;
From source file:bs.java
public static void main(String[] args) throws FileNotFoundException { Options options = new Options(); options.addOption(help);//from w w w .j a v a2s . co m options.addOption(version); options.addOption(loadPath); options.addOption(loadable); options.addOption(eval); // args = new String[] { "Reflection.bs" }; try { Bs.init(); CommandLineParser argParser = new PosixParser(); CommandLine line = argParser.parse(options, args); if (line.hasOption(HELP)) { help(options); } if (line.hasOption(VERSION)) { version(); } if (line.hasOption(LOAD_PATH)) { loadPath(line.getOptionValue(LOAD_PATH)); } if (line.hasOption(EVAL)) { eval(line.getOptionValue(EVAL)); } if (line.hasOption(LOADABLE)) { loadable(line.getOptionValue(LOADABLE)); } List<?> rest = line.getArgList(); if (rest.size() > 0) { eval(rest); } else { repl(); } } catch (ParseException e) { help(options); } }
From source file:com.datastax.sparql.ConsoleCompiler.java
public static void main(final String[] args) throws IOException { //args = "/examples/modern1.sparql"; final Options options = new Options(); options.addOption("f", "file", true, "a file that contains a SPARQL query"); options.addOption("g", "graph", true, "the graph that's used to execute the query [classic|modern|crew|kryo file]"); // TODO: add an OLAP option (perhaps: "--olap spark"?) final CommandLineParser parser = new DefaultParser(); final CommandLine commandLine; try {/*from www. j av a 2 s. c o m*/ commandLine = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); printHelp(1); return; } final InputStream inputStream = commandLine.hasOption("file") ? new FileInputStream(commandLine.getOptionValue("file")) : System.in; final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); final StringBuilder queryBuilder = new StringBuilder(); if (!reader.ready()) { printHelp(1); } String line; while (null != (line = reader.readLine())) { queryBuilder.append(System.lineSeparator()).append(line); } final String queryString = queryBuilder.toString(); final Graph graph; if (commandLine.hasOption("graph")) { switch (commandLine.getOptionValue("graph").toLowerCase()) { case "classic": graph = TinkerFactory.createClassic(); break; case "modern": graph = TinkerFactory.createModern(); System.out.println("Modern Graph Created"); break; case "crew": graph = TinkerFactory.createTheCrew(); break; default: graph = TinkerGraph.open(); System.out.println("Graph Created"); long startTime = System.nanoTime(); graph.io(IoCore.gryo()).readGraph(commandLine.getOptionValue("graph")); long endTime = System.nanoTime(); System.out.println("Time taken to load graph from kyro file: " + (endTime - startTime) / 1000000 + " mili seconds"); break; } } else { graph = TinkerFactory.createModern(); } final Traversal<Vertex, ?> traversal = SparqlToGremlinCompiler.convertToGremlinTraversal(graph, queryString); printWithHeadline("SPARQL Query", queryString); printWithHeadline("Traversal (prior execution)", traversal); Bytecode traversalByteCode = traversal.asAdmin().getBytecode(); //JavaTranslator.of(graph.traversal()).translate(traversalByteCode); System.out.println("the Byte Code : " + traversalByteCode.toString()); printWithHeadline("Result", String.join(System.lineSeparator(), JavaTranslator.of(graph.traversal()) .translate(traversalByteCode).toStream().map(Object::toString).collect(Collectors.toList()))); printWithHeadline("Traversal (after execution)", traversal); }
From source file:com.google.flightmap.parsing.faa.nasr.CommParser.java
public static void main(String args[]) { CommandLine line = null;/*from w ww . ja v a 2 s . co m*/ try { final CommandLineParser parser = new PosixParser(); line = parser.parse(OPTIONS, args); } catch (ParseException pEx) { System.err.println(pEx.getMessage()); printHelp(line); System.exit(1); } if (line.hasOption(HELP_OPTION)) { printHelp(line); System.exit(0); } final String twrFile = line.getOptionValue(TWR_OPTION); final String iataToIcaoFile = line.getOptionValue(IATA_TO_ICAO_OPTION); final String freqUsesNormalizationFile = line.getOptionValue(FREQ_USES_NORMALIZATION_OPTION); final String dbFile = line.getOptionValue(AVIATION_DB_OPTION); try { (new CommParser(twrFile, iataToIcaoFile, freqUsesNormalizationFile, dbFile)).execute(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } }
From source file:com.movielabs.availstool.AvailsTool.java
public static void main(String[] args) throws Exception { String fileName, outFile, sheetName; int sheetNum = -1; Logger log = LogManager.getLogger(AvailsTool.class.getName()); log.info("Initializing logger"); Options options = new Options(); options.addOption(Opts.v.name(), false, "verbose mode"); options.addOption(Opts.s.name(), true, "specify sheet"); options.addOption(Opts.f.name(), true, "specify file name"); options.addOption(Opts.o.name(), true, "specify output file name"); options.addOption(Opts.sstoxml.name(), false, "convert avails spreadsheet to XML"); options.addOption(Opts.xmltoss.name(), false, "convert avails XML to a spreadsheet"); options.addOption(Opts.dumpsheet.name(), false, "dump a single sheet from a spreadsheet"); options.addOption(Opts.dumpss.name(), false, "dump a spreadsheet file"); options.addOption(Opts.wx.name(), false, "treat warning as fatal error"); options.addOption(Opts.clean.name(), false, "clean up data entries"); CommandLineParser cli = new DefaultParser(); try {/*w ww.java2 s . co m*/ CommandLine cmd = cli.parse(options, args); boolean optToXML = cmd.hasOption(Opts.sstoxml.name()); boolean optToSS = cmd.hasOption(Opts.xmltoss.name()); boolean optDumpSS = cmd.hasOption(Opts.dumpss.name()); boolean optDumpSheet = cmd.hasOption(Opts.dumpsheet.name()); fileName = cmd.getOptionValue(Opts.f.name()); sheetName = cmd.getOptionValue(Opts.s.name()); boolean clean = cmd.hasOption(Opts.clean.name()); boolean wx = cmd.hasOption(Opts.wx.name()); boolean verbose = cmd.hasOption(Opts.v.name()); AvailSS ss; AvailsSheet as; String message; if (sheetName != null) { Pattern pat = Pattern.compile("^\\d+$"); Matcher m = pat.matcher(sheetName); if (m.matches()) sheetNum = Integer.parseInt(sheetName); } if (fileName == null) throw new ParseException("input file not specified"); if (!(optToXML | optToSS | optDumpSS | optDumpSheet)) throw new ParseException("missing operation"); if (optToXML) { if (optToSS | optDumpSS | optDumpSheet) throw new ParseException("more than one operation specified"); outFile = cmd.getOptionValue(Opts.o.name()); if (outFile == null) throw new ParseException("output file not specified"); ss = new AvailSS(fileName, log, wx, clean); if (sheetNum < 0) as = ss.addSheet(sheetName); else as = ss.addSheet(sheetNum); message = "toXML file: " + fileName + " sheet: " + sheetName; log.info(message); if (verbose) System.out.println(message); log.info("Options: -clean:" + clean + "; -wx:" + wx + "; output file: " + outFile); String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date()); String shortDesc = String.format("generated XML from %s:%s on %s", fileName, sheetName, timeStamp); as.makeXMLFile(outFile, shortDesc); } else if (optToSS) { if (optToXML | optDumpSS | optDumpSheet) throw new ParseException("more than one operation specified"); // TODO implement this outFile = cmd.getOptionValue(Opts.o.name()); if (outFile == null) throw new ParseException("output file not specified"); AvailXML x = new AvailXML(fileName, log); x.makeSS(outFile); } else if (optDumpSS) { if (optToXML | optToSS | optDumpSheet) throw new ParseException("more than one operation specified"); message = "dumping file: " + fileName; log.info(message); if (verbose) System.out.println(message); AvailSS.dumpFile(fileName); } else { // dumpSheet if (sheetName == null) throw new ParseException("sheet name not specified"); message = "dumping file: " + fileName + " sheet: " + sheetName; log.info(message); if (verbose) System.out.println(message); ss = new AvailSS(fileName, log, wx, clean); if (sheetNum < 0) as = ss.addSheet(sheetName); else as = ss.addSheet(sheetNum); ss.dumpSheet(sheetName); } } catch (ParseException exp) { System.out.println("bad command line: " + exp.getMessage()); usage(); System.exit(-1); } }
From source file:cz.muni.fi.crocs.EduHoc.Main.java
/** * @param args the command line arguments *//* w ww.j ava2 s . c o m*/ public static void main(String[] args) { System.out.println("JeeTool \n"); Options options = OptionsMain.createOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException ex) { System.err.println("cannot parse parameters"); OptionsMain.printHelp(options); System.err.println(ex.toString()); return; } boolean silent = cmd.hasOption("s"); boolean verbose = cmd.hasOption("v"); if (!silent) { System.out.println(ANSI_GREEN + "EduHoc home is: " + System.getenv("EDU_HOC_HOME") + "\n" + ANSI_RESET); } //help if (cmd.hasOption("h")) { OptionsMain.printHelp(options); return; } String filepath; //path to config list of nodes if (cmd.hasOption("a")) { filepath = cmd.getOptionValue("a"); } else { filepath = System.getenv("EDU_HOC_HOME") + "/config/motePaths.txt"; } //create motelist MoteList moteList = new MoteList(filepath); if (verbose) { moteList.setVerbose(); } if (silent) { moteList.setSilent(); } if (verbose) { System.out.println("reading motelist from file " + filepath); } if (cmd.hasOption("i")) { List<Integer> ids = new ArrayList<Integer>(); String arg = cmd.getOptionValue("i"); String[] IdArgs = arg.split(","); for (String s : IdArgs) { if (s.contains("-")) { int start = Integer.parseInt(s.substring(0, s.indexOf("-"))); int end = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length())); for (int i = start; i <= end; i++) { ids.add(i); } } else { ids.add(Integer.parseInt(s)); } } moteList.setIds(ids); } moteList.readFile(); if (cmd.hasOption("d")) { //only detect nodes return; } //if make if (cmd.hasOption("m") || cmd.hasOption("c") || cmd.hasOption("u")) { UploadMain upload = new UploadMain(moteList, cmd); upload.runMake(); } //if execute command if (cmd.hasOption("E")) { try { ExecuteShellCommand com = new ExecuteShellCommand(); if (verbose) { System.out.println("Executing shell command " + cmd.getOptionValue("E")); } com.executeCommand(cmd.getOptionValue("E")); } catch (IOException ex) { System.err.println("Execute command " + cmd.getOptionValue("E") + " failed"); } } //if serial if (cmd.hasOption("l") || cmd.hasOption("w")) { SerialMain serial = new SerialMain(cmd, moteList); if (silent) { serial.setSilent(); } if (verbose) { serial.setVerbose(); } serial.startSerial(); } }
From source file:act.installer.pubchem.PubchemSynonymFinder.java
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());/*w ww.j ava 2 s .c om*/ } 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"); }
From source file:com.chschmid.huemorse.server.HueMorse.java
public static void main(String args[]) throws Exception { // Application Title System.out.println(TITLE);// w w w . ja v a 2 s . com // Apache CLI Parser Options options = getCLIOptions(); CommandLineParser parser = new PosixParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("b")) bridgeIP = line.getOptionValue("b"); else if (!(line.hasOption("s"))) { System.out.println(ERROR_NO_IP); return; } if (line.hasOption("c")) cli = true; if (line.hasOption("d")) DEBUG = true; if (line.hasOption("l")) lightID = Integer.parseInt(line.getOptionValue("l")); if (line.hasOption("u")) username = line.getOptionValue("u"); if (line.hasOption("s")) search = true; if (line.hasOption("h")) { printHelp(); return; } } catch (ParseException exp) { System.out.println(HUEMORSE + ": " + exp.getMessage()); System.out.println(ERROR_CLI); return; } hue = new HueMorseInterface(); if (search && bridgeIP.equals("")) searchAndListBridges(); else { if (DEBUG) { System.out.println("Bridge IP: " + bridgeIP); System.out.println("Username: " + username); } hue.connect(bridgeIP, username); hue.setLightID(lightID); if (search) searchAndListLights(); else { if (cli) simpleCommandLineInterface(); else startServers(); } } hue.close(); System.exit(0); }
From source file:example.ConfigurationsExample.java
public static void main(String[] args) { String jdbcPropToLoad = "prod.properties"; CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("d", "dev", false, "Dev tag to launch app in dev mode. Means that app will launch embedded mckoi db."); try {// w w w . j av a 2s .co m CommandLine line = parser.parse(options, args); if (line.hasOption("d")) { System.err.println("App is in DEV mode"); jdbcPropToLoad = "dev.properties"; } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); } Properties p = new Properties(); try { p.load(ConfigurationsExample.class.getResourceAsStream("/" + jdbcPropToLoad)); } catch (IOException e) { System.err.println("Properties loading failed. Reason: " + e.getMessage()); } try { String clazz = p.getProperty("driver.class"); Class.forName(clazz); System.out.println(" Jdbc driver loaded :" + clazz); } catch (ClassNotFoundException e) { System.err.println("Jdbc Driver class loading failed. Reason: " + e.getMessage()); e.printStackTrace(); } }
From source file:RedPenRunner.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("h", "help", false, "help"); options.addOption("v", "version", false, "print the version information and exit"); OptionBuilder.withLongOpt("port"); OptionBuilder.withDescription("port number"); OptionBuilder.hasArg();/* ww w . j av a 2 s . c o m*/ OptionBuilder.withArgName("PORT"); options.addOption(OptionBuilder.create("p")); OptionBuilder.withLongOpt("key"); OptionBuilder.withDescription("stop key"); OptionBuilder.hasArg(); OptionBuilder.withArgName("STOP_KEY"); options.addOption(OptionBuilder.create("k")); OptionBuilder.withLongOpt("conf"); OptionBuilder.withDescription("configuration file"); OptionBuilder.hasArg(); OptionBuilder.withArgName("CONFIG_FILE"); options.addOption(OptionBuilder.create("c")); OptionBuilder.withLongOpt("lang"); OptionBuilder.withDescription("Language of error messages"); OptionBuilder.hasArg(); OptionBuilder.withArgName("LANGUAGE"); options.addOption(OptionBuilder.create("L")); CommandLineParser parser = new BasicParser(); CommandLine commandLine = null; try { commandLine = parser.parse(options, args); } catch (Exception e) { printHelp(options); System.exit(-1); } int portNum = 8080; String language = "en"; if (commandLine.hasOption("h")) { printHelp(options); System.exit(0); } if (commandLine.hasOption("v")) { System.out.println(RedPen.VERSION); System.exit(0); } if (commandLine.hasOption("p")) { portNum = Integer.parseInt(commandLine.getOptionValue("p")); } if (commandLine.hasOption("L")) { language = commandLine.getOptionValue("L"); } if (isPortTaken(portNum)) { System.err.println("port is taken..."); System.exit(1); } // set language if (language.equals("ja")) { Locale.setDefault(new Locale("ja", "JA")); } else { Locale.setDefault(new Locale("en", "EN")); } final String contextPath = System.getProperty("redpen.home", "/"); Server server = new Server(portNum); ProtectionDomain domain = RedPenRunner.class.getProtectionDomain(); URL location = domain.getCodeSource().getLocation(); HandlerList handlerList = new HandlerList(); if (commandLine.hasOption("key")) { // Add Shutdown handler only when STOP_KEY is specified ShutdownHandler shutdownHandler = new ShutdownHandler(commandLine.getOptionValue("key")); handlerList.addHandler(shutdownHandler); } WebAppContext webapp = new WebAppContext(); webapp.setContextPath(contextPath); if (location.toExternalForm().endsWith("redpen-server/target/classes/")) { // use redpen-server/target/redpen-server instead, because target/classes doesn't contain web resources. webapp.setWar(location.toExternalForm() + "../redpen-server/"); } else { webapp.setWar(location.toExternalForm()); } if (commandLine.hasOption("c")) { webapp.setInitParameter("redpen.conf.path", commandLine.getOptionValue("c")); } handlerList.addHandler(webapp); server.setHandler(handlerList); server.start(); server.join(); }
From source file:eu.scape_project.arc2warc.Arc2WarcMigration.java
/** * Main entry point./*from www.j a v a 2 s. co m*/ * * @param args * @throws java.io.IOException * @throws org.apache.commons.cli.ParseException */ public static void main(String[] args) throws IOException, ParseException { Configuration conf = new Configuration(); // Command line interface config = new Arc2WarcMigrationConfig(); CommandLineParser cmdParser = new PosixParser(); GenericOptionsParser gop = new GenericOptionsParser(conf, args); Arc2WarcMigrationOptions a2wopt = new Arc2WarcMigrationOptions(); CommandLine cmd = cmdParser.parse(a2wopt.options, gop.getRemainingArgs()); if ((args.length == 0) || (cmd.hasOption(a2wopt.HELP_OPT))) { a2wopt.exit("Help", 0); } else { a2wopt.initOptions(cmd, config); } Arc2WarcMigration a2wm = new Arc2WarcMigration(); long startMillis = System.currentTimeMillis(); File input = new File(config.getInputStr()); if (input.isDirectory()) { config.setDirectoryInput(true); a2wm.traverseDir(input); } else { migrate(input); } long elapsedTimeMillis = System.currentTimeMillis() - startMillis; LOG.info("Processing time (sec): " + elapsedTimeMillis / 1000F); System.exit(0); }