List of usage examples for org.apache.commons.cli ParseException ParseException
public ParseException(String message)
ParseException
with the specified detail message. From source file:org.duracloud.mill.manifest.cleaner.ManifestCleanerDriver.java
/** * @param time/*from w w w . j a v a2 s .co m*/ * @return * @throws ParseException */ private Date parseExpirationDate(String time) throws ParseException { Calendar c = Calendar.getInstance(); String pattern = "([0-9]+)([smhd])"; if (!time.matches(pattern)) { throw new ParseException(time + " is not a valid time value."); } int amount = Integer.parseInt(time.replaceAll(pattern, "$1")); String units = time.replaceAll(pattern, "$2"); int field = Calendar.SECOND; if (units.equals("m")) { field = Calendar.MINUTE; } else if (units.equals("h")) { field = Calendar.HOUR; } else if (units.equals("d")) { field = Calendar.DATE; } else { // should never happen. throw new RuntimeException("unit " + units + " not recognized."); } c.add(field, -1 * amount); return c.getTime(); }
From source file:org.duracloud.retrieval.config.RetrievalToolConfigParser.java
protected RetrievalToolConfig processOptions(String[] args) throws ParseException { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(cmdOptions, args); RetrievalToolConfig config = new RetrievalToolConfig(); config.setContext(DEFAULT_CONTEXT);/* w w w . j av a 2s . c o m*/ config.setHost(cmd.getOptionValue("h")); config.setUsername(cmd.getOptionValue("u")); if (null != cmd.getOptionValue("p")) { config.setPassword(cmd.getOptionValue("p")); } else if (null != getPasswordEnvVariable()) { config.setPassword(getPasswordEnvVariable()); } else { ConsolePrompt console = getConsole(); if (null == console) { printHelp("You must either specify a password in the command " + "line or specify the " + CommandLineToolUtil.PASSWORD_ENV_VARIABLE_NAME + " environmental variable."); } else { char[] password = console.readPassword("DuraCloud password: "); config.setPassword(new String(password)); } } if (cmd.hasOption("r")) { try { config.setPort(Integer.valueOf(cmd.getOptionValue("r"))); } catch (NumberFormatException e) { throw new ParseException("The value for port (-r) must be " + "a number."); } } else { config.setPort(DEFAULT_PORT); } if (cmd.hasOption("i")) { config.setStoreId(cmd.getOptionValue("i")); } if (!cmd.hasOption("s") && !cmd.hasOption("a")) { throw new ParseException("Either a list of spaces (-s) should be " + "provided or the all spaces flag (-a) must be set."); } if (cmd.hasOption("s")) { String[] spaces = cmd.getOptionValues("s"); List<String> spacesList = new ArrayList<String>(); for (String space : spaces) { if (space != null && !space.equals("")) { spacesList.add(space); } } config.setSpaces(spacesList); } if (cmd.hasOption("a")) { config.setAllSpaces(true); } else { config.setAllSpaces(false); } File contentDir = new File(cmd.getOptionValue("c")); if (contentDir.exists()) { if (!contentDir.isDirectory()) { throw new ParseException("Content Dir paramter must provide " + "the path to a directory."); } } else { contentDir.mkdirs(); } contentDir.setWritable(true); config.setContentDir(contentDir); if (cmd.hasOption("w")) { File workDir = new File(cmd.getOptionValue("w")); if (workDir.exists()) { if (!workDir.isDirectory()) { throw new ParseException("Work Dir parameter must provide " + "the path to a directory."); } } else { workDir.mkdirs(); } workDir.setWritable(true); config.setWorkDir(workDir); } else { config.setWorkDir(null); } if (cmd.hasOption("o")) { config.setOverwrite(true); } else { config.setOverwrite(false); } if (cmd.hasOption("t")) { try { config.setNumThreads(Integer.valueOf(cmd.getOptionValue("t"))); } catch (NumberFormatException e) { throw new ParseException("The value for threads (-t) must " + "be a number."); } } else { config.setNumThreads(DEFAULT_NUM_THREADS); } if (cmd.hasOption("d")) { config.setApplyTimestamps(false); } else { config.setApplyTimestamps(true); } if (cmd.hasOption("l")) { config.setListOnly(true); } else { config.setListOnly(false); } if (cmd.hasOption("f")) { if ((config.getSpaces() != null && config.getSpaces().size() > 1) || config.isAllSpaces()) { throw new ParseException( "The 'list-file' option (-f) can " + "only operate on one space at a time."); } else if (config.isListOnly()) { throw new ParseException("The 'list-file' option (-f) can " + "not be used at the same time with the 'list-only' option (-l)."); } else { File listFile = new File(cmd.getOptionValue("f")); if (listFile.exists()) { config.setListFile(listFile); } else { throw new ParseException( "The specified 'list-file' containing " + "content IDs to retrieve does not exist."); } } } return config; }
From source file:org.duracloud.sync.config.SyncToolConfigParser.java
protected SyncToolConfig processConfigFileOptions(String[] args) throws ParseException { try {/* w w w . j a v a 2 s . c o m*/ CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(configFileOptions, args); String configFilePath = cmd.getOptionValue("g"); File configFile = new File(configFilePath); if (!configFile.exists()) { throw new ParseException( "No configuration file exists at " + "the indicated path: " + configFilePath); } String[] configFileArgs = retrieveConfig(configFile); return processAndBackup(configFileArgs); } catch (ParseException e) { return processAndBackup(args); } }
From source file:org.duracloud.sync.config.SyncToolConfigParser.java
protected SyncToolConfig processStandardOptions(String[] args, boolean requirePassword) throws ParseException { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(cmdOptions, args); SyncToolConfig config = new SyncToolConfig(); config.setContext(context);/* w w w . j a v a 2 s . com*/ config.setHost(cmd.getOptionValue("h")); config.setUsername(cmd.getOptionValue("u")); if (null != cmd.getOptionValue("p")) { config.setPassword(cmd.getOptionValue("p")); } else if (null != getPasswordEnvVariable()) { config.setPassword(getPasswordEnvVariable()); } else if (requirePassword) { ConsolePrompt console = getConsole(); if (null == console) { printHelp("You must either specify a password in the command " + "line or specify the " + CommandLineToolUtil.PASSWORD_ENV_VARIABLE_NAME + " environmental variable."); } else { char[] password = console.readPassword("DuraCloud password: "); config.setPassword(new String(password)); } } config.setSpaceId(cmd.getOptionValue("s")); if (cmd.hasOption("i")) { config.setStoreId(cmd.getOptionValue("i")); } if (cmd.hasOption("r")) { try { config.setPort(Integer.valueOf(cmd.getOptionValue("r"))); } catch (NumberFormatException e) { throw new ParseException("The value for port (-r) must be " + "a number."); } } else { config.setPort(DEFAULT_PORT); } if (cmd.hasOption("w")) { File workDir = new File(cmd.getOptionValue("w")); if (workDir.exists()) { if (!workDir.isDirectory()) { throw new ParseException("Work Dir parameter must provide " + "the path to a directory. " + "(optional, set to duracloud-" + "sync-work directory in user's " + "home directory by default)"); } } else { workDir.mkdirs(); } workDir.setWritable(true); config.setWorkDir(workDir); } else { config.setWorkDir(null); } String[] contentDirPaths = cmd.getOptionValues("c"); List<File> contentDirs = new ArrayList<File>(); for (String path : contentDirPaths) { File contentDir = new File(path); if (!contentDir.exists() || !contentDir.isDirectory()) { throw new ParseException("Each content dir value must provide " + "the path to a directory."); } contentDirs.add(contentDir); } config.setContentDirs(contentDirs); if (cmd.hasOption("f")) { try { config.setPollFrequency(Long.valueOf(cmd.getOptionValue("f"))); } catch (NumberFormatException e) { throw new ParseException("The value for poll frequency (-f) " + "must be a number."); } } else { config.setPollFrequency(DEFAULT_POLL_FREQUENCY); } if (cmd.hasOption("t")) { try { config.setNumThreads(Integer.valueOf(cmd.getOptionValue("t"))); } catch (NumberFormatException e) { throw new ParseException("The value for threads (-t) must " + "be a number."); } } else { config.setNumThreads(DEFAULT_NUM_THREADS); } if (cmd.hasOption("m")) { String error = "The value for max-file-size (-m) must be a " + "number between 1 and 5."; try { long maxFileSize = Integer.valueOf(cmd.getOptionValue("m")); if (maxFileSize >= 1 && maxFileSize <= 5) { config.setMaxFileSize(maxFileSize * GIGABYTE); } else { throw new ParseException(error); } } catch (NumberFormatException e) { throw new ParseException(error); } } else { config.setMaxFileSize(DEFAULT_MAX_FILE_SIZE * GIGABYTE); } if (cmd.hasOption("o") && cmd.hasOption("n")) { throw new ParseException( "Options -o (no updates) and -n " + "(rename updates) cannot be used together."); } if (cmd.hasOption("o")) { config.setSyncUpdates(false); } if (cmd.hasOption("n") && cmd.hasOption("d")) { throw new ParseException( "Options -n (rename updates) and -d " + "(sync deletes) cannot be used together."); } if (cmd.hasOption("n")) { config.setRenameUpdates(true); String suffix = cmd.getOptionValue("n"); if (StringUtils.isNotBlank(suffix)) { config.setUpdateSuffix(suffix); } } if (cmd.hasOption("d")) { config.setSyncDeletes(true); } else { config.setSyncDeletes(false); } if (cmd.hasOption("l")) { config.setCleanStart(true); } else { config.setCleanStart(false); } if (cmd.hasOption("j")) { config.setJumpStart(true); if (cmd.hasOption("n") || cmd.hasOption("o")) { throw new ParseException("The Jump Start option (-j) requires that updates be " + "handled as overwrites, thus options -n (rename updates) " + "and -o (no-updates) cannot be used at the same time."); } } else { config.setJumpStart(false); } if (cmd.hasOption("x")) { config.setExitOnCompletion(true); } else { config.setExitOnCompletion(false); } if (cmd.hasOption("e")) { File excludeFile = new File(cmd.getOptionValue("e")); if (!excludeFile.exists()) { throw new ParseException("Exclude parameter must provide the " + "path to a valid file."); } config.setExcludeList(excludeFile); } if (cmd.hasOption("a")) { config.setPrefix(cmd.getOptionValue("a")); } return config; }
From source file:org.duracloud.syncoptimize.config.SyncOptimizeConfigParser.java
protected SyncOptimizeConfig processOptions(String[] args) throws ParseException { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(cmdOptions, args); SyncOptimizeConfig config = new SyncOptimizeConfig(); config.setContext(DEFAULT_CONTEXT);/*from ww w .jav a 2 s.c om*/ config.setHost(cmd.getOptionValue("h")); config.setUsername(cmd.getOptionValue("u")); config.setSpaceId(cmd.getOptionValue("s")); if (null != cmd.getOptionValue("p")) { config.setPassword(cmd.getOptionValue("p")); } else if (null != getPasswordEnvVariable()) { config.setPassword(getPasswordEnvVariable()); } else { ConsolePrompt console = getConsole(); if (null == console) { printHelp("You must either specify a password in the command " + "line or specify the " + CommandLineToolUtil.PASSWORD_ENV_VARIABLE_NAME + " environmental variable."); } else { char[] password = console.readPassword("DuraCloud password: "); config.setPassword(new String(password)); } } if (cmd.hasOption("r")) { try { config.setPort(Integer.valueOf(cmd.getOptionValue("r"))); } catch (NumberFormatException e) { throw new ParseException("The value for port (-r) must be " + "a number."); } } else { config.setPort(DEFAULT_PORT); } if (cmd.hasOption("n")) { try { config.setNumFiles(Integer.valueOf(cmd.getOptionValue("n"))); } catch (NumberFormatException e) { throw new ParseException("The value for num-files (-n) must " + "be a number."); } } else { config.setNumFiles(DEFAULT_NUM_FILES); } if (cmd.hasOption("m")) { try { config.setSizeFiles(Integer.valueOf(cmd.getOptionValue("m"))); } catch (NumberFormatException e) { throw new ParseException("The value for size-files (-m) must " + "be a number."); } } else { config.setSizeFiles(DEFAULT_SIZE_FILES); } return config; }
From source file:org.echocat.jconscius.cluster.impl.relay.station.RelayStationLauncher.java
private static int parsePositiveInteger(String string, String messageName) throws ParseException { final int result; try {/*from w ww. j a v a 2 s . c o m*/ result = Integer.parseInt(string.trim()); } catch (NumberFormatException ignored) { //noinspection ThrowInsideCatchBlockWhichIgnoresCaughtException throw new ParseException("'" + string + "' is not a valid " + messageName + "."); } if (result <= 0) { throw new ParseException("'" + string + "' is not a valid " + messageName + "."); } return result; }
From source file:org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.java
public void run(String[] args) { Options options = getOptions();//w w w. j a va 2 s .co m final CommandLineParser parser = new PosixParser(); CommandLine line = null; try { line = parser.parse(options, args); if (line.getArgs().length == 0) throw new ParseException("No module name specified."); if (line.getArgs().length > 1) throw new ParseException("Only one module name expected. But " + line.getArgs().length + " were passed (" + line.getArgList() + ")"); String moduleName = line.getArgs()[0]; Map<String, String> params = new HashMap<String, String>(); String[] optionValues = line.getOptionValues(PARAM); if (optionValues != null) { for (String string : optionValues) { int index = string.indexOf('='); if (index == -1) { throw new ParseException( "Incorrect parameter syntax '" + string + "'. It should be 'name=value'"); } String name = string.substring(0, index); String value = string.substring(index + 1); if (params.put(name, value) != null) { throw new ParseException("Duplicate parameter '" + name + "'."); } } } // check OperationCanceledException is accessible OperationCanceledException.class.getName(); Injector injector = new Mwe2StandaloneSetup().createInjectorAndDoEMFRegistration(); Mwe2Runner mweRunner = injector.getInstance(Mwe2Runner.class); if (moduleName.contains("/")) { mweRunner.run(URI.createURI(moduleName), params); } else { mweRunner.run(moduleName, params); } } catch (NoClassDefFoundError e) { if ("org/eclipse/core/runtime/OperationCanceledException".equals(e.getMessage())) { System.err.println("Could not load class: org.eclipse.core.runtime.OperationCanceledException"); System.err.println("Add org.eclipse.equinox.common to the class path."); } else { throw e; } } catch (final ParseException exp) { final HelpFormatter formatter = new HelpFormatter(); System.err.println("Parsing arguments failed. Reason: " + exp.getMessage()); formatter.printHelp("java " + Mwe2Launcher.class.getName() + " some.mwe2.Module [options]\n", options); return; } }
From source file:org.eclipse.jubula.client.cmd.AbstractCmdlineClient.java
/** * // w w w . j a v a 2 s. co m * @param args * the command line * @throws FileNotFoundException * if config file is missing * @throws ParseException * if wrong options are present * @throws IOException * if io error * @return true to continue processing the commandline run; false to stop * processing further execution. */ protected boolean parseCommandLine(String[] args) throws FileNotFoundException, ParseException, IOException { String[] cloneArgs = args.clone(); Options options = createOptions(false); // Command line arguments parser CommandLineParser parser = new BasicParser(); try { // we will parse the command line until there are no // (more) errors int maxTrys = 5; Boolean parseNotOK = true; while (parseNotOK) { try { m_cmd = parser.parse(options, cloneArgs); parseNotOK = false; } catch (ParseException exp) { cloneArgs = handleParseException(args, exp); if (maxTrys-- < 0) { throw new ParseException(StringConstants.EMPTY); } } } if (m_cmd.hasOption(ClientStrings.HELP)) { printUsage(); return false; } // The first thing to check is, if there is a config file // if there is a config file we read this first, if (m_cmd.hasOption(ClientStrings.CONFIG)) { m_configFile = new File(m_cmd.getOptionValue(ClientStrings.CONFIG)); if (m_configFile.exists() && m_configFile.canRead()) { printConsoleLn(Messages.ClientConfigFile + m_configFile.getAbsolutePath(), true); m_job = JobConfiguration.initJob(m_configFile); } else { throw new FileNotFoundException(StringConstants.EMPTY); } } else { m_job = JobConfiguration.initJob(null); } // now we should have all arguments, either from file or // from commandline if (m_cmd.hasOption(ClientStrings.QUIET)) { quiet = true; } if (m_cmd.hasOption(ClientStrings.NORUN)) { m_noRun = true; } // then set attributes from command Line and check if parameter -startserver was called if (m_cmd.hasOption(ClientTestStrings.STARTSERVER)) { m_job.parseOptionsWithServer(m_cmd); } else { m_job.parseJobOptions(m_cmd); } // check if all needed attributes are set preValidate(m_job); } catch (PreValidateException exp) { String message = exp.getLocalizedMessage(); if (message != null && message.length() > 0) { printlnConsoleError(message); } printUsage(); throw new ParseException(StringConstants.EMPTY); } return true; }
From source file:org.eclipselabs.garbagecat.Main.java
/** * Validate command line options.//from w w w . j a v a2 s . c om * * @param cmd * The command line options. * * @throws ParseException * Command line options not valid. */ public static void validateOptions(CommandLine cmd) throws ParseException { // Ensure log file specified. if (cmd.getArgList().size() == 0) { throw new ParseException("Missing log file"); } String logFileName = null; if (cmd.getArgList().size() > 0) { logFileName = (String) cmd.getArgList().get(cmd.getArgList().size() - 1); } // Ensure gc log file exists. if (logFileName == null) { throw new ParseException("Missing log file not"); } File logFile = new File(logFileName); if (!logFile.exists()) { throw new ParseException("Invalid log file: '" + logFileName + "'"); } // threshold if (cmd.hasOption(Constants.OPTION_THRESHOLD_LONG)) { String thresholdRegEx = "^\\d{1,3}$"; String thresholdOptionValue = cmd.getOptionValue(Constants.OPTION_THRESHOLD_SHORT); Pattern pattern = Pattern.compile(thresholdRegEx); Matcher matcher = pattern.matcher(thresholdOptionValue); if (!matcher.find()) { throw new ParseException("Invalid threshold: '" + thresholdOptionValue + "'"); } } // startdatetime if (cmd.hasOption(Constants.OPTION_STARTDATETIME_LONG)) { String startdatetimeOptionValue = cmd.getOptionValue(Constants.OPTION_STARTDATETIME_SHORT); Pattern pattern = Pattern.compile(GcUtil.START_DATE_TIME_REGEX); Matcher matcher = pattern.matcher(startdatetimeOptionValue); if (!matcher.find()) { throw new ParseException("Invalid startdatetime: '" + startdatetimeOptionValue + "'"); } } }
From source file:org.finra.dm.core.ArgumentParser.java
/** * Retrieves the argument value, if any, as a String object and converts it to a boolean value. * * @param option the option that we want to query for * @param defaultValue the default value to return if option is not set or missing an argument value * * @return the value of the argument converted to a boolean value or default value when the option is not set or missing an argument value * @throws ParseException if the value of the argument is an invalid boolean value * *//* w ww . j ava 2s . c o m*/ @SuppressFBWarnings(value = "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "This is a false positive. A null check is present.") public Boolean getStringValueAsBoolean(Option option, Boolean defaultValue) throws ParseException { Boolean result; ensureCommandLineNotNull(); String stringValue = getStringValue(option); if (StringUtils.isNotBlank(stringValue)) { // Use custom boolean editor without allowed empty strings to convert the value of the argument to a boolean value. CustomBooleanEditor customBooleanEditor = new CustomBooleanEditor(false); try { customBooleanEditor.setAsText(stringValue); } catch (IllegalArgumentException e) { ParseException parseException = new ParseException(e.getMessage()); parseException.initCause(e); throw parseException; } result = (Boolean) customBooleanEditor.getValue(); } else { result = defaultValue; } return result; }