List of usage examples for org.apache.commons.cli Parser parse
public CommandLine parse(Options options, String[] arguments) throws ParseException
arguments
based on the specifed Options . From source file:org.apache.zookeeper.cli.LsCommand.java
private void retainCompatibility(String[] cmdArgs) throws CliParseException { // get path [watch] if (args.length > 2) { // rewrite to option cmdArgs[2] = "-w"; err.println("'ls path [watch]' has been deprecated. " + "Please use 'ls [-w] path' instead."); Parser parser = new PosixParser(); try {//from w ww .j a va 2 s. c o m cl = parser.parse(options, cmdArgs); } catch (ParseException ex) { throw new CliParseException(ex); } args = cl.getArgs(); } }
From source file:org.apache.zookeeper.cli.ReconfigCommand.java
@Override public CliCommand parse(String[] cmdArgs) throws CliParseException { joining = null;/*www . jav a 2 s.c o m*/ leaving = null; members = null; Parser parser = new PosixParser(); try { cl = parser.parse(options, cmdArgs); } catch (ParseException ex) { throw new CliParseException(ex); } if (!(cl.hasOption("file") || cl.hasOption("members")) && !cl.hasOption("add") && !cl.hasOption("remove")) { throw new CliParseException(getUsageStr()); } if (cl.hasOption("v")) { try { version = Long.parseLong(cl.getOptionValue("v"), 16); } catch (NumberFormatException e) { throw new CliParseException("-v must be followed by a long (configuration version)"); } } else { version = -1; } // Simple error checking for conflicting modes if ((cl.hasOption("file") || cl.hasOption("members")) && (cl.hasOption("add") || cl.hasOption("remove"))) { throw new CliParseException( "Can't use -file or -members together with -add or -remove (mixing incremental" + " and non-incremental modes is not allowed)"); } if (cl.hasOption("file") && cl.hasOption("members")) { throw new CliParseException( "Can't use -file and -members together (conflicting non-incremental modes)"); } // Set the joining/leaving/members values based on the mode we're in if (cl.hasOption("add")) { joining = cl.getOptionValue("add").toLowerCase(); } if (cl.hasOption("remove")) { leaving = cl.getOptionValue("remove").toLowerCase(); } if (cl.hasOption("members")) { members = cl.getOptionValue("members").toLowerCase(); } if (cl.hasOption("file")) { try { FileInputStream inConfig = new FileInputStream(cl.getOptionValue("file")); Properties dynamicCfg = new Properties(); try { dynamicCfg.load(inConfig); } finally { inConfig.close(); } //check that membership makes sense; leader will make these checks again //don't check for leader election ports since //client doesn't know what leader election alg is used members = QuorumPeerConfig.parseDynamicConfig(dynamicCfg, 0, true, false).toString(); } catch (Exception e) { throw new CliParseException("Error processing " + cl.getOptionValue("file") + e.getMessage()); } } return this; }
From source file:org.apache.zookeeper.cli.SetAclCommand.java
@Override public CliCommand parse(String[] cmdArgs) throws CliParseException { Parser parser = new PosixParser(); try {/* www . ja v a 2s .c om*/ cl = parser.parse(options, cmdArgs); } catch (ParseException ex) { throw new CliParseException(ex); } args = cl.getArgs(); if (args.length < 3) { throw new CliParseException(getUsageStr()); } return this; }
From source file:org.apache.zookeeper.cli.StatCommand.java
private void retainCompatibility(String[] cmdArgs) throws CliParseException { // stat path [watch] if (args.length > 2) { // rewrite to option cmdArgs[2] = "-w"; err.println("'stat path [watch]' has been deprecated. " + "Please use 'stat [-w] path' instead."); Parser parser = new PosixParser(); try {//from w ww. ja v a 2 s. c o m cl = parser.parse(options, cmdArgs); } catch (ParseException ex) { throw new CliParseException(ex); } args = cl.getArgs(); } }
From source file:org.azyva.dragom.tool.CreateStaticVersionTool.java
/** * Method main./* w w w . j a v a2 s . c o m*/ * * @param args Arguments. */ public static void main(String[] args) { Parser parser; CommandLine commandLine = null; CreateStaticVersion createStaticVersion; CreateStaticVersionTool.init(); try { // Not obvious, but we must use GnuParser to support --long-option=value syntax. // Commons CLI 1.3 (as yet unreleased) is supposed to have a DefaultParser to // replace existing parser implementations. parser = new GnuParser(); try { commandLine = parser.parse(CreateStaticVersionTool.options, args); } catch (ParseException pe) { throw new RuntimeExceptionUserError("Error parsing the command line: " + pe.getMessage() + ". Use the --help option to display help information."); } if (commandLine.hasOption("help")) { CreateStaticVersionTool.help(); System.exit(0); } args = commandLine.getArgs(); if (args.length != 1) { throw new RuntimeExceptionUserError( "An invalid number of arguments was specified. Use the --help option to display help information."); } createStaticVersion = new CreateStaticVersion(Util.getListModuleVersionRoot(commandLine)); createStaticVersion.setReferenceGraphPathMatcher(Util.getReferenceGraphPathMatcher(commandLine)); if (commandLine.hasOption("no-confirm")) { createStaticVersion.setIndNoConfirm(true); } ExecContextHolder.set(Util.setupExecContext(commandLine.getOptionValue("workspace-path"))); // It can be the case that RootManager does not specify any root ModuleVersion. In // that case calling RootManager.saveListModuleVersion simply saves an empty list, // even if the user has specified a root ModuleVersion on the command line. if (createStaticVersion.performTask()) { RootManager.saveListModuleVersion(); } } catch (RuntimeExceptionUserError reue) { System.err.println("ERROR: " + reue.getMessage()); System.exit(1); } finally { ExecContextHolder.unset(); } }
From source file:org.azyva.dragom.tool.SwitchToDynamicVersionTool.java
/** * Method main.//from w ww . j av a2s. c om * * @param args Arguments. */ public static void main(String[] args) { Parser parser; CommandLine commandLine = null; SwitchToDynamicVersion switchToDynamicVersion; SwitchToDynamicVersionTool.init(); try { // Not obvious, but we must use GnuParser to support --long-option=value syntax. // Commons CLI 1.3 (as yet unreleased) is supposed to have a DefaultParser to // replace existing parser implementations. parser = new GnuParser(); try { commandLine = parser.parse(SwitchToDynamicVersionTool.options, args); } catch (ParseException pe) { throw new RuntimeExceptionUserError("Error parsing the command line: " + pe.getMessage() + ". Use the --help option to display help information."); } if (commandLine.hasOption("help")) { SwitchToDynamicVersionTool.help(); System.exit(0); } args = commandLine.getArgs(); if (args.length != 0) { throw new RuntimeExceptionUserError( "An invalid number of arguments was specified. Use the --help option to display help information."); } ExecContextHolder.set(Util.setupExecContext(commandLine.getOptionValue("workspace-path"))); switchToDynamicVersion = new SwitchToDynamicVersion(Util.getListModuleVersionRoot(commandLine)); switchToDynamicVersion.setReferenceGraphPathMatcher(Util.getReferenceGraphPathMatcher(commandLine)); if (commandLine.hasOption("no-confirm")) { switchToDynamicVersion.setIndNoConfirm(true); } // It can be the case that RootManager does not specify any root ModuleVersion. In // that case calling RootManager.saveListModuleVersion simply saves an empty list, // even if the user has specified a root ModuleVersion on the command line. if (switchToDynamicVersion.performTask()) { RootManager.saveListModuleVersion(); } } catch (RuntimeExceptionUserError reue) { System.err.println("ERROR: " + reue.getMessage()); System.exit(1); } finally { ExecContextHolder.unset(); } }
From source file:org.azyva.dragom.tool.TaskInvokerTool.java
/** * Method main./*from w ww. j a v a2 s. c o m*/ * * @param args Arguments. */ public static void main(String[] args) { String taskPluginId; String taskId; String helpRessource; Parser parser; CommandLine commandLine = null; TaskInvoker taskInvoker; taskPluginId = args[0]; taskId = args[1]; helpRessource = args[2]; args = Arrays.copyOfRange(args, 3, args.length); TaskInvokerTool.init(); try { // Not obvious, but we must use GnuParser to support --long-option=value syntax. // Commons CLI 1.3 (as yet unreleased) is supposed to have a DefaultParser to // replace existing parser implementations. parser = new GnuParser(); try { commandLine = parser.parse(TaskInvokerTool.options, args); } catch (ParseException pe) { throw new RuntimeExceptionUserError("Error parsing the command line: " + pe.getMessage() + ". Use the --help option to display help information."); } if (commandLine.hasOption("help")) { TaskInvokerTool.help(helpRessource); System.exit(0); } args = commandLine.getArgs(); if (args.length != 0) { throw new RuntimeExceptionUserError( "An invalid number of arguments was specified. Use the --help option to display help information."); } ExecContextHolder.set(Util.setupExecContext(commandLine.getOptionValue("workspace-path"))); taskInvoker = new TaskInvoker(taskPluginId, taskId, Util.getListModuleVersionRoot(commandLine)); taskInvoker.setReferenceGraphPathMatcher(Util.getReferenceGraphPathMatcher(commandLine)); taskInvoker.performTask(); } catch (RuntimeExceptionUserError reue) { System.err.println("ERROR: " + reue.getMessage()); System.exit(1); } finally { ExecContextHolder.unset(); } }
From source file:org.codehaus.continuum.cli.AbstractCliCommand.java
protected void initialize(String[] args) throws ParseException { Parser parser = new PosixParser(); commandLine = parser.parse(options, args); }
From source file:org.genivi.commonapi.console.CommandExecuter.java
public int executeCommand(String[] arguments) { Assert.isNotNull(arguments);//from www. j a v a2s . co m final List<ConsoleConfiguration> configurations = getParsedExtensionPointConfigurations(); // Print message if there are no registered console commands. if (configurations.size() == 0) { println(HELP_NO_COMMANDS_TEXT_MESSAGE); return DEFAULT_RETURN_VALUE; } // Print help text if no option is available. if (arguments.length == 0) { printHelp(configurations); return DEFAULT_RETURN_VALUE; } // Find a suitable console configuration. final List<ConsoleConfiguration> perfectMatchingConfigurations = new ArrayList<ConsoleConfiguration>(); final List<ConsoleConfiguration> partialMatchingConfigurations = new ArrayList<ConsoleConfiguration>(); final List<ConsoleConfiguration> notMatchingConfigurations = new ArrayList<ConsoleConfiguration>(); Parser parser = new PosixParser(); for (ConsoleConfiguration configuration : configurations) { try { CommandLine commandLine = parser.parse(configuration.options, arguments); // Add ID option and ID information to configuration. Thus if there are several // perfect matches the printHelp method can print this information. configuration.options.addOption(ID_OPTION); configuration.message = String.format(HELP_ID_TEXT_MESSAGE, SHORT_ID_OPTION, configuration.id); configuration.commandLine = commandLine; perfectMatchingConfigurations.add(configuration); } catch (MissingOptionException | MissingArgumentException | AlreadySelectedException exception) { configuration.message = exception.getMessage(); partialMatchingConfigurations.add(configuration); } catch (UnrecognizedOptionException exception) { // Check if the unrecognized option is the ID option. String unrecognizedOption = exception.getOption(); if (unrecognizedOption.equals("-" + SHORT_ID_OPTION) || unrecognizedOption.equals("--" + LONG_ID_OPTION)) { try { // Add ID option to options object an parse arguments again. CommandLine commandLine = parser.parse(configuration.options.addOption(ID_OPTION), arguments); String idValue = commandLine.getOptionValue(SHORT_ID_OPTION); // The correct console configuration is found if parsing did not throw an // exception and the ID option equals extension point ID. if (configuration.id.equals(idValue)) { configuration.commandLine = commandLine; perfectMatchingConfigurations.add(configuration); } else { configuration.message = String.format(HELP_WRONG_ID_MESSAGE, SHORT_ID_OPTION, configuration.id, idValue); partialMatchingConfigurations.add(configuration); } } catch (ParseException e) { configuration.message = e.getMessage(); notMatchingConfigurations.add(configuration); } } else { configuration.message = exception.getMessage(); notMatchingConfigurations.add(configuration); } } catch (ParseException exception) { configuration.message = exception.getMessage(); notMatchingConfigurations.add(configuration); } } // Execute compatible command or print help text if (perfectMatchingConfigurations.size() == 1) { SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { ConsoleConfiguration configuration = perfectMatchingConfigurations.get(0); Object executable = configuration.commandConfiguration .createExecutableExtension(COMMAND_HANDLER_ATTRIBUTE_NAME); ICommandLineHandler handler = (ICommandLineHandler) executable; returnValue = handler.excute(configuration.commandLine); } @Override public void handleException(Throwable throwable) { log(throwable); } }); } else if (perfectMatchingConfigurations.size() > 1) { println(HELP_SEVERAL_COMMANDS_MESSAGE); printHelp(perfectMatchingConfigurations); } else if (partialMatchingConfigurations.size() > 0) { printHelp(partialMatchingConfigurations); } else { printHelp(notMatchingConfigurations); } return returnValue; }
From source file:org.kaazing.gateway.server.GatewayCommandLineProcessor.java
private void launchGateway(String[] args, Properties properties) { CommandLine cmd = null;/*from ww w . j a v a2s .co m*/ Options options = createOptions(); try { Parser parser = new PosixParser(); cmd = parser.parse(options, args); } catch (ParseException ex) { printCliHelp("There was a problem with a command-line argument:\n" + ex.getMessage(), options, cmd); return; } String[] nonProcessedArgs = cmd.getArgs(); if (nonProcessedArgs != null && nonProcessedArgs.length > 0) { System.out.println("There was a problem with the command-line arguments."); System.out.println("One or more unknown arguments were not processed:"); for (String nonProcessedArg : nonProcessedArgs) { System.out.println(" " + nonProcessedArg); } printCliHelp(null, options, cmd); return; } if (cmd.hasOption(HELP_ARG)) { printCliHelp(null, options, cmd); return; } // get the various options String config = cmd.getOptionValue(CONFIG_ARG); if (config != null) { properties.setProperty(Gateway.GATEWAY_CONFIG_PROPERTY, config); } // Because Gateway already has checking for defaults (and they default // to directories under $GATEWAY_HOME), we don't actually have to do anything // here (we do in the InstalledLinux case.) final Gateway gateway = GatewayFactory.createGateway(); gateway.setProperties(properties); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { gateway.destroy(); } catch (Exception e) { e.printStackTrace(); } } }); try { gateway.launch(); } catch (Exception ex) { // Log the exception then exit. It's possible log4j won't be initialized by the time // the exception occurred, so log and print stacktrace (to System.err) LOGGER.error("Gateway failed to launch", ex); ex.printStackTrace(); System.exit(-1); } }