List of usage examples for org.apache.commons.cli Option getOpt
public String getOpt()
From source file:org.obiba.genobyte.cli.BitwiseCli.java
/** * Starts the CLI shell./* w ww. ja va2s.co m*/ * * @throws IOException when an error occurs while reading user input. */ public void execute() throws IOException { CliContext context = new CliContext(this.output); BufferedReader br = new BufferedReader(new InputStreamReader(input)); BasicParser bp = new BasicParser(); output.println("Type '-h' for help, '-q' to quit."); while (true) { prompt(context); boolean quit = false; String str = br.readLine(); CommandLine cl = null; try { if (context.getStore() == null) { cl = bp.parse(noStoreOptions, str.split(" ")); } else { cl = bp.parse(options, str.split(" ")); } } catch (ParseException e) { quit = help.execute(null, context); } if (cl != null) { Iterator<Option> commands = cl.iterator(); // We don't iterate to make sure we execute only one command if (commands.hasNext()) { Option o = commands.next(); CliCommand c = commandMap.get(o.getLongOpt()); if (c == null) { throw new IllegalStateException( "No CliCommand associated with option [" + o.getOpt() + "]"); } else { try { quit = c.execute(o, context); } catch (ParseException e) { quit = help.execute(null, context); } catch (Exception e) { output.println( "An unexpected error occurred while executing the command: " + e.getMessage()); } } } // Not handled by any command: it should be a query. String queryString = str; if (context.getStore() != null && (cl.getOptions() == null || cl.getOptions().length == 0)) { try { QueryParser parser = new QueryParser(); long start = System.currentTimeMillis(); if (StringUtil.isEmptyString(queryString) == false) { Query q = parser.parse(queryString); QueryResult qr = q.execute(context.getActiveRecordStore().getStore()); String reference = context.addQuery(queryString, qr); long end = System.currentTimeMillis(); output.println(reference + ": " + qr.count() + " results in " + (end - start) + " milliseconds."); } } catch (org.obiba.bitwise.query.UnknownFieldException e) { output.println(e.getMessage()); } catch (org.obiba.bitwise.query.ParseException e) { output.println("The query [" + queryString + "] is invalid. Please refer to the query syntax for more information."); } catch (Exception e) { output.println( "An unexpected error occurred while executing the query. The following data may be helpful to debug the problem."); e.printStackTrace(output); } } } if (quit) break; } }
From source file:org.objectweb.proactive.examples.fastdeployment.Main.java
public void parseArguments(String[] args) { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(Params.concurrency.sOpt, Params.concurrency.toString(), true, Params.concurrency.desc); options.addOption(Params.pause.sOpt, Params.pause.toString(), true, Params.pause.desc); Option descOption;/*from www . ja v a 2 s. c om*/ descOption = new Option(Params.descriptor.sOpt, Params.descriptor.toString(), true, Params.descriptor.desc); descOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(descOption); Option vnOption; vnOption = new Option(Params.virtualNode.sOpt, Params.virtualNode.toString(), true, Params.virtualNode.desc); vnOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(vnOption); CommandLine line = null; String arg; try { line = parser.parse(options, args); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fast Deployment", options); System.exit(1); } Option[] pOptions = line.getOptions(); for (Option pOption : pOptions) { if (pOption.getOpt().equals(Params.virtualNode.sOpt)) { for (String s : pOption.getValues()) { virtualNodes.add(s); } } if (pOption.getOpt().equals(Params.descriptor.sOpt)) { for (String s : pOption.getValues()) { descriptors.add(s); } } } arg = line.getOptionValue(Params.concurrency.sOpt); if (arg != null) { try { concurrency = new Integer(arg); } catch (NumberFormatException e) { logger.warn("Invalid option value " + arg); } } arg = line.getOptionValue(Params.pause.sOpt); if (arg != null) { try { pause = new Integer(arg); } catch (NumberFormatException e) { logger.warn("Invalid option value " + arg); } } }
From source file:org.onebusaway.gtfs_merge.GtfsMergerMain.java
private void processOptions(CommandLine cli, GtfsMerger merger) { OptionHandler currentOptionHandler = null; AbstractEntityMergeStrategy mergeStrategy = null; for (Option option : cli.getOptions()) { if (option.getOpt().equals(ARG_FILE)) { String filename = option.getValue(); Class<?> entityClass = _entityClassesByFilename.get(filename); if (entityClass == null) { throw new IllegalStateException("unknown GTFS filename: " + filename); }/* w ww . j a va 2 s.c om*/ mergeStrategy = getMergeStrategyForEntityClass(entityClass, merger); currentOptionHandler = getOptionHandlerForEntityClass(entityClass); } else { if (currentOptionHandler == null) { throw new IllegalArgumentException( "you must specify a --file argument first before specifying file-specific arguments"); } currentOptionHandler.handleOption(option, mergeStrategy); } } }
From source file:org.onebusaway.gtfs_merge.OptionHandler.java
public void handleOption(Option option, AbstractEntityMergeStrategy strategy) { if (option.getOpt().equals(GtfsMergerMain.ARG_DUPLICATE_DETECTION)) { String strategyName = option.getValue().toUpperCase(); strategy.setDuplicateDetectionStrategy(EDuplicateDetectionStrategy.valueOf(strategyName)); } else if (option.getOpt().equals(GtfsMergerMain.ARG_LOG_DROPPED_DUPLICATES)) { strategy.setLogDuplicatesStrategy(ELogDuplicatesStrategy.WARNING); } else if (option.getOpt().equals(GtfsMergerMain.ARG_ERROR_ON_DROPPED_DUPLICATES)) { strategy.setLogDuplicatesStrategy(ELogDuplicatesStrategy.ERROR); }/*from ww w . j a va 2 s . c o m*/ }
From source file:org.onebusaway.gtfs_transformer.GtfsTransformerMain.java
protected void runApplication(CommandLine cli, String[] originalArgs) throws Exception { String[] args = cli.getArgs(); if (args.length < 2) { printHelp();/* w w w . j a v a 2 s . c o m*/ System.exit(-1); } List<File> paths = new ArrayList<File>(); for (int i = 0; i < args.length - 1; ++i) { paths.add(new File(args[i])); _log.info("input path: " + args[i]); } GtfsTransformer transformer = new GtfsTransformer(); transformer.setGtfsInputDirectories(paths); transformer.setOutputDirectory(new File(args[args.length - 1])); _log.info("output path: " + args[args.length - 1]); Option[] options = getOptionsInCommandLineOrder(cli, originalArgs); for (Option option : options) { String name = option.getOpt(); if (name.equals(ARG_REMOVE_REPEATED_STOP_TIMES)) configureRemoveRepeatedStopTimes(transformer); if (name.equals(ARG_REMOVE_DUPLICATE_TRIPS)) configureRemoveDuplicateTrips(transformer); if (name.equals(ARG_CHECK_STOP_TIMES)) configureEnsureStopTimesInOrder(transformer); if (name.equals(ARG_AGENCY_ID)) configureAgencyId(transformer, cli.getOptionValue(ARG_AGENCY_ID)); if (name.equals(ARG_MODIFICATIONS) || name.equals(ARG_TRANSFORM)) GtfsTransformerLibrary.configureTransformation(transformer, option.getValue()); if (name.equals(ARG_LOCAL_VS_EXPRESS)) configureLocalVsExpressUpdates(transformer); if (name.equals(ARG_OVERWRITE_DUPLICATES)) { transformer.getReader().setOverwriteDuplicates(true); } } transformer.run(); }
From source file:org.onebusaway.gtfs_transformer.GtfsTransformerMain.java
private Option[] getOptionsInCommandLineOrder(CommandLine cli, String[] originalArgs) { Option[] options = cli.getOptions(); List<Ordered<Option>> orderedOptions = new ArrayList<Ordered<Option>>(); for (Option option : options) { String argName = option.getOpt(); int optionPosition = originalArgs.length; for (int i = 0; i < originalArgs.length; i++) { if (originalArgs[i].endsWith(argName)) { optionPosition = i;/*from w w w .ja va2s. c o m*/ break; } } orderedOptions.add(new Ordered<Option>(option, optionPosition)); } Collections.sort(orderedOptions); options = new Option[options.length]; for (int i = 0; i < options.length; i++) options[i] = orderedOptions.get(i).getObject(); return options; }
From source file:org.openanzo.client.cli.AnzoConsole.java
AnzoConsole() { try {//from www . ja v a 2 s.c o m dcw = CommandLineInterface.DEFAULT_CONSOLE; if (dcw.cr != null) { dcw.cr.setBellEnabled(true); dcw.cr.setPrompt("Anzo>"); dcw.cr.setHistoryEnabled(true); } dcw.writeOutput( "Anzo Command Line Client. \nCopyright (c) 2009 Cambridge Semantics Inc and others. All rights reserved."); String version = null; if (CommandLineInterface.class.getProtectionDomain() != null && CommandLineInterface.class.getProtectionDomain().getCodeSource() != null && CommandLineInterface.class.getProtectionDomain().getCodeSource().getLocation() != null) { ProtectionDomain domain = CommandLineInterface.class.getProtectionDomain(); CodeSource source = domain.getCodeSource(); URL location = source.getLocation(); if (location != null) { File file = new File(location.toURI()); if (file.exists() && file.getName().toLowerCase().endsWith(".jar")) { JarFile jar = new JarFile(file); version = jar.getManifest().getMainAttributes().getValue("Bundle-Version"); if (version == null) { version = jar.getManifest().getMainAttributes().getValue("Implementation-Build"); } } } } if (version == null) { version = CommandLineInterface.class.getPackage().getImplementationVersion(); } dcw.writeOutput("Version: " + ((version == null) ? "Unknown" : version)); dcw.writeOutput("Type help for usage"); HashMap<String, Completer> completers = new HashMap<String, Completer>(); completers.put("exit", new NullCompleter()); completers.put("quit", new NullCompleter()); completers.put("connect", new NullCompleter()); completers.put("disconnect", new NullCompleter()); completers.put("trace", new StringsCompleter("on", "off")); Options global = CommandLineInterface.getGlobalOptions(); for (SubCommand sc : CommandLineInterface.subcommands) { String command = sc.getName(); ArrayList<String> subcommands = new ArrayList<String>(); for (Object o : sc.getOptions().getOptions()) { Option options = (Option) o; subcommands.add("-" + options.getOpt()); subcommands.add("--" + options.getLongOpt()); } for (Object o : global.getOptions()) { Option options = (Option) o; subcommands.add("-" + options.getOpt()); subcommands.add("--" + options.getLongOpt()); } completers.put(command, new StringsCompleter(subcommands)); } if (dcw.cr != null) { dcw.cr.addCompleter(new CLICompleter(completers)); } boolean showStackTrace = false; while (true) { String command = dcw.readLine("Anzo>"); if (command != null) { if (EXIT.toLowerCase().equals(command.trim().toLowerCase()) || QUIT.toLowerCase().equals(command.trim().toLowerCase())) { if (context != null && context.client != null && context.client.isConnected()) { context.client.disconnect(); context.client.close(); dcw.writeOutput("Disonnected from:" + context.host); } System.exit(0); } String arguments[] = stringToArgs(command); try { if (arguments.length > 0) { String subcommand = arguments[0]; if ("connect".equals(subcommand.toLowerCase())) { Options options = new Options(); CommandLineInterface.appendGlobalOptions(options); CommandLineParser parser = new PosixParser(); String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1, arguments.length); CommandLine cl = parser.parse(options, subcommandArgs); if (context == null) { context = CommandLineInterface.createContext(dcw, cl, options, arguments); } if (!context.client.isConnected()) { context.client.connect(); dcw.writeOutput("Connected to:" + context.host); } } else if ("disconnect".equals(subcommand.toLowerCase())) { if (context != null && context.client != null && context.client.isConnected()) { context.client.disconnect(); context.client.close(); dcw.writeOutput("Disonnected from:" + context.host); } else { dcw.writeOutput("Not connected to:" + context.host); } context = null; } else if ("trace".equals(subcommand.toLowerCase())) { String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1, arguments.length); if (subcommandArgs.length == 0) { dcw.writeOutput("Show Stack Trace:" + showStackTrace); } else { String flag = subcommandArgs[0]; if (flag.equals("on")) showStackTrace = true; else if (flag.equals("off")) showStackTrace = false; else showStackTrace = Boolean.parseBoolean(flag); } if (context != null) { context.showTrace = showStackTrace; } } else if ("version".equals(subcommand.toLowerCase())) { String header = CommandLineInterface.generateVersionHeader(); dcw.writeOutput(header); } else { CommandLineInterface.processCommand(context, false, arguments); } } } catch (AnzoException e) { if (e.getErrorCode() == ExceptionConstants.COMBUS.JMS_CONNECT_FAILED) { dcw.writeError("Connection failed."); if (showStackTrace) dcw.printException(e, showStackTrace); } else { dcw.printException(e, showStackTrace); } } catch (AnzoRuntimeException e) { dcw.printException(e, showStackTrace); } } } } catch (Exception e) { e.printStackTrace(); System.exit(0); } }
From source file:org.openanzo.client.cli.RdfIOCommand.java
RDFFormat getFormatOption(CommandLine cl, Option option) throws AnzoException { RDFFormat format = null;// w w w.j a v a 2 s . c o m if (cl.hasOption(option.getOpt())) { String formatString = cl.getOptionValue(option.getOpt()); format = RDFFormat.forFileName("." + formatString); if (format == null) { throw new InvalidArgumentException("unsupported format: " + formatString); } } return format; }
From source file:org.openanzo.client.cli.RdfIOCommand.java
RDFFormat getFormatOption(CommandLine cl, Option option, String defaultFormat) throws AnzoException { String formatString = cl.getOptionValue(option.getOpt(), defaultFormat); RDFFormat format = RDFFormat.forFileName("." + formatString); if (format == null) { throw new InvalidArgumentException("unrecognized rdf format: " + formatString); }// w ww . j a v a 2 s. co m return format; }
From source file:org.openanzo.client.cli.RdfIOCommand.java
protected String getEncodingOption(CommandLine cl, Option option) throws AnzoException { String charsetName = cl.getOptionValue(option.getOpt()); if (charsetName == null) return Constants.byteEncoding; if (!Charset.isSupported(charsetName)) throw new InvalidArgumentException("unsupported charset: " + charsetName); return charsetName; }