List of usage examples for org.apache.commons.cli CommandLine getOptions
public Option[] getOptions()
From source file:org.seedstack.shell.internal.AbstractShell.java
@SuppressWarnings("unchecked") Command createCommandAction(String qualifiedName, List<String> args) { if (Strings.isNullOrEmpty(qualifiedName)) { throw SeedException.createNew(ShellErrorCode.MISSING_COMMAND); }//from ww w. j a va 2s . c o m String commandScope; String commandName; if (qualifiedName.contains(":")) { String[] splitName = qualifiedName.split(":"); commandScope = splitName[0].trim(); commandName = splitName[1].trim(); } else { commandScope = null; commandName = qualifiedName.trim(); } // Build CLI options Options options = new Options(); for (org.seedstack.seed.command.Option option : commandRegistry.getOptionsInfo(commandScope, commandName)) { options.addOption(option.name(), option.longName(), option.hasArgument(), option.description()); } // Parse the command options CommandLine cmd; try { cmd = commandLineParser.parse(options, args.toArray(new String[args.size()])); } catch (ParseException e) { throw SeedException.wrap(e, ShellErrorCode.OPTIONS_SYNTAX_ERROR); } Map<String, String> optionValues = new HashMap<>(); for (Option option : cmd.getOptions()) { optionValues.put(option.getOpt(), option.getValue()); } return commandRegistry.createCommand(commandScope, commandName, cmd.getArgList(), optionValues); }
From source file:org.sikuli.basics.SikuliScript.java
/** * Main method/*from www . ja v a2s. co m*/ * * @param args passed arguments */ public static void main(String[] args) { if (isRunningScript) { System.out.println("[error] SikuliScript: can only run one at a time!"); return; } isRunningScript = true; Settings.initScriptingSupport(); SikuliX.displaySplash(args); if (args != null && args.length > 1 && args[0].startsWith("-testSetup")) { runner = SikuliX.getScriptRunner(args[1], null, args); if (runner == null) { args[0] = null; } else { String[] stmts = new String[0]; if (args.length > 2) { stmts = new String[args.length - 2]; for (int i = 0; i < stmts.length; i++) { stmts[i] = args[i + 2]; } } if (0 != runner.runScript(null, null, stmts, null)) { args[0] = null; } } isRunningScript = false; return; } CommandArgs cmdArgs = new CommandArgs("SCRIPT"); CommandLine cmdLine = cmdArgs.getCommandLine(CommandArgs.scanArgs(args)); String cmdValue; if (cmdLine == null || cmdLine.getOptions().length == 0) { Debug.error("Did not find any valid option on command line!"); cmdArgs.printHelp(); System.exit(1); } if (cmdLine.hasOption(CommandArgsEnum.HELP.shortname())) { cmdArgs.printHelp(); if (runner != null) { System.out.println(runner.getCommandLineHelp()); } System.exit(1); } if (cmdLine.hasOption(CommandArgsEnum.LOGFILE.shortname())) { cmdValue = cmdLine.getOptionValue(CommandArgsEnum.LOGFILE.longname()); if (!Debug.setLogFile(cmdValue == null ? "" : cmdValue)) { System.exit(1); } } if (cmdLine.hasOption(CommandArgsEnum.USERLOGFILE.shortname())) { cmdValue = cmdLine.getOptionValue(CommandArgsEnum.USERLOGFILE.longname()); if (!Debug.setUserLogFile(cmdValue == null ? "" : cmdValue)) { System.exit(1); } } if (cmdLine.hasOption(CommandArgsEnum.DEBUG.shortname())) { cmdValue = cmdLine.getOptionValue(CommandArgsEnum.DEBUG.longname()); if (cmdValue == null) { Debug.setDebugLevel(3); Settings.LogTime = true; if (!Debug.isLogToFile()) { Debug.setLogFile(""); } } else { Debug.setDebugLevel(cmdValue); } } Settings.setArgs(cmdArgs.getUserArgs(), cmdArgs.getSikuliArgs()); Debug.log(3, me + "CmdOrg: " + System.getenv("SIKULI_COMMAND")); Settings.showJavaInfo(); Settings.printArgs(); //TODO if (cmdLine.hasOption(CommandArgsEnum.IMAGEPATH.shortname())) { if (false) { // imagePath = getScriptRunner(cmdLine.getOptionValue(CommandArgsEnum.IMAGEPATH.longname()), null, args); } else { imagePath = null; } // select script runner and/or start interactive session // option is overloaded - might specify runner for -r/-t if (cmdLine.hasOption(CommandArgsEnum.INTERACTIVE.shortname())) { System.out.println(String.format("SikuliX Package Build: %s %s", Settings.getVersionShort(), RunSetup.timestampBuilt)); int exitCode = 0; if (runner == null) { String givenRunnerName = cmdLine.getOptionValue(CommandArgsEnum.INTERACTIVE.longname()); if (givenRunnerName == null) { runner = SikuliX.getScriptRunner(Settings.RDEFAULT, null, args); } else { runner = SikuliX.getScriptRunner(givenRunnerName, null, args); if (runner == null) { System.exit(1); } } } if (!cmdLine.hasOption(CommandArgsEnum.RUN.shortname()) && !cmdLine.hasOption(CommandArgsEnum.TEST.shortname())) { exitCode = runner.runInteractive(cmdArgs.getUserArgs()); runner.close(); SikuliX.endNormal(exitCode); } } String givenScriptName = null; runAsTest = false; if (cmdLine.hasOption(CommandArgsEnum.LOAD.shortname())) { String loadScript = FileManager.slashify(cmdLine.getOptionValue(CommandArgsEnum.LOAD.longname()), false); Debug.log(3, "Sikuli-Script: requested to run: " + loadScript); givenScriptName = loadScript; } if (cmdLine.hasOption(CommandArgsEnum.RUN.shortname())) { givenScriptName = cmdLine.getOptionValue(CommandArgsEnum.RUN.longname()); } else if (cmdLine.hasOption(CommandArgsEnum.TEST.shortname())) { givenScriptName = cmdLine.getOptionValue(CommandArgsEnum.TEST.longname()); Debug.error("Command line option -t: not yet supported! %s", Arrays.asList(args).toString()); runAsTest = true; } if (givenScriptName != null) { if (givenScriptName.endsWith(".skl")) { givenScriptName = FileManager.unzipSKL(givenScriptName); if (givenScriptName == null) { Debug.error(me + "not possible to make .skl runnable!"); System.exit(1); } } Debug.log(3, me + "givenScriptName: " + givenScriptName); File sf = new File(givenScriptName); File script = FileManager.getScriptFile(sf, runner, args); if (script == null) { System.exit(1); } runner = SikuliX.getRunner(); if (imagePath == null) { imagePath = FileManager.resolveImagePath(script); } SikuliX.callImagePathSetBundlePath(imagePath.getAbsolutePath()); Debug.log(3, "Trying to run script: " + script.getAbsolutePath()); int exitCode = runAsTest ? runner.runTest(script, imagePath, cmdArgs.getUserArgs(), null) : runner.runScript(script, imagePath, cmdArgs.getUserArgs(), null); runner.close(); SikuliX.endNormal(exitCode); } else { Debug.error("Nothing to do according to the given commandline options!"); cmdArgs.printHelp(); if (runner != null) { System.out.println(runner.getCommandLineHelp()); } System.exit(1); } }
From source file:org.sikuli.scriptrunner.ScriptRunner.java
/** * INTERNAL USE: run scripts when sikulix.jar is used on commandline with args -r, -t or -i<br> * If you want to use it the args content must be according to the Sikulix command line parameter rules<br> * use run(script, args) to run one script from a script or Java program * @param args parameters given on commandline *//*from w ww . j av a 2s . c om*/ public static void runscript(String[] args) { if (isRunningScript) { System.out.println("[error] SikuliScript: can only run one at a time!"); return; } isRunningScript = true; initScriptingSupport(); IScriptRunner currentRunner = null; if (args != null && args.length > 1 && args[0].startsWith("-testSetup")) { currentRunner = getRunner(null, args[1]); if (currentRunner == null) { args[0] = null; } else { String[] stmts = new String[0]; if (args.length > 2) { stmts = new String[args.length - 2]; for (int i = 0; i < stmts.length; i++) { stmts[i] = args[i + 2]; } } if (0 != currentRunner.runScript(null, null, stmts, null)) { args[0] = null; } } isRunningScript = false; return; } CommandArgs cmdArgs = new CommandArgs("SCRIPT"); CommandLine cmdLine = cmdArgs.getCommandLine(CommandArgs.scanArgs(args)); String cmdValue; if (cmdLine == null || cmdLine.getOptions().length == 0) { log(-1, "Did not find any valid option on command line!"); cmdArgs.printHelp(); System.exit(1); } if (cmdLine.hasOption(CommandArgsEnum.HELP.shortname())) { cmdArgs.printHelp(); if (currentRunner != null) { System.out.println(currentRunner.getCommandLineHelp()); } System.exit(1); } if (cmdLine.hasOption(CommandArgsEnum.LOGFILE.shortname())) { cmdValue = cmdLine.getOptionValue(CommandArgsEnum.LOGFILE.longname()); if (!Debug.setLogFile(cmdValue == null ? "" : cmdValue)) { System.exit(1); } } if (cmdLine.hasOption(CommandArgsEnum.USERLOGFILE.shortname())) { cmdValue = cmdLine.getOptionValue(CommandArgsEnum.USERLOGFILE.longname()); if (!Debug.setUserLogFile(cmdValue == null ? "" : cmdValue)) { System.exit(1); } } if (cmdLine.hasOption(CommandArgsEnum.DEBUG.shortname())) { cmdValue = cmdLine.getOptionValue(CommandArgsEnum.DEBUG.longname()); if (cmdValue == null) { Debug.setDebugLevel(3); Settings.LogTime = true; if (!Debug.isLogToFile()) { Debug.setLogFile(""); } } else { Debug.setDebugLevel(cmdValue); } } Settings.setArgs(cmdArgs.getUserArgs(), cmdArgs.getSikuliArgs()); log(lvl, "CmdOrg: " + System.getenv("SIKULI_COMMAND")); Settings.showJavaInfo(); Settings.printArgs(); // select script runner and/or start interactive session // option is overloaded - might specify runner for -r/-t if (cmdLine.hasOption(CommandArgsEnum.INTERACTIVE.shortname())) { System.out.println(String.format("SikuliX Package Build: %s %s", Settings.getVersionShort(), Settings.SikuliVersionBuild)); int exitCode = 0; if (currentRunner == null) { String givenRunnerName = cmdLine.getOptionValue(CommandArgsEnum.INTERACTIVE.longname()); if (givenRunnerName == null) { currentRunner = getRunner(null, RDEFAULT); } else { currentRunner = getRunner(null, givenRunnerName); if (currentRunner == null) { System.exit(1); } } } if (!cmdLine.hasOption(CommandArgsEnum.RUN.shortname()) && !cmdLine.hasOption(CommandArgsEnum.TEST.shortname())) { exitCode = currentRunner.runInteractive(cmdArgs.getUserArgs()); currentRunner.close(); Sikulix.endNormal(exitCode); } } runAsTest = false; if (cmdLine.hasOption(CommandArgsEnum.RUN.shortname())) { runScripts = cmdLine.getOptionValues(CommandArgsEnum.RUN.longname()); } else if (cmdLine.hasOption(CommandArgsEnum.TEST.shortname())) { runScripts = cmdLine.getOptionValues(CommandArgsEnum.TEST.longname()); log(-1, "Command line option -t: not yet supported! %s", Arrays.asList(args).toString()); runAsTest = true; //TODO run a script as unittest with HTMLTestRunner System.exit(1); } if (runScripts != null && runScripts.length > 0) { int exitCode = 0; for (String givenScriptName : runScripts) { exitCode = new RunBox(runAsTest).executeScript(givenScriptName, cmdArgs.getUserArgs()); if (exitCode == -9999) { continue; } } System.exit(exitCode); } else { log(-1, "Nothing to do with the given commandline options!"); cmdArgs.printHelp(); System.exit(1); } }
From source file:org.sonatype.gshell.util.cli2.CliProcessor.java
public void process(final String... args) throws Exception { assert args != null; CliParser parser = null;//from w w w . ja v a2 s . co m switch (flavor) { case POSIX: parser = new PosixParser(); break; case GNU: parser = new GnuParser(); break; } assert parser != null; CommandLine cl; try { cl = parser.parse(createOptions(), args, stopAtNonOption); } catch (UnrecognizedOptionException e) { throw new ProcessingException(Messages.UNDEFINED_OPTION.format(e.getOption())); } catch (MissingArgumentException e) { OptionDescriptor desc = ((Opt) e.getOption()).getDescriptor(); throw new ProcessingException( Messages.MISSING_OPERAND.format(desc.getSyntax(), desc.renderToken(messages))); } catch (ParseException e) { throw new ProcessingException(e); } Set<CliDescriptor> present = new HashSet<CliDescriptor>(); boolean override = false; for (Object tmp : cl.getOptions()) { Opt opt = (Opt) tmp; log.trace("Processing option: {}", opt); OptionDescriptor desc = opt.getDescriptor(); present.add(desc); // Track the override, this is used to handle when --help present, but a required arg/opt is missing if (!override) { override = desc.getOverride(); } Handler handler = Handlers.create(desc); String[] values = opt.getValues(); if (values == null || values.length == 0) { // Set the value handler.handle(opt.getValue()); } else { // Set the values for (String value : values) { handler.handle(value); } } } log.trace("Remaining arguments: {}", cl.getArgList()); int i = 0; for (final String arg : cl.getArgs()) { log.trace("Processing argument: {}", arg); // Check if we allow an argument or we have overflowed if (i >= argumentDescriptors.size()) { throw new ProcessingException( argumentDescriptors.size() == 0 ? Messages.NO_ARGUMENT_ALLOWED.format(arg) : Messages.TOO_MANY_ARGUMENTS.format(arg)); } ArgumentDescriptor desc = argumentDescriptors.get(i); present.add(desc); // For single-valued args, increment the argument index, else let the multivalued handler consume it if (!desc.isMultiValued()) { i++; } // Set the value Handler handler = Handlers.create(desc); handler.handle(arg); } // Check for any required arguments which were not present if (!override) { try { parser.ensureRequiredOptionsPresent(); } catch (MissingOptionException e) { throw new ProcessingException(Messages.REQUIRED_OPTION_MISSING.format(e.getMissingOptions())); } for (ArgumentDescriptor arg : argumentDescriptors) { if (arg.isRequired() && !present.contains(arg)) { throw new ProcessingException( Messages.REQUIRED_ARGUMENT_MISSING.format(arg.renderToken(messages))); } } } // TODO: Handle setting defaults }
From source file:org.stathissideris.ascii2image.core.CommandLineConverter.java
private static void printRunInfo(CommandLine cmdLine) { System.out.println("\n" + notice + "\n"); System.out.println("Running with options:"); Option[] opts = cmdLine.getOptions(); for (Option option : opts) { if (option.hasArgs()) { for (String value : option.getValues()) { System.out.println(option.getLongOpt() + " = " + value); }/*from w w w. ja va 2s . com*/ } else if (option.hasArg()) { System.out.println(option.getLongOpt() + " = " + option.getValue()); } else { System.out.println(option.getLongOpt()); } } }
From source file:org.stathissideris.ascii2image.core.ConversionOptions.java
public ConversionOptions(CommandLine cmdLine) throws UnsupportedEncodingException { processingOptions.setVerbose(cmdLine.hasOption("verbose")); renderingOptions.setDropShadows(!cmdLine.hasOption("no-shadows")); this.setDebug(cmdLine.hasOption("debug")); processingOptions.setOverwriteFiles(cmdLine.hasOption("overwrite")); if (cmdLine.hasOption("scale")) { Float scale = Float.parseFloat(cmdLine.getOptionValue("scale")); renderingOptions.setScale(scale.floatValue()); }//from w w w . j a va 2 s . co m processingOptions.setAllCornersAreRound(cmdLine.hasOption("round-corners")); processingOptions.setPerformSeparationOfCommonEdges(!cmdLine.hasOption("no-separation")); renderingOptions.setAntialias(!cmdLine.hasOption("no-antialias")); renderingOptions.setFixedSlope(cmdLine.hasOption("fixed-slope")); if (cmdLine.hasOption("background")) { String b = cmdLine.getOptionValue("background"); Color background = parseColor(b); renderingOptions.setBackgroundColor(background); } if (cmdLine.hasOption("transparent")) { renderingOptions.setBackgroundColor(new Color(0, 0, 0, 0)); } if (cmdLine.hasOption("tabs")) { Integer tabSize = Integer.parseInt(cmdLine.getOptionValue("tabs")); int tabSizeValue = tabSize.intValue(); if (tabSizeValue < 0) tabSizeValue = 0; processingOptions.setTabSize(tabSizeValue); } String encoding = (String) cmdLine.getOptionValue("encoding"); if (encoding != null) { new String(new byte[2], encoding); processingOptions.setCharacterEncoding(encoding); } ConfigurationParser configParser = new ConfigurationParser(); try { for (Option curOption : cmdLine.getOptions()) { if (curOption.getLongOpt().equals("config")) { String configFilename = curOption.getValue(); System.out.println("Parsing configuration file " + configFilename); File file = new File(configFilename); if (file.exists()) { configParser.parseFile(file); HashMap<String, CustomShapeDefinition> shapes = configParser.getShapeDefinitionsHash(); processingOptions.putAllInCustomShapes(shapes); } else { System.err.println("File " + file + " does not exist, skipping"); } } } } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.terracotta.voter.TCVoterMain.java
public void processArgs(String[] args) throws ConfigurationSetupException, ParseException { DefaultParser parser = new DefaultParser(); Options voterOptions = voterOptions(); CommandLine commandLine = parser.parse(voterOptions, args); if (commandLine.getArgList().size() > 0) { throw new ConfigurationSetupException("Invalid arguments provided: " + commandLine.getArgList()); }/* w w w. ja v a2 s . c o m*/ if (commandLine.hasOption(HELP)) { new HelpFormatter().printHelp("start-voter.sh[bat]", voterOptions); return; } if (commandLine.getOptions().length == 0) { throw new ConfigurationSetupException( "Neither the override option -o nor the regular options -s or -f provided"); } if (commandLine.hasOption(SERVER) && commandLine.hasOption(CONFIG_FILE)) { throw new ConfigurationSetupException( "Both -s and -f options provided. Use either one and not both together."); } Optional<Properties> connectionProps = getConnectionProperties(commandLine); if (commandLine.hasOption(SERVER)) { processServerArg(connectionProps, commandLine.getOptionValues(SERVER)); } else if (commandLine.hasOption(CONFIG_FILE)) { processConfigFileArg(connectionProps, commandLine.getOptionValues(CONFIG_FILE)); } else if (commandLine.hasOption(OVERRIDE)) { String hostPort = commandLine.getOptionValue(OVERRIDE); validateHostPort(hostPort); getVoter(connectionProps).overrideVote(hostPort); } else { throw new AssertionError("This should not happen"); } }
From source file:org.vetmeduni.tools.AbstractTool.java
/** * Get the arguments with the string/* w w w. j a va 2 s.c o m*/ * * @param cmd the already parsed command line with the programParser * * @return the string with the arguments in the command line properly formatted */ protected String getCmdLineString(CommandLine cmd) { StringBuilder builder = new StringBuilder(""); for (Option opt : cmd.getOptions()) { if (opt.hasArg()) { for (String val : opt.getValues()) { builder.append("--"); builder.append(opt.getLongOpt()); builder.append(" "); builder.append(val); builder.append(" "); } } else { builder.append("--"); builder.append(opt.getLongOpt()); builder.append(" "); } } return builder.toString(); }
From source file:org.waveprotocol.box.server.robots.agent.AbstractCliRobotAgent.java
@Override public void onDocumentChanged(DocumentChangedEvent event) { Blip blip = event.getBlip();/*from w w w .j a va 2 s . c om*/ String modifiedBy = event.getModifiedBy(); CommandLine commandLine = null; try { commandLine = preprocessCommand(blip.getContent()); } catch (IllegalArgumentException e) { appendLine(blip, e.getMessage()); } if (commandLine != null) { if (commandLine.hasOption("help") // Or if only options. || (commandLine.getArgs().length - commandLine.getOptions().length <= 1)) { appendLine(blip, getFullDescription()); } else { String robotMessage = maybeExecuteCommand(commandLine, modifiedBy); appendLine(blip, robotMessage); } } }
From source file:org.waveprotocol.box.server.robots.agent.AbstractCliRobotAgent.java
/** * Validates and parses the input for the command. * * @param blipContent the blip contents. * @return the command line {@link CommandLine} object with parsed data from * the blip contents or null in case the content doesn't contain a * command.//from w w w. j ava2 s . com * @throws IllegalArgumentException if illegal arguments passed to the * command. */ protected CommandLine preprocessCommand(String blipContent) throws IllegalArgumentException { CommandLine commandLine = null; String lastLine = lastEnteredLineOf(blipContent); if (lastLine != null) { try { commandLine = parse(lastLine.split(" ")); } catch (ParseException e) { throw new IllegalArgumentException(e); } String[] args = commandLine.getArgs(); if (!args[0].equals(getCommandName())) { return null; } int argsNum = args.length - commandLine.getOptions().length - 1; // If there are only options in the command - then it is also invalid and // have to display usage anyway. if ((argsNum > 0) && (argsNum < getMinNumOfArguments() || argsNum > getMaxNumOfArguments())) { String message; if (getMinNumOfArguments() == getMaxNumOfArguments()) { message = String.format("Invalid number of arguments. Expected: %d , actual: %d %s", getMinNumOfArguments(), argsNum, getUsage()); } else { message = String.format( "Invalid number of arguments. Expected between %d and %d, actual: %d. %s", getMinNumOfArguments(), getMaxNumOfArguments(), argsNum, getUsage()); } throw new IllegalArgumentException(message); } } return commandLine; }