From 38185db716f592471cff748fdbe9a34d4e65e4bb Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 25 Jun 2006 20:44:10 +0000 Subject: [PATCH 0001/1663] Moving the CLI-1.0.x codebase off to its own branch so its maintenance can be decoupled git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@417074 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli/AlreadySelectedException.java | 38 - .../org/apache/commons/cli/BasicParser.java | 46 - .../org/apache/commons/cli/CLI2Converter.java | 190 ---- .../org/apache/commons/cli/CommandLine.java | 319 ------ .../apache/commons/cli/CommandLineParser.java | 90 -- .../org/apache/commons/cli/GnuParser.java | 173 ---- .../org/apache/commons/cli/HelpFormatter.java | 908 ------------------ .../commons/cli/MissingArgumentException.java | 38 - .../commons/cli/MissingOptionException.java | 37 - src/java/org/apache/commons/cli/Option.java | 599 ------------ .../org/apache/commons/cli/OptionBuilder.java | 372 ------- .../org/apache/commons/cli/OptionGroup.java | 162 ---- .../apache/commons/cli/OptionValidator.java | 100 -- src/java/org/apache/commons/cli/Options.java | 277 ------ .../apache/commons/cli/ParseException.java | 36 - src/java/org/apache/commons/cli/Parser.java | 406 -------- .../commons/cli/PatternOptionBuilder.java | 211 ---- .../org/apache/commons/cli/PosixParser.java | 309 ------ .../org/apache/commons/cli/TypeHandler.java | 257 ----- .../cli/UnrecognizedOptionException.java | 38 - src/java/org/apache/commons/cli/Util.java | 66 -- src/java/org/apache/commons/cli/overview.html | 28 - src/java/org/apache/commons/cli/package.html | 6 - .../apache/commons/cli/ApplicationTest.java | 130 --- .../commons/cli/ArgumentIsOptionTest.java | 99 -- src/test/org/apache/commons/cli/BugsTest.java | 536 ----------- .../org/apache/commons/cli/BuildTest.java | 101 -- .../apache/commons/cli/CLI2ConverterTest.java | 132 --- .../org/apache/commons/cli/GnuParseTest.java | 269 ------ .../commons/cli/HelpFormatterExamples.java | 112 --- .../commons/cli/LongOptionWithShort.java | 113 --- .../apache/commons/cli/OptionBuilderTest.java | 164 ---- .../apache/commons/cli/OptionGroupTest.java | 280 ------ .../org/apache/commons/cli/OptionsTest.java | 99 -- .../apache/commons/cli/ParseRequiredTest.java | 116 --- .../org/apache/commons/cli/ParseTest.java | 290 ------ .../commons/cli/PatternOptionBuilderTest.java | 86 -- .../apache/commons/cli/TestHelpFormatter.java | 176 ---- .../org/apache/commons/cli/ValueTest.java | 426 -------- .../org/apache/commons/cli/ValuesTest.java | 253 ----- .../apache/commons/cli/bug/BugCLI18Test.java | 42 - 41 files changed, 8130 deletions(-) delete mode 100644 src/java/org/apache/commons/cli/AlreadySelectedException.java delete mode 100644 src/java/org/apache/commons/cli/BasicParser.java delete mode 100644 src/java/org/apache/commons/cli/CLI2Converter.java delete mode 100644 src/java/org/apache/commons/cli/CommandLine.java delete mode 100644 src/java/org/apache/commons/cli/CommandLineParser.java delete mode 100644 src/java/org/apache/commons/cli/GnuParser.java delete mode 100644 src/java/org/apache/commons/cli/HelpFormatter.java delete mode 100644 src/java/org/apache/commons/cli/MissingArgumentException.java delete mode 100644 src/java/org/apache/commons/cli/MissingOptionException.java delete mode 100644 src/java/org/apache/commons/cli/Option.java delete mode 100644 src/java/org/apache/commons/cli/OptionBuilder.java delete mode 100644 src/java/org/apache/commons/cli/OptionGroup.java delete mode 100644 src/java/org/apache/commons/cli/OptionValidator.java delete mode 100644 src/java/org/apache/commons/cli/Options.java delete mode 100644 src/java/org/apache/commons/cli/ParseException.java delete mode 100644 src/java/org/apache/commons/cli/Parser.java delete mode 100644 src/java/org/apache/commons/cli/PatternOptionBuilder.java delete mode 100644 src/java/org/apache/commons/cli/PosixParser.java delete mode 100644 src/java/org/apache/commons/cli/TypeHandler.java delete mode 100644 src/java/org/apache/commons/cli/UnrecognizedOptionException.java delete mode 100644 src/java/org/apache/commons/cli/Util.java delete mode 100644 src/java/org/apache/commons/cli/overview.html delete mode 100644 src/java/org/apache/commons/cli/package.html delete mode 100644 src/test/org/apache/commons/cli/ApplicationTest.java delete mode 100644 src/test/org/apache/commons/cli/ArgumentIsOptionTest.java delete mode 100644 src/test/org/apache/commons/cli/BugsTest.java delete mode 100644 src/test/org/apache/commons/cli/BuildTest.java delete mode 100644 src/test/org/apache/commons/cli/CLI2ConverterTest.java delete mode 100644 src/test/org/apache/commons/cli/GnuParseTest.java delete mode 100644 src/test/org/apache/commons/cli/HelpFormatterExamples.java delete mode 100644 src/test/org/apache/commons/cli/LongOptionWithShort.java delete mode 100644 src/test/org/apache/commons/cli/OptionBuilderTest.java delete mode 100644 src/test/org/apache/commons/cli/OptionGroupTest.java delete mode 100644 src/test/org/apache/commons/cli/OptionsTest.java delete mode 100644 src/test/org/apache/commons/cli/ParseRequiredTest.java delete mode 100644 src/test/org/apache/commons/cli/ParseTest.java delete mode 100644 src/test/org/apache/commons/cli/PatternOptionBuilderTest.java delete mode 100644 src/test/org/apache/commons/cli/TestHelpFormatter.java delete mode 100644 src/test/org/apache/commons/cli/ValueTest.java delete mode 100644 src/test/org/apache/commons/cli/ValuesTest.java delete mode 100644 src/test/org/apache/commons/cli/bug/BugCLI18Test.java diff --git a/src/java/org/apache/commons/cli/AlreadySelectedException.java b/src/java/org/apache/commons/cli/AlreadySelectedException.java deleted file mode 100644 index 69389fe13..000000000 --- a/src/java/org/apache/commons/cli/AlreadySelectedException.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - *

Thrown when more than one option in an option group - * has been provided.

- * - * @author John Keyes ( john at integralsource.com ) - * @see ParseException - */ -public class AlreadySelectedException - extends ParseException { - - /** - *

Construct a new AlreadySelectedException - * with the specified detail message.

- * - * @param message the detail message - */ - public AlreadySelectedException(String message) - { - super(message); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/BasicParser.java b/src/java/org/apache/commons/cli/BasicParser.java deleted file mode 100644 index 2becdb9c8..000000000 --- a/src/java/org/apache/commons/cli/BasicParser.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - * The class BasicParser provides a very simple implementation of - * the {@link Parser#flatten(Options,String[],boolean) flatten} method. - * - * @author John Keyes (john at integralsource.com) - * @see Parser - */ -public class BasicParser extends Parser { - - /** - *

A simple implementation of {@link Parser}'s abstract - * {@link Parser#flatten(Options,String[],boolean) flatten} method.

- * - *

Note: options and stopAtNonOption - * are not used in this flatten method.

- * - * @param options The command line {@link Options} - * @param arguments The command line arguments to be parsed - * @param stopAtNonOption Specifies whether to stop flattening - * when an non option is found. - * @return The arguments String array. - */ - protected String[] flatten(Options options, String[] arguments, - boolean stopAtNonOption) - { - // just echo the arguments - return arguments; - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/CLI2Converter.java b/src/java/org/apache/commons/cli/CLI2Converter.java deleted file mode 100644 index 517b48e2b..000000000 --- a/src/java/org/apache/commons/cli/CLI2Converter.java +++ /dev/null @@ -1,190 +0,0 @@ -/** - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.validation.InvalidArgumentException; -import org.apache.commons.cli2.validation.Validator; - -/** - * A utility class for converting data structures version 1 to - * version 2 Option instances. - */ -public class CLI2Converter { - - private CLI2Converter(){ - // prevent creation of static utility class - } - - /** - * Creates a version 2 Option instance from a version 1 Option instance. - * - * @param option1 the version 1 Option to convert - * @return a version 2 Option - */ - public static Option option(final org.apache.commons.cli.Option option1){ - - final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - obuilder.withRequired(option1.isRequired()); - - final String shortName = option1.getOpt(); - if(shortName!=null && !" ".equals(shortName)){ - obuilder.withShortName(shortName); - } - - final String longName = option1.getLongOpt(); - if(longName!=null){ - obuilder.withLongName(longName); - } - obuilder.withId(option1.getId()); - - final String description = option1.getDescription(); - if(description!=null){ - obuilder.withDescription(description); - } - - if(option1.hasArg()){ - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final String argName = option1.getArgName(); - abuilder.withName(argName); - abuilder.withMaximum(option1.getArgs()); - if(option1.hasValueSeparator()){ - abuilder.withSubsequentSeparator(option1.getValueSeparator()); - } - if(option1.hasOptionalArg()){ - abuilder.withMinimum(0); - } - else{ - //TODO check what non-optional arg means - abuilder.withMinimum(option1.getArgs()); - } - - final Object type = option1.getType(); - if(type!=null){ - abuilder.withValidator(new TypeHandlerValidator(type)); - } - - obuilder.withArgument(abuilder.create()); - } - - return obuilder.create(); - } - - /** - * Creates a version 2 Group instance from a version 1 OptionGroup instance. - * - * @param optionGroup1 the version 1 OptionGroup to convert - * @return a version 2 Group - */ - public static Group group(final OptionGroup optionGroup1){ - - final GroupBuilder gbuilder = new GroupBuilder(); - - for(final Iterator i = optionGroup1.getOptions().iterator();i.hasNext();){ - final org.apache.commons.cli.Option option1 = (org.apache.commons.cli.Option)i.next(); - final Option option2 = option(option1); - gbuilder.withOption(option2); - } - - gbuilder.withMaximum(1); - - if(optionGroup1.isRequired()){ - gbuilder.withMinimum(1); - } - - return gbuilder.create(); - } - - /** - * Creates a version 2 Group instance from a version 1 Options instance. - * - * @param options1 the version 1 Options to convert - * @return a version 2 Group - */ - public static Group group(final Options options1){ - - final GroupBuilder gbuilder = new GroupBuilder(); - - final Set optionGroups = new HashSet(); - - for(final Iterator i = options1.getOptionGroups().iterator();i.hasNext();){ - final OptionGroup optionGroup1 = (OptionGroup)i.next(); - Group group = group(optionGroup1); - gbuilder.withOption(group); - optionGroups.add(optionGroup1); - } - - for(final Iterator i = options1.getOptions().iterator();i.hasNext();){ - final org.apache.commons.cli.Option option1 = (org.apache.commons.cli.Option)i.next(); - if(!optionInAGroup(option1,optionGroups)){ - final Option option2 = option(option1); - gbuilder.withOption(option2); - } - } - - return gbuilder.create(); - } - - private static boolean optionInAGroup(final org.apache.commons.cli.Option option1, final Set optionGroups) { - for (Iterator i = optionGroups.iterator(); i.hasNext();) { - OptionGroup group = (OptionGroup) i.next(); - if(group.getOptions().contains(option1)){ - return true; - } - } - return false; - } -} - -class TypeHandlerValidator implements Validator{ - - private final Object type; - - /** - * Creates a new Validator using the TypeHandler class. - * - * @see TypeHandler - * @param type The required type for valid elements - */ - public TypeHandlerValidator(final Object type){ - this.type = type; - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) - */ - public void validate(final List values) throws InvalidArgumentException { - final ListIterator i = values.listIterator(); - while(i.hasNext()){ - final String value = (String)i.next(); - final Object converted = TypeHandler.createValue(value,type); - if(converted==null){ - throw new InvalidArgumentException("Unable to understand value: " + value); - } - i.set(converted); - } - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/CommandLine.java b/src/java/org/apache/commons/cli/CommandLine.java deleted file mode 100644 index 6c1c278a4..000000000 --- a/src/java/org/apache/commons/cli/CommandLine.java +++ /dev/null @@ -1,319 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -/** - *

Represents list of arguments parsed against - * a {@link Options} descriptor.

- * - *

It allows querying of a boolean {@link #hasOption(String opt)}, - * in addition to retrieving the {@link #getOptionValue(String opt)} - * for options requiring arguments.

- * - *

Additionally, any left-over or unrecognized arguments, - * are available for further processing.

- * - * @author bob mcwhirter (bob @ werken.com) - * @author James Strachan - * @author John Keyes (john at integralsource.com) - */ -public class CommandLine { - - /** the unrecognised options/arguments */ - private List args = new LinkedList(); - - /** the processed options */ - private Map options = new HashMap(); - - /** the option name map */ - private Map names = new HashMap(); - - /** Map of unique options for ease to get complete list of options */ - private Map hashcodeMap = new HashMap(); - - /** the processed options */ - private Option[] optionsArray; - - /** - * Creates a command line. - */ - CommandLine() - { - // nothing to do - } - - /** - * Query to see if an option has been set. - * - * @param opt Short name of the option - * @return true if set, false if not - */ - public boolean hasOption(String opt) - { - return options.containsKey(opt); - } - - /** - * Query to see if an option has been set. - * - * @param opt character name of the option - * @return true if set, false if not - */ - public boolean hasOption(char opt) - { - return hasOption(String.valueOf(opt)); - } - - /** - * Return the Object type of this Option. - * - * @param opt the name of the option - * @return the type of this Option - */ - public Object getOptionObject(String opt) - { - String res = getOptionValue(opt); - - if (!options.containsKey(opt)) - { - return null; - } - - Object type = ((Option) options.get(opt)).getType(); - - return (res == null) ? null : TypeHandler.createValue(res, type); - } - - /** - * Return the Object type of this Option. - * - * @param opt the name of the option - * @return the type of opt - */ - public Object getOptionObject(char opt) - { - return getOptionObject(String.valueOf(opt)); - } - - /** - * Retrieve the argument, if any, of this option. - * - * @param opt the name of the option - * @return Value of the argument if option is set, and has an argument, - * otherwise null. - */ - public String getOptionValue(String opt) - { - String[] values = getOptionValues(opt); - - return (values == null) ? null : values[0]; - } - - /** - * Retrieve the argument, if any, of this option. - * - * @param opt the character name of the option - * @return Value of the argument if option is set, and has an argument, - * otherwise null. - */ - public String getOptionValue(char opt) - { - return getOptionValue(String.valueOf(opt)); - } - - /** - * Retrieves the array of values, if any, of an option. - * - * @param opt string name of the option - * @return Values of the argument if option is set, and has an argument, - * otherwise null. - */ - public String[] getOptionValues(String opt) - { - opt = Util.stripLeadingHyphens(opt); - - String key = opt; - - if (names.containsKey(opt)) - { - key = (String) names.get(opt); - } - - if (options.containsKey(key)) - { - return ((Option) options.get(key)).getValues(); - } - - return null; - } - - /** - * Retrieves the array of values, if any, of an option. - * - * @param opt character name of the option - * @return Values of the argument if option is set, and has an argument, - * otherwise null. - */ - public String[] getOptionValues(char opt) - { - return getOptionValues(String.valueOf(opt)); - } - - /** - * Retrieve the argument, if any, of an option. - * - * @param opt name of the option - * @param defaultValue is the default value to be returned if the option - * is not specified - * @return Value of the argument if option is set, and has an argument, - * otherwise defaultValue. - */ - public String getOptionValue(String opt, String defaultValue) - { - String answer = getOptionValue(opt); - - return (answer != null) ? answer : defaultValue; - } - - /** - * Retrieve the argument, if any, of an option. - * - * @param opt character name of the option - * @param defaultValue is the default value to be returned if the option - * is not specified - * @return Value of the argument if option is set, and has an argument, - * otherwise defaultValue. - */ - public String getOptionValue(char opt, String defaultValue) - { - return getOptionValue(String.valueOf(opt), defaultValue); - } - - /** - * Retrieve any left-over non-recognized options and arguments - * - * @return remaining items passed in but not parsed as an array - */ - public String[] getArgs() - { - String[] answer = new String[args.size()]; - - args.toArray(answer); - - return answer; - } - - /** - * Retrieve any left-over non-recognized options and arguments - * - * @return remaining items passed in but not parsed as a List. - */ - public List getArgList() - { - return args; - } - - /** - * jkeyes - * - commented out until it is implemented properly - *

Dump state, suitable for debugging.

- * - * @return Stringified form of this object - */ - - /* - public String toString() { - StringBuffer buf = new StringBuffer(); - - buf.append("[ CommandLine: [ options: "); - buf.append(options.toString()); - buf.append(" ] [ args: "); - buf.append(args.toString()); - buf.append(" ] ]"); - - return buf.toString(); - } - */ - - /** - * Add left-over unrecognized option/argument. - * - * @param arg the unrecognised option/argument. - */ - void addArg(String arg) - { - args.add(arg); - } - - /** - * Add an option to the command line. The values of - * the option are stored. - * - * @param opt the processed option - */ - void addOption(Option opt) - { - hashcodeMap.put(new Integer(opt.hashCode()), opt); - - String key = opt.getKey(); - - if (key == null) - { - key = opt.getLongOpt(); - } - else - { - names.put(opt.getLongOpt(), key); - } - - options.put(key, opt); - } - - /** - * Returns an iterator over the Option members of CommandLine. - * - * @return an Iterator over the processed {@link Option} - * members of this {@link CommandLine} - */ - public Iterator iterator() - { - return hashcodeMap.values().iterator(); - } - - /** - * Returns an array of the processed {@link Option}s. - * - * @return an array of the processed {@link Option}s. - */ - public Option[] getOptions() - { - Collection processed = options.values(); - - - // reinitialise array - optionsArray = new Option[processed.size()]; - - // return the array - return (Option[]) processed.toArray(optionsArray); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/CommandLineParser.java b/src/java/org/apache/commons/cli/CommandLineParser.java deleted file mode 100644 index ae59f6a15..000000000 --- a/src/java/org/apache/commons/cli/CommandLineParser.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.Properties; - -/** - * A class that implements the CommandLineParser interface - * can parse a String array according to the {@link Options} specified - * and return a {@link CommandLine}. - * - * @author John Keyes (john at integralsource.com) - */ -public interface CommandLineParser { - - /** - * Parse the arguments according to the specified options. - * - * @param options the specified Options - * @param arguments the command line arguments - * @return the list of atomic option and value tokens - * - * @throws ParseException if there are any problems encountered - * while parsing the command line tokens. - */ - CommandLine parse(Options options, String[] arguments) - throws ParseException; - - /** - * Parse the arguments according to the specified options and - * properties. - * - * @param options the specified Options - * @param arguments the command line arguments - * @param properties command line option name-value pairs - * @return the list of atomic option and value tokens - * - * @throws ParseException if there are any problems encountered - * while parsing the command line tokens. - */ - CommandLine parse(Options options, String[] arguments, - Properties properties) - throws ParseException; - - /** - * Parse the arguments according to the specified options. - * - * @param options the specified Options - * @param arguments the command line arguments - * @param stopAtNonOption specifies whether to continue parsing the - * arguments if a non option is encountered. - * - * @return the list of atomic option and value tokens - * @throws ParseException if there are any problems encountered - * while parsing the command line tokens. - */ - CommandLine parse(Options options, String[] arguments, - boolean stopAtNonOption) - throws ParseException; - - /** - * Parse the arguments according to the specified options and - * properties. - * - * @param options the specified Options - * @param arguments the command line arguments - * @param properties command line option name-value pairs - * @param stopAtNonOption specifies whether to continue parsing the - * - * @return the list of atomic option and value tokens - * @throws ParseException if there are any problems encountered - * while parsing the command line tokens. - */ - CommandLine parse(Options options, String[] arguments, - Properties properties, boolean stopAtNonOption) - throws ParseException; -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/GnuParser.java b/src/java/org/apache/commons/cli/GnuParser.java deleted file mode 100644 index b510037b3..000000000 --- a/src/java/org/apache/commons/cli/GnuParser.java +++ /dev/null @@ -1,173 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.ArrayList; - -/** - * The class GnuParser provides an implementation of the - * {@link Parser#flatten(Options,String[],boolean) flatten} method. - * - * @author John Keyes (john at integralsource.com) - * @see Parser - * @version $Revision$ - */ -public class GnuParser extends Parser { - - /** holder for flattened tokens */ - private ArrayList tokens = new ArrayList(); - - /** - *

Resets the members to their original state i.e. remove - * all of tokens entries. - */ - private void init() - { - tokens.clear(); - } - - /** - *

This flatten method does so using the following rules: - *

    - *
  1. If an {@link Option} exists for the first character of - * the arguments entry AND an {@link Option} - * does not exist for the whole argument then - * add the first character as an option to the processed tokens - * list e.g. "-D" and add the rest of the entry to the also.
  2. - *
  3. Otherwise just add the token to the processed tokens list. - *
  4. - *
- *

- * - * @param options The Options to parse the arguments by. - * @param arguments The arguments that have to be flattened. - * @param stopAtNonOption specifies whether to stop - * flattening when a non option has been encountered - * @return a String array of the flattened arguments - */ - protected String[] flatten(Options options, String[] arguments, - boolean stopAtNonOption) - { - init(); - - boolean eatTheRest = false; - Option currentOption = null; - - for (int i = 0; i < arguments.length; i++) - { - if ("--".equals(arguments[i])) - { - eatTheRest = true; - tokens.add("--"); - } - else if ("-".equals(arguments[i])) - { - tokens.add("-"); - } - else if (arguments[i].startsWith("-")) - { - Option option = options.getOption(arguments[i]); - - // this is not an Option - if (option == null) - { - // handle special properties Option - Option specialOption = - options.getOption(arguments[i].substring(0, 2)); - - if (specialOption != null) - { - tokens.add(arguments[i].substring(0, 2)); - tokens.add(arguments[i].substring(2)); - } - else if (stopAtNonOption) - { - eatTheRest = true; - tokens.add(arguments[i]); - } - else - { - tokens.add(arguments[i]); - } - } - else - { - currentOption = option; - - // special option - Option specialOption = - options.getOption(arguments[i].substring(0, 2)); - - if ((specialOption != null) && (option == null)) - { - tokens.add(arguments[i].substring(0, 2)); - tokens.add(arguments[i].substring(2)); - } - else if ((currentOption != null) && currentOption.hasArg()) - { - if (currentOption.hasArg()) - { - tokens.add(arguments[i]); - currentOption = null; - } - else if (currentOption.hasArgs()) - { - tokens.add(arguments[i]); - } - else if (stopAtNonOption) - { - eatTheRest = true; - tokens.add("--"); - tokens.add(arguments[i]); - } - else - { - tokens.add(arguments[i]); - } - } - else if (currentOption != null) - { - tokens.add(arguments[i]); - } - else if (stopAtNonOption) - { - eatTheRest = true; - tokens.add("--"); - tokens.add(arguments[i]); - } - else - { - tokens.add(arguments[i]); - } - } - } - else - { - tokens.add(arguments[i]); - } - - if (eatTheRest) - { - for (i++; i < arguments.length; i++) - { - tokens.add(arguments[i]); - } - } - } - - return (String[]) tokens.toArray(new String[] { }); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/HelpFormatter.java b/src/java/org/apache/commons/cli/HelpFormatter.java deleted file mode 100644 index ebee9fe49..000000000 --- a/src/java/org/apache/commons/cli/HelpFormatter.java +++ /dev/null @@ -1,908 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.io.PrintWriter; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - -/** - * A formatter of help messages for the current command line options - * - * @author Slawek Zachcial - * @author John Keyes (john at integralsource.com) - **/ -public class HelpFormatter { - // --------------------------------------------------------------- Constants - - /** default number of characters per line */ - public static final int DEFAULT_WIDTH = 74; - - /** default padding to the left of each line */ - public static final int DEFAULT_LEFT_PAD = 1; - - /** ?? */ - public static final int DEFAULT_DESC_PAD = 3; - - /** the string to display at the begining of the usage statement */ - public static final String DEFAULT_SYNTAX_PREFIX = "usage: "; - - /** default prefix for shortOpts */ - public static final String DEFAULT_OPT_PREFIX = "-"; - - /** default prefix for long Option */ - public static final String DEFAULT_LONG_OPT_PREFIX = "--"; - - /** default name for an argument */ - public static final String DEFAULT_ARG_NAME = "arg"; - - // -------------------------------------------------------------- Attributes - - /** number of characters per line */ - private int defaultWidth = DEFAULT_WIDTH; - - /** amount of padding to the left of each line */ - private int defaultLeftPad = DEFAULT_LEFT_PAD; - - /** ?? */ - private int defaultDescPad = DEFAULT_DESC_PAD; - - /** the string to display at the begining of the usage statement */ - private String defaultSyntaxPrefix = DEFAULT_SYNTAX_PREFIX; - - /** the new line character/string ?? */ - private String defaultNewLine = System.getProperty("line.separator"); - - /** the shortOpt prefix */ - private String defaultOptPrefix = DEFAULT_OPT_PREFIX; - - /** the long Opt prefix */ - private String defaultLongOptPrefix = DEFAULT_LONG_OPT_PREFIX; - - /** the name of the argument */ - private String defaultArgName = DEFAULT_ARG_NAME; - - /** - * Sets the 'width'. - * - * @param width the new value of 'width' - */ - public void setWidth(int width) - { - this.defaultWidth = width; - } - - /** - * Returns the 'width'. - * - * @return the 'width' - */ - public int getWidth() - { - return this.defaultWidth; - } - - /** - * Sets the 'leftPadding'. - * - * @param padding the new value of 'leftPadding' - */ - public void setLeftPadding(int padding) - { - this.defaultLeftPad = padding; - } - - /** - * Returns the 'leftPadding'. - * - * @return the 'leftPadding' - */ - public int getLeftPadding() - { - return this.defaultLeftPad; - } - - /** - * Sets the 'descPadding'. - * - * @param padding the new value of 'descPadding' - */ - public void setDescPadding(int padding) - { - this.defaultDescPad = padding; - } - - /** - * Returns the 'descPadding'. - * - * @return the 'descPadding' - */ - public int getDescPadding() - { - return this.defaultDescPad; - } - - /** - * Sets the 'syntaxPrefix'. - * - * @param prefix the new value of 'syntaxPrefix' - */ - public void setSyntaxPrefix(String prefix) - { - this.defaultSyntaxPrefix = prefix; - } - - /** - * Returns the 'syntaxPrefix'. - * - * @return the 'syntaxPrefix' - */ - public String getSyntaxPrefix() - { - return this.defaultSyntaxPrefix; - } - - /** - * Sets the 'newLine'. - * - * @param newline the new value of 'newLine' - */ - public void setNewLine(String newline) - { - this.defaultNewLine = newline; - } - - /** - * Returns the 'newLine'. - * - * @return the 'newLine' - */ - public String getNewLine() - { - return this.defaultNewLine; - } - - /** - * Sets the 'optPrefix'. - * - * @param prefix the new value of 'optPrefix' - */ - public void setOptPrefix(String prefix) - { - this.defaultOptPrefix = prefix; - } - - /** - * Returns the 'optPrefix'. - * - * @return the 'optPrefix' - */ - public String getOptPrefix() - { - return this.defaultOptPrefix; - } - - /** - * Sets the 'longOptPrefix'. - * - * @param prefix the new value of 'longOptPrefix' - */ - public void setLongOptPrefix(String prefix) - { - this.defaultLongOptPrefix = prefix; - } - - /** - * Returns the 'longOptPrefix'. - * - * @return the 'longOptPrefix' - */ - public String getLongOptPrefix() - { - return this.defaultLongOptPrefix; - } - - /** - * Sets the 'argName'. - * - * @param name the new value of 'argName' - */ - public void setArgName(String name) - { - this.defaultArgName = name; - } - - /** - * Returns the 'argName'. - * - * @return the 'argName' - */ - public String getArgName() - { - return this.defaultArgName; - } - - - // ------------------------------------------------------------------ Public - - /** - *

Print the help for options with the specified - * command line syntax. This method prints help information to - * System.out.

- * - * @param cmdLineSyntax the syntax for this application - * @param options the Options instance - */ - public void printHelp(String cmdLineSyntax, Options options) - { - printHelp(defaultWidth, cmdLineSyntax, null, options, null, false); - } - - /** - *

Print the help for options with the specified - * command line syntax. This method prints help information to - * System.out.

- * - * @param cmdLineSyntax the syntax for this application - * @param options the Options instance - * @param autoUsage whether to print an automatically generated - * usage statement - */ - public void printHelp(String cmdLineSyntax, Options options, - boolean autoUsage) - { - printHelp(defaultWidth, cmdLineSyntax, null, options, null, autoUsage); - } - - /** - *

Print the help for options with the specified - * command line syntax. This method prints help information to - * System.out.

- * - * @param cmdLineSyntax the syntax for this application - * @param header the banner to display at the begining of the help - * @param options the Options instance - * @param footer the banner to display at the end of the help - */ - public void printHelp(String cmdLineSyntax, String header, Options options, - String footer) - { - printHelp(cmdLineSyntax, header, options, footer, false); - } - - /** - *

Print the help for options with the specified - * command line syntax. This method prints help information to - * System.out.

- * - * @param cmdLineSyntax the syntax for this application - * @param header the banner to display at the begining of the help - * @param options the Options instance - * @param footer the banner to display at the end of the help - * @param autoUsage whether to print an automatically generated - * usage statement - */ - public void printHelp(String cmdLineSyntax, String header, Options options, - String footer, boolean autoUsage) - { - printHelp(defaultWidth, cmdLineSyntax, header, options, footer, - autoUsage); - } - - /** - *

Print the help for options with the specified - * command line syntax. This method prints help information to - * System.out.

- * - * @param width the number of characters to be displayed on each line - * @param cmdLineSyntax the syntax for this application - * @param header the banner to display at the begining of the help - * @param options the Options instance - * @param footer the banner to display at the end of the help - */ - public void printHelp(int width, String cmdLineSyntax, String header, - Options options, String footer) - { - printHelp(width, cmdLineSyntax, header, options, footer, false); - } - - /** - *

Print the help for options with the specified - * command line syntax. This method prints help information to - * System.out.

- * - * @param width the number of characters to be displayed on each line - * @param cmdLineSyntax the syntax for this application - * @param header the banner to display at the begining of the help - * @param options the Options instance - * @param footer the banner to display at the end of the help - * @param autoUsage whether to print an automatically generated - * usage statement - */ - public void printHelp(int width, String cmdLineSyntax, String header, - Options options, String footer, boolean autoUsage) - { - PrintWriter pw = new PrintWriter(System.out); - - printHelp(pw, width, cmdLineSyntax, header, options, defaultLeftPad, - defaultDescPad, footer, autoUsage); - pw.flush(); - } - - /** - *

Print the help for options with the specified - * command line syntax.

- * - * @param pw the writer to which the help will be written - * @param width the number of characters to be displayed on each line - * @param cmdLineSyntax the syntax for this application - * @param header the banner to display at the begining of the help - * @param options the Options instance - * @param leftPad the number of characters of padding to be prefixed - * to each line - * @param descPad the number of characters of padding to be prefixed - * to each description line - * @param footer the banner to display at the end of the help - */ - public void printHelp(PrintWriter pw, int width, String cmdLineSyntax, - String header, Options options, int leftPad, - int descPad, String footer) - { - printHelp(pw, width, cmdLineSyntax, header, options, leftPad, descPad, - footer, false); - } - - - /** - *

Print the help for options with the specified - * command line syntax.

- * - * @param pw the writer to which the help will be written - * @param width the number of characters to be displayed on each line - * @param cmdLineSyntax the syntax for this application - * @param header the banner to display at the begining of the help - * @param options the Options instance - * @param leftPad the number of characters of padding to be prefixed - * to each line - * @param descPad the number of characters of padding to be prefixed - * to each description line - * @param footer the banner to display at the end of the help - * @param autoUsage whether to print an automatically generated - * usage statement - */ - public void printHelp(PrintWriter pw, int width, String cmdLineSyntax, - String header, Options options, int leftPad, - int descPad, String footer, boolean autoUsage) - { - if ((cmdLineSyntax == null) || (cmdLineSyntax.length() == 0)) - { - throw new IllegalArgumentException("cmdLineSyntax not provided"); - } - - if (autoUsage) - { - printUsage(pw, width, cmdLineSyntax, options); - } - else - { - printUsage(pw, width, cmdLineSyntax); - } - - if ((header != null) && (header.trim().length() > 0)) - { - printWrapped(pw, width, header); - } - - printOptions(pw, width, options, leftPad, descPad); - - if ((footer != null) && (footer.trim().length() > 0)) - { - printWrapped(pw, width, footer); - } - } - - /** - *

Prints the usage statement for the specified application.

- * - * @param pw The PrintWriter to print the usage statement - * @param width The number of characters to display per line - * @param app The application name - * @param options The command line Options - * - */ - public void printUsage(PrintWriter pw, int width, String app, - Options options) - { - // initialise the string buffer - StringBuffer buff = new StringBuffer(defaultSyntaxPrefix).append(app) - .append(" "); - - // create a list for processed option groups - final Collection processedGroups = new ArrayList(); - - // temp variable - Option option; - - // iterate over the options - for (Iterator i = options.getOptions().iterator(); i.hasNext();) - { - // get the next Option - option = (Option) i.next(); - - // check if the option is part of an OptionGroup - OptionGroup group = options.getOptionGroup(option); - - // if the option is part of a group - if (group != null) - { - // and if the group has not already been processed - if (!processedGroups.contains(group)) - { - // add the group to the processed list - processedGroups.add(group); - - - // add the usage clause - appendOptionGroup(buff, group); - } - - // otherwise the option was displayed in the group - // previously so ignore it. - } - - // if the Option is not part of an OptionGroup - else - { - appendOption(buff, option, option.isRequired()); - } - - if (i.hasNext()) - { - buff.append(" "); - } - } - - - // call printWrapped - printWrapped(pw, width, buff.toString().indexOf(' ') + 1, - buff.toString()); - } - - /** - * Appends the usage clause for an OptionGroup to a StringBuffer. - * The clause is wrapped in square brackets if the group is required. - * The display of the options is handled by appendOption - * @param buff the StringBuffer to append to - * @param group the group to append - * @see #appendOption(StringBuffer,Option,boolean) - */ - private static void appendOptionGroup(final StringBuffer buff, - final OptionGroup group) - { - if (!group.isRequired()) - { - buff.append("["); - } - - // for each option in the OptionGroup - for (Iterator i = group.getOptions().iterator(); i.hasNext();) - { - // whether the option is required or not is handled at group level - appendOption(buff, (Option) i.next(), true); - - if (i.hasNext()) - { - buff.append(" | "); - } - } - - if (!group.isRequired()) - { - buff.append("]"); - } - } - - /** - * Appends the usage clause for an Option to a StringBuffer. - * - * @param buff the StringBuffer to append to - * @param option the Option to append - * @param required whether the Option is required or not - */ - private static void appendOption(final StringBuffer buff, - final Option option, - final boolean required) - { - if (!required) - { - buff.append("["); - } - - if (option.getOpt() != null) - { - buff.append("-").append(option.getOpt()); - } - else - { - buff.append("--").append(option.getLongOpt()); - } - - // if the Option has a value - if (option.hasArg() && (option.getArgName() != null)) - { - buff.append(" <").append(option.getArgName()).append(">"); - } - - // if the Option is not a required option - if (!required) - { - buff.append("]"); - } - } - - /** - *

Print the cmdLineSyntax to the specified writer, using the - * specified width.

- * - * @param pw The printWriter to write the help to - * @param width The number of characters per line for the usage statement. - * @param cmdLineSyntax The usage statement. - */ - public void printUsage(PrintWriter pw, int width, String cmdLineSyntax) - { - int argPos = cmdLineSyntax.indexOf(' ') + 1; - - printWrapped(pw, width, defaultSyntaxPrefix.length() + argPos, - defaultSyntaxPrefix + cmdLineSyntax); - } - - /** - *

Print the help for the specified Options to the specified writer, - * using the specified width, left padding and description padding.

- * - * @param pw The printWriter to write the help to - * @param width The number of characters to display per line - * @param options The command line Options - * @param leftPad the number of characters of padding to be prefixed - * to each line - * @param descPad the number of characters of padding to be prefixed - * to each description line - */ - public void printOptions(PrintWriter pw, int width, Options options, - int leftPad, int descPad) - { - StringBuffer sb = new StringBuffer(); - - renderOptions(sb, width, options, leftPad, descPad); - pw.println(sb.toString()); - } - - /** - *

Print the specified text to the specified PrintWriter.

- * - * @param pw The printWriter to write the help to - * @param width The number of characters to display per line - * @param text The text to be written to the PrintWriter - */ - public void printWrapped(PrintWriter pw, int width, String text) - { - printWrapped(pw, width, 0, text); - } - - /** - *

Print the specified text to the specified PrintWriter.

- * - * @param pw The printWriter to write the help to - * @param width The number of characters to display per line - * @param nextLineTabStop The position on the next line for the first tab. - * @param text The text to be written to the PrintWriter - */ - public void printWrapped(PrintWriter pw, int width, int nextLineTabStop, - String text) - { - StringBuffer sb = new StringBuffer(text.length()); - - renderWrappedText(sb, width, nextLineTabStop, text); - pw.println(sb.toString()); - } - - // --------------------------------------------------------------- Protected - - /** - *

Render the specified Options and return the rendered Options - * in a StringBuffer.

- * - * @param sb The StringBuffer to place the rendered Options into. - * @param width The number of characters to display per line - * @param options The command line Options - * @param leftPad the number of characters of padding to be prefixed - * to each line - * @param descPad the number of characters of padding to be prefixed - * to each description line - * - * @return the StringBuffer with the rendered Options contents. - */ - protected StringBuffer renderOptions(StringBuffer sb, int width, - Options options, int leftPad, - int descPad) - { - final String lpad = createPadding(leftPad); - final String dpad = createPadding(descPad); - - // first create list containing only -a,--aaa where - // -a is opt and --aaa is long opt; in parallel look for - // the longest opt string this list will be then used to - // sort options ascending - int max = 0; - StringBuffer optBuf; - List prefixList = new ArrayList(); - Option option; - List optList = options.helpOptions(); - - Collections.sort(optList, new OptionComparator()); - - for (Iterator i = optList.iterator(); i.hasNext();) - { - option = (Option) i.next(); - optBuf = new StringBuffer(8); - - if (option.getOpt() == null) - { - optBuf.append(lpad).append(" " + defaultLongOptPrefix) - .append(option.getLongOpt()); - } - else - { - optBuf.append(lpad).append(defaultOptPrefix) - .append(option.getOpt()); - - if (option.hasLongOpt()) - { - optBuf.append(',').append(defaultLongOptPrefix) - .append(option.getLongOpt()); - } - } - - if (option.hasArg()) - { - if (option.hasArgName()) - { - optBuf.append(" <").append(option.getArgName()).append(">"); - } - else - { - optBuf.append(' '); - } - } - - prefixList.add(optBuf); - max = (optBuf.length() > max) ? optBuf.length() : max; - } - - int x = 0; - - for (Iterator i = optList.iterator(); i.hasNext();) - { - option = (Option) i.next(); - optBuf = new StringBuffer(prefixList.get(x++).toString()); - - if (optBuf.length() < max) - { - optBuf.append(createPadding(max - optBuf.length())); - } - - optBuf.append(dpad); - - int nextLineTabStop = max + descPad; - - if (option.getDescription() != null) - { - optBuf.append(option.getDescription()); - } - - renderWrappedText(sb, width, nextLineTabStop, optBuf.toString()); - - if (i.hasNext()) - { - sb.append(defaultNewLine); - } - } - - return sb; - } - - /** - *

Render the specified text and return the rendered Options - * in a StringBuffer.

- * - * @param sb The StringBuffer to place the rendered text into. - * @param width The number of characters to display per line - * @param nextLineTabStop The position on the next line for the first tab. - * @param text The text to be rendered. - * - * @return the StringBuffer with the rendered Options contents. - */ - protected StringBuffer renderWrappedText(StringBuffer sb, int width, - int nextLineTabStop, String text) - { - int pos = findWrapPos(text, width, 0); - - if (pos == -1) - { - sb.append(rtrim(text)); - - return sb; - } - sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); - - // all following lines must be padded with nextLineTabStop space - // characters - final String padding = createPadding(nextLineTabStop); - - while (true) - { - text = padding + text.substring(pos).trim(); - pos = findWrapPos(text, width, nextLineTabStop); - - if (pos == -1) - { - sb.append(text); - - return sb; - } - - sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); - } - } - - /** - * Finds the next text wrap position after startPos for the - * text in text with the column width width. - * The wrap point is the last postion before startPos+width having a - * whitespace character (space, \n, \r). - * - * @param text The text being searched for the wrap position - * @param width width of the wrapped text - * @param startPos position from which to start the lookup whitespace - * character - * @return postion on which the text must be wrapped or -1 if the wrap - * position is at the end of the text - */ - protected int findWrapPos(String text, int width, int startPos) - { - int pos = -1; - - // the line ends before the max wrap pos or a new line char found - if (((pos = text.indexOf('\n', startPos)) != -1 && pos <= width) - || ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width)) - { - return pos+1; - } - else if ((startPos + width) >= text.length()) - { - return -1; - } - - - // look for the last whitespace character before startPos+width - pos = startPos + width; - - char c; - - while ((pos >= startPos) && ((c = text.charAt(pos)) != ' ') - && (c != '\n') && (c != '\r')) - { - --pos; - } - - // if we found it - just return - if (pos > startPos) - { - return pos; - } - - // must look for the first whitespace chearacter after startPos - // + width - pos = startPos + width; - - while ((pos <= text.length()) && ((c = text.charAt(pos)) != ' ') - && (c != '\n') && (c != '\r')) - { - ++pos; - } - - return (pos == text.length()) ? (-1) : pos; - } - - /** - *

Return a String of padding of length len.

- * - * @param len The length of the String of padding to create. - * - * @return The String of padding - */ - protected String createPadding(int len) - { - StringBuffer sb = new StringBuffer(len); - - for (int i = 0; i < len; ++i) - { - sb.append(' '); - } - - return sb.toString(); - } - - /** - *

Remove the trailing whitespace from the specified String.

- * - * @param s The String to remove the trailing padding from. - * - * @return The String of without the trailing padding - */ - protected String rtrim(String s) - { - if ((s == null) || (s.length() == 0)) - { - return s; - } - - int pos = s.length(); - - while ((pos > 0) && Character.isWhitespace(s.charAt(pos - 1))) - { - --pos; - } - - return s.substring(0, pos); - } - - // ------------------------------------------------------ Package protected - // ---------------------------------------------------------------- Private - // ---------------------------------------------------------- Inner classes - /** - *

This class implements the Comparator interface - * for comparing Options.

- */ - private static class OptionComparator - implements Comparator { - - /** - *

Compares its two arguments for order. Returns a negative - * integer, zero, or a positive integer as the first argument - * is less than, equal to, or greater than the second.

- * - * @param o1 The first Option to be compared. - * @param o2 The second Option to be compared. - * - * @return a negative integer, zero, or a positive integer as - * the first argument is less than, equal to, or greater than the - * second. - */ - public int compare(Object o1, Object o2) - { - Option opt1 = (Option)o1; - Option opt2 = (Option)o2; - - return opt1.getKey().compareToIgnoreCase(opt2.getKey()); - } - } -} diff --git a/src/java/org/apache/commons/cli/MissingArgumentException.java b/src/java/org/apache/commons/cli/MissingArgumentException.java deleted file mode 100644 index ccdea497c..000000000 --- a/src/java/org/apache/commons/cli/MissingArgumentException.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - *

Thrown when an option requiring an argument - * is not provided with an argument.

- * - * @author John Keyes (john at integralsource.com) - * @see ParseException - */ -public class MissingArgumentException - extends ParseException { - - /** - *

Construct a new MissingArgumentException - * with the specified detail message.

- * - * @param message the detail message - */ - public MissingArgumentException(String message) - { - super(message); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/MissingOptionException.java b/src/java/org/apache/commons/cli/MissingOptionException.java deleted file mode 100644 index 5dbb0e644..000000000 --- a/src/java/org/apache/commons/cli/MissingOptionException.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - *

Thrown when a required option has not been provided.

- * - * @author John Keyes ( john at integralsource.com ) - * @see ParseException - */ -public class MissingOptionException - extends ParseException { - - /** - *

Construct a new MissingSelectedException - * with the specified detail message.

- * - * @param message the detail message - */ - public MissingOptionException(String message) - { - super(message); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/Option.java b/src/java/org/apache/commons/cli/Option.java deleted file mode 100644 index 55128583a..000000000 --- a/src/java/org/apache/commons/cli/Option.java +++ /dev/null @@ -1,599 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.ArrayList; - -/**

Describes a single command-line option. It maintains - * information regarding the short-name of the option, the long-name, - * if any exists, a flag indicating if an argument is required for - * this option, and a self-documenting description of the option.

- * - *

An Option is not created independantly, but is create through - * an instance of {@link Options}.

- * - * @see org.apache.commons.cli.Options - * @see org.apache.commons.cli.CommandLine - * - * @author bob mcwhirter (bob @ werken.com) - * @author James Strachan - * @version $Revision$ - */ -public class Option { - - /** constant that specifies the number of argument values has - not been specified */ - public static final int UNINITIALIZED = -1; - - /** constant that specifies the number of argument values is infinite */ - public static final int UNLIMITED_VALUES = -2; - - /** opt the name of the option */ - private String opt; - - /** longOpt is the long representation of the option */ - private String longOpt; - - /** hasArg specifies whether this option has an associated argument */ - private boolean hasArg; - - /** argName specifies the name of the argument for this option */ - private String argName = "arg"; - - /** description of the option */ - private String description; - - /** required specifies whether this option is required to be present */ - private boolean required; - - /** specifies whether the argument value of this Option is optional */ - private boolean optionalArg; - - /** - * numberOfArgs specifies the number of argument values this option - * can have - */ - private int numberOfArgs = UNINITIALIZED; - - /** the type of this Option */ - private Object type; - - /** the list of argument values **/ - private ArrayList values = new ArrayList(); - - /** the character that is the value separator */ - private char valuesep; - - /** - * Creates an Option using the specified parameters. - * - * @param opt short representation of the option - * @param description describes the function of the option - * - * @throws IllegalArgumentException if there are any non valid - * Option characters in opt. - */ - public Option(String opt, String description) - throws IllegalArgumentException - { - this(opt, null, false, description); - } - - /** - * Creates an Option using the specified parameters. - * - * @param opt short representation of the option - * @param hasArg specifies whether the Option takes an argument or not - * @param description describes the function of the option - * - * @throws IllegalArgumentException if there are any non valid - * Option characters in opt. - */ - public Option(String opt, boolean hasArg, String description) - throws IllegalArgumentException - { - this(opt, null, hasArg, description); - } - - /** - * Creates an Option using the specified parameters. - * - * @param opt short representation of the option - * @param longOpt the long representation of the option - * @param hasArg specifies whether the Option takes an argument or not - * @param description describes the function of the option - * - * @throws IllegalArgumentException if there are any non valid - * Option characters in opt. - */ - public Option(String opt, String longOpt, boolean hasArg, - String description) - throws IllegalArgumentException - { - // ensure that the option is valid - OptionValidator.validateOption(opt); - - this.opt = opt; - this.longOpt = longOpt; - - // if hasArg is set then the number of arguments is 1 - if (hasArg) - { - this.numberOfArgs = 1; - } - - this.hasArg = hasArg; - this.description = description; - } - - /** - * Returns the id of this Option. This is only set when the - * Option shortOpt is a single character. This is used for switch - * statements. - * - * @return the id of this Option - */ - public int getId() - { - return getKey().charAt(0); - } - - /** - * Returns the 'unique' Option identifier. - * - * @return the 'unique' Option identifier - */ - String getKey() - { - // if 'opt' is null, then it is a 'long' option - if (opt == null) - { - return this.longOpt; - } - - return this.opt; - } - - /** - * Retrieve the name of this Option. - * - * It is this String which can be used with - * {@link CommandLine#hasOption(String opt)} and - * {@link CommandLine#getOptionValue(String opt)} to check - * for existence and argument. - * - * @return The name of this option - */ - public String getOpt() - { - return this.opt; - } - - /** - * Retrieve the type of this Option. - * - * @return The type of this option - */ - public Object getType() - { - return this.type; - } - - /** - * Sets the type of this Option. - * - * @param type the type of this Option - */ - public void setType(Object type) - { - this.type = type; - } - - /** - * Retrieve the long name of this Option. - * - * @return Long name of this option, or null, if there is no long name - */ - public String getLongOpt() - { - return this.longOpt; - } - - /** - * Sets the long name of this Option. - * - * @param longOpt the long name of this Option - */ - public void setLongOpt(String longOpt) - { - this.longOpt = longOpt; - } - - /** - * Sets whether this Option can have an optional argument. - * - * @param optionalArg specifies whether the Option can have - * an optional argument. - */ - public void setOptionalArg(boolean optionalArg) - { - this.optionalArg = optionalArg; - } - - /** - * @return whether this Option can have an optional argument - */ - public boolean hasOptionalArg() - { - return this.optionalArg; - } - - /** - * Query to see if this Option has a long name - * - * @return boolean flag indicating existence of a long name - */ - public boolean hasLongOpt() - { - return (this.longOpt != null); - } - - /** - * Query to see if this Option requires an argument - * - * @return boolean flag indicating if an argument is required - */ - public boolean hasArg() - { - return (this.numberOfArgs > 0) || (numberOfArgs == UNLIMITED_VALUES); - } - - /** - * Retrieve the self-documenting description of this Option - * - * @return The string description of this option - */ - public String getDescription() - { - return this.description; - } - - /** - * Sets the self-documenting description of this Option - * - * @param description The description of this option - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * Query to see if this Option requires an argument - * - * @return boolean flag indicating if an argument is required - */ - public boolean isRequired() - { - return this.required; - } - - /** - * Sets whether this Option is mandatory. - * - * @param required specifies whether this Option is mandatory - */ - public void setRequired(boolean required) - { - this.required = required; - } - - /** - * Sets the display name for the argument value. - * - * @param argName the display name for the argument value. - */ - public void setArgName(String argName) - { - this.argName = argName; - } - - /** - * Gets the display name for the argument value. - * - * @return the display name for the argument value. - */ - public String getArgName() - { - return this.argName; - } - - /** - * Returns whether the display name for the argument value - * has been set. - * - * @return if the display name for the argument value has been - * set. - */ - public boolean hasArgName() - { - return (this.argName != null && this.argName.length() > 0); - } - - /** - * Query to see if this Option can take many values. - * - * @return boolean flag indicating if multiple values are allowed - */ - public boolean hasArgs() - { - return (this.numberOfArgs > 1) - || (this.numberOfArgs == UNLIMITED_VALUES); - } - - /** - * Sets the number of argument values this Option can take. - * - * @param num the number of argument values - */ - public void setArgs(int num) - { - this.numberOfArgs = num; - } - - /** - * Sets the value separator. For example if the argument value - * was a Java property, the value separator would be '='. - * - * @param sep The value separator. - */ - public void setValueSeparator(char sep) - { - this.valuesep = sep; - } - - /** - * Returns the value separator character. - * - * @return the value separator character. - */ - public char getValueSeparator() - { - return this.valuesep; - } - - /** - * Return whether this Option has specified a value separator. - * - * @return whether this Option has specified a value separator. - */ - public boolean hasValueSeparator() - { - return (this.valuesep > 0); - } - - /** - * Returns the number of argument values this Option can take. - * - * @return num the number of argument values - */ - public int getArgs() - { - return this.numberOfArgs; - } - - /** - * Adds the specified value to this Option. - * - * @param value is a/the value of this Option - */ - void addValue(String value) - { - switch (numberOfArgs) - { - case UNINITIALIZED: - throw new RuntimeException("NO_ARGS_ALLOWED"); - - default: - processValue(value); - } - } - - /** - * Processes the value. If this Option has a value separator - * the value will have to be parsed into individual tokens. When - * n-1 tokens have been processed and there are more value separators - * in the value, parsing is ceased and the remaining characters are - * added as a single token. - * - * @param value The String to be processed. - * - * @since 1.0.1 - */ - private void processValue(String value) - { - // this Option has a separator character - if (hasValueSeparator()) - { - // get the separator character - char sep = getValueSeparator(); - - // store the index for the value separator - int index = value.indexOf(sep); - - // while there are more value separators - while (index != -1) - { - // next value to be added - if (values.size() == (numberOfArgs - 1)) - { - break; - } - - - // store - add(value.substring(0, index)); - - - // parse - value = value.substring(index + 1); - - - // get new index - index = value.indexOf(sep); - } - } - - - // store the actual value or the last value that has been parsed - add(value); - } - - /** - * Add the value to this Option. If the number of arguments - * is greater than zero and there is enough space in the list then - * add the value. Otherwise, throw a runtime exception. - * - * @param value The value to be added to this Option - * - * @since 1.0.1 - */ - private void add(String value) - { - if ((numberOfArgs > 0) && (values.size() > (numberOfArgs - 1))) - { - throw new RuntimeException("Cannot add value, list full."); - } - - - // store value - this.values.add(value); - } - - /** - * Returns the specified value of this Option or - * null if there is no value. - * - * @return the value/first value of this Option or - * null if there is no value. - */ - public String getValue() - { - return hasNoValues() ? null : (String) this.values.get(0); - } - - /** - * Returns the specified value of this Option or - * null if there is no value. - * - * @param index The index of the value to be returned. - * - * @return the specified value of this Option or - * null if there is no value. - * - * @throws IndexOutOfBoundsException if index is less than 1 - * or greater than the number of the values for this Option. - */ - public String getValue(int index) - throws IndexOutOfBoundsException - { - return hasNoValues() ? null : (String) this.values.get(index); - } - - /** - * Returns the value/first value of this Option or the - * defaultValue if there is no value. - * - * @param defaultValue The value to be returned if ther - * is no value. - * - * @return the value/first value of this Option or the - * defaultValue if there are no values. - */ - public String getValue(String defaultValue) - { - String value = getValue(); - - return (value != null) ? value : defaultValue; - } - - /** - * Return the values of this Option as a String array - * or null if there are no values - * - * @return the values of this Option as a String array - * or null if there are no values - */ - public String[] getValues() - { - return hasNoValues() - ? null : (String[]) this.values.toArray(new String[] { }); - } - - /** - * @return the values of this Option as a List - * or null if there are no values - */ - public java.util.List getValuesList() - { - return this.values; - } - - /** - * Dump state, suitable for debugging. - * - * @return Stringified form of this object - */ - public String toString() - { - StringBuffer buf = new StringBuffer().append("[ option: "); - - buf.append(this.opt); - - if (this.longOpt != null) - { - buf.append(" ").append(this.longOpt); - } - - buf.append(" "); - - if (hasArg) - { - buf.append("+ARG"); - } - - buf.append(" :: ").append(this.description); - - if (this.type != null) - { - buf.append(" :: ").append(this.type); - } - - buf.append(" ]"); - - return buf.toString(); - } - - /** - * Returns whether this Option has any values. - * - * @return whether this Option has any values. - */ - private boolean hasNoValues() - { - return this.values.size() == 0; - } -} diff --git a/src/java/org/apache/commons/cli/OptionBuilder.java b/src/java/org/apache/commons/cli/OptionBuilder.java deleted file mode 100644 index e1ac1afc6..000000000 --- a/src/java/org/apache/commons/cli/OptionBuilder.java +++ /dev/null @@ -1,372 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - *

OptionBuilder allows the user to create Options using descriptive - * methods.

- *

Details on the Builder pattern can be found at - * - * http://c2.com/cgi-bin/wiki?BuilderPattern.

- * - * @author John Keyes (john at integralsource.com) - * @since 1.0 - */ -public class OptionBuilder { - - /** long option */ - private static String longopt; - - /** option description */ - private static String description; - - /** argument name */ - private static String argName; - - /** is required? */ - private static boolean required; - - /** the number of arguments */ - private static int numberOfArgs = Option.UNINITIALIZED; - - /** option type */ - private static Object type; - - /** option can have an optional argument value */ - private static boolean optionalArg; - - /** value separator for argument value */ - private static char valuesep; - - /** option builder instance */ - private static OptionBuilder instance = new OptionBuilder(); - - /** - * private constructor to prevent instances being created - */ - private OptionBuilder() - { - // hide the constructor - } - - /** - * Resets the member variables to their default values. - */ - private static void reset() - { - description = null; - argName = "arg"; - longopt = null; - type = null; - required = false; - numberOfArgs = Option.UNINITIALIZED; - - - // PMM 9/6/02 - these were missing - optionalArg = false; - valuesep = (char) 0; - } - - /** - * The next Option created will have the following long option value. - * - * @param newLongopt the long option value - * @return the OptionBuilder instance - */ - public static OptionBuilder withLongOpt(String newLongopt) - { - OptionBuilder.longopt = newLongopt; - - return instance; - } - - /** - * The next Option created will require an argument value. - * - * @return the OptionBuilder instance - */ - public static OptionBuilder hasArg() - { - OptionBuilder.numberOfArgs = 1; - - return instance; - } - - /** - * The next Option created will require an argument value if - * hasArg is true. - * - * @param hasArg if true then the Option has an argument value - * @return the OptionBuilder instance - */ - public static OptionBuilder hasArg(boolean hasArg) - { - OptionBuilder.numberOfArgs = (hasArg == true) ? 1 : Option.UNINITIALIZED; - - return instance; - } - - /** - * The next Option created will have the specified argument value - * name. - * - * @param name the name for the argument value - * @return the OptionBuilder instance - */ - public static OptionBuilder withArgName(String name) - { - OptionBuilder.argName = name; - - return instance; - } - - /** - * The next Option created will be required. - * - * @return the OptionBuilder instance - */ - public static OptionBuilder isRequired() - { - OptionBuilder.required = true; - - return instance; - } - - /** - * The next Option created uses sep as a means to - * separate argument values. - * - * Example: - *
-     * Option opt = OptionBuilder.withValueSeparator(':')
-     *                           .create('D');
-     *
-     * CommandLine line = parser.parse(args);
-     * String propertyName = opt.getValue(0);
-     * String propertyValue = opt.getValue(1);
-     * 
- * - * @param sep The value separator to be used for the argument values. - * - * @return the OptionBuilder instance - */ - public static OptionBuilder withValueSeparator(char sep) - { - OptionBuilder.valuesep = sep; - - return instance; - } - - /** - * The next Option created uses '=' as a means to - * separate argument values. - * - * Example: - *
-     * Option opt = OptionBuilder.withValueSeparator()
-     *                           .create('D');
-     *
-     * CommandLine line = parser.parse(args);
-     * String propertyName = opt.getValue(0);
-     * String propertyValue = opt.getValue(1);
-     * 
- * - * @return the OptionBuilder instance - */ - public static OptionBuilder withValueSeparator() - { - OptionBuilder.valuesep = '='; - - return instance; - } - - /** - * The next Option created will be required if required - * is true. - * - * @param newRequired if true then the Option is required - * @return the OptionBuilder instance - */ - public static OptionBuilder isRequired(boolean newRequired) - { - OptionBuilder.required = newRequired; - - return instance; - } - - /** - * The next Option created can have unlimited argument values. - * - * @return the OptionBuilder instance - */ - public static OptionBuilder hasArgs() - { - OptionBuilder.numberOfArgs = Option.UNLIMITED_VALUES; - - return instance; - } - - /** - * The next Option created can have num - * argument values. - * - * @param num the number of args that the option can have - * @return the OptionBuilder instance - */ - public static OptionBuilder hasArgs(int num) - { - OptionBuilder.numberOfArgs = num; - - return instance; - } - - /** - * The next Option can have an optional argument. - * - * @return the OptionBuilder instance - */ - public static OptionBuilder hasOptionalArg() - { - OptionBuilder.numberOfArgs = 1; - OptionBuilder.optionalArg = true; - - return instance; - } - - /** - * The next Option can have an unlimited number of - * optional arguments. - * - * @return the OptionBuilder instance - */ - public static OptionBuilder hasOptionalArgs() - { - OptionBuilder.numberOfArgs = Option.UNLIMITED_VALUES; - OptionBuilder.optionalArg = true; - - return instance; - } - - /** - * The next Option can have the specified number of - * optional arguments. - * - * @param numArgs - the maximum number of optional arguments - * the next Option created can have. - * @return the OptionBuilder instance - */ - public static OptionBuilder hasOptionalArgs(int numArgs) - { - OptionBuilder.numberOfArgs = numArgs; - OptionBuilder.optionalArg = true; - - return instance; - } - - /** - * The next Option created will have a value that will be an instance - * of type. - * - * @param newType the type of the Options argument value - * @return the OptionBuilder instance - */ - public static OptionBuilder withType(Object newType) - { - OptionBuilder.type = newType; - - return instance; - } - - /** - * The next Option created will have the specified description - * - * @param newDescription a description of the Option's purpose - * @return the OptionBuilder instance - */ - public static OptionBuilder withDescription(String newDescription) - { - OptionBuilder.description = newDescription; - - return instance; - } - - /** - * Create an Option using the current settings and with - * the specified Option char. - * - * @param opt the character representation of the Option - * @return the Option instance - * @throws IllegalArgumentException if opt is not - * a valid character. See Option. - */ - public static Option create(char opt) - throws IllegalArgumentException - { - return create(String.valueOf(opt)); - } - - /** - * Create an Option using the current settings - * - * @return the Option instance - * @throws IllegalArgumentException if longOpt has - * not been set. - */ - public static Option create() - throws IllegalArgumentException - { - if (longopt == null) - { - throw new IllegalArgumentException("must specify longopt"); - } - - return create(null); - } - - /** - * Create an Option using the current settings and with - * the specified Option char. - * - * @param opt the java.lang.String representation - * of the Option - * @return the Option instance - * @throws IllegalArgumentException if opt is not - * a valid character. See Option. - */ - public static Option create(String opt) - throws IllegalArgumentException - { - // create the option - Option option = new Option(opt, description); - - - // set the option properties - option.setLongOpt(longopt); - option.setRequired(required); - option.setOptionalArg(optionalArg); - option.setArgs(numberOfArgs); - option.setType(type); - option.setValueSeparator(valuesep); - option.setArgName(argName); - - - // reset the OptionBuilder properties - OptionBuilder.reset(); - - // return the Option instance - return option; - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/OptionGroup.java b/src/java/org/apache/commons/cli/OptionGroup.java deleted file mode 100644 index 905a10f74..000000000 --- a/src/java/org/apache/commons/cli/OptionGroup.java +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; - -/** - * A group of mutually exclusive options. - * @author John Keyes ( john at integralsource.com ) - * @version $Revision$ - */ -public class OptionGroup { - - /** hold the options */ - private HashMap optionMap = new HashMap(); - - /** the name of the selected option */ - private String selected; - - /** specified whether this group is required */ - private boolean required; - - /** - * add opt to this group - * - * @param opt the option to add to this group - * @return this option group with opt added - */ - public OptionGroup addOption(Option opt) - { - // key - option name - // value - the option - optionMap.put(opt.getKey(), opt); - - return this; - } - - /** - * @return the names of the options in this group as a - * Collection - */ - public Collection getNames() - { - // the key set is the collection of names - return optionMap.keySet(); - } - - /** - * @return the options in this group as a Collection - */ - public Collection getOptions() - { - // the values are the collection of options - return optionMap.values(); - } - - /** - * set the selected option of this group to name. - * @param opt the option that is selected - * @throws AlreadySelectedException if an option from this group has - * already been selected. - */ - public void setSelected(Option opt) - throws AlreadySelectedException - { - // if no option has already been selected or the - // same option is being reselected then set the - // selected member variable - if ((this.selected == null) || this.selected.equals(opt.getOpt())) - { - this.selected = opt.getOpt(); - } - else - { - throw new AlreadySelectedException("an option from this group has " - + "already been selected: '" - + selected + "'"); - } - } - - /** - * @return the selected option name - */ - public String getSelected() - { - return selected; - } - - /** - * @param required specifies if this group is required - */ - public void setRequired(boolean required) - { - this.required = required; - } - - /** - * Returns whether this option group is required. - * - * @return whether this option group is required - */ - public boolean isRequired() - { - return this.required; - } - - /** - *

Returns the stringified version of this OptionGroup.

- * @return the stringified representation of this group - */ - public String toString() - { - StringBuffer buff = new StringBuffer(); - - Iterator iter = getOptions().iterator(); - - buff.append("["); - - while (iter.hasNext()) - { - Option option = (Option) iter.next(); - - if (option.getOpt() != null) - { - buff.append("-"); - buff.append(option.getOpt()); - } - else - { - buff.append("--"); - buff.append(option.getLongOpt()); - } - - buff.append(" "); - buff.append(option.getDescription()); - - if (iter.hasNext()) - { - buff.append(", "); - } - } - - buff.append("]"); - - return buff.toString(); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/OptionValidator.java b/src/java/org/apache/commons/cli/OptionValidator.java deleted file mode 100644 index 5096182a7..000000000 --- a/src/java/org/apache/commons/cli/OptionValidator.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - * Validates an Option string. - * - * @author John Keyes ( john at integralsource.com ) - */ -public class OptionValidator { - - /** - *

Validates whether opt is a permissable Option - * shortOpt. The rules that specify if the opt - * is valid are:

- * - * - * @param opt The option string to validate - * @throws IllegalArgumentException if the Option is not valid. - */ - static void validateOption(String opt) - throws IllegalArgumentException - { - // check that opt is not NULL - if (opt == null) - { - return; - } - - // handle the single character opt - else if (opt.length() == 1) - { - char ch = opt.charAt(0); - - if (!isValidOpt(ch)) - { - throw new IllegalArgumentException("illegal option value '" + ch - + "'"); - } - } - - // handle the multi character opt - else - { - char[] chars = opt.toCharArray(); - - for (int i = 0; i < chars.length; i++) - { - if (!isValidChar(chars[i])) - { - throw new IllegalArgumentException( - "opt contains illegal character value '" + chars[i] - + "'"); - } - } - } - } - - /** - *

Returns whether the specified character is a valid Option.

- * - * @param c the option to validate - * @return true if c is a letter, ' ', '?' or '@', - * otherwise false. - */ - private static boolean isValidOpt(char c) - { - return (isValidChar(c) || (c == ' ') || (c == '?') || c == '@'); - } - - /** - *

Returns whether the specified character is a valid character.

- * - * @param c the character to validate - * @return true if c is a letter. - */ - private static boolean isValidChar(char c) - { - return Character.isJavaIdentifierPart(c); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/Options.java b/src/java/org/apache/commons/cli/Options.java deleted file mode 100644 index 815c6a3c0..000000000 --- a/src/java/org/apache/commons/cli/Options.java +++ /dev/null @@ -1,277 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/**

Main entry-point into the library.

- * - *

Options represents a collection of {@link Option} objects, which - * describe the possible options for a command-line.

- * - *

It may flexibly parse long and short options, with or without - * values. Additionally, it may parse only a portion of a commandline, - * allowing for flexible multi-stage parsing.

- * - * @see org.apache.commons.cli.CommandLine - * - * @author bob mcwhirter (bob @ werken.com) - * @author James Strachan - * @version $Revision$ - */ -public class Options { - - /** a map of the options with the character key */ - private Map shortOpts = new HashMap(); - - /** a map of the options with the long key */ - private Map longOpts = new HashMap(); - - /** a map of the required options */ - private List requiredOpts = new ArrayList(); - - /** a map of the option groups */ - private Map optionGroups = new HashMap(); - - /** Construct a new Options descriptor - */ - public Options() - { - // nothing to do - } - - /** - * Add the specified option group. - * - * @param group the OptionGroup that is to be added - * @return the resulting Options instance - */ - public Options addOptionGroup(OptionGroup group) - { - Iterator options = group.getOptions().iterator(); - - if (group.isRequired()) - { - requiredOpts.add(group); - } - - while (options.hasNext()) - { - Option option = (Option) options.next(); - - - // an Option cannot be required if it is in an - // OptionGroup, either the group is required or - // nothing is required - option.setRequired(false); - addOption(option); - - optionGroups.put(option.getKey(), group); - } - - return this; - } - - /** - * Lists the OptionGroups that are members of this Options instance. - * @return a Collection of OptionGroup instances. - */ - Collection getOptionGroups(){ - return new HashSet(optionGroups.values()); - } - - /** - * Add an option that only contains a short-name. - * It may be specified as requiring an argument. - * - * @param opt Short single-character name of the option. - * @param hasArg flag signally if an argument is required after this option - * @param description Self-documenting description - * @return the resulting Options instance - */ - public Options addOption(String opt, boolean hasArg, String description) - { - addOption(opt, null, hasArg, description); - - return this; - } - - /** - * Add an option that contains a short-name and a long-name. - * It may be specified as requiring an argument. - * - * @param opt Short single-character name of the option. - * @param longOpt Long multi-character name of the option. - * @param hasArg flag signally if an argument is required after this option - * @param description Self-documenting description - * @return the resulting Options instance - */ - public Options addOption(String opt, String longOpt, boolean hasArg, - String description) - { - addOption(new Option(opt, longOpt, hasArg, description)); - - return this; - } - - /** - * Adds an option instance - * - * @param opt the option that is to be added - * @return the resulting Options instance - */ - public Options addOption(Option opt) - { - String key = opt.getKey(); - - // add it to the long option list - if (opt.hasLongOpt()) - { - longOpts.put(opt.getLongOpt(), opt); - } - - // if the option is required add it to the required list - if (opt.isRequired() ) - { - if( requiredOpts.contains(key) ) { - requiredOpts.remove( requiredOpts.indexOf(key) ); - } - requiredOpts.add(key); - } - - shortOpts.put(key, opt); - - return this; - } - - /** - * Retrieve a read-only list of options in this set - * - * @return read-only Collection of {@link Option} objects in this descriptor - */ - public Collection getOptions() - { - return Collections.unmodifiableCollection(helpOptions()); - } - - /** - * Returns the Options for use by the HelpFormatter. - * - * @return the List of Options - */ - List helpOptions() - { - List opts = new ArrayList(shortOpts.values()); - - // now look through the long opts to see if there are any Long-opt - // only options - Iterator iter = longOpts.values().iterator(); - - while (iter.hasNext()) - { - Object item = iter.next(); - - if (!opts.contains(item)) - { - opts.add(item); - } - } - - return new ArrayList(opts); - } - - /** - * Returns the required options as a - * java.util.Collection. - * - * @return Collection of required options - */ - public List getRequiredOptions() - { - return requiredOpts; - } - - /** - * Retrieve the named {@link Option} - * - * @param opt short or long name of the {@link Option} - * @return the option represented by opt - */ - public Option getOption(String opt) - { - opt = Util.stripLeadingHyphens(opt); - - if (shortOpts.containsKey(opt)) - { - return (Option) shortOpts.get(opt); - } - - return (Option) longOpts.get(opt); - } - - /** - * Returns whether the named {@link Option} is a member - * of this {@link Options}. - * - * @param opt short or long name of the {@link Option} - * @return true if the named {@link Option} is a member - * of this {@link Options} - */ - public boolean hasOption(String opt) - { - opt = Util.stripLeadingHyphens(opt); - - return shortOpts.containsKey(opt) || longOpts.containsKey(opt); - } - - /** - * Returns the OptionGroup the opt - * belongs to. - * @param opt the option whose OptionGroup is being queried. - * - * @return the OptionGroup if opt is part - * of an OptionGroup, otherwise return null - */ - public OptionGroup getOptionGroup(Option opt) - { - return (OptionGroup) optionGroups.get(opt.getKey()); - } - - /** - * Dump state, suitable for debugging. - * - * @return Stringified form of this object - */ - public String toString() - { - StringBuffer buf = new StringBuffer(); - - buf.append("[ Options: [ short "); - buf.append(shortOpts.toString()); - buf.append(" ] [ long "); - buf.append(longOpts); - buf.append(" ]"); - - return buf.toString(); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/ParseException.java b/src/java/org/apache/commons/cli/ParseException.java deleted file mode 100644 index 9b0653679..000000000 --- a/src/java/org/apache/commons/cli/ParseException.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - *

Base for Exceptions thrown during parsing of a command-line.

- * - * @author bob mcwhirter (bob @ werken.com) - * @version $Revision$ - */ -public class ParseException extends Exception { - - /** - *

Construct a new ParseException - * with the specified detail message.

- * - * @param message the detail message - */ - public ParseException(String message) - { - super(message); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/Parser.java b/src/java/org/apache/commons/cli/Parser.java deleted file mode 100644 index 8eb336c49..000000000 --- a/src/java/org/apache/commons/cli/Parser.java +++ /dev/null @@ -1,406 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.Arrays; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Properties; - -/** - *

Parser creates {@link CommandLine}s.

- * - * @author John Keyes (john at integralsource.com) - * @see Parser - * @version $Revision$ - */ -public abstract class Parser implements CommandLineParser { - - /** commandline instance */ - private CommandLine cmd; - - /** current Options */ - private Options options; - - /** list of required options strings */ - private List requiredOptions; - - /** - *

Subclasses must implement this method to reduce - * the arguments that have been passed to the parse - * method.

- * - * @param opts The Options to parse the arguments by. - * @param arguments The arguments that have to be flattened. - * @param stopAtNonOption specifies whether to stop - * flattening when a non option has been encountered - * @return a String array of the flattened arguments - */ - protected abstract String[] flatten(Options opts, String[] arguments, - boolean stopAtNonOption); - - /** - *

Parses the specified arguments - * based on the specifed {@link Options}.

- * - * @param options the Options - * @param arguments the arguments - * @return the CommandLine - * @throws ParseException if an error occurs when parsing the - * arguments. - */ - public CommandLine parse(Options options, String[] arguments) - throws ParseException - { - return parse(options, arguments, null, false); - } - - /** - * Parse the arguments according to the specified options and - * properties. - * - * @param options the specified Options - * @param arguments the command line arguments - * @param properties command line option name-value pairs - * @return the list of atomic option and value tokens - * - * @throws ParseException if there are any problems encountered - * while parsing the command line tokens. - */ - public CommandLine parse(Options options, String[] arguments, - Properties properties) - throws ParseException - { - return parse(options, arguments, properties, false); - } - - /** - *

Parses the specified arguments - * based on the specifed {@link Options}.

- * - * @param options the Options - * @param arguments the arguments - * @param stopAtNonOption specifies whether to stop - * interpreting the arguments when a non option has - * been encountered and to add them to the CommandLines - * args list. - * - * @return the CommandLine - * @throws ParseException if an error occurs when parsing the - * arguments. - */ - public CommandLine parse(Options options, String[] arguments, - boolean stopAtNonOption) - throws ParseException - { - return parse(options, arguments, null, stopAtNonOption); - } - - /** - * Parse the arguments according to the specified options and - * properties. - * - * @param options the specified Options - * @param arguments the command line arguments - * @param properties command line option name-value pairs - * @param stopAtNonOption stop parsing the arguments when the first - * non option is encountered. - * - * @return the list of atomic option and value tokens - * - * @throws ParseException if there are any problems encountered - * while parsing the command line tokens. - */ - public CommandLine parse(Options options, String[] arguments, - Properties properties, boolean stopAtNonOption) - throws ParseException - { - // initialise members - this.options = options; - requiredOptions = options.getRequiredOptions(); - cmd = new CommandLine(); - - boolean eatTheRest = false; - - if (arguments == null) - { - arguments = new String[0]; - } - - List tokenList = Arrays.asList(flatten(this.options, - arguments, - stopAtNonOption)); - - ListIterator iterator = tokenList.listIterator(); - - // process each flattened token - while (iterator.hasNext()) - { - String t = (String) iterator.next(); - - // the value is the double-dash - if ("--".equals(t)) - { - eatTheRest = true; - } - - // the value is a single dash - else if ("-".equals(t)) - { - if (stopAtNonOption) - { - eatTheRest = true; - } - else - { - cmd.addArg(t); - } - } - - // the value is an option - else if (t.startsWith("-")) - { - if (stopAtNonOption && !options.hasOption(t)) - { - eatTheRest = true; - cmd.addArg(t); - } - else - { - processOption(t, iterator); - } - } - - // the value is an argument - else - { - cmd.addArg(t); - - if (stopAtNonOption) - { - eatTheRest = true; - } - } - - // eat the remaining tokens - if (eatTheRest) - { - while (iterator.hasNext()) - { - String str = (String) iterator.next(); - - // ensure only one double-dash is added - if (!"--".equals(str)) - { - cmd.addArg(str); - } - } - } - } - - processProperties(properties); - checkRequiredOptions(); - - return cmd; - } - - /** - *

Sets the values of Options using the values in - * properties.

- * - * @param properties The value properties to be processed. - */ - private void processProperties(Properties properties) - { - if (properties == null) - { - return; - } - - for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) - { - String option = e.nextElement().toString(); - - if (!cmd.hasOption(option)) - { - Option opt = options.getOption(option); - - // get the value from the properties instance - String value = properties.getProperty(option); - - if (opt.hasArg()) - { - if ((opt.getValues() == null) - || (opt.getValues().length == 0)) - { - try - { - opt.addValue(value); - } - catch (RuntimeException exp) - { - // if we cannot add the value don't worry about it - } - } - } - else if (!("yes".equalsIgnoreCase(value) - || "true".equalsIgnoreCase(value) - || "1".equalsIgnoreCase(value))) - { - // if the value is not yes, true or 1 then don't add the - // option to the CommandLine - break; - } - - cmd.addOption(opt); - } - } - } - - /** - *

Throws a {@link MissingOptionException} if all of the - * required options are no present.

- * - * @throws MissingOptionException if any of the required Options - * are not present. - */ - private void checkRequiredOptions() - throws MissingOptionException - { - // if there are required options that have not been - // processsed - if (requiredOptions.size() > 0) - { - Iterator iter = requiredOptions.iterator(); - StringBuffer buff = new StringBuffer(); - - // loop through the required options - while (iter.hasNext()) - { - buff.append(iter.next()); - } - - throw new MissingOptionException(buff.toString()); - } - } - - /** - *

Process the argument values for the specified Option - * opt using the values retrieved from the - * specified iterator iter. - * - * @param opt The current Option - * @param iter The iterator over the flattened command line - * Options. - * - * @throws ParseException if an argument value is required - * and it is has not been found. - */ - public void processArgs(Option opt, ListIterator iter) - throws ParseException - { - // loop until an option is found - while (iter.hasNext()) - { - String str = (String) iter.next(); - - // found an Option, not an argument - if (options.hasOption(str) && str.startsWith("-")) - { - iter.previous(); - break; - } - - // found a value - try - { - opt.addValue( Util.stripLeadingAndTrailingQuotes(str) ); - } - catch (RuntimeException exp) - { - iter.previous(); - break; - } - } - - if ((opt.getValues() == null) && !opt.hasOptionalArg()) - { - throw new MissingArgumentException("Missing argument for option:" - + opt.getKey()); - } - } - - /** - *

Process the Option specified by arg - * using the values retrieved from the specfied iterator - * iter. - * - * @param arg The String value representing an Option - * @param iter The iterator over the flattened command - * line arguments. - * - * @throws ParseException if arg does not - * represent an Option - */ - private void processOption(String arg, ListIterator iter) - throws ParseException - { - boolean hasOption = options.hasOption(arg); - - // if there is no option throw an UnrecognisedOptionException - if (!hasOption) - { - throw new UnrecognizedOptionException("Unrecognized option: " - + arg); - } - - // get the option represented by arg - final Option opt = options.getOption(arg); - - // if the option is a required option remove the option from - // the requiredOptions list - if (opt.isRequired()) - { - requiredOptions.remove(opt.getKey()); - } - - // if the option is in an OptionGroup make that option the selected - // option of the group - if (options.getOptionGroup(opt) != null) - { - OptionGroup group = options.getOptionGroup(opt); - - if (group.isRequired()) - { - requiredOptions.remove(group); - } - - group.setSelected(opt); - } - - // if the option takes an argument value - if (opt.hasArg()) - { - processArgs(opt, iter); - } - - - // set the option on the command line - cmd.addOption(opt); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/PatternOptionBuilder.java b/src/java/org/apache/commons/cli/PatternOptionBuilder.java deleted file mode 100644 index a359d6096..000000000 --- a/src/java/org/apache/commons/cli/PatternOptionBuilder.java +++ /dev/null @@ -1,211 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - *

- * Allows Options to be created from a single String. - * The pattern contains various single character flags and via - * an optional punctuation character, their expected type. - *

- * - * - * - * - * - * - * - * - *
a-a flag
b@-b [classname]
c>-c [filename]
d+-d [classname] (creates object via empty contructor)
e%-e [number] (creates Number instance)
f/-f [url]
- * - *

- * For example, the following allows command line flags of '-v -p string-value -f /dir/file'. - *

- * Options options = PatternOptionBuilder.parsePattern("vp:f/"); - * - *

- * TODO These need to break out to OptionType and also - * to be pluggable. - *

- * - * @author Henri Yandell (bayard @ generationjava.com) - * @version $Revision$ - */ -public class PatternOptionBuilder { - - /** String class */ - public static final Class STRING_VALUE = java.lang.String.class; - - /** Object class */ - public static final Class OBJECT_VALUE = java.lang.Object.class; - - /** Number class */ - public static final Class NUMBER_VALUE = java.lang.Number.class; - - /** Date class */ - public static final Class DATE_VALUE = java.util.Date.class; - - /** Class class */ - public static final Class CLASS_VALUE = java.lang.Class.class; - - /// can we do this one?? - // is meant to check that the file exists, else it errors. - // ie) it's for reading not writing. - - /** FileInputStream class */ - public static final Class EXISTING_FILE_VALUE = - java.io.FileInputStream.class; - - /** File class */ - public static final Class FILE_VALUE = java.io.File.class; - - /** File array class */ - public static final Class FILES_VALUE = java.io.File[].class; - - /** URL class */ - public static final Class URL_VALUE = java.net.URL.class; - - /** - *

Retrieve the class that ch represents.

- * - * @param ch the specified character - * @return The class that ch represents - */ - public static Object getValueClass(char ch) - { - if (ch == '@') - { - return PatternOptionBuilder.OBJECT_VALUE; - } - else if (ch == ':') - { - return PatternOptionBuilder.STRING_VALUE; - } - else if (ch == '%') - { - return PatternOptionBuilder.NUMBER_VALUE; - } - else if (ch == '+') - { - return PatternOptionBuilder.CLASS_VALUE; - } - else if (ch == '#') - { - return PatternOptionBuilder.DATE_VALUE; - } - else if (ch == '<') - { - return PatternOptionBuilder.EXISTING_FILE_VALUE; - } - else if (ch == '>') - { - return PatternOptionBuilder.FILE_VALUE; - } - else if (ch == '*') - { - return PatternOptionBuilder.FILES_VALUE; - } - else if (ch == '/') - { - return PatternOptionBuilder.URL_VALUE; - } - - return null; - } - - /** - *

Returns whether ch is a value code, i.e. - * whether it represents a class in a pattern.

- * - * @param ch the specified character - * @return true if ch is a value code, otherwise false. - */ - public static boolean isValueCode(char ch) - { - if ((ch != '@') && (ch != ':') && (ch != '%') && (ch != '+') - && (ch != '#') && (ch != '<') && (ch != '>') && (ch != '*') - && (ch != '/') && (ch != '!')) - { - return false; - } - - return true; - } - - /** - *

Returns the {@link Options} instance represented by - * pattern.

- * - * @param pattern the pattern string - * @return The {@link Options} instance - */ - public static Options parsePattern(String pattern) - { - int sz = pattern.length(); - - char opt = ' '; - char ch = ' '; - boolean required = false; - Object type = null; - - Options options = new Options(); - - for (int i = 0; i < sz; i++) - { - ch = pattern.charAt(i); - - // a value code comes after an option and specifies - // details about it - if (!isValueCode(ch)) - { - if (opt != ' ') - { - OptionBuilder.hasArg(type != null); - OptionBuilder.isRequired(required); - OptionBuilder.withType(type); - - // we have a previous one to deal with - options.addOption(OptionBuilder.create(opt)); - required = false; - type = null; - opt = ' '; - } - - opt = ch; - } - else if (ch == '!') - { - required = true; - } - else - { - type = getValueClass(ch); - } - } - - if (opt != ' ') - { - OptionBuilder.hasArg(type != null); - OptionBuilder.isRequired(required); - OptionBuilder.withType(type); - - // we have a final one to deal with - options.addOption(OptionBuilder.create(opt)); - } - - return options; - } -} diff --git a/src/java/org/apache/commons/cli/PosixParser.java b/src/java/org/apache/commons/cli/PosixParser.java deleted file mode 100644 index f3c9d0dfe..000000000 --- a/src/java/org/apache/commons/cli/PosixParser.java +++ /dev/null @@ -1,309 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; - -/** - * The class PosixParser provides an implementation of the - * {@link Parser#flatten(Options,String[],boolean) flatten} method. - * - * @author John Keyes (john at integralsource.com) - * @see Parser - * @version $Revision$ - */ -public class PosixParser extends Parser { - - /** holder for flattened tokens */ - private ArrayList tokens = new ArrayList(); - - /** specifies if bursting should continue */ - private boolean eatTheRest; - - /** holder for the current option */ - private Option currentOption; - - /** the command line Options */ - private Options options; - - /** - *

Resets the members to their original state i.e. remove - * all of tokens entries, set eatTheRest - * to false and set currentOption to null.

- */ - private void init() - { - eatTheRest = false; - tokens.clear(); - currentOption = null; - } - - /** - *

An implementation of {@link Parser}'s abstract - * {@link Parser#flatten(Options,String[],boolean) flatten} method.

- * - *

The following are the rules used by this flatten method. - *

    - *
  1. if stopAtNonOption is true then do not - * burst anymore of arguments entries, just add each - * successive entry without further processing. Otherwise, ignore - * stopAtNonOption.
  2. - *
  3. if the current arguments entry is "--" - * just add the entry to the list of processed tokens
  4. - *
  5. if the current arguments entry is "-" - * just add the entry to the list of processed tokens
  6. - *
  7. if the current arguments entry is two characters - * in length and the first character is "-" then check if this - * is a valid {@link Option} id. If it is a valid id, then add the - * entry to the list of processed tokens and set the current {@link Option} - * member. If it is not a valid id and stopAtNonOption - * is true, then the remaining entries are copied to the list of - * processed tokens. Otherwise, the current entry is ignored.
  8. - *
  9. if the current arguments entry is more than two - * characters in length and the first character is "-" then - * we need to burst the entry to determine its constituents. For more - * information on the bursting algorithm see - * {@link PosixParser#burstToken(String, boolean) burstToken}.
  10. - *
  11. if the current arguments entry is not handled - * by any of the previous rules, then the entry is added to the list - * of processed tokens.
  12. - *
- *

- * - * @param options The command line {@link Options} - * @param arguments The command line arguments to be parsed - * @param stopAtNonOption Specifies whether to stop flattening - * when an non option is found. - * @return The flattened arguments String array. - */ - protected String[] flatten(Options options, String[] arguments, - boolean stopAtNonOption) - { - init(); - this.options = options; - - // an iterator for the command line tokens - Iterator iter = Arrays.asList(arguments).iterator(); - String token = null; - - // process each command line token - while (iter.hasNext()) - { - // get the next command line token - token = (String) iter.next(); - - // handle SPECIAL TOKEN - if (token.startsWith("--")) - { - if (token.indexOf('=') != -1) - { - tokens.add(token.substring(0, token.indexOf('='))); - tokens.add(token.substring(token.indexOf('=') + 1, - token.length())); - } - else - { - tokens.add(token); - } - } - - // single hyphen - else if ("-".equals(token)) - { - processSingleHyphen(token); - } - else if (token.startsWith("-")) - { - int tokenLength = token.length(); - - if (tokenLength == 2) - { - processOptionToken(token, stopAtNonOption); - } - else if (options.hasOption(token)) { - tokens.add(token); - } - // requires bursting - else - { - burstToken(token, stopAtNonOption); - } - } - else - { - if (stopAtNonOption) - { - process(token); - } - else - { - tokens.add(token); - } - } - - gobble(iter); - } - - return (String[]) tokens.toArray(new String[] { }); - } - - /** - *

Adds the remaining tokens to the processed tokens list.

- * - * @param iter An iterator over the remaining tokens - */ - private void gobble(Iterator iter) - { - if (eatTheRest) - { - while (iter.hasNext()) - { - tokens.add(iter.next()); - } - } - } - - /** - *

If there is a current option and it can have an argument - * value then add the token to the processed tokens list and - * set the current option to null.

- *

If there is a current option and it can have argument - * values then add the token to the processed tokens list.

- *

If there is not a current option add the special token - * "--" and the current value to the processed - * tokens list. The add all the remaining argument - * values to the processed tokens list.

- * - * @param value The current token - */ - private void process(String value) - { - if ((currentOption != null) && currentOption.hasArg()) - { - if (currentOption.hasArg()) - { - tokens.add(value); - currentOption = null; - } - else if (currentOption.hasArgs()) - { - tokens.add(value); - } - } - else - { - eatTheRest = true; - tokens.add("--"); - tokens.add(value); - } - } - - /** - *

If it is a hyphen then add the hyphen directly to - * the processed tokens list.

- * - * @param hyphen The hyphen token - */ - private void processSingleHyphen(String hyphen) - { - tokens.add(hyphen); - } - - /** - *

If an {@link Option} exists for token then - * set the current option and add the token to the processed - * list.

- *

If an {@link Option} does not exist and stopAtNonOption - * is set then ignore the current token and add the remaining tokens - * to the processed tokens list directly.

- * - * @param token The current option token - * @param stopAtNonOption Specifies whether flattening should halt - * at the first non option. - */ - private void processOptionToken(String token, boolean stopAtNonOption) - { - if (this.options.hasOption(token)) - { - currentOption = this.options.getOption(token); - tokens.add(token); - } - else if (stopAtNonOption) - { - eatTheRest = true; - } - } - - /** - *

Breaks token into its constituent parts - * using the following algorithm. - *

- *

- * - * @param token The current token to be burst - * @param stopAtNonOption Specifies whether to stop processing - * at the first non-Option encountered. - */ - protected void burstToken(String token, boolean stopAtNonOption) - { - int tokenLength = token.length(); - - for (int i = 1; i < tokenLength; i++) - { - String ch = String.valueOf(token.charAt(i)); - boolean hasOption = options.hasOption(ch); - - if (hasOption) - { - tokens.add("-" + ch); - currentOption = options.getOption(ch); - - if (currentOption.hasArg() && (token.length() != (i + 1))) - { - tokens.add(token.substring(i + 1)); - - break; - } - } - else if (stopAtNonOption) - { - process(token.substring(i)); - } - else - { - tokens.add("-" + ch); - } - } - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/TypeHandler.java b/src/java/org/apache/commons/cli/TypeHandler.java deleted file mode 100644 index 84e48bbc8..000000000 --- a/src/java/org/apache/commons/cli/TypeHandler.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright 1999-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.io.File; - -import java.net.MalformedURLException; -import java.net.URL; - -import java.util.Date; - -import org.apache.commons.lang.math.NumberUtils; - -/** - * This is a temporary implementation. TypeHandler will handle the - * pluggableness of OptionTypes and it will direct all of these types - * of conversion functionalities to ConvertUtils component in Commons - * alreayd. BeanUtils I think. - * - * @author Henri Yandell (bayard @ generationjava.com) - * @version $Revision$ - */ -public class TypeHandler { - - /** - *

Returns the Object of type obj - * with the value of str.

- * - * @param str the command line value - * @param obj the type of argument - * @return The instance of obj initialised with - * the value of str. - */ - public static Object createValue(String str, Object obj) - { - return createValue(str, (Class) obj); - } - - /** - *

Returns the Object of type clazz - * with the value of str.

- * - * @param str the command line value - * @param clazz the type of argument - * @return The instance of clazz initialised with - * the value of str. - */ - public static Object createValue(String str, Class clazz) - { - if (PatternOptionBuilder.STRING_VALUE == clazz) - { - return str; - } - else if (PatternOptionBuilder.OBJECT_VALUE == clazz) - { - return createObject(str); - } - else if (PatternOptionBuilder.NUMBER_VALUE == clazz) - { - return createNumber(str); - } - else if (PatternOptionBuilder.DATE_VALUE == clazz) - { - return createDate(str); - } - else if (PatternOptionBuilder.CLASS_VALUE == clazz) - { - return createClass(str); - } - else if (PatternOptionBuilder.FILE_VALUE == clazz) - { - return createFile(str); - } - else if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz) - { - return createFile(str); - } - else if (PatternOptionBuilder.FILES_VALUE == clazz) - { - return createFiles(str); - } - else if (PatternOptionBuilder.URL_VALUE == clazz) - { - return createURL(str); - } - else - { - return null; - } - } - - /** - *

Create an Object from the classname and empty constructor.

- * - * @param str the argument value - * @return the initialised object, or null if it couldn't create - * the Object. - */ - public static Object createObject(String str) - { - Class cl = null; - - try - { - cl = Class.forName(str); - } - catch (ClassNotFoundException cnfe) - { - System.err.println("Unable to find: " + str); - - return null; - } - - Object instance = null; - - try - { - instance = cl.newInstance(); - } - catch (InstantiationException cnfe) - { - System.err.println("InstantiationException; Unable to create: " - + str); - - return null; - } - catch (IllegalAccessException cnfe) - { - System.err.println("IllegalAccessException; Unable to create: " - + str); - - return null; - } - - return instance; - } - - /** - *

Create a number from a String.

- * - * @param str the value - * @return the number represented by str, if str - * is not a number, null is returned. - */ - public static Number createNumber(String str) - { - // Needs to be able to create - try - { - // do searching for decimal point etc, but atm just make an Integer - return NumberUtils.createNumber(str); - } - catch (NumberFormatException nfe) - { - System.err.println(nfe.getMessage()); - - return null; - } - } - - /** - *

Returns the class whose name is str.

- * - * @param str the class name - * @return The class if it is found, otherwise return null - */ - public static Class createClass(String str) - { - try - { - return Class.forName(str); - } - catch (ClassNotFoundException cnfe) - { - System.err.println("Unable to find: " + str); - - return null; - } - } - - /** - *

Returns the date represented by str.

- * - * @param str the date string - * @return The date if str is a valid date string, - * otherwise return null. - */ - public static Date createDate(String str) - { - Date date = null; - - if (date == null) - { - System.err.println("Unable to parse: " + str); - } - - return date; - } - - /** - *

Returns the URL represented by str.

- * - * @param str the URL string - * @return The URL is str is well-formed, otherwise - * return null. - */ - public static URL createURL(String str) - { - try - { - return new URL(str); - } - catch (MalformedURLException mue) - { - System.err.println("Unable to parse: " + str); - - return null; - } - } - - /** - *

Returns the File represented by str.

- * - * @param str the File location - * @return The file represented by str. - */ - public static File createFile(String str) - { - return new File(str); - } - - /** - *

Returns the File[] represented by str.

- * - * @param str the paths to the files - * @return The File[] represented by str. - */ - public static File[] createFiles(String str) - { - // to implement/port: - // return FileW.findFiles(str); - return null; - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/UnrecognizedOptionException.java b/src/java/org/apache/commons/cli/UnrecognizedOptionException.java deleted file mode 100644 index b417c1953..000000000 --- a/src/java/org/apache/commons/cli/UnrecognizedOptionException.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - *

Exception thrown during parsing signalling an unrecognized - * option was seen.

- * - * @author bob mcwhiter (bob @ werken.com) - * @version $Revision$ - */ -public class UnrecognizedOptionException - extends ParseException { - - /** - *

Construct a new UnrecognizedArgumentException - * with the specified detail message.

- * - * @param message the detail message - */ - public UnrecognizedOptionException(String message) - { - super(message); - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/Util.java b/src/java/org/apache/commons/cli/Util.java deleted file mode 100644 index 86a231bb0..000000000 --- a/src/java/org/apache/commons/cli/Util.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright 1999-2001,2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - * Contains useful helper methods for classes within this package. - * - * @author John Keyes (john at integralsource.com) - */ -class Util { - - /** - *

Remove the hyphens from the begining of str and - * return the new String.

- * - * @param str The string from which the hyphens should be removed. - * - * @return the new String. - */ - static String stripLeadingHyphens(String str) - { - if (str.startsWith("--")) - { - return str.substring(2, str.length()); - } - else if (str.startsWith("-")) - { - return str.substring(1, str.length()); - } - - return str; - } - - /** - * Remove the leading and trailing quotes from str. - * E.g. if str is '"one two"', then 'one two' is returned. - * - * @param str The string from which the leading and trailing quotes - * should be removed. - * - * @return The string without the leading and trailing quotes. - */ - static String stripLeadingAndTrailingQuotes(String str) - { - if (str.startsWith("\"")) { - str = str.substring(1, str.length()); - } - if (str.endsWith("\"")) { - str = str.substring(0, str.length()-1); - } - return str; - } -} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli/overview.html b/src/java/org/apache/commons/cli/overview.html deleted file mode 100644 index eadba1e49..000000000 --- a/src/java/org/apache/commons/cli/overview.html +++ /dev/null @@ -1,28 +0,0 @@ - - - -

Commons CLI -- version ##VERSION## (##QUALITY##)

- -

The commons-cli package aides in parsing command-line arguments.

- -

Allow command-line arguments to be parsed against a descriptor of - valid options (long and short), potentially with arguments.

- -

command-line arguments may be of the typical String[] - form, but also may be a java.util.List. Indexes allow - for parsing only a portion of the command-line. Also, functionality - for parsing the command-line in phases is built in, allowing for - 'cvs-style' command-lines, where some global options are specified - before a 'command' argument, and command-specific options are - specified after the command argument: - - -

-		myApp -p <port> command -p <printer>
-	
- - - -

The homepage for the project is - jakarta commons/ - diff --git a/src/java/org/apache/commons/cli/package.html b/src/java/org/apache/commons/cli/package.html deleted file mode 100644 index 5bf206675..000000000 --- a/src/java/org/apache/commons/cli/package.html +++ /dev/null @@ -1,6 +0,0 @@ - - - - Commons CLI 1.0 - - diff --git a/src/test/org/apache/commons/cli/ApplicationTest.java b/src/test/org/apache/commons/cli/ApplicationTest.java deleted file mode 100644 index 99013b21d..000000000 --- a/src/test/org/apache/commons/cli/ApplicationTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - *

- * This is a collection of tests that test real world - * applications command lines. - *

- * - *

- * The following are the applications that are tested: - *

- *

- * - * @author John Keyes (john at integralsource.com) - */ -public class ApplicationTest extends TestCase { - - public static Test suite() { - return new TestSuite(ApplicationTest.class); - } - - public ApplicationTest(String name) - { - super(name); - } - - /** - * - */ - public void testLs() { - // create the command line parser - CommandLineParser parser = new PosixParser(); - Options options = new Options(); - options.addOption( "a", "all", false, "do not hide entries starting with ." ); - options.addOption( "A", "almost-all", false, "do not list implied . and .." ); - options.addOption( "b", "escape", false, "print octal escapes for nongraphic characters" ); - options.addOption( OptionBuilder.withLongOpt( "block-size" ) - .withDescription( "use SIZE-byte blocks" ) - .withValueSeparator( '=' ) - .hasArg() - .create() ); - options.addOption( "B", "ignore-backups", false, "do not list implied entried ending with ~"); - options.addOption( "c", false, "with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime" ); - options.addOption( "C", false, "list entries by columns" ); - - String[] args = new String[]{ "--block-size=10" }; - - try { - CommandLine line = parser.parse( options, args ); - assertTrue( line.hasOption( "block-size" ) ); - assertEquals( line.getOptionValue( "block-size" ), "10" ); - } - catch( ParseException exp ) { - fail( "Unexpected exception:" + exp.getMessage() ); - } - } - - /** - * Ant test - */ - public void testAnt() { - // use the GNU parser - CommandLineParser parser = new GnuParser( ); - Options options = new Options(); - options.addOption( "help", false, "print this message" ); - options.addOption( "projecthelp", false, "print project help information" ); - options.addOption( "version", false, "print the version information and exit" ); - options.addOption( "quiet", false, "be extra quiet" ); - options.addOption( "verbose", false, "be extra verbose" ); - options.addOption( "debug", false, "print debug information" ); - options.addOption( "version", false, "produce logging information without adornments" ); - options.addOption( "logfile", true, "use given file for log" ); - options.addOption( "logger", true, "the class which is to perform the logging" ); - options.addOption( "listener", true, "add an instance of a class as a project listener" ); - options.addOption( "buildfile", true, "use given buildfile" ); - options.addOption( OptionBuilder.withDescription( "use value for given property" ) - .hasArgs() - .withValueSeparator() - .create( 'D' ) ); - //, null, true, , false, true ); - options.addOption( "find", true, "search for buildfile towards the root of the filesystem and use it" ); - - String[] args = new String[]{ "-buildfile", "mybuild.xml", - "-Dproperty=value", "-Dproperty1=value1", - "-projecthelp" }; - - try { - CommandLine line = parser.parse( options, args ); - - // check multiple values - String[] opts = line.getOptionValues( "D" ); - assertEquals( "property", opts[0] ); - assertEquals( "value", opts[1] ); - assertEquals( "property1", opts[2] ); - assertEquals( "value1", opts[3] ); - - // check single value - assertEquals( line.getOptionValue( "buildfile"), "mybuild.xml" ); - - // check option - assertTrue( line.hasOption( "projecthelp") ); - } - catch( ParseException exp ) { - fail( "Unexpected exception:" + exp.getMessage() ); - } - - } - -} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli/ArgumentIsOptionTest.java b/src/test/org/apache/commons/cli/ArgumentIsOptionTest.java deleted file mode 100644 index 58c4a6b90..000000000 --- a/src/test/org/apache/commons/cli/ArgumentIsOptionTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - - -public class ArgumentIsOptionTest extends TestCase { - private Options options = null; - private CommandLineParser parser = null; - - public ArgumentIsOptionTest(String name) { - super(name); - } - - public static Test suite() { - return new TestSuite(ArgumentIsOptionTest.class); - } - - public void setUp() { - options = new Options().addOption("p", false, "Option p").addOption("attr", - true, "Option accepts argument"); - - parser = new PosixParser(); - } - - public void tearDown() { - } - - public void testOptionAndOptionWithArgument() { - String[] args = new String[] { - "-p", - "-attr", - "p" - }; - - try { - CommandLine cl = parser.parse(options, args); - assertTrue("Confirm -p is set", cl.hasOption("p")); - assertTrue("Confirm -attr is set", cl.hasOption("attr")); - assertTrue("Confirm arg of -attr", - cl.getOptionValue("attr").equals("p")); - assertTrue("Confirm all arguments recognized", cl.getArgs().length == 0); - } - catch (ParseException e) { - fail(e.toString()); - } - } - - public void testOptionWithArgument() { - String[] args = new String[] { - "-attr", - "p" - }; - - try { - CommandLine cl = parser.parse(options, args); - assertFalse("Confirm -p is set", cl.hasOption("p")); - assertTrue("Confirm -attr is set", cl.hasOption("attr")); - assertTrue("Confirm arg of -attr", - cl.getOptionValue("attr").equals("p")); - assertTrue("Confirm all arguments recognized", cl.getArgs().length == 0); - } - catch (ParseException e) { - fail(e.toString()); - } - } - - public void testOption() { - String[] args = new String[] { - "-p" - }; - - try { - CommandLine cl = parser.parse(options, args); - assertTrue("Confirm -p is set", cl.hasOption("p")); - assertFalse("Confirm -attr is not set", cl.hasOption("attr")); - assertTrue("Confirm all arguments recognized", cl.getArgs().length == 0); - } - catch (ParseException e) { - fail(e.toString()); - } - } -} diff --git a/src/test/org/apache/commons/cli/BugsTest.java b/src/test/org/apache/commons/cli/BugsTest.java deleted file mode 100644 index 17f7ca037..000000000 --- a/src/test/org/apache/commons/cli/BugsTest.java +++ /dev/null @@ -1,536 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Properties; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class BugsTest extends TestCase -{ - /** CommandLine instance */ - private CommandLine _cmdline = null; - private Option _option = null; - - public static Test suite() { - return new TestSuite( BugsTest.class ); - } - - public BugsTest( String name ) - { - super( name ); - } - - public void setUp() - { - } - - public void tearDown() - { - } - - public void test11457() { - Options options = new Options(); - options.addOption( OptionBuilder.withLongOpt( "verbose" ) - .create() ); - String[] args = new String[] { "--verbose" }; - - CommandLineParser parser = new PosixParser(); - - try { - CommandLine cmd = parser.parse( options, args ); - assertTrue( cmd.hasOption( "verbose" ) ); - } - catch( ParseException exp ) { - exp.printStackTrace(); - fail( "Unexpected Exception: " + exp.getMessage() ); - } - } - - public void test11458() - { - Options options = new Options(); - options.addOption( OptionBuilder.withValueSeparator( '=' ) - .hasArgs() - .create( 'D' ) ); - options.addOption( OptionBuilder.withValueSeparator( ':' ) - .hasArgs() - .create( 'p' ) ); - String[] args = new String[] { "-DJAVA_HOME=/opt/java" , - "-pfile1:file2:file3" }; - - CommandLineParser parser = new PosixParser(); - - try { - CommandLine cmd = parser.parse( options, args ); - - String[] values = cmd.getOptionValues( 'D' ); - - assertEquals( values[0], "JAVA_HOME" ); - assertEquals( values[1], "/opt/java" ); - - values = cmd.getOptionValues( 'p' ); - - assertEquals( values[0], "file1" ); - assertEquals( values[1], "file2" ); - assertEquals( values[2], "file3" ); - - java.util.Iterator iter = cmd.iterator(); - while( iter.hasNext() ) { - Option opt = (Option)iter.next(); - switch( opt.getId() ) { - case 'D': - assertEquals( opt.getValue( 0 ), "JAVA_HOME" ); - assertEquals( opt.getValue( 1 ), "/opt/java" ); - break; - case 'p': - assertEquals( opt.getValue( 0 ), "file1" ); - assertEquals( opt.getValue( 1 ), "file2" ); - assertEquals( opt.getValue( 2 ), "file3" ); - break; - default: - fail( "-D option not found" ); - } - } - } - catch( ParseException exp ) { - fail( "Unexpected Exception:\nMessage:" + exp.getMessage() - + "Type: " + exp.getClass().getName() ); - } - } - - public void test11680() - { - Options options = new Options(); - options.addOption("f", true, "foobar"); - options.addOption("m", true, "missing"); - String[] args = new String[] { "-f" , "foo" }; - - CommandLineParser parser = new PosixParser(); - - try { - CommandLine cmd = parser.parse( options, args ); - - try { - cmd.getOptionValue( "f", "default f"); - cmd.getOptionValue( "m", "default m"); - } - catch( NullPointerException exp ) { - fail( "NullPointer caught: " + exp.getMessage() ); - } - } - catch( ParseException exp ) { - fail( "Unexpected Exception: " + exp.getMessage() ); - } - } - - public void test11456() - { - // Posix - Options options = new Options(); - options.addOption( OptionBuilder.hasOptionalArg() - .create( 'a' ) ); - options.addOption( OptionBuilder.hasArg() - .create( 'b' ) ); - String[] args = new String[] { "-a", "-bvalue" }; - - CommandLineParser parser = new PosixParser(); - - try { - CommandLine cmd = parser.parse( options, args ); - assertEquals( cmd.getOptionValue( 'b' ), "value" ); - } - catch( ParseException exp ) { - fail( "Unexpected Exception: " + exp.getMessage() ); - } - - // GNU - options = new Options(); - options.addOption( OptionBuilder.hasOptionalArg() - .create( 'a' ) ); - options.addOption( OptionBuilder.hasArg() - .create( 'b' ) ); - args = new String[] { "-a", "-b", "value" }; - - parser = new GnuParser(); - - try { - CommandLine cmd = parser.parse( options, args ); - assertEquals( cmd.getOptionValue( 'b' ), "value" ); - } - catch( ParseException exp ) { - fail( "Unexpected Exception: " + exp.getMessage() ); - } - - } - - public void test12210() { - // create the main options object which will handle the first parameter - Options mainOptions = new Options(); - // There can be 2 main exclusive options: -exec|-rep - - // Therefore, place them in an option group - - String[] argv = new String[] { "-exec", "-exec_opt1", "-exec_opt2" }; - OptionGroup grp = new OptionGroup(); - - grp.addOption(new Option("exec",false,"description for this option")); - - grp.addOption(new Option("rep",false,"description for this option")); - - mainOptions.addOptionGroup(grp); - - // for the exec option, there are 2 options... - Options execOptions = new Options(); - execOptions.addOption("exec_opt1",false," desc"); - execOptions.addOption("exec_opt2",false," desc"); - - // similarly, for rep there are 2 options... - Options repOptions = new Options(); - repOptions.addOption("repopto",false,"desc"); - repOptions.addOption("repoptt",false,"desc"); - - // create the parser - GnuParser parser = new GnuParser(); - - // finally, parse the arguments: - - // first parse the main options to see what the user has specified - // We set stopAtNonOption to true so it does not touch the remaining - // options - try { - CommandLine cmd = parser.parse(mainOptions,argv,true); - // get the remaining options... - argv = cmd.getArgs(); - - if(cmd.hasOption("exec")){ - cmd = parser.parse(execOptions,argv,false); - // process the exec_op1 and exec_opt2... - assertTrue( cmd.hasOption("exec_opt1") ); - assertTrue( cmd.hasOption("exec_opt2") ); - } - else if(cmd.hasOption("rep")){ - cmd = parser.parse(repOptions,argv,false); - // process the rep_op1 and rep_opt2... - } - else { - fail( "exec option not found" ); - } - } - catch( ParseException exp ) { - fail( "Unexpected exception: " + exp.getMessage() ); - } - } - - public void test13425() { - Options options = new Options(); - Option oldpass = OptionBuilder.withLongOpt( "old-password" ) - .withDescription( "Use this option to specify the old password" ) - .hasArg() - .create( 'o' ); - Option newpass = OptionBuilder.withLongOpt( "new-password" ) - .withDescription( "Use this option to specify the new password" ) - .hasArg() - .create( 'n' ); - - String[] args = { - "-o", - "-n", - "newpassword" - }; - - options.addOption( oldpass ); - options.addOption( newpass ); - - Parser parser = new PosixParser(); - - try { - CommandLine line = parser.parse( options, args ); - } - // catch the exception and leave the method - catch( Exception exp ) { - assertTrue( exp != null ); - return; - } - fail( "MissingArgumentException not caught." ); - } - - public void test13666() { - Options options = new Options(); - Option dir = OptionBuilder.withDescription( "dir" ) - .hasArg() - .create( 'd' ); - options.addOption( dir ); - - - final PrintStream oldSystemOut = System.out; - try{ - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final PrintStream print = new PrintStream(bytes); - - // capture this platform's eol symbol - print.println(); - final String eol = bytes.toString(); - bytes.reset(); - - System.setOut(new PrintStream(bytes)); - try { - HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp( "dir", options ); - } - catch( Exception exp ) { - fail( "Unexpected Exception: " + exp.getMessage() ); - } - assertEquals("usage: dir"+eol+" -d dir"+eol,bytes.toString()); - } - finally { - System.setOut(oldSystemOut); - } - } - - public void test13935() { - OptionGroup directions = new OptionGroup(); - - Option left = new Option( "l", "left", false, "go left" ); - Option right = new Option( "r", "right", false, "go right" ); - Option straight = new Option( "s", "straight", false, "go straight" ); - Option forward = new Option( "f", "forward", false, "go forward" ); - forward.setRequired( true ); - - directions.addOption( left ); - directions.addOption( right ); - directions.setRequired( true ); - - Options opts = new Options(); - opts.addOptionGroup( directions ); - opts.addOption( straight ); - - CommandLineParser parser = new PosixParser(); - boolean exception = false; - - String[] args = new String[] { }; - try { - CommandLine line = parser.parse( opts, args ); - } - catch( ParseException exp ) { - exception = true; - } - - if( !exception ) { - fail( "Expected exception not caught."); - } - - exception = false; - - args = new String[] { "-s" }; - try { - CommandLine line = parser.parse( opts, args ); - } - catch( ParseException exp ) { - exception = true; - } - - if( !exception ) { - fail( "Expected exception not caught."); - } - - exception = false; - - args = new String[] { "-s", "-l" }; - try { - CommandLine line = parser.parse( opts, args ); - } - catch( ParseException exp ) { - fail( "Unexpected exception: " + exp.getClass().getName() + ":" + exp.getMessage() ); - } - - opts.addOption( forward ); - args = new String[] { "-s", "-l", "-f" }; - try { - CommandLine line = parser.parse( opts, args ); - } - catch( ParseException exp ) { - fail( "Unexpected exception: " + exp.getClass().getName() + ":" + exp.getMessage() ); - } - } - - public void test14786() throws Exception { - Option o = OptionBuilder.isRequired().withDescription("test").create("test"); - Options opts = new Options(); - opts.addOption(o); - opts.addOption(o); - - CommandLineParser parser = new GnuParser(); - - String[] args = new String[] { "-test" }; - - CommandLine line = parser.parse( opts, args ); - assertTrue( line.hasOption( "test" ) ); - } - - public void test15046() throws Exception { - CommandLineParser parser = new PosixParser(); - final String[] CLI_ARGS = new String[] {"-z", "c"}; - Option option = new Option("z", "timezone", true, - "affected option"); - Options cliOptions = new Options(); - cliOptions.addOption(option); - parser.parse(cliOptions, CLI_ARGS); - - //now add conflicting option - cliOptions.addOption("c", "conflict", true, "conflict option"); - CommandLine line = parser.parse(cliOptions, CLI_ARGS); - assertEquals( option.getValue(), "c" ); - assertTrue( !line.hasOption("c") ); - } - - public void test15648() throws Exception { - CommandLineParser parser = new PosixParser(); - final String[] args = new String[] { "-m", "\"Two Words\"" }; - Option m = OptionBuilder.hasArgs().create("m"); - Options options = new Options(); - options.addOption( m ); - CommandLine line = parser.parse( options, args ); - assertEquals( "Two Words", line.getOptionValue( "m" ) ); - } - - public void test27635() { - Option help = new Option("h", "help", false, "print this message"); - Option version = new Option("v", "version", false, "print version information"); - Option newRun = new Option("n", "new", false, "Create NLT cache entries only for new items"); - Option trackerRun = new Option("t", "tracker", false, "Create NLT cache entries only for tracker items"); - - Option timeLimit = OptionBuilder.withLongOpt("limit") - .hasArg() - .withValueSeparator() - .withDescription("Set time limit for execution, in mintues") - .create("l"); - - Option age = OptionBuilder.withLongOpt("age") - .hasArg() - .withValueSeparator() - .withDescription("Age (in days) of cache item before being recomputed") - .create("a"); - - Option server = OptionBuilder.withLongOpt("server") - .hasArg() - .withValueSeparator() - .withDescription("The NLT server address") - .create("s"); - - Option numResults = OptionBuilder.withLongOpt("results") - .hasArg() - .withValueSeparator() - .withDescription("Number of results per item") - .create("r"); - - Option configFile = OptionBuilder.withLongOpt("config") - .hasArg() - .withValueSeparator() - .withDescription("Use the specified configuration file") - .create(); - - Options mOptions = new Options(); - mOptions.addOption(help); - mOptions.addOption(version); - mOptions.addOption(newRun); - mOptions.addOption(trackerRun); - mOptions.addOption(timeLimit); - mOptions.addOption(age); - mOptions.addOption(server); - mOptions.addOption(numResults); - mOptions.addOption(configFile); - - HelpFormatter formatter = new HelpFormatter(); - final String EOL = System.getProperty("line.separator"); - StringWriter out = new StringWriter(); - formatter.printHelp(new PrintWriter(out),80,"commandline","header",mOptions,2,2,"footer",true); - assertEquals( - "usage: commandline [--config ] [-r ] [-a ] [-h] [-t] [-n] [-l"+EOL+ - " ] [-s ] [-v]"+EOL+ - "header"+EOL+ - " -a,--age Age (in days) of cache item before being recomputed"+EOL+ - " --config Use the specified configuration file"+EOL+ - " -h,--help print this message"+EOL+ - " -l,--limit Set time limit for execution, in mintues"+EOL+ - " -n,--new Create NLT cache entries only for new items"+EOL+ - " -r,--results Number of results per item"+EOL+ - " -s,--server The NLT server address"+EOL+ - " -t,--tracker Create NLT cache entries only for tracker items"+EOL+ - " -v,--version print version information"+EOL+ - "footer"+EOL - ,out.toString()); - } - - public void test31148() throws ParseException { - Option multiArgOption = new Option("o","option with multiple args"); - multiArgOption.setArgs(1); - - Options options = new Options(); - options.addOption(multiArgOption); - - Parser parser = new PosixParser(); - String[] args = new String[]{}; - Properties props = new Properties(); - props.setProperty("o","ovalue"); - CommandLine cl = parser.parse(options,args,props); - - assertTrue(cl.hasOption('o')); - assertEquals("ovalue",cl.getOptionValue('o')); - } - - public void test21215() { - Options options = new Options(); - HelpFormatter formatter = new HelpFormatter(); - String SEP = System.getProperty("line.separator"); - String header = SEP+"Header"; - String footer = "Footer"; - StringWriter out = new StringWriter(); - formatter.printHelp(new PrintWriter(out),80, "foobar", header, options, 2, 2, footer, true); - assertEquals( - "usage: foobar"+SEP+ - ""+SEP+ - "Header"+SEP+ - ""+SEP+ - "Footer"+SEP - ,out.toString()); - } - - public void test19383() { - Options options = new Options(); - options.addOption(new Option("a","aaa",false,"aaaaaaa")); - options.addOption(new Option(null,"bbb",false,"bbbbbbb")); - options.addOption(new Option("c",null,false,"ccccccc")); - - HelpFormatter formatter = new HelpFormatter(); - String SEP = System.getProperty("line.separator"); - StringWriter out = new StringWriter(); - formatter.printHelp(new PrintWriter(out),80, "foobar", "", options, 2, 2, "", true); - assertEquals( - "usage: foobar [-a] [-c] [--bbb]"+SEP+ - " -a,--aaa aaaaaaa"+SEP+ - " --bbb bbbbbbb"+SEP+ - " -c ccccccc"+SEP - ,out.toString()); - } - -} diff --git a/src/test/org/apache/commons/cli/BuildTest.java b/src/test/org/apache/commons/cli/BuildTest.java deleted file mode 100644 index 7e7289723..000000000 --- a/src/test/org/apache/commons/cli/BuildTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class BuildTest extends TestCase -{ - - public static Test suite() { - return new TestSuite(BuildTest.class); - } - - public BuildTest(String name) - { - super(name); - } - - public void setUp() - { - - } - - public void tearDown() - { - - } - - public void testSimple() - { - Options opts = new Options(); - - opts.addOption("a", - false, - "toggle -a"); - - opts.addOption("b", - true, - "toggle -b"); - } - - public void testDuplicateSimple() - { - Options opts = new Options(); - opts.addOption("a", - false, - "toggle -a"); - - opts.addOption("a", - true, - "toggle -a*"); - - assertEquals( "last one in wins", "toggle -a*", opts.getOption("a").getDescription() ); - } - - public void testLong() - { - Options opts = new Options(); - - opts.addOption("a", - "--a", - false, - "toggle -a"); - - opts.addOption("b", - "--b", - true, - "set -b"); - - } - - public void testDuplicateLong() - { - Options opts = new Options(); - opts.addOption("a", - "--a", - false, - "toggle -a"); - - opts.addOption("a", - "--a", - false, - "toggle -a*"); - assertEquals( "last one in wins", "toggle -a*", opts.getOption("a").getDescription() ); - } -} diff --git a/src/test/org/apache/commons/cli/CLI2ConverterTest.java b/src/test/org/apache/commons/cli/CLI2ConverterTest.java deleted file mode 100644 index 038023fee..000000000 --- a/src/test/org/apache/commons/cli/CLI2ConverterTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.builder.PatternBuilder; -import org.apache.commons.cli2.option.GroupImpl; - -import junit.framework.TestCase; - -public class CLI2ConverterTest extends TestCase { - - private Options aceOptions; - private OptionGroup aceOptionGroup; - private Options abcdeOptions; - private Options pattern; - - private Option a; - private Option bbb; - private Option c; - private Option ddd; - private Option e; - private Option f; - private Option g; - private Option h; - private Option i; - - public void setUp(){ - a = OptionBuilder.withDescription("A description").create('a'); - bbb = OptionBuilder.create("bbb"); - c = OptionBuilder.withLongOpt("ccc").create('c'); - ddd = OptionBuilder.withLongOpt("ddd").create(); - e = OptionBuilder.isRequired(true).create("e"); - f = OptionBuilder.hasArg().withArgName("argument").create('f'); - g = OptionBuilder.hasArgs(5).create('g'); - h = OptionBuilder.hasOptionalArg().create('h'); - i = OptionBuilder.hasOptionalArgs(5).create('i'); - - aceOptions = new Options(); - aceOptions.addOption(OptionBuilder.create('a')); - aceOptions.addOption(OptionBuilder.create('c')); - aceOptions.addOption(OptionBuilder.create('e')); - - aceOptionGroup = new OptionGroup(); - aceOptionGroup.addOption(OptionBuilder.create('a')); - aceOptionGroup.addOption(OptionBuilder.create('c')); - aceOptionGroup.addOption(OptionBuilder.create('e')); - - abcdeOptions = new Options(); - abcdeOptions.addOption(OptionBuilder.create('d')); - OptionGroup og = new OptionGroup(); - og.addOption(OptionBuilder.create('a')); - og.addOption(OptionBuilder.create('c')); - og.addOption(OptionBuilder.create('e')); - abcdeOptions.addOptionGroup(og); - abcdeOptions.addOption(OptionBuilder.create('b')); - - pattern = PatternOptionBuilder.parsePattern("a%ce:"); - } - - /* - * Class to test for Option option(Option) - */ - public void testOption() { - assertTrue(e.isRequired()); - - assertEquals("A description",a.getDescription()); - assertEquals('a',a.getId()); - assertEquals("[-a]",CLI2Converter.option(a).toString()); - assertEquals("[-bbb]",CLI2Converter.option(bbb).toString()); - assertEquals("[-c (--ccc)]",CLI2Converter.option(c).toString()); - assertEquals("[--ddd]",CLI2Converter.option(ddd).toString()); - assertEquals("-e",CLI2Converter.option(e).toString()); - assertEquals("[-f ]",CLI2Converter.option(f).toString()); - assertEquals("[-g ]",CLI2Converter.option(g).toString()); - assertEquals("[-h []]",CLI2Converter.option(h).toString()); - assertEquals("[-i [ [ [ [ []]]]]]",CLI2Converter.option(i).toString()); - } - /* - * Class to test for Group group(OptionGroup) - */ - public void testGroupOptionGroup() { - GroupImpl group; - - group = (GroupImpl)CLI2Converter.group(aceOptionGroup); - assertEquals("[-a|-c|-e]",group.toString()); - assertEquals(0,group.getMinimum()); - assertEquals(1,group.getMaximum()); - - aceOptionGroup.setRequired(true); - group = (GroupImpl)CLI2Converter.group(aceOptionGroup); - assertEquals("-a|-c|-e",group.toString()); - assertEquals(1,group.getMinimum()); - assertEquals(1,group.getMaximum()); - } - /* - * Class to test for Group group(Options) - */ - public void testGroupOptions() { - - GroupImpl group; - - group = (GroupImpl)CLI2Converter.group(aceOptions); - assertEquals("[-a|-c|-e]",group.toString()); - assertEquals(0,group.getMinimum()); - assertEquals(Integer.MAX_VALUE,group.getMaximum()); - - group = (GroupImpl)CLI2Converter.group(abcdeOptions); - - assertEquals("[-a|-c|-e|-d|-b]",group.toString()); - assertEquals(0,group.getMinimum()); - assertEquals(Integer.MAX_VALUE,group.getMaximum()); - - group = (GroupImpl)CLI2Converter.group(pattern); - assertEquals("[-a |-c|-e ]",group.toString()); - assertEquals(0,group.getMinimum()); - assertEquals(Integer.MAX_VALUE,group.getMaximum()); - } -} diff --git a/src/test/org/apache/commons/cli/GnuParseTest.java b/src/test/org/apache/commons/cli/GnuParseTest.java deleted file mode 100644 index 3a460d167..000000000 --- a/src/test/org/apache/commons/cli/GnuParseTest.java +++ /dev/null @@ -1,269 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class GnuParseTest extends TestCase -{ - private Options _options = null; - private CommandLineParser _parser = null; - - public static Test suite() { - return new TestSuite( GnuParseTest.class ); - } - - public GnuParseTest( String name ) - { - super( name ); - } - - public void setUp() - { - _options = new Options() - .addOption("a", - "enable-a", - false, - "turn [a] on or off") - .addOption("b", - "bfile", - true, - "set the value of [b]") - .addOption("c", - "copt", - false, - "turn [c] on or off"); - - _parser = new GnuParser( ); - } - - public void tearDown() - { - - } - - public void testSimpleShort() - { - String[] args = new String[] { "-a", - "-b", "toast", - "foo", "bar" }; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testSimpleLong() - { - String[] args = new String[] { "--enable-a", - "--bfile", "toast", - "foo", "bar" }; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testExtraOption() - { - String[] args = new String[] { "-a", "-d", "-b", "toast", - "foo", "bar" }; - - boolean caught = false; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm size of extra args", cl.getArgList().size() == 3); - } - catch (UnrecognizedOptionException e) - { - caught = true; - } - catch (ParseException e) - { - fail( e.toString() ); - } - assertTrue( "Confirm UnrecognizedOptionException caught", caught ); - } - - public void testMissingArg() - { - - String[] args = new String[] { "-b" }; - - boolean caught = false; - - try - { - CommandLine cl = _parser.parse(_options, args); - } - catch (MissingArgumentException e) - { - caught = true; - } - catch (ParseException e) - { - fail( e.toString() ); - } - - assertTrue( "Confirm MissingArgumentException caught", caught ); - } - - public void testStop() - { - String[] args = new String[] { "-c", - "foober", - "-b", - "toast" }; - - try - { - CommandLine cl = _parser.parse(_options, args, true); - assertTrue( "Confirm -c is set", cl.hasOption("c") ); - assertTrue( "Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testMultiple() - { - String[] args = new String[] { "-c", - "foobar", - "-b", - "toast" }; - - try - { - CommandLine cl = _parser.parse(_options, args, true); - assertTrue( "Confirm -c is set", cl.hasOption("c") ); - assertTrue( "Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); - - cl = _parser.parse(_options, cl.getArgs() ); - - assertTrue( "Confirm -c is not set", ! cl.hasOption("c") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); - assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") ); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testMultipleWithLong() - { - String[] args = new String[] { "--copt", - "foobar", - "--bfile", "toast" }; - - try - { - CommandLine cl = _parser.parse(_options,args, - true); - assertTrue( "Confirm -c is set", cl.hasOption("c") ); - assertTrue( "Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); - - cl = _parser.parse(_options, cl.getArgs() ); - - assertTrue( "Confirm -c is not set", ! cl.hasOption("c") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); - assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") ); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testDoubleDash() - { - String[] args = new String[] { "--copt", - "--", - "-b", "toast" }; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -c is set", cl.hasOption("c") ); - assertTrue( "Confirm -b is not set", ! cl.hasOption("b") ); - assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); - - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testSingleDash() - { - String[] args = new String[] { "--copt", - "-b", "-", - "-a", - "-" }; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("-") ); - assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); - assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("-") ); - } - catch (ParseException e) - { - fail( e.toString() ); - } - - } -} diff --git a/src/test/org/apache/commons/cli/HelpFormatterExamples.java b/src/test/org/apache/commons/cli/HelpFormatterExamples.java deleted file mode 100644 index 722e47496..000000000 --- a/src/test/org/apache/commons/cli/HelpFormatterExamples.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -/** - * A sample program shpwing the use of Options and the HelpFormatter class - * - * @author Slawek Zachcial - **/ -public class HelpFormatterExamples -{ - // --------------------------------------------------------------- Constants - - // ------------------------------------------------------------------ Static - - public static void main( String[] args ) - { - System.out.println("\n#\n# 'man' example\n#"); - manExample(); -/* - System.out.println("\n#\n# 'bzip2' example\n#"); - bzip2Example(); - System.out.println("\n#\n# 'ls' example\n#"); - lsExample(); -*/ - } - - static void manExample() - { - String cmdLine = - "man [-c|-f|-k|-w|-tZT device] [-adlhu7V] [-Mpath] [-Ppager] [-Slist] " + - "[-msystem] [-pstring] [-Llocale] [-eextension] [section] page ..."; - Options opts = - new Options(). - addOption("a", "all", false, "find all matching manual pages."). - addOption("d", "debug", false, "emit debugging messages."). - addOption("e", "extension", false, "limit search to extension type 'extension'."). - addOption("f", "whatis", false, "equivalent to whatis."). - addOption("k", "apropos", false, "equivalent to apropos."). - addOption("w", "location", false, "print physical location of man page(s)."). - addOption("l", "local-file", false, "interpret 'page' argument(s) as local filename(s)"). - addOption("u", "update", false, "force a cache consistency check."). - //FIXME - should generate -r,--prompt string - addOption("r", "prompt", true, "provide 'less' pager with prompt."). - addOption("c", "catman", false, "used by catman to reformat out of date cat pages."). - addOption("7", "ascii", false, "display ASCII translation or certain latin1 chars."). - addOption("t", "troff", false, "use troff format pages."). - //FIXME - should generate -T,--troff-device device - addOption("T", "troff-device", true, "use groff with selected device."). - addOption("Z", "ditroff", false, "use groff with selected device."). - addOption("D", "default", false, "reset all options to their default values."). - //FIXME - should generate -M,--manpath path - addOption("M", "manpath", true, "set search path for manual pages to 'path'."). - //FIXME - should generate -P,--pager pager - addOption("P", "pager", true, "use program 'pager' to display output."). - //FIXME - should generate -S,--sections list - addOption("S", "sections", true, "use colon separated section list."). - //FIXME - should generate -m,--systems system - addOption("m", "systems", true, "search for man pages from other unix system(s)."). - //FIXME - should generate -L,--locale locale - addOption("L", "locale", true, "defaine the locale for this particular man search."). - //FIXME - should generate -p,--preprocessor string - addOption("p", "preprocessor", true, "string indicates which preprocessor to run.\n" + - " e - [n]eqn p - pic t - tbl\n" + - " g - grap r - refer v - vgrind"). - addOption("V", "version", false, "show version."). - addOption("h", "help", false, "show this usage message."); - - HelpFormatter hf = new HelpFormatter(); - //hf.printHelp(cmdLine, opts); - hf.printHelp(60, cmdLine, null, opts, null); - } - - static void bzip2Example() - { - System.out.println( "Coming soon" ); - } - - static void lsExample() - { - System.out.println( "Coming soon" ); - } - - - // -------------------------------------------------------------- Attributes - - // ------------------------------------------------------------ Constructors - - // ------------------------------------------------------------------ Public - - // --------------------------------------------------------------- Protected - - // ------------------------------------------------------- Package protected - - // ----------------------------------------------------------------- Private - - // ----------------------------------------------------------- Inner classes - -} diff --git a/src/test/org/apache/commons/cli/LongOptionWithShort.java b/src/test/org/apache/commons/cli/LongOptionWithShort.java deleted file mode 100644 index c947f4b64..000000000 --- a/src/test/org/apache/commons/cli/LongOptionWithShort.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - - -/** - *

- * This is a collection of tests that test real world - * applications command lines focusing on options with - * long and short names. - *

- */ -public class LongOptionWithShort extends TestCase { - public LongOptionWithShort(String name) { - super(name); - } - - public static Test suite() { - return new TestSuite(LongOptionWithShort.class); - } - - /** - * - */ - public void testLongOptionWithShort() { - Option help = new Option("h", "help", false, "print this message"); - Option version = new Option("v", "version", false, - "print version information"); - Option newRun = new Option("n", "new", false, - "Create NLT cache entries only for new items"); - Option trackerRun = new Option("t", "tracker", false, - "Create NLT cache entries only for tracker items"); - - Option timeLimit = OptionBuilder.withLongOpt("limit").hasArg() - .withValueSeparator() - .withDescription("Set time limit for execution, in mintues") - .create("l"); - - Option age = OptionBuilder.withLongOpt("age").hasArg() - .withValueSeparator() - .withDescription("Age (in days) of cache item before being recomputed") - .create("a"); - - Option server = OptionBuilder.withLongOpt("server").hasArg() - .withValueSeparator() - .withDescription("The NLT server address") - .create("s"); - - Option numResults = OptionBuilder.withLongOpt("results").hasArg() - .withValueSeparator() - .withDescription("Number of results per item") - .create("r"); - - Option configFile = OptionBuilder.withLongOpt("file").hasArg() - .withValueSeparator() - .withDescription("Use the specified configuration file") - .create(); - - Options options = new Options(); - options.addOption(help); - options.addOption(version); - options.addOption(newRun); - options.addOption(trackerRun); - options.addOption(timeLimit); - options.addOption(age); - options.addOption(server); - options.addOption(numResults); - options.addOption(configFile); - - // create the command line parser - CommandLineParser parser = new PosixParser(); - - String[] args = new String[] { - "-v", - "-l", - "10", - "-age", - "5", - "-file", - "filename" - }; - - try { - CommandLine line = parser.parse(options, args); - assertTrue(line.hasOption("v")); - assertEquals(line.getOptionValue("l"), "10"); - assertEquals(line.getOptionValue("limit"), "10"); - assertEquals(line.getOptionValue("a"), "5"); - assertEquals(line.getOptionValue("age"), "5"); - assertEquals(line.getOptionValue("file"), "filename"); - } - catch (ParseException exp) { - fail("Unexpected exception:" + exp.getMessage()); - } - } -} diff --git a/src/test/org/apache/commons/cli/OptionBuilderTest.java b/src/test/org/apache/commons/cli/OptionBuilderTest.java deleted file mode 100644 index e1f3083f9..000000000 --- a/src/test/org/apache/commons/cli/OptionBuilderTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import junit.textui.TestRunner; - -public class OptionBuilderTest extends TestCase { - - public OptionBuilderTest( String name ) { - super( name ); - } - - public static Test suite() { - return new TestSuite( OptionBuilderTest.class ); - } - - public static void main( String args[] ) { - TestRunner.run( suite() ); - } - - public void testCompleteOption( ) { - Option simple = OptionBuilder.withLongOpt( "simple option") - .hasArg( ) - .isRequired( ) - .hasArgs( ) - .withType( new Float( 10 ) ) - .withDescription( "this is a simple option" ) - .create( 's' ); - - assertEquals( "s", simple.getOpt() ); - assertEquals( "simple option", simple.getLongOpt() ); - assertEquals( "this is a simple option", simple.getDescription() ); - assertEquals( simple.getType().getClass(), Float.class ); - assertTrue( simple.hasArg() ); - assertTrue( simple.isRequired() ); - assertTrue( simple.hasArgs() ); - } - - public void testTwoCompleteOptions( ) { - Option simple = OptionBuilder.withLongOpt( "simple option") - .hasArg( ) - .isRequired( ) - .hasArgs( ) - .withType( new Float( 10 ) ) - .withDescription( "this is a simple option" ) - .create( 's' ); - - assertEquals( "s", simple.getOpt() ); - assertEquals( "simple option", simple.getLongOpt() ); - assertEquals( "this is a simple option", simple.getDescription() ); - assertEquals( simple.getType().getClass(), Float.class ); - assertTrue( simple.hasArg() ); - assertTrue( simple.isRequired() ); - assertTrue( simple.hasArgs() ); - - simple = OptionBuilder.withLongOpt( "dimple option") - .hasArg( ) - .withDescription( "this is a dimple option" ) - .create( 'd' ); - - assertEquals( "d", simple.getOpt() ); - assertEquals( "dimple option", simple.getLongOpt() ); - assertEquals( "this is a dimple option", simple.getDescription() ); - assertNull( simple.getType() ); - assertTrue( simple.hasArg() ); - assertTrue( !simple.isRequired() ); - assertTrue( !simple.hasArgs() ); - } - - public void testBaseOptionCharOpt() { - Option base = OptionBuilder.withDescription( "option description") - .create( 'o' ); - - assertEquals( "o", base.getOpt() ); - assertEquals( "option description", base.getDescription() ); - assertTrue( !base.hasArg() ); - } - - public void testBaseOptionStringOpt() { - Option base = OptionBuilder.withDescription( "option description") - .create( "o" ); - - assertEquals( "o", base.getOpt() ); - assertEquals( "option description", base.getDescription() ); - assertTrue( !base.hasArg() ); - } - - public void testSpecialOptChars() { - - // '?' - try { - Option opt = OptionBuilder.withDescription( "help options" ) - .create( '?' ); - assertEquals( "?", opt.getOpt() ); - } - catch( IllegalArgumentException arg ) { - fail( "IllegalArgumentException caught" ); - } - - // '@' - try { - Option opt = OptionBuilder.withDescription( "read from stdin" ) - .create( '@' ); - assertEquals( "@", opt.getOpt() ); - } - catch( IllegalArgumentException arg ) { - fail( "IllegalArgumentException caught" ); - } - } - - public void testOptionArgNumbers() { - Option opt = OptionBuilder.withDescription( "option description" ) - .hasArgs( 2 ) - .create( 'o' ); - assertEquals( 2, opt.getArgs() ); - } - - public void testIllegalOptions() { - // bad single character option - try { - Option opt = OptionBuilder.withDescription( "option description" ) - .create( '"' ); - fail( "IllegalArgumentException not caught" ); - } - catch( IllegalArgumentException exp ) { - // success - } - - // bad character in option string - try { - Option opt = OptionBuilder.create( "opt`" ); - fail( "IllegalArgumentException not caught" ); - } - catch( IllegalArgumentException exp ) { - // success - } - - // valid option - try { - Option opt = OptionBuilder.create( "opt" ); - // success - } - catch( IllegalArgumentException exp ) { - fail( "IllegalArgumentException caught" ); - } - } -} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli/OptionGroupTest.java b/src/test/org/apache/commons/cli/OptionGroupTest.java deleted file mode 100644 index 8d66b1d70..000000000 --- a/src/test/org/apache/commons/cli/OptionGroupTest.java +++ /dev/null @@ -1,280 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * @author John Keyes (john at integralsource.com) - * @version $Revision$ - */ -public class OptionGroupTest extends TestCase -{ - - private Options _options = null; - private CommandLineParser parser = new PosixParser(); - - - public static Test suite() - { - return new TestSuite ( OptionGroupTest.class ); - } - - public OptionGroupTest( String name ) - { - super( name ); - } - - public void setUp() - { - Option file = new Option( "f", "file", false, "file to process" ); - Option dir = new Option( "d", "directory", false, "directory to process" ); - OptionGroup group = new OptionGroup(); - group.addOption( file ); - group.addOption( dir ); - _options = new Options().addOptionGroup( group ); - - Option section = new Option( "s", "section", false, "section to process" ); - Option chapter = new Option( "c", "chapter", false, "chapter to process" ); - OptionGroup group2 = new OptionGroup(); - group2.addOption( section ); - group2.addOption( chapter ); - - _options.addOptionGroup( group2 ); - - Option importOpt = new Option( null, "import", false, "section to process" ); - Option exportOpt = new Option( null, "export", false, "chapter to process" ); - OptionGroup group3 = new OptionGroup(); - group3.addOption( importOpt ); - group3.addOption( exportOpt ); - _options.addOptionGroup( group3 ); - - _options.addOption( "r", "revision", false, "revision number" ); - } - - public void tearDown() - { - } - - public void testSingleOptionFromGroup() - { - String[] args = new String[] { "-f" }; - - try - { - CommandLine cl = parser.parse( _options, args); - - assertTrue( "Confirm -r is NOT set", !cl.hasOption("r") ); - assertTrue( "Confirm -f is set", cl.hasOption("f") ); - assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); - assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); - assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); - assertTrue( "Confirm no extra args", cl.getArgList().size() == 0); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testSingleOption() - { - String[] args = new String[] { "-r" }; - - try - { - CommandLine cl = parser.parse( _options, args); - - assertTrue( "Confirm -r is set", cl.hasOption("r") ); - assertTrue( "Confirm -f is NOT set", !cl.hasOption("f") ); - assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); - assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); - assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); - assertTrue( "Confirm no extra args", cl.getArgList().size() == 0); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testTwoValidOptions() - { - String[] args = new String[] { "-r", "-f" }; - - try - { - CommandLine cl = parser.parse( _options, args); - - assertTrue( "Confirm -r is set", cl.hasOption("r") ); - assertTrue( "Confirm -f is set", cl.hasOption("f") ); - assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); - assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); - assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); - assertTrue( "Confirm no extra args", cl.getArgList().size() == 0); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testSingleLongOption() - { - String[] args = new String[] { "--file" }; - - try - { - CommandLine cl = parser.parse( _options, args); - - assertTrue( "Confirm -r is NOT set", !cl.hasOption("r") ); - assertTrue( "Confirm -f is set", cl.hasOption("f") ); - assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); - assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); - assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); - assertTrue( "Confirm no extra args", cl.getArgList().size() == 0); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testTwoValidLongOptions() - { - String[] args = new String[] { "--revision", "--file" }; - - try - { - CommandLine cl = parser.parse( _options, args); - - assertTrue( "Confirm -r is set", cl.hasOption("r") ); - assertTrue( "Confirm -f is set", cl.hasOption("f") ); - assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); - assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); - assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); - assertTrue( "Confirm no extra args", cl.getArgList().size() == 0); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testNoOptionsExtraArgs() - { - String[] args = new String[] { "arg1", "arg2" }; - - try - { - CommandLine cl = parser.parse( _options, args); - - assertTrue( "Confirm -r is NOT set", !cl.hasOption("r") ); - assertTrue( "Confirm -f is NOT set", !cl.hasOption("f") ); - assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); - assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); - assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); - assertTrue( "Confirm TWO extra args", cl.getArgList().size() == 2); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testTwoOptionsFromGroup() - { - String[] args = new String[] { "-f", "-d" }; - - try - { - CommandLine cl = parser.parse( _options, args); - fail( "two arguments from group not allowed" ); - } - catch (ParseException e) - { - if( !( e instanceof AlreadySelectedException ) ) - { - fail( "incorrect exception caught:" + e.getMessage() ); - } - } - } - - public void testTwoLongOptionsFromGroup() - { - String[] args = new String[] { "--file", "--directory" }; - - try - { - CommandLine cl = parser.parse( _options, args); - fail( "two arguments from group not allowed" ); - } - catch (ParseException e) - { - if( !( e instanceof AlreadySelectedException ) ) - { - fail( "incorrect exception caught:" + e.getMessage() ); - } - } - } - - public void testTwoOptionsFromDifferentGroup() - { - String[] args = new String[] { "-f", "-s" }; - - try - { - CommandLine cl = parser.parse( _options, args); - assertTrue( "Confirm -r is NOT set", !cl.hasOption("r") ); - assertTrue( "Confirm -f is set", cl.hasOption("f") ); - assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); - assertTrue( "Confirm -s is set", cl.hasOption("s") ); - assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); - assertTrue( "Confirm NO extra args", cl.getArgList().size() == 0); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testValidLongOnlyOptions() - { - try - { - CommandLine cl = parser.parse( _options, new String[]{"--export"}); - assertTrue( "Confirm --export is set", cl.hasOption("export") ); - } - catch (ParseException e) - { - fail( e.toString() ); - } - - try - { - CommandLine cl = parser.parse( _options, new String[]{"--import"}); - assertTrue( "Confirm --import is set", cl.hasOption("import") ); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - -} diff --git a/src/test/org/apache/commons/cli/OptionsTest.java b/src/test/org/apache/commons/cli/OptionsTest.java deleted file mode 100644 index 1cdae6864..000000000 --- a/src/test/org/apache/commons/cli/OptionsTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.ArrayList; -import java.util.Collection; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * @author Rob Oxspring roxspring@apache.org - * @version $Revision$ - */ -public class OptionsTest extends TestCase -{ - - public static Test suite() - { - return new TestSuite ( OptionsTest.class ); - } - - public OptionsTest( String name ) - { - super( name ); - } - - public void setUp() - { - } - - public void tearDown() - { - } - - public void testHelpOptions(){ - - Option longOnly1 = OptionBuilder - .withLongOpt("long-only1") - .create(); - - Option longOnly2 = OptionBuilder - .withLongOpt("long-only2") - .create(); - - Option shortOnly1 = OptionBuilder - .create("1"); - - Option shortOnly2 = OptionBuilder - .create("2"); - - Option bothA = OptionBuilder - .withLongOpt("bothA") - .create("a"); - - Option bothB = OptionBuilder - .withLongOpt("bothB") - .create("b"); - - Options options = new Options(); - options.addOption(longOnly1); - options.addOption(longOnly2); - options.addOption(shortOnly1); - options.addOption(shortOnly2); - options.addOption(bothA); - options.addOption(bothB); - - Collection allOptions = new ArrayList(); - allOptions.add(longOnly1); - allOptions.add(longOnly2); - allOptions.add(shortOnly1); - allOptions.add(shortOnly2); - allOptions.add(bothA); - allOptions.add(bothB); - - Collection helpOptions = options.helpOptions(); - - assertTrue("Everything in all should be in help",helpOptions.containsAll(allOptions)); - assertTrue("Everything in help should be in all",allOptions.containsAll(helpOptions)); - } - - - -} - diff --git a/src/test/org/apache/commons/cli/ParseRequiredTest.java b/src/test/org/apache/commons/cli/ParseRequiredTest.java deleted file mode 100644 index 104da9332..000000000 --- a/src/test/org/apache/commons/cli/ParseRequiredTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * @author John Keyes (john at integralsource.com) - * @version $Revision$ - */ -public class ParseRequiredTest extends TestCase -{ - - private Options _options = null; - private CommandLineParser parser = new PosixParser(); - - public static Test suite() { - return new TestSuite(ParseRequiredTest.class); - } - - public ParseRequiredTest(String name) - { - super(name); - } - - public void setUp() - { - _options = new Options() - .addOption("a", - "enable-a", - false, - "turn [a] on or off") - .addOption( OptionBuilder.withLongOpt( "bfile" ) - .hasArg() - .isRequired() - .withDescription( "set the value of [b]" ) - .create( 'b' ) ); - } - - public void tearDown() - { - - } - - public void testWithRequiredOption() - { - String[] args = new String[] { "-b", "file" }; - - try - { - CommandLine cl = parser.parse(_options,args); - - assertTrue( "Confirm -a is NOT set", !cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("file") ); - assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testOptionAndRequiredOption() - { - String[] args = new String[] { "-a", "-b", "file" }; - - try - { - CommandLine cl = parser.parse(_options,args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("file") ); - assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testMissingRequiredOption() - { - String[] args = new String[] { "-a" }; - - try - { - CommandLine cl = parser.parse(_options,args); - fail( "exception should have been thrown" ); - } - catch (ParseException e) - { - if( !( e instanceof MissingOptionException ) ) - { - fail( "expected to catch MissingOptionException" ); - } - } - } - -} diff --git a/src/test/org/apache/commons/cli/ParseTest.java b/src/test/org/apache/commons/cli/ParseTest.java deleted file mode 100644 index 96ce866e5..000000000 --- a/src/test/org/apache/commons/cli/ParseTest.java +++ /dev/null @@ -1,290 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class ParseTest extends TestCase -{ - - private Options _options = null; - private CommandLineParser _parser = null; - - public static Test suite() { - return new TestSuite(ParseTest.class); - } - - public ParseTest(String name) - { - super(name); - } - - public void setUp() - { - _options = new Options() - .addOption("a", - "enable-a", - false, - "turn [a] on or off") - .addOption("b", - "bfile", - true, - "set the value of [b]") - .addOption("c", - "copt", - false, - "turn [c] on or off"); - - _parser = new PosixParser(); - } - - public void tearDown() - { - - } - - public void testSimpleShort() - { - String[] args = new String[] { "-a", - "-b", "toast", - "foo", "bar" }; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testSimpleLong() - { - String[] args = new String[] { "--enable-a", - "--bfile", "toast", - "foo", "bar" }; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm arg of --bfile", cl.getOptionValue( "bfile" ).equals( "toast" ) ); - assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testComplexShort() - { - String[] args = new String[] { "-acbtoast", - "foo", "bar" }; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm -c is set", cl.hasOption("c") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testExtraOption() - { - String[] args = new String[] { "-adbtoast", - "foo", "bar" }; - - boolean caught = false; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm size of extra args", cl.getArgList().size() == 3); - } - catch (UnrecognizedOptionException e) - { - caught = true; - } - catch (ParseException e) - { - fail( e.toString() ); - } - assertTrue( "Confirm UnrecognizedOptionException caught", caught ); - } - - public void testMissingArg() - { - - String[] args = new String[] { "-acb" }; - - boolean caught = false; - - try - { - CommandLine cl = _parser.parse(_options, args); - } - catch (MissingArgumentException e) - { - caught = true; - } - catch (ParseException e) - { - fail( e.toString() ); - } - - assertTrue( "Confirm MissingArgumentException caught", caught ); - } - - public void testStop() - { - String[] args = new String[] { "-c", - "foober", - "-btoast" }; - - try - { - CommandLine cl = _parser.parse(_options, args, true); - assertTrue( "Confirm -c is set", cl.hasOption("c") ); - assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testMultiple() - { - String[] args = new String[] { "-c", - "foobar", - "-btoast" }; - - try - { - CommandLine cl = _parser.parse(_options, args, true); - assertTrue( "Confirm -c is set", cl.hasOption("c") ); - assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); - - cl = _parser.parse(_options, cl.getArgs() ); - - assertTrue( "Confirm -c is not set", ! cl.hasOption("c") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); - assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") ); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testMultipleWithLong() - { - String[] args = new String[] { "--copt", - "foobar", - "--bfile", "toast" }; - - try - { - CommandLine cl = _parser.parse(_options,args, - true); - assertTrue( "Confirm -c is set", cl.hasOption("c") ); - assertTrue( "Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); - - cl = _parser.parse(_options, cl.getArgs() ); - - assertTrue( "Confirm -c is not set", ! cl.hasOption("c") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); - assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") ); - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testDoubleDash() - { - String[] args = new String[] { "--copt", - "--", - "-b", "toast" }; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -c is set", cl.hasOption("c") ); - assertTrue( "Confirm -b is not set", ! cl.hasOption("b") ); - assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); - - } - catch (ParseException e) - { - fail( e.toString() ); - } - } - - public void testSingleDash() - { - String[] args = new String[] { "--copt", - "-b", "-", - "-a", - "-" }; - - try - { - CommandLine cl = _parser.parse(_options, args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("-") ); - assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); - assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("-") ); - } - catch (ParseException e) - { - fail( e.toString() ); - } - - } -} diff --git a/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java b/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java deleted file mode 100644 index 805ff6b72..000000000 --- a/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Test case for the PatternOptionBuilder class - * - * @author Henri Yandell - **/ -public class PatternOptionBuilderTest -extends TestCase -{ - public static void main( String[] args ) - { - String[] testName = { PatternOptionBuilderTest.class.getName() }; - junit.textui.TestRunner.main(testName); - } - - public static TestSuite suite() - { - return new TestSuite(PatternOptionBuilderTest.class); - } - - public PatternOptionBuilderTest( String s ) - { - super( s ); - } - - public void testSimplePattern() - { - try { - Options options = PatternOptionBuilder.parsePattern("a:b@cde>f+n%t/"); - String[] args = new String[] { "-c", "-a", "foo", "-b", "java.util.Vector", "-e", "build.xml", "-f", "java.util.Calendar", "-n", "4.5", "-t", "http://jakarta.apache.org/" }; - - CommandLineParser parser = new PosixParser(); - CommandLine line = parser.parse(options,args); - - // tests the char methods of CommandLine that delegate to - // the String methods - assertEquals("flag a", "foo", line.getOptionValue("a")); - assertEquals("flag a", "foo", line.getOptionValue('a')); - assertEquals("string flag a", "foo", line.getOptionObject("a")); - assertEquals("string flag a", "foo", line.getOptionObject('a')); - assertEquals("object flag b", new java.util.Vector(), line.getOptionObject("b")); - assertEquals("object flag b", new java.util.Vector(), line.getOptionObject('b')); - assertEquals("boolean true flag c", true, line.hasOption("c")); - assertEquals("boolean true flag c", true, line.hasOption('c')); - assertEquals("boolean false flag d", false, line.hasOption("d")); - assertEquals("boolean false flag d", false, line.hasOption('d')); - assertEquals("file flag e", new java.io.File("build.xml"), line.getOptionObject("e")); - assertEquals("file flag e", new java.io.File("build.xml"), line.getOptionObject('e')); - assertEquals("class flag f", java.util.Calendar.class, line.getOptionObject("f")); - assertEquals("class flag f", java.util.Calendar.class, line.getOptionObject('f')); - assertEquals("number flag n", new Float(4.5), line.getOptionObject("n")); - assertEquals("number flag n", new Float(4.5), line.getOptionObject('n')); - assertEquals("url flag t", new java.net.URL("http://jakarta.apache.org/"), line.getOptionObject("t")); - assertEquals("url flag t", new java.net.URL("http://jakarta.apache.org/"), line.getOptionObject('t')); - /// DATES NOT SUPPORTED YET. - // assertEquals("number flag t", new java.util.Date(1023400137276L), line.getOptionObject('z')); - // input is: "Thu Jun 06 17:48:57 EDT 2002" - } - catch( ParseException exp ) { - fail( exp.getMessage() ); - } - catch( java.net.MalformedURLException exp ) { - fail( exp.getMessage() ); - } - } - -} diff --git a/src/test/org/apache/commons/cli/TestHelpFormatter.java b/src/test/org/apache/commons/cli/TestHelpFormatter.java deleted file mode 100644 index 039efd919..000000000 --- a/src/test/org/apache/commons/cli/TestHelpFormatter.java +++ /dev/null @@ -1,176 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.io.ByteArrayOutputStream; -import java.io.PrintWriter; - -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Test case for the HelpFormatter class - * - * @author Slawek Zachcial - * @author John Keyes ( john at integralsource.com ) - **/ -public class TestHelpFormatter extends TestCase -{ - public static void main( String[] args ) - { - String[] testName = { TestHelpFormatter.class.getName() }; - junit.textui.TestRunner.main(testName); - } - - public static TestSuite suite() - { - return new TestSuite(TestHelpFormatter.class); - } - - public TestHelpFormatter( String s ) - { - super( s ); - } - - public void testFindWrapPos() - throws Exception - { - HelpFormatter hf = new HelpFormatter(); - - String text = "This is a test."; - //text width should be max 8; the wrap postition is 7 - assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0)); - //starting from 8 must give -1 - the wrap pos is after end - assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8)); - //if there is no a good position before width to make a wrapping look for the next one - text = "aaaa aa"; - assertEquals("wrap position 3", 4, hf.findWrapPos(text, 3, 0)); - } - - public void testPrintWrapped() - throws Exception - { - StringBuffer sb = new StringBuffer(); - HelpFormatter hf = new HelpFormatter(); - - String text = "This is a test."; - String expected; - - expected = "This is a" + hf.getNewLine() + "test."; - hf.renderWrappedText(sb, 12, 0, text); - assertEquals("single line text", expected, sb.toString()); - - sb.setLength(0); - expected = "This is a" + hf.getNewLine() + " test."; - hf.renderWrappedText(sb, 12, 4, text); - assertEquals("single line padded text", expected, sb.toString()); - - text = - "aaaa aaaa aaaa" + hf.getNewLine() + - "aaaaaa" + hf.getNewLine() + - "aaaaa"; - - expected = text; - sb.setLength(0); - hf.renderWrappedText(sb, 16, 0, text); - assertEquals("multi line text", expected, sb.toString()); - - expected = - "aaaa aaaa aaaa" + hf.getNewLine() + - " aaaaaa" + hf.getNewLine() + - " aaaaa"; - sb.setLength(0); - hf.renderWrappedText(sb, 16, 4, text); - assertEquals("multi-line padded text", expected, sb.toString()); - } - - public void testPrintOptions() - throws Exception - { - StringBuffer sb = new StringBuffer(); - HelpFormatter hf = new HelpFormatter(); - final int leftPad = 1; - final int descPad = 3; - final String lpad = hf.createPadding(leftPad); - final String dpad = hf.createPadding(descPad); - Options options = null; - String expected = null; - - options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); - expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa"; - hf.renderOptions(sb, 60, options, leftPad, descPad); - assertEquals("simple non-wrapped option", expected, sb.toString()); - - int nextLineTabStop = leftPad+descPad+"-a".length(); - expected = - lpad + "-a" + dpad + "aaaa aaaa aaaa" + hf.getNewLine() + - hf.createPadding(nextLineTabStop) + "aaaa aaaa"; - sb.setLength(0); - hf.renderOptions(sb, nextLineTabStop+17, options, leftPad, descPad); - assertEquals("simple wrapped option", expected, sb.toString()); - - - options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd"); - expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd"; - sb.setLength(0); - hf.renderOptions(sb, 60, options, leftPad, descPad); - assertEquals("long non-wrapped option", expected, sb.toString()); - - nextLineTabStop = leftPad+descPad+"-a,--aaa".length(); - expected = - lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + - hf.createPadding(nextLineTabStop) + "dddd dddd"; - sb.setLength(0); - hf.renderOptions(sb, 25, options, leftPad, descPad); - assertEquals("long wrapped option", expected, sb.toString()); - - options = new Options(). - addOption("a", "aaa", false, "dddd dddd dddd dddd"). - addOption("b", false, "feeee eeee eeee eeee"); - expected = - lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + - hf.createPadding(nextLineTabStop) + "dddd dddd" + hf.getNewLine() + - lpad + "-b " + dpad + "feeee eeee" + hf.getNewLine() + - hf.createPadding(nextLineTabStop) + "eeee eeee"; - sb.setLength(0); - hf.renderOptions(sb, 25, options, leftPad, descPad); - assertEquals("multiple wrapped options", expected, sb.toString()); - } - - public void testAutomaticUsage() - throws Exception - { - HelpFormatter hf = new HelpFormatter(); - Options options = null; - String expected = "usage: app [-a]"; - ByteArrayOutputStream out = new ByteArrayOutputStream( ); - PrintWriter pw = new PrintWriter( out ); - - options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); - hf.printUsage( pw, 60, "app", options ); - pw.flush(); - assertEquals("simple auto usage", expected, out.toString().trim()); - out.reset(); - - expected = "usage: app [-a] [-b]"; - options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa") - .addOption("b", false, "bbb" ); - hf.printUsage( pw, 60, "app", options ); - pw.flush(); - assertEquals("simple auto usage", expected, out.toString().trim()); - out.reset(); - } -} diff --git a/src/test/org/apache/commons/cli/ValueTest.java b/src/test/org/apache/commons/cli/ValueTest.java deleted file mode 100644 index 98bf2bf09..000000000 --- a/src/test/org/apache/commons/cli/ValueTest.java +++ /dev/null @@ -1,426 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import java.util.Arrays; -import java.util.Properties; - -public class ValueTest extends TestCase -{ - - public static Test suite() { - return new TestSuite(ValueTest.class); - } - - private CommandLine _cl = null; - private CommandLine _clOptional = null; - private Options opts = new Options(); - - public ValueTest(String name) - { - super(name); - } - - public void setUp() - { - opts.addOption("a", - false, - "toggle -a"); - - opts.addOption("b", - true, - "set -b"); - - opts.addOption("c", - "c", - false, - "toggle -c"); - - opts.addOption("d", - "d", - true, - "set -d"); - - opts.addOption( OptionBuilder.hasOptionalArg() - .create( 'e') ); - - opts.addOption( OptionBuilder.hasOptionalArg() - .withLongOpt( "fish" ) - .create( ) ); - - opts.addOption( OptionBuilder.hasOptionalArgs() - .withLongOpt( "gravy" ) - .create( ) ); - - opts.addOption( OptionBuilder.hasOptionalArgs( 2 ) - .withLongOpt( "hide" ) - .create( ) ); - - opts.addOption( OptionBuilder.hasOptionalArgs( 2 ) - .create( 'i' ) ); - - opts.addOption( OptionBuilder.hasOptionalArgs( ) - .create( 'j' ) ); - - opts.addOption( OptionBuilder.hasArgs( ).withValueSeparator( ',' ) - .create( 'k' ) ); - - String[] args = new String[] { "-a", - "-b", "foo", - "--c", - "--d", "bar" - }; - - try - { - CommandLineParser parser = new PosixParser(); - _cl = parser.parse(opts,args); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void tearDown() - { - - } - - public void testShortNoArg() - { - assertTrue( _cl.hasOption("a") ); - assertNull( _cl.getOptionValue("a") ); - } - - public void testShortWithArg() - { - assertTrue( _cl.hasOption("b") ); - assertNotNull( _cl.getOptionValue("b") ); - assertEquals( _cl.getOptionValue("b"), "foo"); - } - - public void testLongNoArg() - { - assertTrue( _cl.hasOption("c") ); - assertNull( _cl.getOptionValue("c") ); - } - - public void testLongWithArg() - { - assertTrue( _cl.hasOption("d") ); - assertNotNull( _cl.getOptionValue("d") ); - assertEquals( _cl.getOptionValue("d"), "bar"); - } - - public void testShortOptionalArgNoValue() - { - String[] args = new String[] { "-e" - }; - try - { - CommandLineParser parser = new PosixParser(); - CommandLine cmd = parser.parse(opts,args); - assertTrue( cmd.hasOption("e") ); - assertNull( cmd.getOptionValue("e") ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void testShortOptionalArgValue() - { - String[] args = new String[] { "-e", "everything" - }; - try - { - CommandLineParser parser = new PosixParser(); - CommandLine cmd = parser.parse(opts,args); - assertTrue( cmd.hasOption("e") ); - assertEquals( "everything", cmd.getOptionValue("e") ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void testLongOptionalNoValue() - { - String[] args = new String[] { "--fish" - }; - try - { - CommandLineParser parser = new PosixParser(); - CommandLine cmd = parser.parse(opts,args); - assertTrue( cmd.hasOption("fish") ); - assertNull( cmd.getOptionValue("fish") ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void testLongOptionalArgValue() - { - String[] args = new String[] { "--fish", "face" - }; - try - { - CommandLineParser parser = new PosixParser(); - CommandLine cmd = parser.parse(opts,args); - assertTrue( cmd.hasOption("fish") ); - assertEquals( "face", cmd.getOptionValue("fish") ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void testShortOptionalArgValues() - { - String[] args = new String[] { "-j", "ink", "idea" - }; - try - { - CommandLineParser parser = new PosixParser(); - CommandLine cmd = parser.parse(opts,args); - assertTrue( cmd.hasOption("j") ); - assertEquals( "ink", cmd.getOptionValue("j") ); - assertEquals( "ink", cmd.getOptionValues("j")[0] ); - assertEquals( "idea", cmd.getOptionValues("j")[1] ); - assertEquals( cmd.getArgs().length, 0 ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void testLongOptionalArgValues() - { - String[] args = new String[] { "--gravy", "gold", "garden" - }; - try - { - CommandLineParser parser = new PosixParser(); - CommandLine cmd = parser.parse(opts,args); - assertTrue( cmd.hasOption("gravy") ); - assertEquals( "gold", cmd.getOptionValue("gravy") ); - assertEquals( "gold", cmd.getOptionValues("gravy")[0] ); - assertEquals( "garden", cmd.getOptionValues("gravy")[1] ); - assertEquals( cmd.getArgs().length, 0 ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void testShortOptionalNArgValues() - { - String[] args = new String[] { "-i", "ink", "idea", "isotope", "ice" - }; - try - { - CommandLineParser parser = new PosixParser(); - CommandLine cmd = parser.parse(opts,args); - assertTrue( cmd.hasOption("i") ); - assertEquals( "ink", cmd.getOptionValue("i") ); - assertEquals( "ink", cmd.getOptionValues("i")[0] ); - assertEquals( "idea", cmd.getOptionValues("i")[1] ); - assertEquals( cmd.getArgs().length, 2 ); - assertEquals( "isotope", cmd.getArgs()[0] ); - assertEquals( "ice", cmd.getArgs()[1] ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void testLongOptionalNArgValues() - { - String[] args = new String[] { - "--hide", "house", "hair", "head" - }; - - CommandLineParser parser = new PosixParser(); - - try - { - CommandLine cmd = parser.parse(opts,args); - assertTrue( cmd.hasOption("hide") ); - assertEquals( "house", cmd.getOptionValue("hide") ); - assertEquals( "house", cmd.getOptionValues("hide")[0] ); - assertEquals( "hair", cmd.getOptionValues("hide")[1] ); - assertEquals( cmd.getArgs().length, 1 ); - assertEquals( "head", cmd.getArgs()[0] ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void testPropertyOptionSingularValue() - { - Properties properties = new Properties(); - properties.setProperty( "hide", "seek" ); - - CommandLineParser parser = new PosixParser(); - - try - { - CommandLine cmd = parser.parse(opts, null, properties); - assertTrue( cmd.hasOption("hide") ); - assertEquals( "seek", cmd.getOptionValue("hide") ); - assertTrue( !cmd.hasOption("fake") ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void testPropertyOptionFlags() - { - Properties properties = new Properties(); - properties.setProperty( "a", "true" ); - properties.setProperty( "c", "yes" ); - properties.setProperty( "e", "1" ); - - CommandLineParser parser = new PosixParser(); - - try - { - CommandLine cmd = parser.parse(opts, null, properties); - assertTrue( cmd.hasOption("a") ); - assertTrue( cmd.hasOption("c") ); - assertTrue( cmd.hasOption("e") ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - - properties = new Properties(); - properties.setProperty( "a", "false" ); - properties.setProperty( "c", "no" ); - properties.setProperty( "e", "0" ); - try - { - CommandLine cmd = parser.parse(opts, null, properties); - assertTrue( !cmd.hasOption("a") ); - assertTrue( !cmd.hasOption("c") ); - assertTrue( !cmd.hasOption("e") ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - - properties = new Properties(); - properties.setProperty( "a", "TRUE" ); - properties.setProperty( "c", "nO" ); - properties.setProperty( "e", "TrUe" ); - try - { - CommandLine cmd = parser.parse(opts, null, properties); - assertTrue( cmd.hasOption("a") ); - assertTrue( !cmd.hasOption("c") ); - assertTrue( cmd.hasOption("e") ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - - properties = new Properties(); - properties.setProperty( "a", "just a string" ); - properties.setProperty( "e", "" ); - try - { - CommandLine cmd = parser.parse(opts, null, properties); - assertTrue( !cmd.hasOption("a") ); - assertTrue( !cmd.hasOption("c") ); - assertTrue( !cmd.hasOption("e") ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - - } - - public void testPropertyOptionMultipleValues() - { - Properties properties = new Properties(); - properties.setProperty( "k", "one,two" ); - - CommandLineParser parser = new PosixParser(); - - String[] values = new String[] { - "one", "two" - }; - try - { - CommandLine cmd = parser.parse(opts, null, properties); - assertTrue( cmd.hasOption("k") ); - assertTrue( Arrays.equals( values, cmd.getOptionValues('k') ) ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void testPropertyOverrideValues() - { - String[] args = new String[] { - "-j", - "found", - "-i", - "ink" - }; - - Properties properties = new Properties(); - properties.setProperty( "j", "seek" ); - try - { - CommandLineParser parser = new PosixParser(); - CommandLine cmd = parser.parse(opts, args, properties); - assertTrue( cmd.hasOption("j") ); - assertEquals( "found", cmd.getOptionValue("j") ); - assertTrue( cmd.hasOption("i") ); - assertEquals( "ink", cmd.getOptionValue("i") ); - assertTrue( !cmd.hasOption("fake") ); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - -} diff --git a/src/test/org/apache/commons/cli/ValuesTest.java b/src/test/org/apache/commons/cli/ValuesTest.java deleted file mode 100644 index c49318659..000000000 --- a/src/test/org/apache/commons/cli/ValuesTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/** - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli; - -import java.util.Arrays; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class ValuesTest extends TestCase -{ - /** CommandLine instance */ - private CommandLine _cmdline = null; - private Option _option = null; - - public static Test suite() { - return new TestSuite( ValuesTest.class ); - } - - public ValuesTest( String name ) - { - super( name ); - } - - public void setUp() - { - Options opts = new Options(); - - opts.addOption("a", - false, - "toggle -a"); - - opts.addOption("b", - true, - "set -b"); - - opts.addOption("c", - "c", - false, - "toggle -c"); - - opts.addOption("d", - "d", - true, - "set -d"); - - opts.addOption( OptionBuilder.withLongOpt( "e" ) - .hasArgs() - .withDescription( "set -e ") - .create( 'e' ) ); - - opts.addOption("f", - "f", - false, - "jk"); - - opts.addOption( OptionBuilder.withLongOpt( "g" ) - .hasArgs( 2 ) - .withDescription( "set -g") - .create( 'g' ) ); - - opts.addOption( OptionBuilder.withLongOpt( "h" ) - .hasArgs( 2 ) - .withDescription( "set -h") - .create( 'h' ) ); - - opts.addOption( OptionBuilder.withLongOpt( "i" ) - .withDescription( "set -i") - .create( 'i' ) ); - - opts.addOption( OptionBuilder.withLongOpt( "j" ) - .hasArgs( ) - .withDescription( "set -j") - .withValueSeparator( '=' ) - .create( 'j' ) ); - - opts.addOption( OptionBuilder.withLongOpt( "k" ) - .hasArgs( ) - .withDescription( "set -k") - .withValueSeparator( '=' ) - .create( 'k' ) ); - - _option = OptionBuilder.withLongOpt( "m" ) - .hasArgs( ) - .withDescription( "set -m") - .withValueSeparator( ) - .create( 'm' ); - - opts.addOption( _option ); - - String[] args = new String[] { "-a", - "-b", "foo", - "--c", - "--d", "bar", - "-e", "one", "two", - "-f", - "arg1", "arg2", - "-g", "val1", "val2" , "arg3", - "-h", "val1", "-i", - "-h", "val2", - "-jkey=value", - "-j", "key=value", - "-kkey1=value1", - "-kkey2=value2", - "-mkey=value"}; - - CommandLineParser parser = new PosixParser(); - - try - { - _cmdline = parser.parse(opts,args); - } - catch (ParseException e) - { - fail("Cannot setUp() CommandLine: " + e.toString()); - } - } - - public void tearDown() - { - - } - - public void testShortArgs() - { - assertTrue( _cmdline.hasOption("a") ); - assertTrue( _cmdline.hasOption("c") ); - - assertNull( _cmdline.getOptionValues("a") ); - assertNull( _cmdline.getOptionValues("c") ); - } - - public void testShortArgsWithValue() - { - assertTrue( _cmdline.hasOption("b") ); - assertTrue( _cmdline.getOptionValue("b").equals("foo")); - assertTrue( _cmdline.getOptionValues("b").length == 1); - - assertTrue( _cmdline.hasOption("d") ); - assertTrue( _cmdline.getOptionValue("d").equals("bar")); - assertTrue( _cmdline.getOptionValues("d").length == 1); - } - - public void testMultipleArgValues() - { - String[] result = _cmdline.getOptionValues("e"); - String[] values = new String[] { "one", "two" }; - assertTrue( _cmdline.hasOption("e") ); - assertTrue( _cmdline.getOptionValues("e").length == 2); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues("e") ) ); - } - - public void testTwoArgValues() - { - String[] result = _cmdline.getOptionValues("g"); - String[] values = new String[] { "val1", "val2" }; - assertTrue( _cmdline.hasOption("g") ); - assertTrue( _cmdline.getOptionValues("g").length == 2); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues("g") ) ); - } - - public void testComplexValues() - { - String[] result = _cmdline.getOptionValues("h"); - String[] values = new String[] { "val1", "val2" }; - assertTrue( _cmdline.hasOption("i") ); - assertTrue( _cmdline.hasOption("h") ); - assertTrue( _cmdline.getOptionValues("h").length == 2); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues("h") ) ); - } - - public void testExtraArgs() - { - String[] args = new String[] { "arg1", "arg2", "arg3" }; - assertTrue( _cmdline.getArgs().length == 3 ); - assertTrue( Arrays.equals( args, _cmdline.getArgs() ) ); - } - - public void testCharSeparator() - { - // tests the char methods of CommandLine that delegate to - // the String methods - String[] values = new String[] { "key", "value", "key", "value" }; - assertTrue( _cmdline.hasOption( "j" ) ); - assertTrue( _cmdline.hasOption( 'j' ) ); - assertEquals( 4, _cmdline.getOptionValues( "j" ).length ); - assertEquals( 4, _cmdline.getOptionValues( 'j' ).length ); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( "j" ) ) ); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( 'j' ) ) ); - - values = new String[] { "key1", "value1", "key2", "value2" }; - assertTrue( _cmdline.hasOption( "k" ) ); - assertTrue( _cmdline.hasOption( 'k' ) ); - assertTrue( _cmdline.getOptionValues( "k" ).length == 4 ); - assertTrue( _cmdline.getOptionValues( 'k' ).length == 4 ); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( "k" ) ) ); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( 'k' ) ) ); - - values = new String[] { "key", "value" }; - assertTrue( _cmdline.hasOption( "m" ) ); - assertTrue( _cmdline.hasOption( 'm' ) ); - assertTrue( _cmdline.getOptionValues( "m" ).length == 2); - assertTrue( _cmdline.getOptionValues( 'm' ).length == 2); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( "m" ) ) ); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( 'm' ) ) ); - } - - /** - * jkeyes - commented out this test as the new architecture - * breaks this type of functionality. I have left the test - * here in case I get a brainwave on how to resolve this. - */ - /* - public void testGetValue() - { - // the 'm' option - assertTrue( _option.getValues().length == 2 ); - assertEquals( _option.getValue(), "key" ); - assertEquals( _option.getValue( 0 ), "key" ); - assertEquals( _option.getValue( 1 ), "value" ); - - try { - assertEquals( _option.getValue( 2 ), "key" ); - fail( "IndexOutOfBounds not caught" ); - } - catch( IndexOutOfBoundsException exp ) { - - } - - try { - assertEquals( _option.getValue( -1 ), "key" ); - fail( "IndexOutOfBounds not caught" ); - } - catch( IndexOutOfBoundsException exp ) { - - } - } - */ -} diff --git a/src/test/org/apache/commons/cli/bug/BugCLI18Test.java b/src/test/org/apache/commons/cli/bug/BugCLI18Test.java deleted file mode 100644 index a17d74508..000000000 --- a/src/test/org/apache/commons/cli/bug/BugCLI18Test.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli.bug; - -import org.apache.commons.cli.*; - -import java.io.PrintWriter; -import java.io.StringWriter; - -import junit.framework.TestCase; - -/** - * http://issues.apache.org/jira/browse/CLI-18 - */ -public class BugCLI18Test extends TestCase { - - public void testCLI18() { - Options options = new Options(); - options.addOption(new Option("a","aaa",false,"aaaaaaa")); - options.addOption(new Option(null,"bbb",false,"bbbbbbb dksh fkshd fkhs dkfhsdk fhskd hksdks dhfowehfsdhfkjshf skfhkshf sf jkshfk sfh skfh skf f")); - options.addOption(new Option("c",null,false,"ccccccc")); - - HelpFormatter formatter = new HelpFormatter(); - StringWriter out = new StringWriter(); - - formatter.printHelp(new PrintWriter(out),80, "foobar", "dsfkfsh kdh hsd hsdh fkshdf ksdh fskdh fsdh fkshfk sfdkjhskjh fkjh fkjsh khsdkj hfskdhf skjdfh ksf khf s", options, 2, 2, "blort j jgj j jg jhghjghjgjhgjhg jgjhgj jhg jhg hjg jgjhghjg jhg hjg jhgjg jgjhghjg jg jgjhgjgjg jhg jhgjh" + '\r' + '\n' + "rarrr", true); - } -} - From 7e7e4d85577cd94e159a99160c357d1337494b44 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Wed, 12 Jul 2006 06:06:07 +0000 Subject: [PATCH 0002/1663] Unit test created by Andrew Shirley (see CLI-12) added to show that the issue does not crop up in the CLI 2 API. git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@421150 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli2/bug/BugCLI12Test.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI12Test.java diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java new file mode 100644 index 000000000..db2e3d1aa --- /dev/null +++ b/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java @@ -0,0 +1,56 @@ +/** + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.option.PropertyOption; + +/** + * http://issues.apache.org/jira/browse/CLI-12 + */ +public class BugCLI12Test extends TestCase { + + public void testBug() { + Argument arg = new ArgumentBuilder().withName("file").create(); + + Option option = new PropertyOption(); + + Group group = new GroupBuilder().withOption(option).withOption(arg).create(); + + Parser p = new Parser(); + p.setGroup(group); + + CommandLine cl = p.parseAndHelp( new String[] { "-Dmyprop1=myval1", "-Dmyprop2=myval2", "myfile" } ); + if(cl == null) { + assertTrue("Couldn't parse valid commandLine", false); + } + + assertEquals( "myval1", cl.getProperty("myprop1")); + assertEquals( "myval2", cl.getProperty("myprop2")); + + String extraArgs = (String) cl.getValue(arg); + assertEquals( "myfile", extraArgs); + } + +} From 536b3f6a1a7d89ed07e580fb2e2e9cf89c84d0d9 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Wed, 12 Jul 2006 06:09:02 +0000 Subject: [PATCH 0003/1663] Fix copyright year. Though I think we'll stop doing this pretty soon git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@421154 13f79535-47bb-0310-9956-ffa450edef68 --- src/test/org/apache/commons/cli2/bug/BugCLI12Test.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java index db2e3d1aa..9cc3e426a 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java @@ -1,5 +1,5 @@ /** - * Copyright 2004 The Apache Software Foundation + * Copyright 2006 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From 58107ae990fea55d1f8e1c7c30409d4ad11ed4cb Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Wed, 12 Jul 2006 06:21:58 +0000 Subject: [PATCH 0004/1663] Unit test created by Andrew Shirley (see CLI-80) added to show that the issue of allowing repeated options does not crop up in the CLI 2 API. git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@421163 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli2/bug/BugCLI80Test.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI80Test.java diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java new file mode 100644 index 000000000..9ec56a18c --- /dev/null +++ b/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java @@ -0,0 +1,66 @@ +/** + * Copyright 2006 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; + +import junit.framework.TestCase; + +/** + * http://issues.apache.org/jira/browse/CLI-80 + */ +public class BugCLI80Test extends TestCase { + + public void testBug() { + final String optName = "option"; + + Argument arg = new ArgumentBuilder().withName(optName) + .withMaximum(1) + .create(); + + Option option = new DefaultOptionBuilder().withArgument(arg) + .withDescription("singular option") + .withLongName(optName) + .withShortName("o") + .create(); + + Group group = new GroupBuilder().withOption(option).create(); + + Parser p = new Parser(); + p.setGroup(group); + + CommandLine cl = p.parseAndHelp( new String[] { "-o", "yes" } ); + assertNotNull("Couldn't parse valid commandLine", cl); + + assertEquals("Couldn't look up value by short name", "yes", cl.getValue("-o") ); + + try { + cl = p.parse( new String[] { "-o", "yes", "-o", "jam" } ); + fail("Parsed invalid commandLine"); + } catch(OptionException e) { + // ok + } + } + +} From 541729cb40080091bff7125a620e69f4eaea3843 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 7 Aug 2006 17:09:33 +0000 Subject: [PATCH 0005/1663] Applying James Ring's commons-dev posted patch for the issue tracking page; we moved from Bugzilla to JIRA git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@429391 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/index.xml | 4 +--- xdocs/issue-tracking.xml | 17 ++++------------- 2 files changed, 5 insertions(+), 16 deletions(-) diff --git a/xdocs/index.xml b/xdocs/index.xml index 405f49808..0d81491e6 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -70,9 +70,7 @@ Please remember that the lists are shared between all commons components, so prefix your email by [cli].

-Issues may be reported via ASF Bugzilla. -Please remember that Bugzilla is shared between all commons components, -so prefix your issue by [cli]. +Issues may be reported via ASF JIRA.

diff --git a/xdocs/issue-tracking.xml b/xdocs/issue-tracking.xml index fc4acd835..23193cb27 100644 --- a/xdocs/issue-tracking.xml +++ b/xdocs/issue-tracking.xml @@ -23,19 +23,18 @@ limitations under the License.

- Commons CLI uses ASF Bugzilla for tracking issues. - To use Bugzilla you may need to create an account. + Commons CLI uses ASF JIRA for tracking issues. + To use JIRA you may need to create an account.

If you would like to report a bug, or raise an enhancement request with Commons CLI please do the following:

    -
  1. Search existing open bugs. +
  2. Search existing open bugs. If you find your issue listed then please add a comment with your details.
  3. Search the mailing list archive. You may find your issue or idea has already been discussed.
  4. -
  5. Submit a bug report or enhancement request. - Please prefix all new issues with [cli] in the summary line. +
  6. Submit a bug report or enhancement request.

@@ -47,14 +46,6 @@ limitations under the License.
  • the developers of Commons CLI are all unpaid volunteers
  • -

    - You may also find these links useful: -

    -

    From 37ead87cdd8de8ddb6cbb2f8f091eb572565080c Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 28 Aug 2006 06:33:05 +0000 Subject: [PATCH 0006/1663] Fixing the ASF copyright and placing it in the NOTICE file git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@437564 13f79535-47bb-0310-9956-ffa450edef68 --- NOTICE.txt | 3 ++ maven.xml | 11 +++---- project.xml | 11 +++---- .../org/apache/commons/cli2/Argument.java | 11 +++---- .../org/apache/commons/cli2/CommandLine.java | 11 +++---- .../apache/commons/cli2/DisplaySetting.java | 11 +++---- src/java/org/apache/commons/cli2/Group.java | 11 +++---- .../org/apache/commons/cli2/HelpLine.java | 11 +++---- src/java/org/apache/commons/cli2/Option.java | 11 +++---- .../apache/commons/cli2/OptionException.java | 11 +++---- src/java/org/apache/commons/cli2/Parent.java | 11 +++---- .../commons/cli2/WriteableCommandLine.java | 11 +++---- .../commons/cli2/builder/ArgumentBuilder.java | 11 +++---- .../commons/cli2/builder/CommandBuilder.java | 11 +++---- .../cli2/builder/DefaultOptionBuilder.java | 11 +++---- .../commons/cli2/builder/GroupBuilder.java | 11 +++---- .../commons/cli2/builder/PatternBuilder.java | 11 +++---- .../commons/cli2/builder/SwitchBuilder.java | 11 +++---- .../cli2/commandline/CommandLineImpl.java | 11 +++---- .../commandline/DefaultingCommandLine.java | 11 +++---- .../commons/cli2/commandline/Parser.java | 11 +++---- .../commandline/PreferencesCommandLine.java | 11 +++---- .../commandline/PropertiesCommandLine.java | 11 +++---- .../commandline/WriteableCommandLineImpl.java | 11 +++---- .../commons/cli2/option/ArgumentImpl.java | 11 +++---- .../apache/commons/cli2/option/Command.java | 11 +++---- .../commons/cli2/option/DefaultOption.java | 11 +++---- .../apache/commons/cli2/option/GroupImpl.java | 11 +++---- .../commons/cli2/option/HelpLineImpl.java | 11 +++---- .../commons/cli2/option/OptionImpl.java | 11 +++---- .../commons/cli2/option/ParentImpl.java | 11 +++---- .../commons/cli2/option/PropertyOption.java | 11 +++---- .../cli2/option/SourceDestArgument.java | 11 +++---- .../apache/commons/cli2/option/Switch.java | 11 +++---- .../cli2/resource/ResourceConstants.java | 25 +++++++++------- .../commons/cli2/resource/ResourceHelper.java | 11 +++---- .../apache/commons/cli2/util/Comparators.java | 11 +++---- .../commons/cli2/util/HelpFormatter.java | 11 +++---- .../cli2/validation/ClassValidator.java | 11 +++---- .../cli2/validation/DateValidator.java | 11 +++---- .../cli2/validation/EnumValidator.java | 11 +++---- .../cli2/validation/FileValidator.java | 11 +++---- .../validation/InvalidArgumentException.java | 11 +++---- .../cli2/validation/NumberValidator.java | 11 +++---- .../commons/cli2/validation/UrlValidator.java | 11 +++---- .../commons/cli2/validation/Validator.java | 11 +++---- .../org/apache/commons/cli2/CLITestCase.java | 11 +++---- .../commons/cli2/CommandLineDefaultsTest.java | 11 +++---- .../commons/cli2/CommandLineTestCase.java | 11 +++---- .../commons/cli2/DocumentationTest.java | 11 +++---- .../apache/commons/cli2/PrecedenceTest.java | 11 +++---- .../cli2/WriteableCommandLineTestCase.java | 11 +++---- .../commons/cli2/application/AntTest.java | 11 +++---- .../commons/cli2/application/CpTest.java | 11 +++---- .../commons/cli2/application/CvsTest.java | 11 +++---- .../commons/cli2/application/LsTest.java | 11 +++---- .../apache/commons/cli2/bug/Bug13886Test.java | 11 +++---- .../apache/commons/cli2/bug/Bug13935Test.java | 11 +++---- .../apache/commons/cli2/bug/Bug15046Test.java | 11 +++---- .../apache/commons/cli2/bug/Bug15648Test.java | 11 +++---- .../apache/commons/cli2/bug/Bug27575Test.java | 11 +++---- .../apache/commons/cli2/bug/Bug28005Test.java | 11 +++---- .../apache/commons/cli2/bug/Bug32533Test.java | 11 +++---- .../apache/commons/cli2/bug/BugCLI12Test.java | 11 +++---- .../apache/commons/cli2/bug/BugCLI18Test.java | 11 +++---- .../apache/commons/cli2/bug/BugCLI80Test.java | 11 +++---- .../bug/BugLoopingOptionLookAlikeTest.java | 27 +++++++++-------- .../cli2/builder/ArgumentBuilderTest.java | 25 +++++++++------- .../builder/DefaultOptionBuilderTest.java | 11 +++---- .../DefaultingCommandLineTest.java | 11 +++---- .../PreferencesCommandLineTest.java | 11 +++---- .../PropertiesCommandLineTest.java | 11 +++---- .../WriteableCommandLineImplTest.java | 11 +++---- .../commons/cli2/jdepend/JDependTest.java | 11 +++---- .../commons/cli2/option/ArgumentTest.java | 11 +++---- .../commons/cli2/option/ArgumentTestCase.java | 11 +++---- .../commons/cli2/option/CommandTest.java | 11 +++---- .../cli2/option/DefaultOptionTest.java | 11 +++---- .../apache/commons/cli2/option/GroupTest.java | 11 +++---- .../commons/cli2/option/GroupTestCase.java | 11 +++---- .../commons/cli2/option/NestedGroupTest.java | 11 +++---- .../commons/cli2/option/OptionTestCase.java | 11 +++---- .../commons/cli2/option/ParentTest.java | 11 +++---- .../commons/cli2/option/ParentTestCase.java | 11 +++---- .../cli2/option/PropertyOptionTest.java | 11 +++---- .../commons/cli2/option/SwitchTest.java | 11 +++---- .../cli2/resource/ResourceHelperTest.java | 25 +++++++++------- .../commons/cli2/util/ComparatorsTest.java | 11 +++---- .../commons/cli2/util/HelpFormatterTest.java | 25 +++++++++------- .../cli2/validation/ClassValidatorTest.java | 11 +++---- .../cli2/validation/DateValidatorTest.java | 11 +++---- .../cli2/validation/EnumValidatorTest.java | 11 +++---- .../cli2/validation/FileValidatorTest.java | 11 +++---- .../cli2/validation/NumberValidatorTest.java | 11 +++---- .../cli2/validation/TimeZoneTestSuite.java | 11 +++---- .../cli2/validation/UrlValidatorTest.java | 11 +++---- .../validation/protect/ProtectedClass.java | 11 +++---- xdocs/building.xml | 11 +++---- xdocs/cvs-usage.xml | 11 +++---- xdocs/examples/ant.xml | 11 +++---- xdocs/examples/cp.xml | 11 +++---- xdocs/examples/cvs.xml | 11 +++---- xdocs/examples/index.xml | 11 +++---- xdocs/examples/ls.xml | 11 +++---- xdocs/images/svg/commandlines.svg | 11 +++---- xdocs/images/svg/diagrams-cli2.js | 11 +++---- xdocs/images/svg/diagrams.css | 11 +++---- xdocs/images/svg/diagrams.js | 11 +++---- xdocs/images/svg/options.svg | 11 +++---- xdocs/images/svg/util.svg | 11 +++---- xdocs/index.xml | 29 ++++++++++--------- xdocs/introduction.xml | 29 ++++++++++--------- xdocs/issue-tracking.xml | 11 +++---- xdocs/manual/builders.xml | 11 +++---- xdocs/manual/commandlines.xml | 11 +++---- xdocs/manual/index.xml | 11 +++---- xdocs/manual/options.xml | 11 +++---- xdocs/manual/utilities.xml | 11 +++---- xdocs/manual/validators.xml | 11 +++---- xdocs/navigation.xml | 11 +++---- xdocs/properties.xml | 29 ++++++++++--------- xdocs/release_1_0.xml | 11 +++---- xdocs/usage.xml | 29 ++++++++++--------- 123 files changed, 816 insertions(+), 673 deletions(-) diff --git a/NOTICE.txt b/NOTICE.txt index 3f59805ce..9e5f2d43b 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -1,2 +1,5 @@ +Apache Jakarta Commons CLI +Copyright 2002-2006 The Apache Software Foundation + This product includes software developed by The Apache Software Foundation (http://www.apache.org/). diff --git a/maven.xml b/maven.xml index 30381eddd..14c612c00 100644 --- a/maven.xml +++ b/maven.xml @@ -1,9 +1,10 @@ diff --git a/xdocs/introduction.xml b/xdocs/introduction.xml index 4147d3bc9..709f67d75 100644 --- a/xdocs/introduction.xml +++ b/xdocs/introduction.xml @@ -1,18 +1,21 @@ diff --git a/xdocs/issue-tracking.xml b/xdocs/issue-tracking.xml index 23193cb27..8daf677b3 100644 --- a/xdocs/issue-tracking.xml +++ b/xdocs/issue-tracking.xml @@ -1,10 +1,11 @@ diff --git a/xdocs/release_1_0.xml b/xdocs/release_1_0.xml index 6ed38a7af..f211696bf 100644 --- a/xdocs/release_1_0.xml +++ b/xdocs/release_1_0.xml @@ -1,10 +1,11 @@ From e68118e769f32d969472bd684339bbc7c33b1242 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 10 Sep 2006 06:13:41 +0000 Subject: [PATCH 0007/1663] Finder is also going to want to use CLI, so creating an m2 pom for it as well git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@441918 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 175 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 pom.xml diff --git a/pom.xml b/pom.xml new file mode 100644 index 000000000..abe9bf201 --- /dev/null +++ b/pom.xml @@ -0,0 +1,175 @@ + + + + + org.apache.commons + commons + 1-SNAPSHOT + + 4.0.0 + org.apache.commons + commons-cli + 2.0-SNAPSHOT + CLI + + 2002 + + Commons CLI provides a simple API for presenting, processing and + validating a command line interface. + + + http://jakarta.apache.org/commons/cli/ + + + Apache Software Foundation + http://www.apache.org + + + + + The Apache Software License, Version 2.0 + /LICENSE.txt + repo + + + + + jira + http://issues.apache.org/jira/browse/CLI + + + + scm:svn:scm:svn:https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk + scm:svn:scm:svn:https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk + http://svn.apache.org/viewvc/jakarta/commons/proper/cli/trunk + + + + + James Strachan + jstrachan + jstrachan@apache.org + SpiritSoft, Inc. + + + Bob McWhirter + bob + bob@werken.com + Werken + + contributed ideas and code from werken.opt + + + + John Keyes + jkeyes + jbjk@mac.com + integral Source + + contributed ideas and code from Optz + + + + Rob Oxspring + roxspring + roxspring@imapmail.org + Indigo Stone + + designed CLI2 + + + + + + + Peter Donald + + contributed ideas and code from Avalon Excalibur's cli package + + + + Berin Loritsch + bloritsch@apache.org + + helped in the Avalon CLI merge + + + + Peter Maddocks + peter_maddocks@hp.com + Hewlett-Packard + + supplied patch + + + + + + + + + commons-lang + commons-lang + 2.1 + + + + + junit + junit + 3.8.1 + test + + + + + jdepend + jdepend + 2.5 + test + + + + + + src/java + src/test + + + src/java/org/apache/commons/cli2 + org/apache/commons/cli2 + + **/*.properties + + + + + + src/test/org/apache/commons/cli2/resource + org/apache/commons/cli2/resource + + **/*.properties + + + + + + From 2726e40e098780785c1185e4d92ac6e925658ce7 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 7 Nov 2006 20:49:30 +0000 Subject: [PATCH 0008/1663] Points to new commons-parent id git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@472248 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/pom.xml b/pom.xml index abe9bf201..c0a86659d 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> org.apache.commons - commons + commons-parent 1-SNAPSHOT 4.0.0 @@ -38,19 +38,6 @@ http://jakarta.apache.org/commons/cli/ - - Apache Software Foundation - http://www.apache.org - - - - - The Apache Software License, Version 2.0 - /LICENSE.txt - repo - - - jira http://issues.apache.org/jira/browse/CLI From 5b2317c4e7761252cd0663213af449ba48e05cae Mon Sep 17 00:00:00 2001 From: Rahul Akolkar Date: Thu, 9 Nov 2006 00:14:44 +0000 Subject: [PATCH 0009/1663] Missing SVN properties, possibly some large diffs, no functional change. git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@472712 13f79535-47bb-0310-9956-ffa450edef68 From 5e1dcb648bd4108cf05e5a4f60e808a34865467f Mon Sep 17 00:00:00 2001 From: Rahul Akolkar Date: Thu, 9 Nov 2006 00:26:31 +0000 Subject: [PATCH 0010/1663] Point DOAP files to JIRA. git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@472714 13f79535-47bb-0310-9956-ffa450edef68 --- doap_cli.rdf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doap_cli.rdf b/doap_cli.rdf index e71b44c7d..7e8603270 100644 --- a/doap_cli.rdf +++ b/doap_cli.rdf @@ -6,7 +6,7 @@ Java - + Commons CLI From 718bbcb98b58ac05b78ea049a52bfe3f38a287b1 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Thu, 9 Nov 2006 06:31:40 +0000 Subject: [PATCH 0011/1663] Making sure all the pom.xmls have NOTICE/LICENSEs in - though haven't done VFS git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@472790 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pom.xml b/pom.xml index c0a86659d..881500840 100644 --- a/pom.xml +++ b/pom.xml @@ -147,6 +147,14 @@ **/*.properties + + . + META-INF + + NOTICE.txt + LICENSE.txt + + From f33816952983d4878b1adc50abd8c458543b4dc0 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 13 Nov 2006 04:49:07 +0000 Subject: [PATCH 0012/1663] Hooking to the newly released v1 commons-parent pom git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@474146 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 881500840..eae41fa94 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.apache.commons commons-parent - 1-SNAPSHOT + 1 4.0.0 org.apache.commons From df96689ce7f2aa8e61e42fe5a46de66923393fc7 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 25 Nov 2006 19:01:23 +0000 Subject: [PATCH 0013/1663] Rolling the org.apache.commons groupId back to the individual component ids. It sounds as though we're not ready for the project.xmls to move to the new id. Intentionally leaving the pom.xmls as they are - sounds like when a component moves to maven-2, that that is when it should use the new groupId git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@479168 13f79535-47bb-0310-9956-ffa450edef68 --- project.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project.xml b/project.xml index 5f478397d..df057480d 100644 --- a/project.xml +++ b/project.xml @@ -16,7 +16,7 @@ limitations under the License. --> - org.apache.commons + commons-cli commons-cli CLI 2.0-SNAPSHOT From f562a8cd6f229e2e070054a05c27c305305c8670 Mon Sep 17 00:00:00 2001 From: Rahul Akolkar Date: Wed, 6 Dec 2006 15:44:10 +0000 Subject: [PATCH 0014/1663] Missing props on various m2 poms. git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@483119 13f79535-47bb-0310-9956-ffa450edef68 From a407dd682e5cbf6b7fbb999bf1fec3041d931720 Mon Sep 17 00:00:00 2001 From: Rahul Akolkar Date: Wed, 6 Dec 2006 15:55:07 +0000 Subject: [PATCH 0015/1663] Match groupIds for m1 and m2. We should account for the fact that its relatively easier to deploy snaps with m2 (such as IO was last night) and we shouldn't spray component artifacts in two different places (without relocation). git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@483126 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index eae41fa94..86de743a8 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ 1 4.0.0 - org.apache.commons + commons-cli commons-cli 2.0-SNAPSHOT CLI From 9315c439e05bc018d6f0bae570d10c713f1882dd Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Dec 2006 22:11:41 +0000 Subject: [PATCH 0016/1663] Setting the maven repo - apologies if this borks anything git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@486363 13f79535-47bb-0310-9956-ffa450edef68 --- project.properties | 2 ++ 1 file changed, 2 insertions(+) diff --git a/project.properties b/project.properties index 14ae9816e..eaa18dec0 100644 --- a/project.properties +++ b/project.properties @@ -1,6 +1,8 @@ # ------------------------------------------------------------------- # P R O J E C T P R O P E R T I E S # ------------------------------------------------------------------- +maven.repo.remote=http://repo1.maven.org/maven + maven.changelog.factory=org.apache.maven.svnlib.SvnChangeLogFactory compile.debug = on From 0bcfa8d31caf293b712a694906f511962d0d34fd Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Thu, 15 Mar 2007 16:44:48 +0000 Subject: [PATCH 0017/1663] Fixing tests so they pass in Italy as per #CLI-127 git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@518683 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli2/validation/DateValidatorTest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java b/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java index fa058fe60..ba5112c50 100644 --- a/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java @@ -17,6 +17,7 @@ package org.apache.commons.cli2.validation; import java.text.DateFormat; +import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; @@ -59,7 +60,8 @@ public void testSingleFormatValidate() public void testDefaultDateFormatValidate() throws InvalidArgumentException { - final Object[] array = new Object[] { "23-Dec-2003" }; + DateFormatSymbols symbols = new DateFormatSymbols(); + final Object[] array = new Object[] { "23-" + symbols.getShortMonths()[11] + "-2003" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator( new SimpleDateFormat("dd-MMM-yyyy") ); @@ -89,7 +91,8 @@ public void testDefaultTimeFormatValidate() public void testDefaultDateTimeFormatValidate() throws InvalidArgumentException { - final Object[] array = new Object[] { "23-Jan-2003 18:00:00" }; + DateFormatSymbols symbols = new DateFormatSymbols(); + final Object[] array = new Object[] { "23-" + symbols.getShortMonths()[0] + "-2003 18:00:00" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator( new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss") ); From a68348bfb4feeedf534b68bf8a3eb058fa55bfcc Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 28 May 2007 08:07:04 +0000 Subject: [PATCH 0018/1663] Removing dead file git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@542145 13f79535-47bb-0310-9956-ffa450edef68 --- project.properties | 1 - style.css | 39 --------------------------------------- 2 files changed, 40 deletions(-) delete mode 100644 style.css diff --git a/project.properties b/project.properties index eaa18dec0..b6e66a40a 100644 --- a/project.properties +++ b/project.properties @@ -24,7 +24,6 @@ maven.xdoc.developmentProcessUrl=http://jakarta.apache.org/commons/charter.html maven.xdoc.poweredby.image=maven-feather.png maven.javadoc.links=http://java.sun.com/j2se/1.4/docs/api/ -#maven.javadoc.stylesheet=${basedir}/style.css # Jar Manifest and Additional Attributes maven.jar.manifest=${basedir}/src/conf/MANIFEST.MF diff --git a/style.css b/style.css deleted file mode 100644 index 1878e66c8..000000000 --- a/style.css +++ /dev/null @@ -1,39 +0,0 @@ -body { - font-family: "Verdana", "Arial", sans-serif; - font-size: 10pt; -} - -h1 { - font-size: 12pt; -} - -h2, h3, .TableHeadingColor b, .FrameTitleFont, .FrameHeadingFont { - font-size: 10pt; - font-weight: bold; -} - -a b, .TableRowColor b, .NavBarCell1 b, .NavBarCell2 b { - font-weight: normal; -} - -tr, td { - border: none; -} - -.TableHeadingColor td { - border-bottom: 1px solid #666; -} - -.TableRowColor td { - padding-bottom: 5px; - border-bottom: 1px solid #CCC; -} - -a:link, a:visited, a:active { - text-decoration:none; - color: blue; -} - -a:hover { - text-decoration: underline; -} From d963fa14064b6db0884678bb9fff0cd9f529eb99 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 5 Jun 2007 04:12:11 +0000 Subject: [PATCH 0019/1663] the ASF JIRA, rather than ASF JIRA git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@544364 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/index.xml | 2 +- xdocs/issue-tracking.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/xdocs/index.xml b/xdocs/index.xml index fbc8028be..d1663a780 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -73,7 +73,7 @@ Please remember that the lists are shared between all commons components, so prefix your email by [cli].

    -Issues may be reported via ASF JIRA. +Issues may be reported via the ASF JIRA.

    diff --git a/xdocs/issue-tracking.xml b/xdocs/issue-tracking.xml index 8daf677b3..418a0592a 100644 --- a/xdocs/issue-tracking.xml +++ b/xdocs/issue-tracking.xml @@ -24,7 +24,7 @@ limitations under the License.

    - Commons CLI uses ASF JIRA for tracking issues. + Commons CLI uses the ASF JIRA for tracking issues. To use JIRA you may need to create an account.

    From 9297c2e8f37117d394ca7f6626adc5ca2a725db5 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Jun 2007 00:23:38 +0000 Subject: [PATCH 0020/1663] Fixing link to viewvc git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@546324 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/cvs-usage.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xdocs/cvs-usage.xml b/xdocs/cvs-usage.xml index aed5678aa..f0c8c5a09 100644 --- a/xdocs/cvs-usage.xml +++ b/xdocs/cvs-usage.xml @@ -33,7 +33,7 @@ limitations under the License.

    The best way to view the repository is via the - subversion viewer. + subversion viewer.

    The alternative is to use the From f8c46775d2aa5bf0ee21096e2db2d9671b5cb771 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Jun 2007 00:28:17 +0000 Subject: [PATCH 0021/1663] Updating the website. Instead of doing things in the xdocs on the 1.0 branch, I'm going to keep the 'one true xdoc' here in trunk and have it support both 1.0 and 2.0 git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@546325 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/changes.xml | 54 ++++++++++++++++++++++++++++++++++++++++ xdocs/index.xml | 12 ++++----- xdocs/issue-tracking.xml | 26 ++++++++++++++----- 3 files changed, 80 insertions(+), 12 deletions(-) create mode 100644 xdocs/changes.xml diff --git a/xdocs/changes.xml b/xdocs/changes.xml new file mode 100644 index 000000000..cf054e129 --- /dev/null +++ b/xdocs/changes.xml @@ -0,0 +1,54 @@ + + + + + + Commons CLI Release Notes + + + + + Parameter value "-something" misinterpreted as a parameter. + CLI_1_BRANCH build.xml doesn't work. + No Javadoc for HelpFormatter!. + Options should not be able to be added more than once. + Infinite Loop in Command-Line processing. + Documentation errors. + A weakness of parser. + CommandLine.getOptionValue() behaves contrary to docs. + Dependecy on commons-lang-2.0 but commons-lang-1.0 is obtained. + Document enhancement. + Error parsing option arguments. + HelpFormatter doesn't function correctly for options with only LongOpt. + Line separator as first char for helpformatter (footer) throws exception. + Missing arguments in HelpFormatter.renderOptions(..). + Only long options without short option seems to be noticed. + Parser breaks up command line parms into single characters. + Passing properties in Parser does not work for options with a single argument. + Wrong usage summary. + clone method in Option should use super.clone(). + clone() method doesn't fully clone contents. + HelpFormatter doesn't sort options properly. + Remove the Commons Lang dependency. + Setting description of a Option. + + + + + diff --git a/xdocs/index.xml b/xdocs/index.xml index d1663a780..3bd4e69cd 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -43,21 +43,21 @@ as are various project reports. The JavaDoc API documents are available online:

    The subversion repository can be -browsed. +browsed.

    -The latest version is v1.0. - +The latest version is v1.1. - Download now!
    -The release notes are also available. +The release notes are also available.

    For previous releases, see the Apache Archive diff --git a/xdocs/issue-tracking.xml b/xdocs/issue-tracking.xml index 418a0592a..977fce1a0 100644 --- a/xdocs/issue-tracking.xml +++ b/xdocs/issue-tracking.xml @@ -12,7 +12,7 @@ the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific iouage governing permissions and +See the License for the specific language governing permissions and limitations under the License. --> @@ -24,19 +24,25 @@ limitations under the License.

    - Commons CLI uses the ASF JIRA for tracking issues. - To use JIRA you may need to create an account. + Commons CLI uses the ASF JIRA for tracking issues. +

    +

    + To use JIRA you may need to create an account + (if you have previously created/updated Commons issues using Bugzilla an account will have been automatically + created and you can use the Forgot Password + page to get a new password).

    If you would like to report a bug, or raise an enhancement request with Commons CLI please do the following:

      -
    1. Search existing open bugs. +
    2. Search existing open bugs. If you find your issue listed then please add a comment with your details.
    3. Search the mailing list archive. You may find your issue or idea has already been discussed.
    4. -
    5. Submit a bug report or enhancement request. -
    6. +
    7. Decide if your issue is a bug or an enhancement.
    8. +
    9. Submit either a bug report + or enhancement request.

    @@ -47,6 +53,14 @@ limitations under the License.

  • the developers of Commons CLI are all unpaid volunteers
  • +

    + You may also find these links useful: +

    +

    From 9c27a7e68c42b176eda9cd2df0ef95d166a7aa45 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Jun 2007 00:32:30 +0000 Subject: [PATCH 0022/1663] Removing three unused imports (Parser/ArgumentImpl), and a pointless iteration through a list in DateValidator git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@546329 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli2/commandline/Parser.java | 2 -- src/java/org/apache/commons/cli2/option/ArgumentImpl.java | 2 -- .../org/apache/commons/cli2/validation/DateValidator.java | 4 ---- 3 files changed, 8 deletions(-) diff --git a/src/java/org/apache/commons/cli2/commandline/Parser.java b/src/java/org/apache/commons/cli2/commandline/Parser.java index 0bb64f7b9..4dd3f9670 100644 --- a/src/java/org/apache/commons/cli2/commandline/Parser.java +++ b/src/java/org/apache/commons/cli2/commandline/Parser.java @@ -16,8 +16,6 @@ */ package org.apache.commons.cli2.commandline; -import java.io.IOException; - import java.util.LinkedList; import java.util.List; import java.util.ListIterator; diff --git a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java index 01f919f8e..a5f9c2526 100644 --- a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java @@ -16,10 +16,8 @@ */ package org.apache.commons.cli2.option; -import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; -import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; diff --git a/src/java/org/apache/commons/cli2/validation/DateValidator.java b/src/java/org/apache/commons/cli2/validation/DateValidator.java index 065bdd371..28e833d43 100644 --- a/src/java/org/apache/commons/cli2/validation/DateValidator.java +++ b/src/java/org/apache/commons/cli2/validation/DateValidator.java @@ -101,10 +101,6 @@ public DateValidator(final DateFormat format) { * a List of DateFormats which dates must conform to */ public DateValidator(final List formats) { - for (Iterator iter = formats.iterator(); iter.hasNext();) { - DateFormat format = (DateFormat) iter.next(); - } - setFormats(formats); } From 9e19b1213173589db95b221a903704439c7f1236 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Jun 2007 00:37:28 +0000 Subject: [PATCH 0023/1663] Tighter list of projects, though I imagine we'll move to m2 asap git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@546332 13f79535-47bb-0310-9956-ffa450edef68 --- project.xml | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/project.xml b/project.xml index df057480d..71ea8172a 100644 --- a/project.xml +++ b/project.xml @@ -194,23 +194,15 @@ - - - - + maven-changes-plugin maven-jdepend-plugin - maven-checkstyle-plugin + maven-javadoc-plugin maven-jdepend-plugin maven-junit-report-plugin maven-jxr-plugin maven-license-plugin - maven-tasklist-plugin maven-pmd-plugin - - From 407d8246f87693378f2caf88104918a4541da8dd Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Jun 2007 00:54:15 +0000 Subject: [PATCH 0024/1663] Setting the JIRA format git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@546339 13f79535-47bb-0310-9956-ffa450edef68 --- project.properties | 2 ++ 1 file changed, 2 insertions(+) diff --git a/project.properties b/project.properties index b6e66a40a..eab423880 100644 --- a/project.properties +++ b/project.properties @@ -5,6 +5,8 @@ maven.repo.remote=http://repo1.maven.org/maven maven.changelog.factory=org.apache.maven.svnlib.SvnChangeLogFactory +maven.changes.issue.template=http://issues.apache.org/jira/browse/%ISSUE% + compile.debug = on compile.optimize = off compile.deprecation = off From c63390639c1ccd848400f178d189e7e66aa117c9 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Jun 2007 00:55:11 +0000 Subject: [PATCH 0025/1663] Removing unused import git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@546340 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli2/validation/DateValidator.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/java/org/apache/commons/cli2/validation/DateValidator.java b/src/java/org/apache/commons/cli2/validation/DateValidator.java index 28e833d43..85fff682d 100644 --- a/src/java/org/apache/commons/cli2/validation/DateValidator.java +++ b/src/java/org/apache/commons/cli2/validation/DateValidator.java @@ -20,7 +20,6 @@ import java.text.ParsePosition; import java.util.Date; -import java.util.Iterator; import java.util.List; import java.util.ListIterator; From d833beff286086771da4771f6eee4ed7da97a073 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Jun 2007 01:01:42 +0000 Subject: [PATCH 0026/1663] Adding Brian Egge to the list of contributors git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@546343 13f79535-47bb-0310-9956-ffa450edef68 --- project.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/project.xml b/project.xml index 71ea8172a..8b8aa4108 100644 --- a/project.xml +++ b/project.xml @@ -114,6 +114,12 @@ contributed ideas and code from Avalon Excalibur's cli package + + Brian Egge + + made the 1.1 release happen + + Berin Loritsch bloritsch@apache.org From de24647b43c9d760208a6af80056416ed9417033 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Jun 2007 01:25:02 +0000 Subject: [PATCH 0027/1663] Updating site. Bringing some of the 2.0 content in; removing the stubbed out 2.0 examples; updating the nav and adding the all important '1.x vs 2.x?' section to the front page git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@546345 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/building.xml | 87 ---------------------------------------- xdocs/examples/cp.xml | 36 ----------------- xdocs/examples/cvs.xml | 36 ----------------- xdocs/examples/index.xml | 6 +++ xdocs/examples/ls.xml | 36 ----------------- xdocs/index.xml | 15 ++++++- xdocs/navigation.xml | 42 ++++++------------- 7 files changed, 31 insertions(+), 227 deletions(-) delete mode 100644 xdocs/building.xml delete mode 100644 xdocs/examples/cp.xml delete mode 100644 xdocs/examples/cvs.xml delete mode 100644 xdocs/examples/ls.xml diff --git a/xdocs/building.xml b/xdocs/building.xml deleted file mode 100644 index 9adb558b1..000000000 --- a/xdocs/building.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - - Building - Commons Documentation Team - - - -
    -

    - Commons CLI uses Maven as its - primary build system. -

    -

    - You may also be interested in the release notes:
    - Release 1.0
    -

    -
    - - - - - -
    -

    - There are various active versions and branches of commons CLI: -

    - - - - - - - - - - - - - - - - - - - - - -
    NameDescription
    CLI_1_0Released CLI v1.0
    CLI_1_0_BETA_1First beta release of CLI 1.0.
    CLI_2_DEV_BRANCHDevelopment branch for jkeyes's CLI 2 code
    RESEARCH_CLI_2_ROXSPRINGDevelopment branch for roxspring's CLI 2 code
    -
    - - -
    diff --git a/xdocs/examples/cp.xml b/xdocs/examples/cp.xml deleted file mode 100644 index bb2ac5b67..000000000 --- a/xdocs/examples/cp.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - commons-dev - Examples - cp - - - -
    -

    TODO what is cp

    - - - - - - -
    - -
    diff --git a/xdocs/examples/cvs.xml b/xdocs/examples/cvs.xml deleted file mode 100644 index c2dc187de..000000000 --- a/xdocs/examples/cvs.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - commons-dev - Examples - cvs - - - -
    -

    TODO what is cvs

    - - - - - - -
    - -
    diff --git a/xdocs/examples/index.xml b/xdocs/examples/index.xml index 3c61549fa..9893ced20 100644 --- a/xdocs/examples/index.xml +++ b/xdocs/examples/index.xml @@ -39,5 +39,11 @@ found on the commons-user@jakarta.apache.org mailing list.

    + +
    + +
    diff --git a/xdocs/examples/ls.xml b/xdocs/examples/ls.xml deleted file mode 100644 index e7d3fdc28..000000000 --- a/xdocs/examples/ls.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - commons-dev - Examples - ls - - - -
    -

    TODO what is ls

    - - - - - - -
    - -
    diff --git a/xdocs/index.xml b/xdocs/index.xml index 3bd4e69cd..0837d2f23 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -29,8 +29,19 @@

    The Jakarta Commons CLI library provides an API for processing command line interfaces. -It was formed by the merger of ideas and code from three different libraries - -Werken, Avalon and Optz. +

    +
    + +
    +

    +Commons CLI 1.0 was formed from the merger of ideas and code from three different libraries - +Werken, Avalon and Optz. In dealing with the bugs and the feature requests a freshly designed and not backwards compatible +CLI 2.0 was created, but never finished or released. Since then a CLI 1.1 bugfix release has been made. +

    +

    +There are currently no plans to continue the 1.x line beyond bugfixes. The 2.x design is generally preferred and is in use, +however there is no current activity to make a 2.0 release. To this end, the 1.1 release is recommended to most users +while the 2.x line is recommended for anyone interested in helping to get this better API released.

    diff --git a/xdocs/navigation.xml b/xdocs/navigation.xml index c19840305..e79fc7fcd 100644 --- a/xdocs/navigation.xml +++ b/xdocs/navigation.xml @@ -27,44 +27,26 @@ - - + + + - - - - - - + - - - - - - - - - ---> - - - - - - - + From 3832c03c5d667acc6ed5f39e1ef637e14243ff44 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Jun 2007 19:03:06 +0000 Subject: [PATCH 0028/1663] Removing CLI1 bits from manifest git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@546598 13f79535-47bb-0310-9956-ffa450edef68 --- src/conf/MANIFEST.MF | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/conf/MANIFEST.MF b/src/conf/MANIFEST.MF index c7f076871..6d4aafeee 100644 --- a/src/conf/MANIFEST.MF +++ b/src/conf/MANIFEST.MF @@ -1,10 +1,5 @@ Implementation-Title: Jakarta Commons CLI2 -Name: org/apache/commons/cli/ -Specification-Title: Jakarta Commons CLI -Specification-Vendor: Apache Software Foundation -Specification-Version: 1.0 - Name: org/apache/commons/cli2/ Specification-Title: Jakarta Commons CLI2 Specification-Vendor: Apache Software Foundation From 2b7190a51fcb0dd1f37d76f57507c65e93244f8d Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 12 Jun 2007 19:16:17 +0000 Subject: [PATCH 0029/1663] Improving release notes so they discuss the backwards compatibility issues git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@546604 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/index.xml | 2 +- xdocs/navigation.xml | 1 + xdocs/upgrading-1.0-to-1.1.xml | 47 ++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 xdocs/upgrading-1.0-to-1.1.xml diff --git a/xdocs/index.xml b/xdocs/index.xml index 0837d2f23..ea97af5d5 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -68,7 +68,7 @@ The subversion repository can be

    The latest version is v1.1. - Download now!
    -The release notes are also available. +The release notes are also available.

    For previous releases, see the Apache Archive diff --git a/xdocs/navigation.xml b/xdocs/navigation.xml index e79fc7fcd..d85d2ea61 100644 --- a/xdocs/navigation.xml +++ b/xdocs/navigation.xml @@ -36,6 +36,7 @@ + diff --git a/xdocs/upgrading-1.0-to-1.1.xml b/xdocs/upgrading-1.0-to-1.1.xml new file mode 100644 index 000000000..9478ee777 --- /dev/null +++ b/xdocs/upgrading-1.0-to-1.1.xml @@ -0,0 +1,47 @@ + + + + + Upgrading from 1.0 to 1.1 + Commons Documentation Team + + + +

    +

    CLI 1.1 is a bugfix release of CLI. The following changes were not backward compatible:

    + +
      +
    • The CommandLineParser interface has two additional methods. If you were extending this, + then you will need to add methods to your classes. If you were extending the abstract + Parser class, then you should be okay.
    • +
    • The HelpFormatter class had publicly accessible fields. These are now accessed via + get/set methods.
    • +
    • Two of HelpFormatter's methods no longer throw IllegalArgumentException.
    • +
    • The Option class is no longer cloneable, and no longer has an addValue(String) method.
    • +
    + +

    The best way to test any of the above is to recompile your code against CLI 1.1. All of the above + should result in compile time errors.

    +
    +
    +

    The list of bugs fixed in 1.1 may be seen via the + changes report.

    +
    + + +
    From c5804756063fb7f86df700a51e2bc8845d0c0f9f Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 30 Jun 2007 18:26:35 +0000 Subject: [PATCH 0030/1663] Upgrading release notes git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@552192 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/changes.xml | 5 +++++ xdocs/upgrading-1.0-to-1.1.xml | 21 +++++++++++---------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/xdocs/changes.xml b/xdocs/changes.xml index cf054e129..327b45ded 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -47,6 +47,11 @@ HelpFormatter doesn't sort options properly. Remove the Commons Lang dependency. Setting description of a Option. + Options class returns options in random order. + MissingOptionException should contain a useful error message. + NullPointerException in Util.stripLeadingHyphens when passed a null argument. + 1.1 is not backwards compatible because it adds methods to the CommandLineParser interface. + Backwards compatibility between 1.1 and 1.0 broken due to Option.addValue removal. diff --git a/xdocs/upgrading-1.0-to-1.1.xml b/xdocs/upgrading-1.0-to-1.1.xml index 9478ee777..bce498f46 100644 --- a/xdocs/upgrading-1.0-to-1.1.xml +++ b/xdocs/upgrading-1.0-to-1.1.xml @@ -23,20 +23,21 @@ limitations under the License.
    -

    CLI 1.1 is a bugfix release of CLI. The following changes were not backward compatible:

    +

    CLI 1.1 is a bugfix release of CLI. The following changes notable API changes were made:

      -
    • The CommandLineParser interface has two additional methods. If you were extending this, - then you will need to add methods to your classes. If you were extending the abstract - Parser class, then you should be okay.
    • -
    • The HelpFormatter class had publicly accessible fields. These are now accessed via - get/set methods.
    • -
    • Two of HelpFormatter's methods no longer throw IllegalArgumentException.
    • -
    • The Option class is no longer cloneable, and no longer has an addValue(String) method.
    • +
    • The Parser abstract class has two additional parse methods that take a Properties parameter.
    • +
    • The HelpFormatter class had publicly accessible fields. These should now be accessed via + get/set methods and the public fields are deprecated.
    • +
    • The Option class addValue(String) method now throws UnsupportedOperationException.
    • +
    • OptionValidator is a newly added class.
    • +
    • Option's now have equals(Object) and hashCode() methods.
    • +
    • The Option class also received two new methods, setDescription(String) and hasValueSeparator();boolean.
    -

    The best way to test any of the above is to recompile your code against CLI 1.1. All of the above - should result in compile time errors.

    +

    The jar should be API backwards compatible, though if you were calling addValue(String) then you won't be happy. Please + let us know your use case if that is so.

    +

    The list of bugs fixed in 1.1 may be seen via the From 49994a4b4de81e057feb243a77ae0c17851ed9d4 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 30 Jun 2007 18:30:44 +0000 Subject: [PATCH 0031/1663] Sorted git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@552194 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/changes.xml | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 327b45ded..617eaf298 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -24,29 +24,29 @@ - Parameter value "-something" misinterpreted as a parameter. - CLI_1_BRANCH build.xml doesn't work. - No Javadoc for HelpFormatter!. - Options should not be able to be added more than once. - Infinite Loop in Command-Line processing. - Documentation errors. - A weakness of parser. - CommandLine.getOptionValue() behaves contrary to docs. + Wrong usage summary. Dependecy on commons-lang-2.0 but commons-lang-1.0 is obtained. - Document enhancement. - Error parsing option arguments. - HelpFormatter doesn't function correctly for options with only LongOpt. Line separator as first char for helpformatter (footer) throws exception. - Missing arguments in HelpFormatter.renderOptions(..). - Only long options without short option seems to be noticed. - Parser breaks up command line parms into single characters. - Passing properties in Parser does not work for options with a single argument. - Wrong usage summary. + CommandLine.getOptionValue() behaves contrary to docs. clone method in Option should use super.clone(). - clone() method doesn't fully clone contents. + Passing properties in Parser does not work for options with a single argument. + Only long options without short option seems to be noticed. + Infinite Loop in Command-Line processing. + Options should not be able to be added more than once. HelpFormatter doesn't sort options properly. - Remove the Commons Lang dependency. + HelpFormatter doesn't function correctly for options with only LongOpt. + Document enhancement. + Documentation errors. + Parameter value "-something" misinterpreted as a parameter. + clone() method doesn't fully clone contents. + No Javadoc for HelpFormatter!. + Parser breaks up command line parms into single characters. + Missing arguments in HelpFormatter.renderOptions(..). + Error parsing option arguments. + A weakness of parser. Setting description of a Option. + CLI_1_BRANCH build.xml doesn't work. + Remove the Commons Lang dependency. Options class returns options in random order. MissingOptionException should contain a useful error message. NullPointerException in Util.stripLeadingHyphens when passed a null argument. From 51dcfbca1e551ccf1736c516f6ecb8fabca52841 Mon Sep 17 00:00:00 2001 From: Rahul Akolkar Date: Wed, 4 Jul 2007 18:26:27 +0000 Subject: [PATCH 0032/1663] Update NOTICE files in trunks-proper in light of TLP move (and add component names to NOTICEs where missing). git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@553294 13f79535-47bb-0310-9956-ffa450edef68 --- NOTICE.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NOTICE.txt b/NOTICE.txt index 9e5f2d43b..bdbcc0703 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -1,4 +1,4 @@ -Apache Jakarta Commons CLI +Apache Commons CLI Copyright 2002-2006 The Apache Software Foundation This product includes software developed by From ba14eb67df141162db7fdb65cdba959c6359f777 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Fri, 27 Jul 2007 12:26:35 +0000 Subject: [PATCH 0033/1663] Update pom version, fix scm urls git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@560213 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 86de743a8..7c9a73bdf 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.apache.commons commons-parent - 1 + 3 4.0.0 commons-cli @@ -44,8 +44,8 @@ - scm:svn:scm:svn:https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk - scm:svn:scm:svn:https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk + scm:svn:https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk + scm:svn:https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk http://svn.apache.org/viewvc/jakarta/commons/proper/cli/trunk From 6019b2192e0d51599b7d507649eb88eb441b3a04 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Fri, 27 Jul 2007 17:52:04 +0000 Subject: [PATCH 0034/1663] Remove jakarta references from m1 and m2 builds git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@560337 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 8 ++++---- project.xml | 30 +++++++++++++++--------------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/pom.xml b/pom.xml index 7c9a73bdf..f4e7d268b 100644 --- a/pom.xml +++ b/pom.xml @@ -36,7 +36,7 @@ validating a command line interface. - http://jakarta.apache.org/commons/cli/ + http://commons.apache.org/cli/ jira @@ -44,9 +44,9 @@ - scm:svn:https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk - scm:svn:https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk - http://svn.apache.org/viewvc/jakarta/commons/proper/cli/trunk + scm:svn:https://svn.apache.org/repos/asf/commons/proper/cli/trunk + scm:svn:https://svn.apache.org/repos/asf/commons/proper/cli/trunk + http://svn.apache.org/viewvc/commons/proper/cli/trunk diff --git a/project.xml b/project.xml index 8b8aa4108..1d349ff6a 100644 --- a/project.xml +++ b/project.xml @@ -28,13 +28,13 @@ /images/logo.png - http://jakarta.apache.org/commons/cli/ + http://commons.apache.org/cli/ org.apache.commons Apache Software Foundation - http://www.apache.org - http://jakarta.apache.org/images/original-jakarta-logo.gif + http://commons.apache.org/ + http://commons.apache.org/images/logo.png @@ -45,29 +45,29 @@ - jakarta + commons http://issues.apache.org/jira/ people.apache.org - /www/jakarta.apache.org/commons/cli/ - /www/jakarta.apache.org/builds/jakarta-commons/cli/ + /www/commons.apache.org/cli/ + /www/people.apache.org/builds/commons/cli/ - scm:svn:http://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk - http://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk + scm:svn:http://svn.apache.org/repos/asf/commons/proper/cli/trunk + http://svn.apache.org/repos/asf/commons/proper/cli/trunk Commons Dev List - commons-dev-subscribe@jakarta.apache.org - commons-dev-unsubscribe@jakarta.apache.org - http://mail-archives.apache.org/eyebrowse/SummarizeList?listName=commons-dev@jakarta.apache.org + dev-subscribe@commons.apache.org + dev-unsubscribe@commons.apache.org + http://mail-archives.apache.org/mod_mbox/commons-dev/ Commons User List - commons-user-subscribe@jakarta.apache.org - commons-user-unsubscribe@jakarta.apache.org - http://mail-archives.apache.org/eyebrowse/SummarizeList?listName=commons-user@jakarta.apache.org + user-subscribe@commons.apache.org + user-unsubscribe@commons.apache.org + http://mail-archives.apache.org/mod_mbox/commons-user/ @@ -175,7 +175,7 @@ - commons-dev@jakarta.apache.org + dev@commons.apache.org src/java src/test From 8c74c799744ae908f1ae33eaca52e7a0710059f9 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 28 Jul 2007 08:12:57 +0000 Subject: [PATCH 0035/1663] Updating to reflect website change git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk@560518 13f79535-47bb-0310-9956-ffa450edef68 --- doap_cli.rdf | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/doap_cli.rdf b/doap_cli.rdf index 7e8603270..90f305060 100644 --- a/doap_cli.rdf +++ b/doap_cli.rdf @@ -1,14 +1,14 @@ - - Apache Jakarta Commons CLI - + + Apache Apache Commons CLI + Java - + Commons CLI Commons CLI provides a simple API for presenting, proecessing and @@ -27,6 +27,6 @@ 1.0 - + From 6b3b19dab54cbd674f37fce96da4148aeeee8ce2 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 03:40:41 +0000 Subject: [PATCH 0036/1663] Moving to TLP git-svn-id: https://svn.apache.org/repos/asf/commons/commons/proper/cli/trunk@560657 13f79535-47bb-0310-9956-ffa450edef68 From db4418c870d94d07473e7eef6b61256372167bd6 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 03:42:34 +0000 Subject: [PATCH 0037/1663] Moving to TLP git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560660 13f79535-47bb-0310-9956-ffa450edef68 From c7efeafe0314840c8b688b7a161b44b388a70db0 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 15:31:48 +0000 Subject: [PATCH 0038/1663] Fixing the broken links reported in CLI-139 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560730 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/introduction.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/xdocs/introduction.xml b/xdocs/introduction.xml index 709f67d75..fcaf36cc9 100644 --- a/xdocs/introduction.xml +++ b/xdocs/introduction.xml @@ -39,9 +39,9 @@ to define the interface to the application.

    - CLI uses the + CLI uses the Options class, as a container for - + Option instances. There are two ways to create Options in CLI. One of them is via the constructors, the other way is via the factory methods defined in @@ -66,11 +66,11 @@

    The parse method defined on - + CommandLineParser takes an Options instance and a String[] of arguments and returns a - + CommandLine.

    From 062ee682595d9cd42a93a7476956a119d4f2ab2e Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 15:42:06 +0000 Subject: [PATCH 0039/1663] Changing name from Jakarta Commons to Apache Commons git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560738 13f79535-47bb-0310-9956-ffa450edef68 --- README.txt | 4 ++-- src/conf/MANIFEST.MF | 4 ++-- .../apache/commons/cli2/util/HelpFormatterTest.java | 10 +++++----- xdocs/cvs-usage.xml | 2 +- xdocs/index.xml | 2 +- xdocs/navigation.xml | 2 +- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/README.txt b/README.txt index 21a93c355..9870f05b3 100644 --- a/README.txt +++ b/README.txt @@ -1,7 +1,7 @@ -Jakarta Commons CLI +Apache Commons CLI =================== -Welcome to the CLI component of the Jakarta Commons project. +Welcome to the CLI component of the Apache Commons project. The information in this file is relevant if you have downloaded a CLI source distribution. diff --git a/src/conf/MANIFEST.MF b/src/conf/MANIFEST.MF index 6d4aafeee..a70cbe6f7 100644 --- a/src/conf/MANIFEST.MF +++ b/src/conf/MANIFEST.MF @@ -1,6 +1,6 @@ -Implementation-Title: Jakarta Commons CLI2 +Implementation-Title: Apache Commons CLI2 Name: org/apache/commons/cli2/ -Specification-Title: Jakarta Commons CLI2 +Specification-Title: Apache Commons CLI2 Specification-Vendor: Apache Software Foundation Specification-Version: 2.0 diff --git a/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java b/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java index 1b0981133..4b2d8e4dc 100644 --- a/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java +++ b/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java @@ -54,7 +54,7 @@ public class HelpFormatterTest public void setUp() { helpFormatter = new HelpFormatter("|*", "*-*", "*|", 80); helpFormatter.setDivider("+------------------------------------------------------------------------------+"); - helpFormatter.setHeader("Jakarta Commons CLI"); + helpFormatter.setHeader("Apache Commons CLI"); helpFormatter.setFooter("Copyright 2003\nApache Software Foundation"); helpFormatter.setShellCommand("ant"); @@ -102,7 +102,7 @@ public void testPrint() helpFormatter.getDivider()); // test header - assertEquals("incorrect header", "Jakarta Commons CLI", helpFormatter.getHeader()); + assertEquals("incorrect header", "Apache Commons CLI", helpFormatter.getHeader()); // test footer assertEquals("incorrect footer", "Copyright 2003\nApache Software Foundation", @@ -116,7 +116,7 @@ public void testPrint() final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); - assertEquals("|*Jakarta Commons CLI *|", + assertEquals("|*Apache Commons CLI *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); @@ -169,7 +169,7 @@ public void testComparator() final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); - assertEquals("|*Jakarta Commons CLI *|", + assertEquals("|*Apache Commons CLI *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); @@ -311,7 +311,7 @@ public void testPrintHeader() final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); - assertEquals("|*Jakarta Commons CLI *|", + assertEquals("|*Apache Commons CLI *|", reader.readLine()); assertNull(reader.readLine()); } diff --git a/xdocs/cvs-usage.xml b/xdocs/cvs-usage.xml index f0c8c5a09..6be4c012d 100644 --- a/xdocs/cvs-usage.xml +++ b/xdocs/cvs-usage.xml @@ -24,7 +24,7 @@ limitations under the License.

    - Jakarta Commons CLI is hosted on the Apache + Apache Commons CLI is hosted on the Apache subversion repository.

    diff --git a/xdocs/index.xml b/xdocs/index.xml index ea97af5d5..dd5b39b42 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -28,7 +28,7 @@

    -The Jakarta Commons CLI library provides an API for processing command line interfaces. +The Apache Commons CLI library provides an API for processing command line interfaces.

    diff --git a/xdocs/navigation.xml b/xdocs/navigation.xml index d85d2ea61..7fac9910b 100644 --- a/xdocs/navigation.xml +++ b/xdocs/navigation.xml @@ -22,7 +22,7 @@ - + From f7cc62d350c6158383e459171a7e188bae5afdaf Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 15:48:41 +0000 Subject: [PATCH 0040/1663] Fixing email address git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560743 13f79535-47bb-0310-9956-ffa450edef68 --- gump.xml | 2 +- xdocs/cvs-usage.xml | 2 +- xdocs/examples/ant.xml | 2 +- xdocs/examples/index.xml | 4 ++-- xdocs/index.xml | 2 +- xdocs/introduction.xml | 2 +- xdocs/issue-tracking.xml | 2 +- xdocs/manual/builders.xml | 2 +- xdocs/manual/commandlines.xml | 2 +- xdocs/manual/index.xml | 2 +- xdocs/manual/options.xml | 2 +- xdocs/manual/utilities.xml | 2 +- xdocs/manual/validators.xml | 2 +- xdocs/properties.xml | 2 +- xdocs/release_1_0.xml | 2 +- xdocs/upgrading-1.0-to-1.1.xml | 2 +- xdocs/usage.xml | 2 +- 17 files changed, 18 insertions(+), 18 deletions(-) diff --git a/gump.xml b/gump.xml index 0586b7f3c..79f83c5c8 100644 --- a/gump.xml +++ b/gump.xml @@ -30,7 +30,7 @@ - + \ No newline at end of file diff --git a/xdocs/cvs-usage.xml b/xdocs/cvs-usage.xml index 6be4c012d..4ff4471a2 100644 --- a/xdocs/cvs-usage.xml +++ b/xdocs/cvs-usage.xml @@ -18,7 +18,7 @@ limitations under the License. Source repository - Commons Documentation Team + Commons Documentation Team diff --git a/xdocs/examples/ant.xml b/xdocs/examples/ant.xml index cfe171663..fb9cf0e6e 100644 --- a/xdocs/examples/ant.xml +++ b/xdocs/examples/ant.xml @@ -18,7 +18,7 @@ - commons-dev + commons-dev Examples - ant diff --git a/xdocs/examples/index.xml b/xdocs/examples/index.xml index 9893ced20..b3865e01f 100644 --- a/xdocs/examples/index.xml +++ b/xdocs/examples/index.xml @@ -18,7 +18,7 @@ - commons-dev + commons-dev Examples @@ -36,7 +36,7 @@ great detail. If more information is required then the reader is encouraged to review the API documentation and look at the unit tests for inspiration. Failing that, further advice and discussion can be - found on the commons-user@jakarta.apache.org mailing list. + found on the user@commons.apache.org mailing list.

    diff --git a/xdocs/index.xml b/xdocs/index.xml index dd5b39b42..3d8cb4d1d 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -21,7 +21,7 @@ Home - commons-dev + commons-dev diff --git a/xdocs/introduction.xml b/xdocs/introduction.xml index fcaf36cc9..58808be9a 100644 --- a/xdocs/introduction.xml +++ b/xdocs/introduction.xml @@ -20,7 +20,7 @@ - commons-dev + commons-dev Introduction diff --git a/xdocs/issue-tracking.xml b/xdocs/issue-tracking.xml index 977fce1a0..16e5a8b4a 100644 --- a/xdocs/issue-tracking.xml +++ b/xdocs/issue-tracking.xml @@ -18,7 +18,7 @@ limitations under the License. Issue tracking - Commons Documentation Team + Commons Documentation Team diff --git a/xdocs/manual/builders.xml b/xdocs/manual/builders.xml index 32988fde0..eda27441a 100644 --- a/xdocs/manual/builders.xml +++ b/xdocs/manual/builders.xml @@ -18,7 +18,7 @@ - commons-dev + commons-dev CLI2 - Builders diff --git a/xdocs/manual/commandlines.xml b/xdocs/manual/commandlines.xml index 0281c8abd..aa3d5b87f 100644 --- a/xdocs/manual/commandlines.xml +++ b/xdocs/manual/commandlines.xml @@ -18,7 +18,7 @@ - commons-dev + commons-dev CLI2 - CommandLines diff --git a/xdocs/manual/index.xml b/xdocs/manual/index.xml index 913dee539..8678e3864 100644 --- a/xdocs/manual/index.xml +++ b/xdocs/manual/index.xml @@ -18,7 +18,7 @@ - commons-dev + commons-dev CLI2 - Overview diff --git a/xdocs/manual/options.xml b/xdocs/manual/options.xml index 0f3267110..c34294ed8 100644 --- a/xdocs/manual/options.xml +++ b/xdocs/manual/options.xml @@ -18,7 +18,7 @@ - commons-dev + commons-dev CLI2 - Options diff --git a/xdocs/manual/utilities.xml b/xdocs/manual/utilities.xml index 371c75795..55e6fd735 100644 --- a/xdocs/manual/utilities.xml +++ b/xdocs/manual/utilities.xml @@ -18,7 +18,7 @@ - commons-dev + commons-dev CLI2 - Utilities diff --git a/xdocs/manual/validators.xml b/xdocs/manual/validators.xml index 7014766e2..8f165dbb3 100644 --- a/xdocs/manual/validators.xml +++ b/xdocs/manual/validators.xml @@ -18,7 +18,7 @@ - commons-dev + commons-dev CLI2 - Validators diff --git a/xdocs/properties.xml b/xdocs/properties.xml index 51ddbe579..7654be627 100644 --- a/xdocs/properties.xml +++ b/xdocs/properties.xml @@ -20,7 +20,7 @@ - commons-dev + commons-dev Option Properties diff --git a/xdocs/release_1_0.xml b/xdocs/release_1_0.xml index f211696bf..2c530407e 100644 --- a/xdocs/release_1_0.xml +++ b/xdocs/release_1_0.xml @@ -18,7 +18,7 @@ limitations under the License. Release notes for 1.0 - Commons Documentation Team + Commons Documentation Team diff --git a/xdocs/upgrading-1.0-to-1.1.xml b/xdocs/upgrading-1.0-to-1.1.xml index bce498f46..866477fb0 100644 --- a/xdocs/upgrading-1.0-to-1.1.xml +++ b/xdocs/upgrading-1.0-to-1.1.xml @@ -18,7 +18,7 @@ limitations under the License. Upgrading from 1.0 to 1.1 - Commons Documentation Team + Commons Documentation Team diff --git a/xdocs/usage.xml b/xdocs/usage.xml index 4159f62b2..127db3568 100644 --- a/xdocs/usage.xml +++ b/xdocs/usage.xml @@ -20,7 +20,7 @@ - commons-dev + commons-dev Usage Scenarios From 3c05da7a4c83f29274de060373b48c17821ce7c9 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 15:50:00 +0000 Subject: [PATCH 0041/1663] Fixing website url git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560744 13f79535-47bb-0310-9956-ffa450edef68 --- RELEASE-NOTES.txt | 2 +- gump.xml | 2 +- project.properties | 2 +- xdocs/index.xml | 6 +++--- xdocs/navigation.xml | 4 ++-- xdocs/release_1_0.xml | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt index 19f743311..c6a8dfa86 100644 --- a/RELEASE-NOTES.txt +++ b/RELEASE-NOTES.txt @@ -14,7 +14,7 @@ This is the first release of the CLI component, therefore all features are new, there are no bug-fixes, nothing is deprecated and there are no changes. For more information, read the documentation on the project site at -http://jakarta.apache.org/commons/cli/ +http://commons.apache.org/cli/ NEW FEATURES: diff --git a/gump.xml b/gump.xml index 79f83c5c8..41a93f05a 100644 --- a/gump.xml +++ b/gump.xml @@ -2,7 +2,7 @@ Commons CLI - + diff --git a/project.properties b/project.properties index eab423880..67f6176e4 100644 --- a/project.properties +++ b/project.properties @@ -22,7 +22,7 @@ maven.checkstyle.format=sun maven.xdoc.date=left maven.xdoc.version=${pom.currentVersion} -maven.xdoc.developmentProcessUrl=http://jakarta.apache.org/commons/charter.html +maven.xdoc.developmentProcessUrl=http://commons.apache.org/charter.html maven.xdoc.poweredby.image=maven-feather.png maven.javadoc.links=http://java.sun.com/j2se/1.4/docs/api/ diff --git a/xdocs/index.xml b/xdocs/index.xml index 3d8cb4d1d..c6eca535d 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -118,10 +118,10 @@ Issues may be reported via the ASF JIRA.

    The latest version of this documentation is available on the web:

    diff --git a/xdocs/navigation.xml b/xdocs/navigation.xml index 7fac9910b..c0d72405a 100644 --- a/xdocs/navigation.xml +++ b/xdocs/navigation.xml @@ -15,14 +15,14 @@ See the License for the specific language governing permissions and limitations under the License. --> - + Commons CLI - + diff --git a/xdocs/release_1_0.xml b/xdocs/release_1_0.xml index 2c530407e..284223c61 100644 --- a/xdocs/release_1_0.xml +++ b/xdocs/release_1_0.xml @@ -36,7 +36,7 @@ This is the first release of the CLI component, therefore all features are new, there are no bug-fixes, nothing is deprecated and there are no changes. For more information, read the documentation on the project site at -http://jakarta.apache.org/commons/cli/ +http://commons.apache.org/cli/

    From 1883f943c3dec21b89705fa0e6a9907a3848ffdb Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 19:31:16 +0000 Subject: [PATCH 0042/1663] I think this is dead git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560784 13f79535-47bb-0310-9956-ffa450edef68 --- gump.xml | 36 ------------------------------------ 1 file changed, 36 deletions(-) delete mode 100644 gump.xml diff --git a/gump.xml b/gump.xml deleted file mode 100644 index 41a93f05a..000000000 --- a/gump.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - Commons CLI - - - - - - - - - - org.apache.commons.cli - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file From e3724b887747d7f12ebf316b277824261af998bf Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 19:35:36 +0000 Subject: [PATCH 0043/1663] Updating site further to not point to Jakarta things git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560789 13f79535-47bb-0310-9956-ffa450edef68 --- README.txt | 4 ++-- doap_cli.rdf | 4 ++-- xdocs/cvs-usage.xml | 6 +++--- xdocs/index.xml | 4 ++-- xdocs/issue-tracking.xml | 2 +- xdocs/navigation.xml | 2 +- xdocs/style/project.css | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/README.txt b/README.txt index 9870f05b3..edf5fb339 100644 --- a/README.txt +++ b/README.txt @@ -16,7 +16,7 @@ There are two ways to build CLI, either with ant or maven. Ant can be found here : - http://jakarta.apache.org/ant + http://ant.apache.org/ and to build and test the system use: @@ -24,7 +24,7 @@ and to build and test the system use: Maven can be found here : - http://maven.apache.org + http://maven.apache.org/ and to build and test the system use: diff --git a/doap_cli.rdf b/doap_cli.rdf index 90f305060..a6bb62be5 100644 --- a/doap_cli.rdf +++ b/doap_cli.rdf @@ -16,8 +16,8 @@ - - + + diff --git a/xdocs/cvs-usage.xml b/xdocs/cvs-usage.xml index 4ff4471a2..2b06de3ff 100644 --- a/xdocs/cvs-usage.xml +++ b/xdocs/cvs-usage.xml @@ -29,15 +29,15 @@ limitations under the License.

    The project URL is:
    - http://svn.apache.org/repos/asf/jakarta/commons/proper/cli/trunk + http://svn.apache.org/repos/asf/commons/proper/cli/trunk

    The best way to view the repository is via the - subversion viewer. + subversion viewer.

    The alternative is to use the - native subversion display. + native subversion display.

    diff --git a/xdocs/index.xml b/xdocs/index.xml index c6eca535d..9719a76a5 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -60,7 +60,7 @@ The JavaDoc API documents are available online:

    The subversion repository can be -browsed. +browsed.

    @@ -71,7 +71,7 @@ The latest version is v1.1. - The release notes are also available.

    -For previous releases, see the Apache Archive +For previous releases, see the Apache Archive

    diff --git a/xdocs/issue-tracking.xml b/xdocs/issue-tracking.xml index 16e5a8b4a..d884a440a 100644 --- a/xdocs/issue-tracking.xml +++ b/xdocs/issue-tracking.xml @@ -38,7 +38,7 @@ limitations under the License.
    1. Search existing open bugs. If you find your issue listed then please add a comment with your details.
    2. -
    3. Search the mailing list archive. +
    4. Search the mailing list archive. You may find your issue or idea has already been discussed.
    5. Decide if your issue is a bug or an enhancement.
    6. Submit either a bug report diff --git a/xdocs/navigation.xml b/xdocs/navigation.xml index c0d72405a..200479a1b 100644 --- a/xdocs/navigation.xml +++ b/xdocs/navigation.xml @@ -28,7 +28,7 @@ - + diff --git a/xdocs/style/project.css b/xdocs/style/project.css index 013020460..c1d541c82 100644 --- a/xdocs/style/project.css +++ b/xdocs/style/project.css @@ -1 +1 @@ -@import url("http://jakarta.apache.org/style/jakarta-maven.css"); +@import url("http://commons.apache.org/style/commons-maven.css"); From 55353969c964d3f86969ab6597a1a42077dc31dd Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 19:41:30 +0000 Subject: [PATCH 0044/1663] Fixing javadoc links git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560790 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/properties.xml | 4 ++-- xdocs/usage.xml | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/xdocs/properties.xml b/xdocs/properties.xml index 7654be627..7a47d0902 100644 --- a/xdocs/properties.xml +++ b/xdocs/properties.xml @@ -28,10 +28,10 @@

      The following are the properties that each - Option has. All of these + Option has. All of these can be set using the accessors or using the methods defined in the - OptionBuilder. + OptionBuilder.

      diff --git a/xdocs/usage.xml b/xdocs/usage.xml index 127db3568..0335fe37d 100644 --- a/xdocs/usage.xml +++ b/xdocs/usage.xml @@ -45,7 +45,7 @@

      - An + An Options object must be created and the Option must be added to it.

      @@ -78,7 +78,7 @@ CommandLine cmd = parser.parse( options, args);

      Now we need to check if the t option is present. To do this we will interrogate the - CommandLine + CommandLine object. The hasOption method takes a java.lang.String parameter and returns true if the option represented by the java.lang.String is present, otherwise @@ -208,11 +208,11 @@ Option find = OptionBuilder.withArgName( "file" )

      Now that we have created each - Option we need + Option we need to create the - Options + Options instance. This is achieved using the - addOption + addOption method of Options.

      Options options = new Options(); @@ -239,8 +239,8 @@ options.addOption( property );

      We now need to create a Parser. This will parse the command line arguments, using the rules specified by the Options and - return an instance of CommandLine. - This time we will use a GnuParser + return an instance of CommandLine. + This time we will use a GnuParser which is able to handle options that are more than one character long.

      public static void main( String[] args ) { @@ -272,7 +272,7 @@ if( line.hasOption( "buildfile" ) ) {

      CLI also provides the means to automatically generate usage and help information. This is achieved with the - HelpFormatter + HelpFormatter class.

      // automatically generate the help statement @@ -307,7 +307,7 @@ formatter.printHelp( "ant", options );

      One of the most widely used command line applications in the *nix world is ls. To parse a command line for an application like this - we will use the PosixParser. + we will use the PosixParser. Due to the large number of options required for ls this example will only cover a small proportion of the options. The following is a section of the help output. @@ -328,7 +328,7 @@ Sort entries alphabetically if none of -cftuSUX nor --sort. -C list entries by columns

      The following is the code that is used to create the - Options for this example. + Options for this example.

      // create the command line parser CommandLineParser parser = new PosixParser(); From 5546e39a62fa73f1da330b0e007db4fa000162bc Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 19:44:54 +0000 Subject: [PATCH 0045/1663] Setting release date for 1.1 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560792 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/changes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 617eaf298..c3e400a7e 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -21,7 +21,7 @@ Commons CLI Release Notes - Wrong usage summary. From eb404fe6a4f5486dbcecc243611fd3aafeb7db6e Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 19:50:20 +0000 Subject: [PATCH 0046/1663] Switching link to be in an anchor git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560795 13f79535-47bb-0310-9956-ffa450edef68 --- src/test/org/apache/commons/cli2/application/CpTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/org/apache/commons/cli2/application/CpTest.java b/src/test/org/apache/commons/cli2/application/CpTest.java index 107ede716..bdcc9a5ba 100644 --- a/src/test/org/apache/commons/cli2/application/CpTest.java +++ b/src/test/org/apache/commons/cli2/application/CpTest.java @@ -44,7 +44,7 @@ * tested e.g. -a and -d are the same Option type.

      * *

      The following is the man output for 'cp'. See - * http://www.rt.com/man/cp.1.html.

      + * http://www.rt.com/man/cp.1.html.

      * *
        *  CP(1) FSF CP(1)
      
      From b4b029ff6870f823eba96c98411c27529869aab7 Mon Sep 17 00:00:00 2001
      From: Henri Yandell 
      Date: Sun, 29 Jul 2007 19:50:46 +0000
      Subject: [PATCH 0047/1663] Switching link to be in an anchor
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560796 13f79535-47bb-0310-9956-ffa450edef68
      ---
       src/test/org/apache/commons/cli2/application/LsTest.java | 2 +-
       1 file changed, 1 insertion(+), 1 deletion(-)
      
      diff --git a/src/test/org/apache/commons/cli2/application/LsTest.java b/src/test/org/apache/commons/cli2/application/LsTest.java
      index 3df75db2a..e68a248f5 100644
      --- a/src/test/org/apache/commons/cli2/application/LsTest.java
      +++ b/src/test/org/apache/commons/cli2/application/LsTest.java
      @@ -38,7 +38,7 @@
        * tested e.g. -a and -d are the same Option type.

      * *

      The following is the man output for 'ls'. See - * http://www.rt.com/man/ls.1.html.

      + * http://www.rt.com/man/ls.1.html.

      * *
        *  LS(1) FSF LS(1)
      
      From 07e18a3b82ffbea69b7a8a0173428ba551db1842 Mon Sep 17 00:00:00 2001
      From: Henri Yandell 
      Date: Mon, 30 Jul 2007 05:18:23 +0000
      Subject: [PATCH 0048/1663] Removing dead pages and dead images
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560863 13f79535-47bb-0310-9956-ffa450edef68
      ---
       xdocs/manual/commandlines.xml | 51 -----------------------------------
       xdocs/manual/index.xml        |  7 ++---
       xdocs/manual/options.xml      |  1 -
       xdocs/manual/utilities.xml    | 39 ---------------------------
       xdocs/manual/validators.xml   |  2 --
       5 files changed, 2 insertions(+), 98 deletions(-)
       delete mode 100644 xdocs/manual/commandlines.xml
       delete mode 100644 xdocs/manual/utilities.xml
      
      diff --git a/xdocs/manual/commandlines.xml b/xdocs/manual/commandlines.xml
      deleted file mode 100644
      index aa3d5b87f..000000000
      --- a/xdocs/manual/commandlines.xml
      +++ /dev/null
      @@ -1,51 +0,0 @@
      -
      -
      -
      -
      -  
      -    commons-dev
      -    CLI2 - CommandLines
      -  
      -
      -  
      -    
      - - - - - - - - - - - - - - - - - - - -
      -
      -

      TODO commons-configuration

      -
      - -
      diff --git a/xdocs/manual/index.xml b/xdocs/manual/index.xml index 8678e3864..b9c83f390 100644 --- a/xdocs/manual/index.xml +++ b/xdocs/manual/index.xml @@ -117,8 +117,7 @@ Option outputOption = to the user in a manner typical of command line applications. The HelpFormatter is designed with flexibility in mind so it should be possible to control exactly which structures are described to the user and what level of - detail to use. The HelpFormatter is discussed in detail in the - Utilities section of the manual. + detail to use.

      Any errors that occur while parsing result in an OptionException being thrown @@ -183,9 +182,7 @@ if(cl.hasOption("--output")) { provided that can wrap a Properties or Preferences instance as a CommandLine. These can then be combined with the DefaultingCommandLine and the parsed CommandLine to provide a variety of different defaulting and overriding - scenarios. The CommandLine interface and implementations are discussed - further in the CommandLines section of the - manual. + scenarios.

      diff --git a/xdocs/manual/options.xml b/xdocs/manual/options.xml index c34294ed8..f61be9769 100644 --- a/xdocs/manual/options.xml +++ b/xdocs/manual/options.xml @@ -24,7 +24,6 @@
      -

      In CLI2 every element of the command line interface is modelled as an diff --git a/xdocs/manual/utilities.xml b/xdocs/manual/utilities.xml deleted file mode 100644 index 55e6fd735..000000000 --- a/xdocs/manual/utilities.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - commons-dev - CLI2 - Utilities - - - -

      - - - - - -
      -
      -

      TODO xml2cli

      -

      TODO cli2ant

      -

      TODO cli2html

      -
      - - diff --git a/xdocs/manual/validators.xml b/xdocs/manual/validators.xml index 8f165dbb3..b6e76f902 100644 --- a/xdocs/manual/validators.xml +++ b/xdocs/manual/validators.xml @@ -41,8 +41,6 @@
    7. URL
    8. - -

      The ClassValidator validates a value using three criteria: From df9bd917a3616c9df6f4a2430ec082f78fef1382 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 30 Jul 2007 05:18:31 +0000 Subject: [PATCH 0049/1663] Removing dead pages and dead images git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560864 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/images/commandlines.png | Bin 18192 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 xdocs/images/commandlines.png diff --git a/xdocs/images/commandlines.png b/xdocs/images/commandlines.png deleted file mode 100644 index 94ac189918eb803fa40a0e70e7fc5b0955d9a0b0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 18192 zcmb5W1za3kmoM5#LV_j)hekuNV8PwpJvhN7xI2Uc!JXjlo?wkjaCZoe1$PLI`>Q_Z zn{Q_BoqOMV@S~us>8f4Td#|V@-~_Ea(cXa^%r}GAD$=yXB`t!lil_di}+N^@J}Wy&C&0i?oCN_ z5Fvr0(ZY`VH(Pc>lrJA%ur7X3dGX`VQ@hZuU*>+sG=w)(@xn`x)U|ylWBkTIaL2p- zgC&!^0X4|R@@eP5^Yf7#kp0+2LUgaSC#sA&s+~JF0IfgZ zGsOlGFq1Dg#z|06sH~q3CKTsM8FYs*hhIVKP7BP2izX83x?I-9L#5x4+_M!HJxZGN zU&cMQ7f0Yf6;JTL!5&M1T=~e#HjBHtRZqIFdM1?Hpm=R1QPg=~@uzXvfH`a~KPY5y z2Rxp}B%k|*=r^CETpS(9H8sW1y+3r`ht4Xt+S%Gl(9vm?T8u08o`LzcWe=7jKd_xl zVF?`;lxsb`WvjI|PB-u>HORe~;V|^|G`8W3=d`_k-g$1=0n)z0qox{?k&UTb?q+;A6g0}v88PRi4-3|@K1k2)OLw;Cg z*lRZncHcjATSDt7&Zm_OBaoUSv6hOJ4D*JQxgvsGJN(+$FH+g&Cnj>2tp?*|HrJ;N zEbz_r&t{WpE)F`#!L8G~KZ7wSKl(pCn9C}*zkdkc(nYD?J7+9c%uI7Rf@18MlC!T` zgrL7Hz#zUa5U!OoyYp7CFOD5g*ozBk;WV953L)c_U(wf@Rf@TY?)AD3y zWX$Asx1*3Hbb`hR?lWg$kz8|T^17-V@Heq)wB$npYwT~TmLX1fi^T3 zmfL-mUUK8%Z6_w2(LQ}CKq@=j9_6FNDA$E>3iw5DK0xs&N}TN*XF^LkPvdl@k^_^O2F>`J{ZsY>oD3ToO(>_Y22hICqElt zwxS0IOHBVTp;M*%Lvy=Ltn~W(j9s>%9(Z^*sLk8G511N}#IcRmVT(-HIRjlenv7_f zR)$`sOafks44CnHmH7w4e@yn&wzt-wb0tGwkzZ_ib*u){`G$C1QIgU8<>3>)Wi?ktGv>XZw2gD+pvwSTPhG z)H#+Z)yuAB+thM!EIXgPmz}o>eve zoyWN^Jj;c{I%T>q%1^>>`fwpDFBz=0e5(BvjysMNzuml_X732=Nx5N0!^{$0SwW+v z+sm_LSZuIum^;bkzPVicS}Q@EWZsgs-3kJ^sCWw%fL==t89B_7`9~Ii|E@o^@BrD@ zYVJgMLthjS;Lx;VY_uZy97Ib&h@Z^s_aq>e7}<#2JwJdWHJZlpXA}WMPM$=nHJv1> zsEFRq0}7CRZnA&?3Xq}IB*s=6z|TZXoNM-izc$M&J}jAGLJB|Q91A@`(XReo?Vxv+!9G4^DB9P)9m zwRL;){^rf@Wd3rU%bsZ(%cr;+OxOLH0-JfeiLf`hH-cxM+qwt)idbzIu%+RtNhSZe z7esBo)qG4(Ozf*$F}2*gxCpsB+37+egqI-t4BJJ_$r2R-iM`GHn~R}?xVXFCz_g~8 zmWd(-?_Ty~%jcLbIE7$~9k-#KCYLU1OeQNFn&q%J6r1qi>b!UOGuUQ`ci@cnI@RI; zqEvz3(Ql=g*<9kz=Q_$jNf}MV)qpeoaOeJdyo+1e3TSJ?$<;=0x8E7AI zSvr=f8(JpH!QDpE1EiEh?$|$W=4KL~q-arIJb+?j(sgOV;i1MI2sOE_VA7fHdHfCzf)HJd;F0?xYCFPx6bK2Sz!oCT8PGQh*a?+Q#U-e7L z$n^cLmh%@fXzSBh#*dlWonrO;5FXp5-Qw2ABglq0bIY$^$fb#<@3NAE2L^HAsrBD7blkTMa9 z%-C`e)K44%0f&Gfv`eF_^G>62_a!Yjr&rKi@3d@QNugCF2@C?IAj6jud=-IWbJdUn z;v9Xwe0(TBAfg+uwyUkP3JR|5+DgyO@ocWGg#;igPwKU}RZak*!6DEp`h<}{y! z1G`L-uu*ceA$EldadGGVDk?5yA}_*~)le0E?=A~PkWi+)Pugg{XqaJ1`pl~bz|0SG zOlJb>jJITO?H+w(;<&@K*4us{?$D+0}oNoi_@*z8Xdb_0Zif`wnd)S*Y)Mw_3`iK`I!v1F5& z$iaMm8D5wB5~))QOvzsaZy&wAcDk`jn|UM|5nUhOC51nirlx${=&T#*|B6YpZ`^4P7etR2KJqb9Nh~uGqbp$ zASAGW7Y-p(KtKVp*0kebC?BJXgKHr*3T7yqe!x`OVou<%?3MjREtmK`>LUv}I=TS@ zAmSbgk_hO~5su#8Sd{5Qn4E~wL*y1(4F{>InVFeiX8@HwU3OttmkX_+K^@`f!Vjdb z7enu9pGinX#B)LDD)pMMQxO9K&PlQhnLf6Dly^o6>9AQ!MDLtvytRW(6&ib89xfy% zBm~JL2n&0KFnetsL^j%RT@@kG+AK{5UO~=*J4t`!FR{?#&inx*haUMYX<*=~tK_Z% zO5fD@qAtJW_K`nyslz|J{qfdjf2ED@19~SiA-nPBwjf?N0&Dy3>`dm}7CtZD8!>-_ zHrXiK&n5i>aWj9ipDMl^7CF~j<6NCvP}mvjG`rB% z+pm&#+@gLb8@8UQkeOrDotn`oA80UM zq;kb8!cM-wm#%kU*<1UuBA5Cf>>7*GLgzRc4->8jsDYl_I<43T<{%D0|HT zRD*vfezK=Gf{veD_@%Tqmz}b@bf|~V?PeIk&{l5q{#Ot+7(Mkcc5x7hR1^z4)SH53)Eig(}<&&7kb^LQEmVopzlFsYd8ceXUi zp<@|5VzmV)(9zM#p(p|aZI`{(Y{U?Bm8^r?N){!nr_7qqgwK>xMJZ?$Lmgi|toSB> z@ViquBwIoVQ4+p5T79;IfXhy9X1atIv$VW81CGON&z9{HQOnmd$Q>`pRL6t$;?Jz~ z1`D2_<)>U6(7E)Xr@aGr5@I2zyIsDwZFC5X$0W%aUG-PezrDz3*)tm0sJxM#eyvqi zqS#+pAA`?S&=4J+=(8L9;^V=1c5#~P{zR0`JgxfeC(9y>wW*kr`XHpJ*g1O$&N&gg zwR#2r1lI`%o5hp^-GDZy-TN_R&(Gyy5qPQR?m9})llI$v1{G0MRMb4Hsh3h79*t$f zb!NkOX-t{HHf;7Q{6udvl><&s!;J1@gy<2Ze8_nH7!DtoTk_aj_pcpK`IS*k{Zzvm zqt5x(=)Eva%L^aGRv+~pNR9ZPAI&&y%cpsaj17Ib!SGK^pu!xuJ&cJgI2QXFZiVme z4sEegYp-SR4@8o%D$cBB14A34yrPMy#~KDbsjIRK+WqUw@8@;w){{-OzlsS_YX185@wDGonItkC z+JQEPL~r@BRHNKNL(<1Kv~(kWIOy1pca=EzzEPEA!Ip`hzX;9Z$VHP|&9D-r||C__wiIRlr#F8MIYF$xm$ zewg%!U*=yN%qP^U^Ui)P-&AJQV#V2k{Ipsse1q`_c8-DOu$qW#=t(Sflp_XxlQ}vx zcoS3V*=wxUchRql$5g;36&<>xHI`LqL`LQ)NxhNzxI309`+9X@xou=_=e#RuW~?`u zx2b8;aqsIiFzfQlISMY;8W{UD0z(ev*Lgn^=#Sedt@FBNQ)2EG{Wf0l>xT&J{HBa~ zJ{DB%bkb}xrTszOr}w5ZG8qvMvJ8_c+!|(%h!)0meUf}xij1%q-0UiW#53QW<}`nz z1#lcnX_H2LFyA!Xf!177540X6n)q_EJHx|Ty%ZPZu{aO&%2dwBmFuv0TJ8K-?aL5 z3YRTZd_mRVa&P);v)d8H6mV9AvEI59adt8i!HHj4Ux}UmtgN+Dhsv^ixw|O2R7Np=0E8 zfzu%4%uhyEt0Zs*@uM@{vRJV>cHDV5z9`7pLMTGR>iYw|KOf zvqP?DO-)Vf=GH#16qS^UNun0{)Frs=R|=jUuR3Oam`Lp}x40)^i7v?{pvZ3h*ejd5 zkRTF2wzcz#t?Q|o;(OXl+j0V-9- zQY8bT6*}FjQD4HI6n9vJCeo>iml_=}HJw|n>>`0c8qW~pU;efp&XZJ_WFyl zAUTsx-HX&`z;2O+Qy2_8#=2~)k(g!m`c-6ctCTgogwOZ9J-2G#K|nyryMuIebfkp9 zGz_RXK}F6>q*{Ze$bz1!cA;$%A&%EEUZ>mdqd~6PbveiSjy@HZP1Rs0ysp21cfRF zgk_4HsH^;e^KYgg0k};7O92oA@Qp+#aEX1viWneXBVd{XX9UXDmmpJq)u8(NdJkk^ zv;j`}JgP{EBhxfWaW8=vD{Js*IgefKtjuIGQR}Nd+|2Z--{xK6pF95PV&1V_u5e`^w;{Dfg^F`MHEOSQl;^?vU)^Y`CZGPQaf^NmAw!bWbo;6TWa=;!1HefipO0^ z0m<_c>{V)jBT>%fIGM<}=e(YrC-bRnb>li?k{F4|DNIOK{X^5W-sHpixC8JEwUx!# zBdx1{irn9?LgA2fzh{mXE3oW!TcPv@h5>~~F< zWQZ=SKdrkm5n`lr{&m<4RpF?$2I^!CtM&D;M1t&;lUibP`&WxSi*7sH;H|c}2CCjm zbYI(&kAARRQ$W z56*f~I6Rm<2+3xa&1a=^1FP3U%;K-9I*sWbZ{`{Qz^SpK$q+Q+9ueQOtMpR24kny$B;V}8 zGey%$T(=F3OF|hse04>y{irOj`j%&MRDz6sV{W%A5BMa65lafV2aumX-}ezBC(jvh z0bm2s*&=n}v|y}RnIvzJ7Lr8IWa4i+<7T-hCiYeD_PHRffv{I*X>#x8ne^BOU`;M- z+!HE^E~w9k9{@&1Iu}o2p0N*isnnGcNHvrnLsYanJfaSt}UT$4O0+rn>U%R zL#xHk_V!@SQ1<1H$R*Ng+B-~jy!!V&=WUBuJzY9kLLD^TuxpvzfWAfbSg6Y_Ome=# z%)*@Epno_PGWzPK=<@Gd6;Ky7)2ZR)L?=yVyLZilQt%vO-@2eS-r$NhmPrq}pcy_t z7Kw=3pwgaWC|4yFC6q$_v&wq1o*0-GGa`UXDyE2W0wV)LWelB{HgP75?a=_h*U^)^l!tbrl(5Be+jNv z81$WON?!0@>`!Q=cVI^yJ&U??%aE=$8b_Qx7~^`kX_I4)ktxw8;5{AGGXCwR?5LdG zYyn3{(6z}@&a-XffPFVXWRv|D-73t(x2ZopH8s`4K=XVnsvW4jeTZ+cV8va6L1-6$ zF^qCZ!Ed9cf*Eg>_n)ie4{SLDd>?t&q%}qL3cE4ZR3*#H@V?Y+ZEn6T`$YlH^vGsIm7#DCG0%X=|?;}^) z#0Nv=z&;|(>ToL9NVPEyv+UjfMi`g8Xl&uS`o19rqV?XL0p%bWdYgtGuYdxu0pc2< z=9Ew2b%l*sd+$1_pp(qw@Cl{=micST#h&{zu}6o>_k(wFxQ~RzKJzcS${!ug~cf^!98Vr^)J# z#KY>7%H_k|^(ETxNrY=G*cY|Yv>AxKArZIbtG25ZZ_1B^LEF+8eHG1USgR8GQYdQ? zU!5%e;o6*fQPZB5-4n|kw=J%qHm3F_V&5(f)E@8+N~R3`zNw4K%PZjCOy<}v1H-#= za-!Y1w2dRXhfse|y>~1f93PK)rJeem0K@-tCO1UYEzuscZC&x+-qBZ=>cNJl~&< zP*qipWd&*$Xw>5$u|m`HvkGl>h@0&u=L>+n1q7DAy#NI0$u*uG@p7^T1_qSegxEld zSAvW{=dq_6F61IzM|hONhVnNJCxP-T>|Zq8RL)tllr_sGhcs~X=RYk^O z27}X($(4tPCrk=d5&%#>Mn*oFDxOzG-mr7J_BHySEruNycZQ|~UE8JbvTA9X<{B)@ zgIut*)Njm9erfRXU^%_HWf~l{_E&UaLF~h?A1>r{GMI@Xj{ z3!Bf^#3GvaBPk?d=r9O1IBJ7c>RJITAW3C5=T?CCLLB40( zi5`!w1m7WLhVO~5&OIN=R{T;l)B2c{lZgGb^j^^AJuNHi4Hg zRi2sY@i-oWVRhOQhVzP)32`c_;yr5I*#1piIl)aWhM|v2K|Po!p40D!8UuD!4CSy< z-96vSBXV(3ezlw+8^*UiR>(P;R;pNR&!_9Q6wsXbG%s3`vA z`=>G`_D!F8j@3L^)B_u22A%xDG4AfDW&R;B? zl&%R8PxbV^0ccn~}4oiNNAm#{xP3D*V-p z`2bw74QPvUGReCfE%O6+eD?dlZx63FC#QnoSV0c%`JnR;nYXzcI!g5VkQ8!*NyT8} z+Cjs!3JBdL_Z9IPZh#x0m&*N$sT6Zcn~98jYoB*f%doKM=^CZJt^rTO@NjpbmNN4i zy8s)=)P!Kedf5ZQ=6i1EQ6eH}Tg$nGB4zUB5uL-)*^jhFWH$ew$X<2cklh~~pC&1{ z+VG}e?xX^;LOz$Nw6i`p-B`hM+N-Tird+=U=?rhRh&Zs%Oh|UG$vdP`Rl$b-ndX0m z(C>MCU#PXRa{1K#{IyHRYO8kS);AKocbJC{KE4r2imPsOafl1`#9X_7)%lE$U&{qf z7de_hu?c7uafonV^hr$q^B%uH`$D)nR8aBf*{YAtD_j3GNW{c9MN(FN1_oU!zhB?VZq$s4gB!=m_u%W?K*qPB5Ioo6}(%krG#t+-!dyh7ucZ=pMqYbqyrjla$&;m z_e~Z@qpPDG-3k{y)pQnr#3R2tUE~poH(5_v)^nvYTvf|C6L5j{%`q7hjMYIdhxUlW zQoVIGq3Q-NDO=+Mc_z=Tk8S|-isyS>;vD=eL}${*p~-AN zO59QT!xndU8FsNgfAg@e83ec*RBkl$-sCNgD~3Matv-EQzzR80!=Zg_bBzf|c0Po4G8=Cv^jEl5d(-x$B?$+nf! z)yZtsX?>*KiQ}d{$g|gN6yJcOB{wJ!Bp;}@RmN2WdcBZ3F1&EKA$r_TNzb^& zZA~ZF4EKJdeZbea?b_APu$EU1L;sACUZ~tONxxikZv6*4MDaHgK3M_j*7j7@)BRUB zK>zp13=-wqllR&lh+Fp^1r-!=k&#uf6GO|>1!8)+PL^_`e*8$hyZ(`qoY2+=Tj}n2 z9CH73^6(Wag2SGv&4DKJ3qFc-PMO&!5y;81T0`&8CB0TA@B2-eT%#ge-PxjPNG1%1 zHk7Eyw0W^%=HQ2u92}i~us00BPKt$v6nW{>TM;3~OpveUC~dE;<+8PHdqbxjUxo$6 z{~NSPDA)X8_MCNBvBmWHp0wNo*p5iI@wV4;mFrQAXVh zCjKTa8NSckq_Eb@>nbi4(nQQfUzorCyE7ISx9~#1&W7;%axw2HL{3*Ps_3SPVZJ)T zTFh=^(rx^m@7eKk6WaqVI8^d#zp%B>mRk%Fk=AUP_f$KJ84lwdV(A%f8`SU>8Bka- zD+)1)tj{XNso&E54)09V+NWpqEO@RkH#b*yyj{)+7TO7z$q~_ya?zYRAbmC!91)-n z33NOT>qYUbf^HyDlj+@bR(UEXAPEC#vQQvI=uHx?#{SlR8VYkiV08LeZNl15YbhUF zf_V6EY$^04;7E)KiK~>;E_T;Nk6KJzA-!(+sKxZ!$@P;8cO^+Dw;={0JNjv+dKo<* zU(0+Vef`vLObnk_WCp)~>Qq73_e)6aTXU=0>m@M?#o0z?HIVTd9{zlCx;#~x0`vQ( z=|StMAc~o^+t-fP3v~eCj7ho_QZ4-gj-SFv-d2lk_q@X-Q$z#EXDW-a&>f3vJ&Nq# zMrj=8ksf0R#uh7|m)|f%AQMQpv9=)|L`q6pU^vqZx*wyJk zyx$~RZTg$UQ!w-% zySJesMt%Uk1#Z^Tne9!3Z5~SY`0uVfi;Q=+^Tee`uuA6D@Cf_$WRK&F#}I{XVu$`< zk!*BTUf$hBJTbILbe!RJ&RRi}yHIQ;mByXLhOI?$tabp2OFV9)eblMqQeE6?;a&|Z zEi3u}o)@^jlS?I3?g795>i0dKQ%Zc|XN(XYiUG*v#Y%J1J4OTfpaS3Helmad0sf}& zC_XA_zVNLZQ34_XJ!Y*mqu+9}wv6gaMdZtX*p!wx^_3h2we$G7GNuykoD1&~TZ21eD8IIsohh17BeWB8_O*0jX@S6FYx*S$57FPIvu< zY(0^K5F8Q`KE(sj=eR$YP4n~fO97Q7Pp-CmbFicxDd@K~?^mm7TI(mj*ME5k)iQSV zPFc&|E_Exe?xKT~5fHJxH=?*`nV1ym=;}$?BwbvDPxxr*jyospej@XF?I+R_g1H@X zMkFu4N$Hl1%#$Oe#DA#X_?-h_Nme2OuR4Mdvz`o|^>?m5QrhidhBC}q!DT^mbGijn zuiTFm$A~?W|EppW?^85LT{v5=6@iA-B-c1zW41niZ1{xTJ^7~+sV?dbipF$X$0N4M z^r?ezm?s4MX{kQld)g5tq{fbo{v?iwe*FlEo|x4ASo4;VHJ&TxqsnTHU*YODZ0RHt zipuYH`0;dOrP-B1LQ*n(QGrGdCByVhV=Y4p)A7*J_O|5l@i83!Pcm7d!x-PDP)J%U z`y*Ne=a_zpzogM9J*scu^gBwLY@t5YX2d%A=?@oD+@^iLjsqT!p~1l}11#BB>kU$* zv`PI%<+Ahm0xi_Rw(Z1^A`2d{&9H%;RsW~VD!nGkB7oeIA3d`JdEH+-^7`J^(Wbf| z{+cwR8cg?N8JhI6Nd&Mv>T?=96ECr?-DQvl4Xr2no1s@IM23cjj-q;hFuMi3&V?V< zd~SM>57R)(+JFHj?6>pzuF52Wx$?@#bimw#Lrlz|7=AWW)PL0c?} zS_1;nzrkepp%TXwhqG*lho4V*=X(Ya_JXhkUnOHWB(XGKPyrrCf&%0ogs&(r=1b3K z%C(p$1sO3NR9}V$VPZ9x^I-FLjDbzzl#XcZ;_HblBb~-uTR;nP*`1(pw54+QXmZ>L z@z|V-<}b>Q1$a*`&y9TgFyZzuTy!kWrMu;op)-HT9hd9g>N7&5=M-34 zN#DLj1Dx6}mSmM(mCMzf{uT$OBq?D1Ct>jb^cgl&0pZ@xS(oMI=IKmb_kkg3_{z;6 zuqmoKJ^Y|=2`<1BT8WX|1fz=rF$RzG!vh2*>VQ*FS>(&)QRL$J)jR*drbJV;=r@7a9!W7I@@+ht9d48WC?o8&W@C6 z{5omMs}=%`u8FC4S7hN*98@e0EO1a~x5aXt0%$_`m5O?dMVaM1YD?3NqSI;DuG&#) z90SdT918jzNuT+kX*0J-!0R_v_z=ZBpHsP=&PbT)9ChijEw3GYwdy^`t@Bu2N3DHS z=5+Ysqsl=UD zKN*zxp4;yg#M*VAE}x@5zD@b2Xdvrux1utI>1p;tU!h5M75ym$j(z}=xc9)F?L@Vw z^+jBkQ2%)SsNw1@fPSov>6^G*i;uULB_1<*oSySh0wcFf+u?|LHcCy7t^ix`LD95<7UZQbB;MB4K0%Xef2= z(cm|07xQ< zzdzZ1QjBpTr8^Pu`4hX}rml1|(%p(l!9Nmjevz*2%9eRHFR{wsH$o&f`DrrI>3y)D z4(yGm--gU6l)XFVIS^ewCj!fyx=Y{~s4_VLmP6vTM`LpY);1;*i6y`p$XZDo-sWuz z4sq;rwkbb7E41N6QH;>RyZO=+bcmu3$TdF7J?)V42vpFIr zUlQphX?fHa5Y#D)v9gNXn2t&kbZJxs=IhMVPQ7B{1a|$ko|s+9=JYjgzcf~Et4>in zf})>Tvp(|)oaBw_L$=~&w0{S9y6j9^P?v{tJGuEASpWC|$?fLDjMx)MzogahuIkp? zyG=SUPV+v!;lA6==%~7w=ZZPa?2m|kP4bq}umK0m3=g6sf21+=MA!SnDOop+(xPhO_$!^{QVxd(kMtt=6LdWRwk8;uXC9YAsfh@mjSS z%Wg4uR^qC1+T8hYd^1g>O?44|AT$+?E&3(95x zu#-$0MXIt38bSiD`^)-1*Kvb>QtxJukyMHJM96)(vcO*a5tam)e`*u4VxXIk<>kLe zL@owjzQ82_Q?2tY+#;|c3b#p<1NGVmQo2AnX#&>2Z?WDW;8UOiB?{C58l2JCY(~-^ zpzp=H%GsnfThlMN)iGYSs=iUPx`>>eX>zw9VsR7>9{TDGbh80Sad*7jU)3bNZ^pzF z%ldje1ox6J%9}{bQpb=N5Sv(DrlAyeFJeuH?=e`Ow)ggC#jLjYvAg%{S+_S`(O%vWk#y^A+6DaG8pBrh=4>_st90-_G|!Nie7%h&)0d-032g(4fhzD?HaUSg z!CuG^Sh^H~Z??(aeUXkBW85vj>d3p;na6Kh>ZAzVgmlF~x$9nQxcK}w%xp}H1}MVp z5Wh5L=6`X7Y^-3I#EW`&DB*8vyMWI{cithyX?@}>JN4t>5c z@zou@x*(ZVOQhUHa#I=J5>9^w?{|xe40`RIcqUDf=(<4Gl--PV#8jleq;Gjr)HdV| z<8=aTsm^?6ZKzeXP!~PpO{1R19=D^P^`gV{*Qvg7cRgOG2ltP?YWNZLO8dhW^{ZTf zu=!4LQ5xe`(w3GUoE*zdyRf)uS>QY!&!mD(O&sNNi!=MJ6GdeKC<$+PMN>59{S9%324F6egoAV3oKnLvOZw1Bddy zJ^Py;%W4(8Z$2E{pb7qx+Hj!?ccAj&v;aLP5-@<*y1c<^)PYg)vFU0H8T1)qJ<&e~ z>PZQfKeWFFLQY0Q9MMelO3wetC}{!Si9cO@^bA8rd*SJtn#Bg-A>TyZUEwl&gQepQ z!DW4Q1*e$i99EG$Xsq`$Ck?ae$+pD0rI2o0s{_@!Fi)5T@XiE&2~yWyqi=?wv@^~n z$;IjEf5iER;|f71qQ0?%hhE7w-jSp#!zQMpCWWs4g<^I1`Q`>I-yB5&Z7lqf>}0vt z1{-`a_(xnMAKwGHH4}jV68BlVF?fuGhbqgE$2<6o?-z-%aK`}d=Cj?}DN}J0o)*4j z?Z)%^dl3vw_B#uwq((jah^NY|N@rHo(T{ zwFhWaI)F3)lH={Fg6F?U4nln8P4N57KjkPBmsF@PUS$%8-+~>J!0vXPfaJ~Z;O==G zRqQ6Dk*@f^_r?I(>wk2zC4>OxHTfB+1^ydRo^{r3yTVoMd^awD*xA>e>xbu9W!H~3 zOF0-KgD!86l*(%EC;)o^?#1CZoQCyx{>lwm{GODso2ym-Vg{|M(7mo86t%PM(cZiM z7_#E&Vx@$nBwSZOZGO+lST6lH;>7_x2lRxA{IM_1LXo1XtC^|ay;GHxlx)B9I^PYv zFTQrtrUx>!x{kKCHsv)5(8T%K*4AnwM`ZmXF%c&`DvBEDwQ+KC%Hvw~NzkdcmZ++# z%40{~0%{BpJ?{U4c5jIR{t>wVOYk~?h}}}y&CPAyJREL5P~OLWg_7|OVBmKC!MsDG zqrPqd39`Z@E^u0hh}+@!8B+GS7Z7IR0^#YEx_{Qb#qB6h>?@{Uv zQ{CC56j_){baeD4z$~~P%t;hcz%g}nax%W{N~?D1mjuT>X{Ogd3gwb1YvFz3vR{$V zAP9~pTy`kyzX2~K)yl?-10X@?p;qZa>}LKG`hvD->FC0Yjg3*02 z%L~uOvbs7KxP#H3#mUvVumy5VU;R&|u^rGA6#rxG@(l$W{Xo&(ZW(aHF#x?i z?y+>rr9g3^9&0q?E^MgsVciI>OM2ZHGECnIoa=|crw1s(KNmn!4)eVT3nILN@MDSRV{v#TIta(Wox6=`icExqwvsO- z;qRTK>;DPwDi`JDMQ?gnF%nqOpTtiCSsN~c`Z&T_goUM!CuROJ!oa{Fm5E()Cx)+% z{icAPZt1#i&3dFan!29VhnvP(2e>131WY(wkC#)Q%ai2nv$YD={P)U;V+e)-6tq88 z{|oYMu0T{40c6$5C9rd;cDi}*ZN~O3VD$SBMVu1~6A{uQKvV9r%DTx`;#OL*_n79x zJDF&_+@Pi443vaM7YO-3sI_LF>OS{uIGssvFEO(eoWCd;kJSp9m`yB)I~y%WM>rBa z1=Kua<{9^d<3Hm6ueM1Z<_(}Ui?`4n_o2qSDmtE7Zf*IM#U?dYf_lB<$D>tYHoREU zX;KkJqrgM6Nw)$wTk^9HraDL zHYu|+$UMwE>|LmRBKKFJ|BXaOMt)JqY=cF{UjQifZ>C#EzItYIo8G5IewCZ5c+Os4 z^+4kFzgGY{i|*m{gGr_f5`}7fO3r|V*o4WO)WP{d~0iJ*=Am&S`~Z{HKFZ{6cT~n?mn_ zfaGP)lm0`;jPFNxjXkt=H!?fR9V9)Vh&5f@^VG6B7S;crm>(0>hVgGjrY>lA{olD? zD+BILbb%-OOhoQ$o%YW%+FUiVnaS44m7MyH(?i!S3&cN?nP?30z{E2nz*ykj$h6-& z2ZZ5<30r*MzRTCtuX$cLq{|S0|GeX>5&%0n>VJYIBMZ+qsAx2wlI z>gj0z-Mlh=QtQNDVw8`4ezAVpxq;^B{!?*D*7}NvAVVElXECx;?z0uNUE?W<$*K?D zi-)4aj7;^zn(0-IR%RwUk%da$ezMyfBZKz&*=3%4Ls)9Xm#}@%-uUXOKh858PyN5% zM5F$@u~k~)AsP|!XQ7LYRbryzYFFB#?{!6LbyygHu0O$Y-!rEKPoX7W3LXFWcV2%9 zN76QOUy6~ZBVF0(XS|$o$$*A+Vd|f=_Di-cd0~TLUCAgqK=u4L==;|O4t4*tt$i10 zQ3kz}J##|@X?*GsgS*jzZqygDMymg0_pLa0IT(-)OrIy}vczAB0TCIQ+7wZp2QVA{ z19kr=2;7{r$Q2OxY~5I^)9-Ud08WfOsxX?(0SPj7$zON%YmzQ-7%a_#h@{?UWI7Ph z2$Y*cz-O!ofBL^46{mcWi)kAP6!8CSQgTe~DWM4f5V_W# From cebd91b2dd09a826b2d22c604efaf71ebef123b0 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 30 Jul 2007 05:18:55 +0000 Subject: [PATCH 0050/1663] Removing dead pages and dead images git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560865 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/manual/builders.xml | 46 --------------------------------------- 1 file changed, 46 deletions(-) delete mode 100644 xdocs/manual/builders.xml diff --git a/xdocs/manual/builders.xml b/xdocs/manual/builders.xml deleted file mode 100644 index eda27441a..000000000 --- a/xdocs/manual/builders.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - commons-dev - CLI2 - Builders - - - -

      -

      TODO describe builders and resaons for their use

      - - - - - - - - - - - - - -

      TODO PropertyOption

      -

      TODO SourceDestArgument

      -
      -
      - - From fc13a2ac1cea3977e29bd65d69deadd0ea3122c7 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 30 Jul 2007 05:19:45 +0000 Subject: [PATCH 0051/1663] Adjusting the commented out part of the menu git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@560866 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/navigation.xml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/xdocs/navigation.xml b/xdocs/navigation.xml index 200479a1b..8caa56426 100644 --- a/xdocs/navigation.xml +++ b/xdocs/navigation.xml @@ -44,11 +44,14 @@ - - - + + &commons; From 7fc09eb253386e2f98ac3372aed4125a6875069f Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Tue, 31 Jul 2007 18:13:25 +0000 Subject: [PATCH 0052/1663] Move Commons TLP changes git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@561417 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/index.xml | 2 +- xdocs/navigation.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/xdocs/index.xml b/xdocs/index.xml index 9719a76a5..a32b4f44b 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -67,7 +67,7 @@ The subversion repository can be

      The latest version is v1.1. - -Download now!
      +Download now!
      The release notes are also available.

      diff --git a/xdocs/navigation.xml b/xdocs/navigation.xml index 8caa56426..29eb9269c 100644 --- a/xdocs/navigation.xml +++ b/xdocs/navigation.xml @@ -27,7 +27,7 @@

      - + From a87932dadc4a8a10ba8e9c0d3e563b90f68925cb Mon Sep 17 00:00:00 2001 From: Matthew Jason Benson Date: Tue, 31 Jul 2007 20:37:11 +0000 Subject: [PATCH 0053/1663] Apache Apache git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@561501 13f79535-47bb-0310-9956-ffa450edef68 --- doap_cli.rdf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doap_cli.rdf b/doap_cli.rdf index a6bb62be5..5b246e680 100644 --- a/doap_cli.rdf +++ b/doap_cli.rdf @@ -1,7 +1,7 @@ - Apache Apache Commons CLI + Apache Commons CLI Java From 822672873c5bfb4ca130c83c6684381e18a3937b Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Wed, 1 Aug 2007 22:56:34 +0000 Subject: [PATCH 0054/1663] Add missing license headers git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@561984 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli2/commandline/ParserTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/test/org/apache/commons/cli2/commandline/ParserTest.java b/src/test/org/apache/commons/cli2/commandline/ParserTest.java index 096a91927..0077f5df3 100644 --- a/src/test/org/apache/commons/cli2/commandline/ParserTest.java +++ b/src/test/org/apache/commons/cli2/commandline/ParserTest.java @@ -1,3 +1,19 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.commons.cli2.commandline; import java.io.BufferedReader; From 777661ab2bd27d3a36ab087715e85de6cdd6a2b9 Mon Sep 17 00:00:00 2001 From: Phil Steitz Date: Sun, 19 Aug 2007 23:06:31 +0000 Subject: [PATCH 0055/1663] Updated commons parent version to 4. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@567499 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f4e7d268b..1f4bf94e9 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.apache.commons commons-parent - 3 + 4 4.0.0 commons-cli From b468965263c9175b1ffedfcb72e3684fb4fa19a5 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Wed, 22 Aug 2007 12:38:26 +0000 Subject: [PATCH 0056/1663] Fixing the user svn url git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@568589 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1f4bf94e9..fad929257 100644 --- a/pom.xml +++ b/pom.xml @@ -44,7 +44,7 @@ - scm:svn:https://svn.apache.org/repos/asf/commons/proper/cli/trunk + scm:svn:http://svn.apache.org/repos/asf/commons/proper/cli/trunk scm:svn:https://svn.apache.org/repos/asf/commons/proper/cli/trunk http://svn.apache.org/viewvc/commons/proper/cli/trunk From 6b97c7a4a95e70c4e88fdd172c0290dedc5307b2 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Thu, 23 Aug 2007 13:38:00 +0000 Subject: [PATCH 0057/1663] Changing name to 'Commons Xxx' git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@568979 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index fad929257..efcdc95e6 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ commons-cli commons-cli 2.0-SNAPSHOT - CLI + Commons CLI 2002 From f04a1fb1a6453bb22509bd0cc4422af4d3506db4 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 27 Oct 2007 23:05:31 +0000 Subject: [PATCH 0058/1663] Applying Brian Egge's fix and test from CLI-122 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@589237 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli2/option/ArgumentImpl.java | 7 +-- .../commons/cli2/option/ParentImpl.java | 8 +++- .../commons/cli2/bug/BugCLI122Test.java | 45 +++++++++++++++++++ 3 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI122Test.java diff --git a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java index a5f9c2526..066a8ce82 100644 --- a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java @@ -143,17 +143,18 @@ public void processValues(final WriteableCommandLine commandLine, int argumentCount = commandLine.getValues(option, Collections.EMPTY_LIST).size(); while (arguments.hasNext() && (argumentCount < maximum)) { - final String allValues = stripBoundaryQuotes((String) arguments.next()); + final String allValuesQuoted = (String) arguments.next(); + final String allValues = stripBoundaryQuotes(allValuesQuoted); // should we ignore things that look like options? - if (allValues.equals(consumeRemaining)) { + if (allValuesQuoted.equals(consumeRemaining)) { while (arguments.hasNext() && (argumentCount < maximum)) { ++argumentCount; commandLine.addValue(option, arguments.next()); } } // does it look like an option? - else if (commandLine.looksLikeOption(allValues)) { + else if (commandLine.looksLikeOption(allValuesQuoted)) { arguments.previous(); break; diff --git a/src/java/org/apache/commons/cli2/option/ParentImpl.java b/src/java/org/apache/commons/cli2/option/ParentImpl.java index 892b95ddc..064c80418 100644 --- a/src/java/org/apache/commons/cli2/option/ParentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ParentImpl.java @@ -217,7 +217,13 @@ private void handleInitialSeparator(final ListIterator arguments, if (initialIndex > 0) { arguments.remove(); arguments.add(newArgument.substring(0, initialIndex)); - arguments.add(newArgument.substring(initialIndex + 1)); + String value = newArgument.substring(initialIndex + 1); + // The value obviously isn't an option, so we need to quote it if looks like an option. + // The quotes will be removed later + if (value.startsWith("-")) { + value = '"' + value + '"'; + } + arguments.add(value); arguments.previous(); } diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java new file mode 100644 index 000000000..5e818e6f3 --- /dev/null +++ b/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java @@ -0,0 +1,45 @@ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; +import org.apache.commons.cli2.*; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.validation.FileValidator; + +/** + * @author brianegge + */ +public class BugCLI122Test extends TestCase { + public void testArgumentWhichStartsWithDash() throws OptionException { + Argument wdArg = new ArgumentBuilder() + .withName("anything") + .withMaximum(1) + .withMinimum(1) + .withInitialSeparator('=') + .create(); + + Option wdOpt = new DefaultOptionBuilder().withArgument(wdArg) + .withDescription("anything, foo or -foo") + .withLongName("argument") + .withShortName("a") + .create(); + + Group group = new GroupBuilder().withOption(wdOpt).create(); + + Parser p = new Parser(); + p.setGroup(group); + CommandLine normal = p.parse (new String[]{"-a", "foo"}); + assertNotNull(normal); + assertEquals(normal.getValue(wdOpt), "foo"); + + CommandLine withDash = p.parse (new String[]{"--argument", "\"-foo\""}); + assertNotNull(withDash); + assertEquals("-foo", withDash.getValue(wdOpt)); + + CommandLine withDashAndEquals = p.parse (new String[]{"--argument=-foo"}); + assertNotNull(withDashAndEquals); + assertEquals("-foo", withDashAndEquals.getValue(wdOpt)); + } +} From cf02136ba447af6d182eef75b95f995a2623eb86 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Fri, 16 Nov 2007 15:24:00 +0000 Subject: [PATCH 0059/1663] Update m2 build git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@595700 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 34 +- src/assembly/bin.xml | 44 +++ src/assembly/src.xml | 47 +++ src/site/resources/images/1x1.gif | Bin 0 -> 43 bytes src/site/resources/images/logo.jpg | Bin 0 -> 5776 bytes src/site/resources/images/logo.png | Bin 0 -> 10153 bytes src/site/resources/images/options.png | Bin 0 -> 27463 bytes .../resources/images/svg/commandlines.svg | 57 +++ .../resources/images/svg/diagrams-cli2.js | 291 ++++++++++++++ src/site/resources/images/svg/diagrams.css | 65 ++++ src/site/resources/images/svg/diagrams.js | 368 ++++++++++++++++++ src/site/resources/images/svg/options.svg | 66 ++++ src/site/resources/images/svg/util.svg | 47 +++ src/site/site.xml | 53 +++ 14 files changed, 1071 insertions(+), 1 deletion(-) create mode 100644 src/assembly/bin.xml create mode 100644 src/assembly/src.xml create mode 100755 src/site/resources/images/1x1.gif create mode 100644 src/site/resources/images/logo.jpg create mode 100644 src/site/resources/images/logo.png create mode 100644 src/site/resources/images/options.png create mode 100644 src/site/resources/images/svg/commandlines.svg create mode 100644 src/site/resources/images/svg/diagrams-cli2.js create mode 100644 src/site/resources/images/svg/diagrams.css create mode 100644 src/site/resources/images/svg/diagrams.js create mode 100644 src/site/resources/images/svg/options.svg create mode 100644 src/site/resources/images/svg/util.svg create mode 100644 src/site/site.xml diff --git a/pom.xml b/pom.xml index efcdc95e6..7cb8ba100 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.apache.commons commons-parent - 4 + 5 4.0.0 commons-cli @@ -165,6 +165,38 @@ + + + maven-assembly-plugin + + + src/assembly/bin.xml + src/assembly/src.xml + + gnu + + + + + + + org.apache.maven.plugins + maven-changes-plugin + + ${basedir}/xdocs/changes.xml + %URL%/%ISSUE% + + + + + changes-report + + + + + + + diff --git a/src/assembly/bin.xml b/src/assembly/bin.xml new file mode 100644 index 000000000..576229197 --- /dev/null +++ b/src/assembly/bin.xml @@ -0,0 +1,44 @@ + + + bin + + tar.gz + zip + + false + + + + LICENSE.txt + NOTICE.txt + RELEASE-NOTES.txt + + + + target + + + *.jar + + + + target/site/apidocs + apidocs + + + diff --git a/src/assembly/src.xml b/src/assembly/src.xml new file mode 100644 index 000000000..a2262284f --- /dev/null +++ b/src/assembly/src.xml @@ -0,0 +1,47 @@ + + + src + + tar.gz + zip + + ${artifactId}-${version}-src + + + + build.xml + checkstyle.xml + default.properties + LICENSE.txt + maven.xml + NOTICE.txt + pom.xml + project.properties + project.xml + README.txt + RELEASE-NOTES.txt + + + + src + + + xdocs + + + diff --git a/src/site/resources/images/1x1.gif b/src/site/resources/images/1x1.gif new file mode 100755 index 0000000000000000000000000000000000000000..35d42e808f0a8017b8d52a06be2f8fec0b466a66 GIT binary patch literal 43 scmZ?wbhEHbWMp7uXkcLY|NlP&1B2pE7Dgb&paUX6G7L;iE{qJ;0LZEa`2YX_ literal 0 HcmV?d00001 diff --git a/src/site/resources/images/logo.jpg b/src/site/resources/images/logo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bcb742221707b247a0231d132867f702cc005368 GIT binary patch literal 5776 zcmb7HcT^MKww{m#P)ZWIp;tq10V$!E&=CR%A|-$d2uLpi(t8a>kPgzMNKpi=bWo)C z-lYgiQBV+g_`BD;?qBb%x6iCub7p^guXSdx{mr+}C(joFxR$!6IsgKJ0F8?UoSy;o zD(<)Op11ATd>lOO*^KOOvtc!Lub6qxLX^^xC1Oqz*l9`#6m6e*FgNuWOi;0Dm}0omU!UQP~iz4mcuz9qhBY;&&|ZHh^_Ky>hSqa zBUPr%PM_!gGI$Z4EYWZp2jbOZKibE0c9*p}C;(^2n*Ec;3Dv67*uhm-GS!<7oA-^c zb##8}OX|wWT-xR^)9GT@fWgXAT|B9{EhU&<(mYnf@x~y@vV4f}5yLH!fgKw30fpu@O$NiF)c}zE>l8%9DL3khMo$!Yki}MG0iE z^2s!*>t|pyyZJc~M87wF4!FX)LypK-epNBPaN~Tr{I)E{>bc+RB_UP<9YTnJ_o8zSPr3E%w|<@)MBT4f6}h4g zvAu<8va62Xp=5w_RYk99SZ~VIb2MA4d52jssR=ODjQRqgOBNJ{0-{($ieh^_M96*! z?JKHLw-^lL_QZ0Th7r+;^p;}pA;)+0t@soucqxHe)$yLK-xHkq#nQ9&i+Eam4*cmC8pMB**gp;9`cGF}u$ux1 z`o92({sPqC01@b-$wVOW%4usD0w{ zRhJT1-@~j4tbEniB78bmcgocAr}|>s!)%(WdR~h8WWTc%7D#RCZS?z+j1rQ&E~xHV zw-0$f$&R*%BhyZwzY1cdzljcFow+3EsTD-`u@;nD5kg$b6{I$M5%*S&$}~GkWpeIlwUXb}dYk z#r)%EbOz=sf0|obsAL;V!K~6hj>il4u~mNPbJ;6G9g?TspYL8j{6j-R9ql_m>76f6 z>KbFG@$;B_WhC2AT7ABnMJkJXta`-8x_P;_X_AUQ-w#Z868`KRt}f}?R@D2PNl(T`0 zw2~0aAmd?_@y_fz2c~IXZ=3`CH+eBLx|l6&f|9VH*`#le-`Pj)*O~rV!{QYv{eYb{ zq-Mcxv|m)3Ou6Z9+!1=u{h?1P!78PR{~&Z*a=6Af*n3!+F_mGyyLhO{?0RQ|o~4gZ zfywB{Pz8RItt=0Y=;AD0!Q7b-ozA6M=p^Pn$7GGIS5M|rXLKp2B;$J{`j0hU#=RhS zZ(cCj6)3l(vMZPE+G;c+X!BXef1`CGXeAm@R$rB>e$^XufWS}&jH*oz7cizy!y!mbL@!hMNbCzTzuW9ODAjE1OTqeIf;NJSR)4jUj zYE>7%0~3OuGC4FxvX&0Beuw{-Ygbg25Pz%S>12^j3^nHX25sb(s!kgF2V-t#MSaef zZ2Pq?3o?m5m2DLCJV>+sL8j}**Nr@Qj=KtRwL8k3 ztI8$2S+c0+bvoBFQ2!)S)}dpEO}U=jVL@G6iY=3GwNjcqVDwR~tEbw+Gp*mNs;ozL zgbx24b-RsmSJd?EuBS|0vI#C!E}iL!Zcv3f!E~Bx@-Wa{*3L%ohlA4STfz0>#t>!o zFn|)}tByK*z)Nq5!RMg{wj0}5)qYEz^qH(2Y40A-eW{U(sM{{HU2fAjOiIa%3y@c} zx**jtl1i(n@%6@Yz+LR!kP_GG)+gt@uyf!&w;bJ1w-=6E7P4z3zUA+uSp6zsChuX- zBui2zsYWLJ$}JM zIxuBPPk&%A^Rqlg3F3aWtBR1jzH>k3 z4T+hH>XW;o>fAajOgTNqd$Z>5!CuoY?gg>cK*Hu?rx=p|)|U1uTY|o+)mZ)oq4UBo zgeVb+i1Gwjt?Oe?$))6C=OlUWBV(P6xc7s(G_70d3+%cVVBfN!uai? zHwCG$7?amsr~Mg$fHsH;cltq}W(@L1tUQCQc9%bCf3;0NGXjwf_;o*f=ep!$ zj{WHgiifo+i+-?oKqa5^NilWj zv0%trCNKU_jbuD(rC6E!zSld%cOQvYP0S4ksO_R6(+ar*52rPyd#mO}c*~M0O!P^+ zc-q>R-qeq5X2W0ejcFNcVO&B6bV=*AtC!}FZEyrL3urdA@VvGxeXjgm$=tS5XL?%& z#a$Y3#6pYWgGsQXWvRUFkcgLo7ve}jC^TYxIt6{PWtQoX70TVipzD( zuvWMa>Mi|va1N+yv-*S|KgjnV5VI9=fK|)u3x9H+0HZe+zwP}dXc=;@hO8+~KZA>o z1!Y_Al`IJEzDdPTV3a<&G}3>2T~@_=bpveXxt9ri{)BwB^_G6S zFsE)e^G5FR_vm(6ir_}4Mswm^5xpEjHJu<)oN=|$)U^t%CuWU6v!s5cl%}jg)GRlg zn@xs@tlj*?!#Z`HZ_qjPQk}i{EO=LcE*>;bb?4#t-NrHG_jGwkr-S>G?iH(`#Td=9 zLpNjZP5UP4qldVkrlYsYcgcM*Z#Hs#1CCu{3ejgh3Z@N9%1g*sPM9QXtgDt*2P=ZY zFjd-crc&xXNq*pvgu;t^lv$3>R{Mdo9dU%aeb=DHOJ18ecIvhpHGMi%ma^W`_@L+F z(9RMup^7S=wyd#YmfXgp0rU4kTv7MjbM8qAVP}Py@P&{ve}?!|@bamR$lB-8%=m zFSz2L`Szcg3x1Gl(o9lVU&@uKz`u{*kWm|4X|51K@*SOn(<#2myh? z|CX)@;13nz-9iX(5ye8b>lbu5wDeb>UgSL+RC`q=7cOOS7$38$-(v4&MOn0adKc~I zu^s!6=NyoZuM!q&5|OcmlyxelR;z{eWa-F+T|X@nqEIbD>nnt4E(%g{%OY3}+IxIv ztN5%3vqWHgiyIQGy-)K)meAHL#@(C}o-kSZUEL6aV83?l6pDSS2dl1b$la$&OMzA5 zmQZ@3b^sYJYA~Vv<2Z(eZM5tww3tn;iK`^^*4l`%V`8biPeZiMMuTovlG7!&=;(sP z58jS(U0EGmTi-GfkGSAYisdRyWg|JhssgRtFy*Yr)hKr>Bh6xv zP-whZfzmKCZi=8-X%}-4SkV-GF?Cz9ukUI{Hm2a(+t=gvY_0Et?~H`?*Kuk^F)B%e z)&{L_7#?Rw(|k^o!qUv8R`}b)Ez)i%-C9FbTxX&fV}8}jBCpaS;qWC`+E8hK`b$bW z?@0a1u8g0HyrGTUff`)XZo^HAT=Wglb(T%nVs-6KbC9ml51aIi9{S7{=_$f8>T+Kd z?2WE96r^nVR$qS7vy~N({UWGbQ_J}~P>5H|V2O^keP!gD-!=FOan2c)TdZhW`bI#>zo4pGBoqCT+ReIs%h+(Wgp9k#&k*yDGcQM@GUyWQA zYFp%T+=b(w!O+O%>>)-tX}BqO`8ArJc(|5D$jIfw^mQzh_6z8yP_&7S1S&8&SBb2v zc7H30#W}wp?5xms-r;_?Lj-UabNg@B9)P_!0h*c+k?!6xG-z!)Vry)=ISb@ z{#@#N->j;QB7t#j@{T3*4R8hrUtxXowsp z5%G?RHW^)+QI`o6v3TlbZ%6dF-IE&j4(vGg5jj?{uDWwC?)W}sqVzL+X20QC4PzFM z^6{VsGNUL+s*3I+#TB}tLbO)64XimU_!whcVk_Te@%k~^qj0(D#0fK)zL^?g32F~d zCIFH1!K@73yz^4=%4xWDW*&m-PPrkHDkw<`X8hTy55MB{ih(^>KW(S}>|<*q zYZf=}?VPN>Sp6geo}Ua-YkqoT)0K&vu7)zuyX5rAp4kQAv~EOp=YUoAuYsI9x4tlU zAB!-B8@m~vt?em-X@JAV6$s_G$c$6t)QEmQYS2)QCUPHqH)?$mvVw$aZRNO!Agnta*1U`a#vmP0jMSPXO?()5cYiPe*o#- B3YGu> literal 0 HcmV?d00001 diff --git a/src/site/resources/images/logo.png b/src/site/resources/images/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..7c689339b56e61ec5c04ffff32653aad0cee3165 GIT binary patch literal 10153 zcmb7Kg| zE)Vg{aL=6Bd+oi}x>4$?3fLIr7zhXm*f7Nxng|Gp9N=#YGzj?FWS*4{exaJZRCs~# z_up4RcXITk)jI?POoD&kh_mbd58%ZoZZH+OC-aEtCBpL=XSmqJhF1W! z{?=6ceU8u6ZEp9p@cl8pV)CHd{>&G5E;n~XxBcIRvdo1zltx&&p(1W>+-?MiGhc>g zU=^|or2qdn2Il?o*Mza8@kErgMN7jb=t|C4mDb2C_q#eymZBX4Gv9Ylx?t5+`3DlDD#KBPm&yhZaWb(9U^6>DqDa$Icv$3(UuoUPZUS3^YHR4)W zSU4xkMu#m@;yh96<7{?V{7e@4hR0x!jztgV&xtdj?(} ziKl$2s;Z08x_UzT+_>xg6%*Q%v3_`QRt9_Ez?RqJuSM?qv@{Y9S*}J*QceduyCQd; zSFhSF#t0Tx)S1586oYM8s4tuRc`-t5jvk_O4E8jg<5h52M6{!m)1SlY`n>nw$rhMa z+uvDhX%RZ|ED&s4508wL|92sElbIhJ9B_rp7_TrMQ?+3ekPs7_`fwO`{qFty_}0(Q z&&X)~M}B~W;|kvjbhY(ueSQ5~J3EZ8=9ib3>hnc%F%=ab*!8ZD788`l$Hr`JY}BtM zBL*5hP7HRb=mZ59e_SmrEn*MI%T6+b_}-`znu`2eDM&6{5Tj0}?E ziVB;tWJWmE+10JD#6}n3pH@TU@%e7 zQwJNH^IKo=FH4^s4P|5?#6o^|ZZ=F#&ST@_*~0J2KFYYhdv|nrC~>z>uRh-2;JEs! zqoZSZc=-EwtA(!-1Yj2eF2|VT;^Jn0f>DHAcNNXd=-`#r)nFDY8>`}Yoak4VmkqYy zT=uVS>x?>e4Gn#6FD>gAk1o9A6R1=Sw@+F(dcb1+{JKA)F4h^vjCmX{Y3S*VM7egZ zr!cFP&6cU=dOzN|v#AgbF}_Tj$Pp$~rr|ugymZ}n7RYwo`W)8Y-oE)mB!vd;hAM{-FgwP(_Og z9hJ(S)P3_N;AEvGD~mi~M9av?h;aw3w&)rD)2D_yIy#1i;|ny=X0dzUzZ-XZFC6{S z6haEa8|E2!*Y{mlQ#n-14KC3Q4)X3q4Z?6*B*Q&Zmw z^mKK-yT5gGh}69ip}?`&j3wi(d((^aW>TkSd~c=Ag?=Ox95eK_lqX_VcDD6IM!ycJ zuYs*?<>FDd@9oEt9hdgkZvq~Fb>Dn@sbyttEt;!p<5z{-_~*pqKJKYtLFmH5f>Z12 z&V^UEas8stW*?%W)~i z%_mH_pmFlWU!bI!$JkHSTQ&_m~QNi&Sa3oqA2FF zJ-FWKdG9Ns7yzPD^sMXM`DQ-^(RZLiqgc1@b=0eXiy_jT;kebV_wO7WY8YUBguNRZ zD=Xy0#5#Iu7O0SClk@SQ!l6 zrzUYbc;X?ueRy~nLFJ8hgu$N1E#S7V9x;G82JU)Bf~k+4%zz#oNNmpq4aXvL1+$$i zSCicaXAg%fLHTWlWK8!JZhd?B?Z1lsn%DaB<%{~2x}pZr6C8?+{QLw~FoUH=^TvZX zdHTpnI2=O7#KfeU!G)-VmT%6JSr7`6FhAhWEx@Nd|2x}#C{qf0z)2cAU*Qe9^<)-G zfY{^DIdPwB2M3424qoy&l9(a87K7Taou?f!*{%<}%#r{grG^+`v!E(mEHdYL6*V^E zTj3P3$nXX>qmkvD{7mnCC@m}uQWeNpsT)4u8qllJM;wQ8tp>&0@MKO{@mlZWP)qnO zROzUz9=GU2MdVClg(>38%9yI6w}gKxX1QK$519|g1|5+2OGNT#PtNS%zf9+R9D45m zWoZfRpzw$3dOSHlhE~VA6AJZvIX0uw|qw(jx%8sK* zU}Ho*u#9bOZ4twYYYcz0ROnEIfxudJP*qkg(Up~xL-EI1Fwq}PP9}KJNoK%fHtG*goN2gU(H1ymaj9Pl&NDNZ<6c!e?nW;Busj{BVb91k*sE9NOF&~L{bZ`h| z5`WQ}qIdSvzHFp19AquJ?pwku8N;zc>3s z^ieIwJKT@B`a{tP&)*?S_f4s=3((O8XFK;iT#m0rj#-d9Q-^(G)Ke8%|K%kH3bmVf zrg;m<>SkL)UkD!_mYTW&^k&kkY0ToVZY6;Z866V?!GS>7A?r?D|Gz1GX(wY7b(CIxN2BaEa{qewMD;OH&z7Kr|)l+{7)4`_4k@o^e#--|+9Dl5MF0wc(caHr?jNR*-*M% zH8(gK1!ZXd)98nmXyWk&gehp{SYONcDxGSp>AZhXNAV>?%wgSg!;j`Vq5!u=QL$E` z09zHQt(_;{Vm|HYOR)k7j0HRXOl5$i+C2M&IaRE3g?;y@oeAuqhaxj*pXqyjwb|J~ z9z@>9BHK;3`^^>$nK|>&!!90`9SP^88LJ-}V_CrZAxe%+9kqN87Es#69~TV~-3-^1?<0B-!bw#9y-4BCz@r--$0L3@h) z=NXIuC(#X?kkEu0LU6tRg#SK-^+W_RpUGPdhgx;U+rXC9sXfhFF? zEp@5HPiqpWDxQTK=C!wz(rZf5&h>t2S^XKpS4W|ccug8z zhf%~jM@D4hTKz_|vv1vg_t$&=wN+K#TVbT9?LYGBd+so_MUJk&t#0KryLGNpIBKWR zI?BYGIy&uSWI(5;ZsW&h_SP_8g$w9$&|6tNeOZPsBG1gsOfBjE0Pfdfde{CM;L&=M zHSVdio4o0tzncQzJ0ox?i~MEDSwD~z%;I0{e<|)S!_Hwj9h)hXeZ_q9;fz%12TzT@ zi2XtXDc~2>HR|priA}o50CF}XAjYCad^zWa?gMjHgaYGFa#H+@{ z3BZQ(`Rz$4wS<-O#eGQRY&}U2xe%zLUMt)NX(cuBh*2es?BJsZcPp}c3`XMn-Tgdp zK%L4H7iDM1+N zlyo|a|0w_O1M>+61v)6+5n}Vu-8PkmC)B>`G%;uEK6@g{3`|U}lgRw_-5x`bBagK< z7qD%b>)>AVqzWT)O3KG#>PMU5Sh56(I~FF7&h$-r=G{-a;#AXz3)SrG z>|X*jmxufMKvNnTihOADAtPhdQGi0+n}~EUq&7;+GjZe3b*pnEqUWqT0nae9w0?sL zqTeOxID+)zhUMeu4hFG@mzI_ysQvY6zCo(8&rTv3V7Iro^BKY7&o*f*1}7$z?=XHz zV}FJ9oXyY`(xAnVJloF6j;9djv7X8SNe7puDEeAwl%11v>@4JQx`r;=J5MVlD3~6- z((U8v?#}NGt%`rQ??O&W`h?wfUjSt_K?Jujb0421VWi1?1jk8`Uw?>acypevR$r$z zFJ1_L0}-L!bbil*??7FoRi;~g;x zNfAAYcbw;F;A6Lw-f!QK{=}3NS+$%R!`7)i*Dab+R@q1_NI>teuZ9f_NJ^E(V%mIY zDY?0ilY$%Sd*PFIjrw->_S}rnu{DVCjVzjq4Hp#f=uZyIMGq}iRd%570+hjLzcAwa zRBor!x(JQ3s_N8W6ye1@*=cKVWlB;KA}s*|n7QBgOzVp0EI6z0-@li#&7S-On$&OI zJ};9)f0XxOBgor3eH-O_FNaGZg(%Y#eC{Q-HBm1U{4&-O?Fm&vgb&1B)TA#ESMnk8 z(iv2EoQM!|dW499Acf{nPU~4|Y2m83>aCl~&(VU%_b_@*=Est_zyI>ScpIOnT7Gr= zBmaq{j);5+Te$v{*hX|hCb7#=`V}0VbtGD49B9$(++6!rOV$2j{l@CsUUB~iFR@Ez zl#X`kXVw-LU7(71q5cFNT4iM=U>gdg-+(lcnwq-YWX(H#>~RmGYN=d}Iw=Q^L{K!s zYP4q_ODXJ%>>cQuuAI!k**LNz?ERDF51f{rJ%&lb=ekCd=b=Apy~UmszKc3akfPn$I|H|`#+i}2srsd@1xP~bu{e2H+OCRrV zJcTF#t-QZJA!JfU@Gp{%EY7Aud)sv(pFurDSsv{AQR+^Ess~Iyg-InChAp1k<*>{% z>UKC^`BcC`%KG9|{4XxPr*^X148MSYahKOc6mwqR5*~#=fHKMJC38HDU=%9h;?rW5 z+MXW&e{|rJO&1&zck;4v{zj0@}g5Cy6iIsoUas;UYOhH$!KnR75PSuHh~0z%yL z_s{(kTq=hagO@K~0_{hKkaw8M_q-pL!h}sBk4`@zsc2|uST(gbG@OI@g8#uV8;N_Go{^D}l_g>` zLlZMpl;j0Id1oYnn#)AW&h8Mje_MmO3@{+QsHmu5V`BpW#<0;0Y-5<+(2B#S@_c_0 zUS2{q-quf_f}`+>iHY&?HFR}#H8q3F;y&j5)-bMb1#(hBL7=E=*q$<2g_;^QkA>ok z7olSoS-jQ&R*qL&>o)+Ge!L+w2aEw79sOrR_N0~1VP!d$&oOr-@{gPQNh@BC)fX>b zY+lGLsNLt$@u3Gr08I#J5nxK`oJMS{tio>lcsA`|DfsmAvDA`OBWx7i=PZI*g31yp z7?Zg74W*@}V0r+F5Or+%$N}sB#}>D@O>7ad*ffZ+QITT5(p)X}{^2LlOij4mx_Avm z`97VWpOpnjiJ-$$;1m*9f58X}&702k9l+jU~uGzhju~>Nr{PEjw{Vyzv@EY8yXlu z&Ao(hdYZ3vV>>Vk>7C7QAXM8u*e9o>)M5j0ZajtOY}jmB^7sApcIscG5O&eU^I}xD zX3qN#@9w3a#-JwF0tjW42F7L#9L* zO&71#(2gbk6dqU(Gs#30AsY=HjOA90H7g|G;wFMZf=$fW$YK!11{M2@d=2vJ+7L_& zyj@%faL=S)N)O2h)7rBzpEk@T1W!i<5%XvCn=}~Is#iM~so){^Zs6vJe1PeNWE|%v z*q6%}c3iTK#<$x9Ykr!EE}lJq))9v&`#d*NcA=Ux zTIO^g7vV9AI~*RDMBe~GrwgwMr=^H4OoB3)o6U=HVQs}IQz;dAr9MRn>6fB>Me{~6 z)?6%-f7CR-?HPY67E$TFEEkasd19<}aD$nxA#@jN4J|+(M}X*z!XOt7VzUdC9MkwLVRMuy! zBbQF4<(iVZX_CQjb)m(IkDs3mt9w2tFL#IXw8Pm2cW=hh4K9VF?8JK~LKMYDmT1Bt zg-I9`WqT{EQmq`Dtii}*W>u_e5;}m!hf=AZ1sxAGdQIQRjn|xA#Q2=xhNwp0pp`;4 z6??LMou$btsOfc_!O);~(A*#A>Nm+Nn=9S-Th~sOG9l8*i*s_@648SLI3-5*1h4Ey znEHD@L)@887_}h+l2035AsQVPic!*Xue}l9V#6lP~^NdYrX2 zqsAInd8;2vRKXGTQH>BFp({B`cdF*{f(~iQN}7gGL3Xjo=P(ACYB{f@WG~PXMA2kSo0dW81wtGPb5m0j zU^%Z~$y{)lzkkp8-uCB+YRKoY{sk$wk>Jx7#pKYxvz~>0K*m(E{uw`6AwI)j7(bK9 zP}$Zd#LoWmy#WNq2-AeY&^@(ht(q8_m^xl_I!8`VPKL#+62An^@a5k4hfGj0a&jn~ z1xF%Map%QZa%!^x>UqmrSzF8t>}RPfpb1gLm%dEbyjyno^z+~4w%;~SD3x6D`SWL> zZVjB!tCpwC5sx977zQ`qBoAG|0eLz9P_e9XxX_k3$p!3s+z zd2Y-BoBe1x-j)xPptaVwZ-oA={E1ybFd{shkuf%=%Bhp*Fle>`5>d_^u7cd~5*WwW z_d@Q};SV7EZL20y1KK(|kH^-M#nXfY1lMO9&r$B!Xt`(7<3w;#wY27!3xH5s*Lk|l zbGI3STQR=tXgN>IFb{U8AOmoSasbkM#i7^Jl(3rTmuviVhsoIg5uJ$!r|hza7Jr>|F{_$M^bFs0OdLM&O5k1T_p!7XVSx%YR~Gx6gr zCU@tS$jMsD!#@DqZifVn28VB(O+3?YpkZPv)9HadrDxk@P}0mH{yrF8B;>T#288LT z7e|SZMcNOHgkMm%6-kR&7qAG7|0I2Y zakZPGW+vFpiWICqYe<)xB0C=uOf!)!h)bn(nZ<@36%N(G|G1Yo{IrvYMDjXgmWGiW@~UUy{_lONWMs>5wk$kXHCnggMAl;snzL|7fS#p{16^ zhc0l_hcPrnkn|!l1(J?ui@<_VrQ&pt;~rVX)1T{|lYq{Uh6^w3NQG-mvS)lHhN*K% z<30FG%C}){(h28t5T@rQ;+~;G)h+(c;^t%l*(cL@wo4mE1Qm;( zQ>56_wk@kg*R>s zk=U-GOU`h4Sj7XsvIKH=!0c;=kN4#h)w~{unc#Mgwr6mtJ^G7x?|7@ELnts)c@l>Y z`4jOHMy1xq`WypI*2QzErVkjgDHl}#gyw5JEdcXvRoCHJyA(GT8r#Kok=~lFRFY98 z`y3r}eeJ18<;u&q7uqnn37>mUh6udi-y|yxCB{?1$2)Y1io0u}Gm58ZT%*hv&KG4Z zEyNF>gB@G!If6nf8H6?9%eg$yPsdKI=B@S_9tvfB_9!DGu#gRj_@K!cQ3_;=u*fbT zV2GC-&|)PGx+p*)#Ub>YivnB>6sT-te<{^9K*|mWpS{r2(UDV7n0v}d%wD*kEZ8h|M&~)n(^=AtfH2DQv{jXn#o4U>9=O zhN(@Gy-#`Eh}~2wLb#VdYqJdi5dv*}gh6hQv?Rs#`>?oaP*#d}Ymn1}YOgM~(dfH> z#fz4kJIUvA**ZT;x=0V1{wZcp>a?xu+L$_{ltLpNMM9=?vO5*n%r=x#rk~#3Kc@53 ziP9;$wP+B*(*bP%o&{hlv=hX@;F6Jpk4@bcy#2DrHx~}hw{-@%aX{TT-2%J>Bfy0D z>;5FUqzeb}XjD1QVko=_b%)k(R)=E&RzZ&dytv&wA`+6XU%$HI3cs;CnUoK$$|R2s zbwo&`Wn|m~w6Az@PIt$sn&BVnNXf{225MG&#Qn{go~E28(x1V{3!~3l&P2q-{d>G? z(2KuwbYS3+5n%tdGoN+e7=voKN1MyY_E((^21^E_!`;ouC=$M*%Y|Io}iT)+~ZdVK6~r{(B)!d~B{2}+FE;FOBz)sU28 z@~)f6S?}LJpvL~6otug)g^rCvtgKdL@VSUZBzFp^ooU=@Nl8IS$m0CFF#8(?TxFlj@)_MC-4#S{RdN=BjI!^H^Ta;f>r z6n&y4!P`uk6vEQ;z$N3gnt--NI0LncAWAcYdp*^3U5pABv&ErUd8Tpq*jo*S(g;Ty z$0D4HYjZR?EzM(E{D$LA&%;{#yNrKc1R%qp=TTBo@!Je~^1wjH<r5p`}GsHPSHD zPA)MaViDIg3@u?4=A&A)4OY>btKr45*nm+L?&!lD!*TAu;M zrn;)?d=Z#iocaxYR!yezdx?ZJr;QGm8&C6HaNoEbcV+3xcmG;do8z+Z2Wa;$Oj zihg%5kQgJ%T|Ab;JkZkV-@9?(cDmk4%0n*f3S7tOKn@&ol3We z2;S@7(Bhv3Skly=sqvguQq6~ff!nZFqgyS93U%n85Bu0_`qczo3mfZJ2G40Yv6Py4j|OA_&1UL+b7?hN|<6xj;RWpG8celInzXx38Y$b}oX(&9DHIw*U)h4z0hQ z+^Jw;eUH(=IzSCqRK?{{X;MihRXkveoW06sDw_`rW7Oyo!}Bk_XIz_&f$nPuE|cx* z3vmc_o_~nf3{eIMjeO#ZDjb;g!UOV!iEos4+g43Zf`*ZSz#yD;?Tygir?AQ5FnU^* z1l?-s9==7X&pEDkiH2Jxe8aKlToE59niDAve<1t=2KuBbR&;+ePom_SmJj&{1nYU+Hp; zPJEL6SJj?LNrv8oc+!`auDqn=1= zRdGi=W>ku{r>(AoJIC>2*-wFHD^_>~QyNQq;l~zu@G1VS^at83kJp>%#|1xCWqwCx z6S}5w=1^;DRAtRb$)Fc|eAdw=*Gyu?(zg7nZK;8c#cMo;75*A(&P7%h6x&|p!SNsB zm*5##CNq$YJt|cc*g!S4JxA%VwNj`mo&+T#*dPc;7om01CwCDcPk*?uO=T)_EmOb@ zL_)0TpV>C$45m;fPJb_4+%ZsX1a_XPIa?Ez?tR6F$SY3HOg!iS-BQ3Snybtj|AP)3 zLDPY@sCk0);d$q+XP}}1HGzF%`4C=m0r}2f1x@Z;L234SdbHbElEnEGay&?7&;G%!4n-7 zZEDTZ{`MxDGftZZ{Jb4awpNuV%2!XmS)jc|X(C{~*-yq&iK0eZnLfLb<@{Y&KvKS> z=+u6o|6h}jAw;DV)JbYGO1AgZNc(2HLRITyd@*vXSIA+!L6^29=3rLoVJeDn)wE^A qn-RyOxmM?uG44dIF3RA)Nao^-OnX7^KY@qp5MXkuFY07Wg8v854`avx literal 0 HcmV?d00001 diff --git a/src/site/resources/images/options.png b/src/site/resources/images/options.png new file mode 100644 index 0000000000000000000000000000000000000000..b0f9d8febf66b837cbeb3ec6e5e62cf9f8fdd21c GIT binary patch literal 27463 zcma&O1z258o27m52ol^SxH}<%V8PuXxVyVc0zrez!QC~u9^Bmt?(XjJZ{F|g>7Jhc z=bGfohGV+m$qL**cglp86P!2aWXmC}wk43>l@p z`)M(+$t07m>ONF4p#LJrdfs_j^KdRwOx<4`J-BmC8M*Nox$zvm@x1qLIXT%mfAS0l z`tg7LQ&b>A5q}lUqfXM#KU`@TQ7Q%x8gto>dlRoG#yCa-D-B`}@ugu>gNF|nF8ZNP z|NT$t)H57NcNa>Lh<<1E=3CJZ%Ab@VUu`x)G@v08UFiR{F_#a+V-)i@&q>z5e>&|P zovPS?t^Bh~mo}Q-`qLj8l&u?1?z``PPAGPN^-;k~cW_%JjK7LkGx(w>**p?ejyI#M-Vz8tp+n|M9%~-PdoUSU&eX7e@Tx_a# zyZG4XekIGwR{YUhFowe0`y&YC!@+=0_&NAfT z+)B==;k>0-8lP$Y&l*`0ms8EH^n{6mBHLc73-oT?ihW;ud;GU=j|Cn#wX`q1-O+g% z?4#)`v_4+9wkGZ;5Q;t{kS@lQ3dKV|RVL|ai8_a{O5-iI*ZrQzorlW_Rv&aYZYnQC zVCW(jHVmILhmaduh`F-Xy1+5DrKP>v^Ul!y_B7~of^1r|MDz3cAd{TEedBF&snw+Z zit>!fcU@ha;gl~wuaC8;p~L-Q1{)l}yXRX=qzQ<4n@rm2+%E6K2<8G+%F`qu9xn73 zXhD@T8rn(hmfv--G%I((I?f?6!AvcGrT6y0MiGDX7c%zkx4cv#?lpV!HTab=abexO zZ2Dc$^9^kLSZ^W*W_VJ0Z*`4wy>*1oFHQ!3Iyr2z0;gOF1J_Lo7JGYdF1e$#72FDr zi<8!Bs>RA>H=7fWS;o5P41kE6jA|=2$}om;eW}5o)GWH&0$b?c_Y$+2?aGOs-Hm5! zb>Gw8BQCV^CH91SNydI<()=r5Le6d2H+f~(AL{pcgSIH-ZZJ-B*af9CDQzrl+;+L&{|GU1Xv z)bq_sxso6UnUISnuVH^;vg%NhqkjLixcoZUtnBz;sxWS1D>`~a{$!c3Z@4t{(AQgi znW%?Q37P0CV_s)x#6U6W-~-~uEGcOVwv}(GIz)BN29IMPu1vFmF%N~{vkW66TP&mM zj5}Qn<-C-S_-q-moW6e2n@Xk@QwATMR7 zvM$gLfjEun{mts8b|sl8BPnq@l;h2@*IA>!jU*Os1Aj@(0)GQ11DF<9^{U2VHaY+~ zmFj2d`faU|R{(<=tM;XTsq$co^U=G4Q%*RzyCCgKO^(6bJg0+a3SDtY`n94_4M%yan9w7T%sdB8>Luv6m2aXUDv>?xSHkDqHxI$>b-tnwj%K+QfZO!aG-)RfB&j;@i{Ug8fXw#G=+y{sp&`M zV#8#bFMUu2p_5ezAm6eA2Hk;P@J3oCFmm@~l(2LZqcd-{D=dNIfG2RijS1xw1HZsZ z{r_w>48qAlp#GWC!0ysB&{U!Dd;Ifrd%-sPVO$RcUjg{R(#<0X;#(*@eX93K+Un0E zuCdHe{7;pYm79||oE$m$r|(;k?xOW#Uv@@DD!bP`-ucD* z%w*1!z7>zXT-4YoyEu^uZ7GKx>&$~$hpk-kZiQTSt>wn~>a(n_E_Qoc9NFPy4+Zsk z3UXecDc`l*%@{eBcf&=>iUkfkKI8f6*0HTO{~9d0j{c(Z*VamRdnlMGs1;T=J53j> zCYNb737Cvn=J+9iCo%+{#XMh+Stly4+i#KZL$W*`9uGy=+ne(n??;xH0Awd}wko_z zg}mbLwM7RK;tl+r0bhchAkXfSuM^6@`%v%okoHD@sG}q0-FxDJl_sATC=T-}eyQZ- z*_@w05tOyTmw2zUEly4V(!n4TIt{J6kkkJ6zLjFN$=|?W8oCGE@C9}oJ4MZm{B5ux zX4BU}GY~lyV-gkBZgcO>#e@g}L4(Wnv_1hDg^#w}x>TzveqzGd?Ew0<_kP!NCg@#8 zq>EK?3%G9D(a9d*`5Fsx!N3u8Lg$<_CpTQ9RObN=Y#aooA{gI(^NFqyXy_hluak*f zzP{yW%=so4y^7g<*_#h2!BYmc%}#NL%AppV@*O}|@HDU9`2y!m?ng%l4mtEcqCp93 zo*60wr)AE@(~}krdW!VpT8V3TL`44G#g4^QlSVZ)ITI5n&@;Jmi`lX`F5oI=vZV|P zWGtXFCDn!Y9V<~|yK~fC{Z9S{hrNtOPfcx(S`XUS*!E9s*%w&mfQ&-M-Afoi-2v_X zj~iW2M|U-Gd3n^_ygUVWcdo6?O*wCG-e)qBsY1m-OH0eX<>fR20)oCp0#*LKm{JXt z;;Z{lz5}M?9U`SsbEou;R&?W74m zt^IQAZdl1-cT;Np@>F298?O%bF17|~=-3pW=jkfZ{7Xw<$H(TA_BkzsctHLg9yhzr zGRQ`Gc_E^kX*}!gxg);5pd?nKcWC0G7?SY@FfdUh8OjS-^wc%Pc*<=<0|TT?Iyw?T zVQ~okP`tcTk}B$d%*LTTK(PlZ&Yvjyer~lR;qThJb4jOi#gUSdQq$A_wzRT};^*pU zpO75%GlQXqm(G5lkS~*-S9gDtuc>DCLozC+<@V=&IIbYaI3*mdyS7RZ0V$pQxgX5V zJT4nG4NWkY%dyn>`1n+*1}8Zh$TUU7qu>6Iqq7}qdvvi@T?)6TwYK(~csU~(A|ic0 zbF%l*Zf26<|T*+8Qm9)Y8&I>I&QuN^OX0RRPf( z8^Xz3(S8W1^a2I~4r-3o1r4j8hOZ80$>c$8w$PO6TjjUsk}Si7o=Mb;u~_^|_3krF zFF~VDt7Zzd@J2+!_o#o{3f-js4)&toV88ajmph)k4TUkvFBpa-@(A-_7Ip6Qb0u zu)SZXNF!1EVpn6?zjlF4%qvx8GK#e^@zZSek*rX;=~IpAWB~8{pC5-@E;Iet)Z11- zi?)d47ru!}Ni>XPYx^vUgzY;6cNf+BohW89-xK;0zLqSk%V$%c^1Yz$DMW>uj1J^i zWEY2XKUYV?b-u5>+=hC}ZAWySUs=(KWpp|G`w@D3B$Yc#m+~763L&4Z@62$Lu+9K< zG~<7?CeK%+(w~>FgEd-9>50|qHBO4hz|AjdQjvm1wlkD@YUG2W!n2+W-ZdA2XCUH9 zsvSy|Y?v*_<|bpj8#=dM%t#dws5ZWLe0O${&CO{OG7B*@88!%#8S(}hYw%*nReSCp^P;+r{&ef{Iyqry=j`1>E^Ti_Wv%F(onR8|b>Gj<9yXJ%&&AJv@bX=8bd-tLNQMtuU`DOo#Ri9J zDQDlrFAkKY8g(+c8h&T|_!@QA%J*qtFm{crih=&nV0UjXA5Z=E7F~{HZ9TX6*;bm$ z-PX<)?odm+mB-nNCmFna6viS%(%9IzdhK%0{^GlvTf848!smlLY2ml=y`NJn&6NwU zW+Qnd-MHzQBg2WmirL5}2~o8^gg4eVDDU6O&s-~Q-L?Z4i+tPTUOv6wpxD0i$+cA_ z^|-gOwVnV9CZo%0?c3f=L19Y!xYUmUQpuF8I&R^@A`^#U_}z{+vaSrdD)%S@yRugtIrAc>-}jD@0j*t8EL2ZJv>?E zSq9u$xm8P}#i;n}`mc0%C6#{`oSN3)g#dbUOGZMYmW+!YITc zshS-ZA&IN)PY+WW@?mdFaOk|S;fwRsKBcq7!<)*g5$_WS zmCuo>>t`oo_JZ$ujp^x3BK+$^r7nj>%|EY2oB0*oL3@c^8&BFMvF0#oh z7szjz&)67IC}OLb$yUG?4V-1u_I@DXn-VNd^*%h(VM!>$lRkTgm{SgB#GEGhjX&1V z?j2iFO}577VBHzX3S&a_*2PEFx%PJZkDlZCSZ2P-a3x|lE>cL-tz~OfT^%;mN6q-! zP%MTlTsGq%w4FT@D`n6?EVy@IpsFleWcfs$fLWGX+c59S~%=i6rYV`sTcb937${6`ZnKP zTwLrO9MHkhh|#&l$;tR=?_+8IIXqrJf9^)ow>p&K-6*A2SZg&LfX}Zj2)Tkb1i3|f zC5ZV37Knhcyf`3a@XUvdnc3E|a6d76nXuspsq;x5ifS2o#NK37hs3JB{?$UAF_PC8 zCt5dG*D>Id@`EjeE{om@=f~V~_~)mAQSL`3%p#vC6Um3YuDAF5*%79thq%3w19P+s zJGILCe9C|eUC*2k?74`Y!rIIJ6hT((yZXE>D;m`Ctn0RqsZL z*@L`?2ePyw?&IXY-nT)45J`0_|NH@HLoF6KVTh0wRsem9h#q_3x;Qq691#6k0FWqR zhb02}F2hN+AcrF~*H%|!XeB-o5X$qsH*cT*!)Ej_Sy4cZO76y2RaGSjC<8rssp}qm z8#ztQl;)f-Wm??hsBa)9nML(}qnpTtyNCTTS%!%T3Dm7|*dSj@vu5N_zwJWB{4T3_ z*OCDW;D!<@!&%)Rvu3p_x*3L@wj1tZQOnqr6s_l^-}oe179iY@2Kr5@%UYJU6}_D& zo!s?n+_S$QP&Hi}${rppL+C3>!M)tDx;{%yR6PM(YscOyIOb7Iglo%x7TXc5;u~v9 zQ<}1Too%fM)8(`uwy;^wBWM=Y<-rfBDiNPIdLyuTOmB`BM5CgjFfcKNv5nd<)~gf* z#V@vpv$qDplRR_n=u+4^v>k%;Ztm_OnaA~71df3ShN5Frd}h7jiHF{%u~3ShnI%eX zo#3-6H=z3} z?tWvBq4ls!x(q1eLQ)1gc)V(64o{K(K_p&5I>gvLma{XIRn z809u&>$UV-y`LhVG0Kw@a?ATs(a^q4=1HTQNFB_SqNfG`o~mB%B#)_RF{yW!o>(OOS0 zFX2%!5J<55N2JZv@DEl%d7h^u?RRikDYSXsEV*_c9?%&6qG7eijkOzQ zvA-l(_+56g-3uarTS@Kes;>ELS!(@neq3H|d=7JrtD^O9v@vwMI{-p&e#&q0HnM7KywS2x3Txv(QFzxCmmyFw7!*IPnTGCLt5 zL4kr%u=6OAhK6Qc-L8cw+M~fxJe+$)^d6W^{{uzqD^w#)2%(9y(?~8gM^3=vr zT@-T$)`abEHMRLxEpot27jS%UY-|``(x}@kxBGLM#77(qV~&zEZyb<=0CHM2|I1sc z>n4gte^=|})%#l@%U50iFsn7Nk~bd(h5DoYj83D-F4v38N%h(aG9<7-Q)u)yJDYMb z#>1vYngrH}D6gy_BnO#SvvO0nfr|yT9qpA4NWe=L`k^3*$I?SVp@TAD%L3vg;uVr9 zep0-eP3q4+yrBeykgba&_p2;236Y%%ZTt|V#7xb1;{xyfMFidjwbDe6xz9fM4h6MhJVTLbJ*D=d&WsmuOnUeHq=^qLc9r4m3CSPG^k~B^XKZ31aAm6nyb68}LVn@3J^1 z^A&^AiI*DOsydwhG&M9}pc2sYcBXILMIV4AIwq>>AUyx5-0ht+qs0KZ@dsz;%boJp z0ltlFxsYx2U%@ub0$vRCT{pR1J+ur~@ff^JoGi0blJK`IN~ww0G&?aPXJkJ;^*5R+a(S=%?q;wX zO&94O?9@tj?~ii^B4uwNpiC^pP>%PXv}7|{TTA#Q>C-eW_(EN_?wZ=CGyjn3?vlF^ z@Y_5=c(|Vkq*GP!prWcs9c+e}_5ONKo3EzU3MB`S1oY^;jfl<9jsD?@d;YUMiVhAn`bez)BjgR8eU?Y=I?m<^SC*OwRZFA}P^$ zgqssZKasF5M`;HK_YB)f<23MMla~h3;t&J+zseJ>oeI7D?}FkZ=Sn1CjN+b=UO^4KRE1LBA(zzg*<7U-cM_*# z!LG2z%oZIw@5Aq`Z-T;@G%ho1Zpt%j=omtQpKP$ElNLRkdm5dL%2s^FNYw2v3lerL zWE-riQ?s)NTH|1D%CQ;84k&o5NLUptx$BaV3HY>Q10>fS*G|f3GoXeSAj#I6O)7i; zJ|0Sic~2V?6!Jyt^)5CI={4pPLYI-HLtHp@R_-H7%4@Z5eG)N`a`Z^8^DU5OD<#Zk z%j#&|zwO<^U&$BPSS74r(uIWjB%-2uMj0(=PB?wHGr;tqUBa?=(}7O0)vi<2nvFlu z0OI%@B)@x9H0TtI;eE&Y`~?74000F>&;N1bi`s5P0g|KeVveZk=-vlIalMQGHF_=hI<`H$&e$NrklFsatVxvrdFTJV)&E-1 z`_Ize|MuHIAK^Dzg`Y5&Q&JKtEG&#oOOyHXMH;C zc2Cq6FsDnXsj1x}_{mh8%8O}hTfa#Nz#zZzdSDO^2vnT%d6B$>gA>D`=5w7XlRiE^ zW*_SGgGV8v|5>O9KiK(-m0#q>zE~kh!w%7YZ?z_5czJXfQ2N|i>$8Pv|EGrHAONXQ z@9AEQ{KGLOmcq!aS+}2LDijnHyU_rK--9#&3D5T`ei)p|!k5n1>S`1| zeSlJALcvhmJlGPhc>DI8WRFc3gmgR|s@{j}3)<>$aSFZeyG}(yKvB5g8f16cR|*LV z%6L`1ajBNLc*ybE7m(8kxKuc4SScQ-`zf0Jml=)Nm}EMMC>^OJA%pvCii;$UsLvT_ z$vf%!G=c#^2nZv%7PATp3TRHpi-}p;*@b}n2MV7&0os+c@RHajCaClc^H+=U44Yfq z0lIIMx7Rkwud{)|qMWui(HAbRiT)U>C}!XW4hSvQYcT9jb=Tx}%Icaf{s*F!&@*&D zZ!SZcc70bsh>AKimPR(X= z-lD;=2NatKK0bCi%E^7e#KIz#f87%dibUJ2+IcS7B0d)XWIfr36PvlYxoVpgUh+3U zwMuUl)e}d@BzXBx1_L?*l6&Keum~y3@2Qwx*-LjXxlfvbg|Mo<=e91t5h$3AzH$w7 zLqR!Sjq(ZCT)L!tiImq_2B!-7SNVg zw9lSX5|hM}d6$H=5FB$qDh4RsJ#3_PMcIhz%*Qqs{`D|HADOt1m{r`4NHkn%kLT4q z`#5(~t!f4dIf!Y2`M_L*O|GEWZA7lgV?021o1)l(mXMOn4o9a9y2E#K z!>D$klGdpTc>MNlcRQ8)+{mIHgRc|3t%Jw%leJ7ccRUn(a*;t}*WJ2IJin=WMf~BT zsYtO*DYdQ%h{4k(Goclz1CahCqwZqzpOMlb+s;*3NLPI!Prv3p=jT2P3!a+IVv^qd z{6j%sae%%%o}>Ks{#tm!top?il|Hf5k0C6DExH5zYY>ckHu0u0$u15HsLW_=TW2mF zG)TLj1j^20^Ce}KYCI3bPh5Y9X*x?sBX zq8PsM2>p$Rw)YyGL_Ay|Ar#d4sO9smL5#G^0X$L{+X}4=q3bD93nBOw!I_R{{j~^L z-`GeeGQBv*`my_)^t&zW!;caY{)gg=lZZ)isSFZn#vJBBcYOxErW=QI`twyT zHutB4Omv6|e8$ETa-yOY;p1gx?9wW%99zEqE}VKVH$E@<@mF@bvF8zv>xH-K;)R8Y z@6vhbHDvDiXA|EI;`-GGeNL)1PD(gFb4F3;wQG2jkPAJYD0jzR#|Bto^_rHOnxwZ?Yso&djtAkLHqF9#17v znH&5M*@whSB+vYz5Wni4Geq8Ij5oVE*g2OBqisi#i56^FlJUA$kX@B_eckdNaz1VP#c1{k8jofVs4U z9y7iw3UaKh-%v`bt4>RAQc(XCUd)}_h8c&gyk=7W?s{0yX2KyXJ$pt=BeY1?=<{x2 z)0rB~O@)Ct7a zVi~qdVAC|Fep+nEahS?( zzl*smti$xAt`sLBkiz}=JBdxA1rfX*LHv~wC2z4uZRVbwU`m$AJqf#^ajtt3?!{4& zT5lgXVgnKqo-sPs*=*C2lD894fCgaiThVa@t^2yz?oHU2cRpHnz`g^@c7J0r#&LJ6 zOduw>KJl~D8QMH{g#$JCoLvVEE+-1yb6kM~+8ZY+<=y)(UY(qYGEa9V3Hjvmu3I7t2cUJj?M8GE(`$*o*dn}|_F2Ivi z=aIInsW{<3N*QFNLg2-9Xdxex=INLL6kA!{&EbzW8hJ%B>i%b3zDrz+oO>mxvYl5Y^t!*=!yfX?{p_bxA z*MP)jq_UA#>(SiB^>|1w5qRkkCq5v zy^bhna$U1O${zHz5*My}bAcTtzQ2hdAqzQBT$CxM zRLKgo6yEc-;8YHzonuAxz#``)<|3b8=XWrlE&3(oYAon@Ir(Jsm${}ihWi#49^SlW zgP;IgwFw$JZyE2aD>H}1jFi&g@mG7;w^;(eSXjhh8N;Y81(h0Z((n}y7PFJu)h2C{nbDC^8Eb5%z1ZmIUbOC1>tb~ZS3@#zqSq!=^4pS z_)NmS+x4>X!gDB+n97H5R{@pM@L83m91xRe`JFL zD!af@yM15Buh`h=Zz?J()pi>q@=cjC69v2!fgLaaHKm$DI=cs)ETdzDGBh@V~qaT z23yQ_nexvd;p0tRuRI(uv3#OOap@(y6}z24Jw_TN^c+IE{A9l{P#^l%6eR-HgYF@| z-r!vX?9^Ce=J<=T*0BqKxtP5lUB~^LSAeQFE-p|zmyc!SCdt!j4(b}uFfcQNhdg-} z1_5OKm2F0O)@v;?%Mw_9V84=^uV9b4hlD(QgwAWh9yZE_MnOS2qo$?JnwnCQkd@6p zJhY^xrx$`Q+&$aqUAGTh@p;i&q)y2XL?MRj&-~A0O&zGwps6r6u9ct!6j*U_alivHY44!bJMz1} z0?I86P32$~8II86GuJU_#yFDFC_WGrx}$5r5N;Ym5g2*o>EQvol%8NCt}71cQ1 zl$?hjG>H%3%#?!5%bAXrAsX7h$k(b&_I@Y+^7kjH0Nugd!9bz^#y7FFHdtGBTO8>~ zT$q_rY3_ww-A3bZ)>ba)KM!xKatlJt|)d5cTu2qG~Yxlp);G-S^FvM9$Xo{0$B zJA*cEpPh(Vu4WOQWszslRb+qx5PJ}LJNe;fZgMf*Qlp3JGaka=9nKvr`v>-E0d%sb zSTLXFlIGrVY3l_7f@Jw!A92QWMxj+bu`z`$M~p@~uj9c8p&fTQi`N6-STN2-iR*YB zcV-AH&GZDldP#hI?F8CNy4rPvnwqH9?Eid4BakX@xg|w|za&yUvVW@>J8NJ5OSbFfy7F_tzp zT9hz14}FB{L9j}|jO4nteZ`*Z`_ozeZ$UmTr)$v^2!qqX#lk>N3ThG-1zrJx7&%(A zQs@utEw_&tq335Y`+l@n>?!?0l}(&NvTzu9w0iRRF^)d>lO(JpFaiqfjHWX=k2{q+ zADQk%k>$oKngG1Bv!7V4@^OtJ-Db9!kZ?|o%V)RffDh<4mawoeX0j?4J!ag`urU9Yn|-S_tkH+Oca zCLnok(uaSk_3#2?-(&BF1*7+8+34(l)`RZO%TcoMLfW6sK4@szgjnKwHS57F^$iwZ zf6~6+Krtud#x=cK_J~bM(>}U7`@}Hck{U3QESk^CTBIeN>T$yeCn^-FBlZTcS|US! zYa3|O|29byD}2>kk#F9Na(I_b94M%$H~lw1HT{HNbOD(#Y3SOYTa39+xXBE*k;+Mz zc_jCdb+0wo7hZyQ%-&_dIV6Od47!C!m^|-~*;|Vut3=!ojZrNvnz>hRePku%a*O`t z^T>jIQo|Vn+b>ygi*DjH}GI^1j7VAlZ%gq6uclH?_PeSHsfp4k(=x7g^dWvdV zs<4?RY)wp9i{#QVE?d+zPd!G9H*{@6M`kv!dcRRufr?qtqzd^fQA2Zb2CB(%1 z-QHha`8zeQF6A&?&*fcJIB_Y)x9@oUSIv9@QhE>VC`6#f>D5SV*B`f2W3MmQe{!@r z9}HO0uFkS5LMw@-9LFy*$<+pCe+!*ptrDhl{swRLSNYu!bGw+TTGC_kxC?D_SVUL( z3D(Tqtd_U-Ra$G^9l)UwDS6BM^6`PX;?Zq&GdGDpl#8fMBH%> z5UXgc%(~{f{&V^O5Z)cv8;`Z4^}8-xmgEif zimg4fpSQ(>g3c3g&&t{CR8Hw!_Kd;fyCHD0T1w)Liu+t#)e>-ZFd26+TX@I!ED(|Y z74>3zNyHl4>${Q=*7mmf-SDGEF1kP99_TPv2kwX6C>T$mImWZ-pal{t;fJ z<1xY2@z{^WM#s#A$^1g;i|uK3ow`p}yB2D}aTJ3yJoD2v^9y|oSZ7Z+vEFx;ySIv3 zX_XVJ;R!e_!_yGt+S+OL73w*g%@|nc)muCJL>3tC__wyU&KYbg>GBKrnxYL8S9G#B zWY)x~YgwsJ1(hog0<$R83@p-`4rWhT99v7S^A+VPN9vaut0#E5Q@2V{BED#O<3XB# ze7_mxW|tgV;_=yLP}?c@o~3)E&3c4uHO6Yk$FX9EZO$nvRZRc7cOc z^6>JM-dBCNi4oN$8OGslo`TQ!vXs-s4TVU>p0}rKP6H-~#li?$S{8nH}^^ z!N5<%Xv#SavkqoGjjcCiWvrzVdlii<#Y5FV(zm+{(~;#U%k%+po|s%a{d5lYoOn}~ zF1*auy~C44&G8WmRw{dqluqkhFuKCaqh`isr|G2Y;**b0jTPCADdhHQ)?7m;8y<-o zKofVKPP4-Y$yK}ISbGD@Kw#V2J-OP%}I*5;&4BEXQ+D% z8nvp2kM>T<})W0uxq+TOs?v6>{j*TF9RYjplm%IIGoPy{{@a$#$7HpYIO zXfF0xcV}QC0!%@`vKMraqg1-cJ=AM$0%9aa_Vm9k`*=myYn9RVYw-%cPi2<-^~zYj zACCaFC~@j!@g^xl_94^T3XJrVa(CK0$hS~%B8Yl70HqNzejhJUR6XK;W{2{@BJdH4 zYl!$?;2QES3Don!bDC!YPF;AfUcXIu|@VT#eM;jbS zLY_>^v3)0^v^g=l4g5J`#tmdyRoa12=}Vw>8MO##D!7Rzb zej%zAJNp9z1M#vENCcritfteoa0?Pgfo~GrgNienJt5Q|KM4?#BitfpX#06YNx#P@ z{{TcouNfr%#_%I>666f-fz9@(3NcVo1@!dv3@t2*D^8|?X_kNFQr`D^-Vt|SUCk7M_Wr5o^RK^ex&iTK8Bi8t!{Bvne zg|IBY5^muY#;nHp|Cw-0^d)_e2$uy2wJEtC1pFgz_dI7~V$`}Ttvb4se ztgI}df0Ci~UToy#{#?$71?ODAT@z99a2J@qr!+)!f3crFHC0P<<fe>fNJVL_EO>2pvkN{Q(!r}2wuli-o9u= zk=Ec2n~~BG%ryD7XML>2RecxvS)*J}MG!H6CPUsYpCav(cGl(q1+BLAUVHB5 zR%oG(m&3k>ybD7cU36@FxBze(`e2LA4eyi3Y%9$eS)}=FsdUw+5%+nRc@NyBRu`Sa z6$Txf!gKqrEjA;!K)%ieC*3Eg0U+fsau?ANnVN_5nii~f5Ab}vJnL zxG|43?`oWlqcQCh+4?3rPdjX?tr2QCnNv2F8O)#|!e%mp;fGv+MtyTQCs<`XtZ=Vw zYs(De&w|W|BC|L7;m^*_*1s^FoGeV9fo45jqSps=Lv|j&ZZw501^ZE%UiZv(YkREa zV()GY6Nm1N$$l#|I0IOk3&HNChDT`;>@q&dI+-`_H#nwm4riqpKUfWKr7j zTAh(c{YvhDsqi@~T~70*8V;`yk3SxH7{5r|NySka`vCqGUWwMUpj7y>E(TbzLM9FiI|WR7)`5T@X1HmbqL^wX#lC{=nrTvr?R zqa}T|%aTanQZRI*kP5Cu=GW}loF_o|mG{Qz27eRH_*;iswq@n&#LCm-LoPhc8o#-G z@6Y3<7Aij6O)szx_^bD2z0x1$nNIELE!qK-fpZye>lV+4TkdD~Q*74QLRhJ{2$EJR z{q`pBkQ0PaScDQ;H90P~|8NQ~Ab}|xl8TyPH43cG<_rTE^QLYy~ho>wZ|%GF`$*lpy_XVL*h?AGz3=U ztoz7O^5zl@-7lx$uL8gJ19FTHBonwNVb+n@|JbGJGh?%T$5p);};%5m+<=WW^%guMcT{<`=z2laK}}B&in$otZ+lmvy`@ z<4ma@Rd;-%0G4V`bWFd(>9!&pERCAF;Hpi0p6Ks!bo^r8y8DCMv&VMa4{ItPh?&|g zN$X}Drn9tmaF=iwTW!>b1aVXLwR}IAje>BWYlZwJ{ODe27XURD;AL?=4pwZ%0BXA} zcOu1iyC+)%qdS@ugM>eBR}Yof&OrQ-TQuThtMYyCqJ8_KEJE-JuOf@Ic$QvWQe*i0Dx}Fh$X$}4d zkRMG82J)l-0fs#h368zDyd%IIgs+~pk(fdP(WXHp3Y~= z`;>G=ceOtqN-3S>F9hgG_OGv+!^(<*ktLDakntyF0nc|vg33sRXoW5gFg~Ys*Y^sb z#em?ZHBnK~nB3glU5VqJ-N1b{x%XuOse7Me!i5RZ1)^`*xVf)ZzJ*yx)CbaApTPP0 z7TVb~pTT!`clS#sZOn(E6aE=5N+%H?92|VE;byj;6TyVr&XE9` z_G?U+fR!fF>t0yU`2ETOC@@;+Q{ZnAKX4}YtisEomL-0!-ASl-^!MmwwXWJU|1J&W z%>aIEa*LQMnUws=3Ju%!f`SSVL6{M$M>?3Da%ZK9uFc|dD2&|>8Ef1e)t0l-cW$^Iu^aBfLszWXO)=QhGSoBri|C+~umEJ^I z!qlzSDGu~ioA!^1dzZs42*gr@lb`bP^A(+)KfPA$e<)qvo*BqP-#^`~bbArF0SkuL zrizs5&Yt%s^Y?)D3Ryxk4Gt#b;g+TX(RGQvRNEDLVQcpTudEgQg${tA(tqfc+z-CM zO2NEMTkPpakwY?Z^zrer%ZiGLQ9OirKiy}F<}V{iKl()SInroz_PQS?Wr%xP(2hI; z3xY5RHF7*Sj13LtEGg2IdBxBb*~ZQzmrbvYNOO6{OkWzh5biT5#${rsNjf zmKya7rd$5ur?V5z1nML1BYu;hTU~#@d%D&co039bCcYI;&uP8*Vbt>zeb}%4%}sLm zU*^S})YMcpE}2X3?|?jjfFzJeHM==pI;SOno6aL?GDJ^K4jY^+ngckBf8G%G*}wt+ z{msaRGuFsrZEfv3&v9ulc*qtLEkcgXc9s8Z$m;q)`OSZ10T}+>5xKnTYW9%eU>YY8 zGt>H13JMBgO~HX#4@?Yn3^sh{{?7*+A# z%oM<=Ee7`hMvdfa6C%-7S=U|V?b1s5a?wt5E5;1D-47MR0d1l%qZUM$cD1iMk64)l zy1MkYMlikzaCQM3M;*<@e45BcjHp6Y*3%9`451Xg7kCB=Es?~CImn2fAKDVxa7d-Y zF8v;%-XxF!1lMt!zNUXw7v%f;M8@jl-9zQs70(lLdfrh;bODSg)K6}L3^ zoLg_of7iufAc7=#|9*%PfpAH*gv+ix$L5u%%7p1yYVLF2HLa7bce%irvdPAB@U7>f zI&y3j{RP(zEs@IH=6HENWF4{F?0y~i94B9*URUBtTB_>a^558I+?QAO$^Xhe2NsG; zS8S%cLK=~FMaDIlSGl3{P$P@N28wtaW1WMqeQMI+R6VJEnErAmP%@=U zi4qZgZ2iEe&fym43R$&=N=!@~517R7`s$Kr`nUcg+~J!K?G2euf_Gf;1m9n6v*X20 za&AjnQysE0oLZ{i8^AW^e(unbe*Z;`C z2HB(PJBL!X4?FEe(_IrVw`9DE>(C)L4Ui+vMX%I2QSU?LfvIYRO_hHi?EcZ5#{bvY zSBFK}b?*)$BBG#@l1j%A0*-V@NlOUQAl==KAUz;Rr$|V5mk5GLN_Te(3^mkm&+Gfu zIp1}Dhd-W+YvS3@?3rinweEG__ihAaxV&*e9aTX_rvs7)lB2-HfGhs7n@(ayXP?s4 zu2n%*)8xfvW06_sVCmsHWRiX4%}kbbZomYoi86BE(JpQ}(+V5aYu73B5pQ%^TO|*j zA&`j-r3g93!Zg7=Tf?7XcI9yh%e}4#h4V%UrcYjFQTz}aN>&GLPVd)o)BJjBW}lV5 z>23=|$)>}?&5?ko_lZI1xvsbWn+Bbox96^IXJQXxR}Ui@BLY%-ed77O_>rBo~S2r2bt(CH1V z9DgS&#jZBAst{d7>Ox!V+lA?jBopQ1ufNUAv(ob!CcOL3S@+sJ7d!W)c7iXU812#L zwfSdR-fc*H6g>hq0-(^e^!)n2CMHFk9D945*Oy6MJ2meI2fYh!ygw~pyd#_!vHMs$ zHP=9%sG#_D`wqu>^CW#v%n7|RAV8@g<*!(;Q`eagov+1p+^^xO}!3c}z%X@bHBXK(#p|cqm^^S>m_LipYSO%zHA@0B4 zUeM4HMCGgd+CB6?ByTdX`q6nOzvLWc#7#iqomhdb#QEh-v>xBg4^A9{D0ffMc^TFp zV-1&-k5oqEu#&fnmV+dI@W?K?^W0&MXvkCe6)al%bq!j0B#5YaP;39-+J{fl=MJYR z&bV~hdaO>dPgtQ#-AjU}QWQLIypm zih;++CvTUK1MHIB2VZasP;`%&OmBefWIfq6)sva`5+IKMqS>0>13LI{vcKU~0=+Cs z$dPa?6ubrin!k^twZ64G#h_rzS2$)_l-{>cs)hgV(GcV3hYk6!XOd2Ue5Jnloq++$ zf^0db`6K=1#{;p1EO(5~D@egGU*fq2ag`-Uwt=-n*ObSjhlGyuQzCc(8)Z^|+xrJv zyovTt#w;ELL4xY4>b$%?pgu4Rb3_6w3KTf}=P*E0segl*CmaC?5LghVuV8{V{g~AM zT=o0|x7vV^4{j&~HiK;NrO?G)qzre=%3_qvnn{oUOx0gss~1!))p$>sjFGFQC0LJO8%Bdz@*3s4?hmmJW={E-RAXc9W{;w`=Mb=~u7IAL6?A$xkcR^l@l94|3Yg+12J-*Tl> zaI#F>5#8^jg?!gI=^A1*7&EjoXEOBdeX+3?ZU1W8q8;PT!z(Oa-)?D$Y?Na+oA@7u zg-ut#&eHC0e8n?xMYdPdU@lXj;CSHh+A~dO>o-Z0~tF`tz3I(B+!--Q0;e@h>qmZkjhUy$Q(Y0T2Y`*p_u%yCS zQyat@*!FS&fZGKUYjLfRukdg%;Ym5J-6he$Vu&D)@1Nwo#H5gP1$^3{=PrB7h&a=F zuS1xd>|qATJn+$;@84_f(w;gg`^ULAIh-Y#7m){5|;}Aws>)ahkKj}x|U;Dr!rx0 z(gmcm%0n57=p;Kr8nQx6?ld=+)Hqu*=c!wVyQ=Uonuus-`5rj=8(SwxZ5bEgb*I94 zix zz$>Kj@svBt&SN$DBrf>m^cf~SX6VENYJd8c{%p~-Jy@w`onMI#Skn=u!96UtrlXQ5 zlZaPRd$Qg^C`jwhE`IP91Fn@Ijelm=-1#K~D;3uCbi2&dXud1d-Rdi{L~7zt1+5V;zIJU|kK%OuZg_S+ZMLR0$YXEo4ASXZ2iF zu8@I=OG8vCMD(uVN9!{09sjItvR6JgmPtI9L#OVy>pB+a&FN19Nlf zO3KQN^z^yo9+$`?QKT}ezXQHqVabDo12J2Ew*wl$75@;_IV3X9$-%(@gT?jq_I6E7 zB-T4^Nmxx))2gYdDJI>VK?R%vDj-MvY>o5rAIuw{rHJRtXooW{bF|FN%;i9o{QUeD zDhzyP6R{Vz94$;tScCnzx;$4_RQxrBURrpwOT-R1b#PgZm$u;cl#k8K%zW?#(H7DX zR-lFpEEl@Ey6`C}6`VGQKLI=<7%2bblenayYXAqdwzf7jGYb(z%^5p6aHIH_#!o3E z`Y+xMs%I5WiYaLQZh5v~8mFtZ{}1U#9UB{4oWP<)r^$5wtKVYc6xCn4HCZz=GkiQe z<@|Od(^_&4TH3(!ii+GmklmR_O5)=vrX)sE{M_Jr<6Y{zB zABsH*Ny#wG_4n0)Ujst>2$08`e&s`7J}hx^jc{+ALB~Qje{!!gAvQJw{Ah@sOC6mY zvKwl4f9fvjZ9JR9{-f7>Kjneut6}@h@;{g{2=RXx?CoY6cC~W+v&ds-`Vx%+q5>K{6V}a#Y~=eOODP%A_uB z6?Z!hwP>J9I;g!PBCfw?YXlD8=2tT3(RRATM7^`=K7mu_cw@O<-fdb1cEZ}in-He# zjCnuT)d!v(w*WKcDZM35-Rrlf9PuQq(z(osbY4_0O$fkB26<*QDB3hr=VvUH!ilwn;(53&qmOD2|o^ zjf2T%Q@&nO-bfC4qc2)s1)FO)Ry;H~vw!NH%vwuhb2>NJNtWQMm+2xY-bOB-P{^2M zBbPr|MzX(uCIUJ?O@%1e~mvxT?hyKN+Z{M0dp8a^J2~PkjKAfe3)LZqF#(-)$ zY$g0WboOlu`XDv9Df=w%O-svJB@cokroDA)6N9L!*OwgaEjg*s%$v=M*5+0&w=+ZDgWtDN%V>UALHib{QeuE- z1Z$3hw@WlYXca9;Og)nSu7JSM5S47hym5*zZ;(>KvKg~!O?jYxwkKH?BLW_6W~uq! zyW3?I!_^*|RaP?eWAd3FzvDLaIae||4Gk$xM(e5wBk#9IawE%J$d>xrz~Cq2WihB-XYRO?1==OB%cFU=Y_yu?dX+OWk2j}LJuE#V)htVd5uevfO%*ZfU5<1P)VD=J^F|7H zS199F1WB+_?app%1za)o-=O=l@OKsOTvOi>WAa(stYpBhg$_rOZcWY_%iGAipu)(r z#cJ^lJx`%)LBR50=A2hOb|{o@;$6%rCgv)rU}+2o)u8*qX$XV*-!zNIaV!19RfWvW zCBTYHbG1oU#pu8TwU&c6%gWx-qlutq?L(G2*ZLptGU^9WpLDDIi-G>fbLM$6Rj{~$?ydE*>qV@;W8D;jP%=utoNLl3|F&II$rt?J{%JBE%pAT;n=9(SU8;H z!gcZGHXUuM46h`)yUYC@FHqtrAHsT9_IU2OJbYa^gXyfsBk)=d-O9$n+%vzCCKRPf zOZr`vblx(l;78%d1(4|aWDm8X^q9#>m5rC5fAZ!QB}y>U6=#H*5rG!fGmIVFhb4#Q zEK^nZ0;-x$=Gh4QWQ-5k3`|_1-^QV59j`Rx_8g+7IsRlp|ky>4o$ai7eN%?0I zVUx|U3!9Y!b> zO;+VM;aJZd0*W@^L2MjVvr<$gsp#16h# zkoXQ55V(N$N(Wh|1%6f&x_qEn|KhDL+}~)S0;tbGE-h&4{^Wsh(4x~p(f`}A3Kbdu zSXuoQRR5R5U$1`ksMfEN1Yo|3=H^V<0Q8lY$5~lhqgE9DqMVB}F+LvE)Fi;e%^g)& zXJ=Rk9BGtPRSB`a5ln4y~oL#i#0<{M7YWA@C@#a>{sruPD#^@;#90-ND}bwKK)@ zF)@*e;=>1z_WvT&GeG|%)3Xx!r%bP$lSEhgWiZO?3f=RIT1jg;x*j%)&@ftLIni7Z zghMec9M6_J1RT5=si^z`t=o`Zv-;MF2lpFyx86=6LPtU_P>zA8b2o}=kjmE9a0YSt zBm~CM4&Qt8QL%^q=4n2&@891|q@p0>2FiR9kXQ@@^g9#|&#|7VfARr>Aa?J{Cx)h` zYKxUFn~$+*_JJldkw2|UVoXfXc;sZ|hQxoET>p#q{hPz@_OXTrsF?=@xdHmtI z^2zRQCZ78B)g>b}HCUGcERfIc#3_LtKmFleO_V-&KauIUHvxE^oBbv^s^S*SaxdRxT3#Zq|eZb?zJZwqRo7YICw(@a7v-<&V)FG(gfvQnm(9SE_q7PlL4Bg>q3G~73`kJ)TlTn^pG^VL1Tjp8<^m!h}vDAC& z0L>*x%6`;WYOKcVvJURfkb>kc#2dMh0=+xfaxIp;_P}vhD{tVCNXIo+@O)c$xK!Vv zVuGU*D`?}@?-!f=5dm!m8rrS&ELO};>jUY>+Y{SSnfyLiwRAp2@)vdv79#5EkKP7t zzP)wfI$3Epm;j`msoXultHVO|9X8?3S0y@V!+Ar(^*+}WR*4-NqwivTtOiZHHj1%xWpy@#MU!x_+z8L~>>zTb?ha-5%I({xitC)4JfUft%wL>4 zon6lkj1tW`fcwFnJ9nZ9{3>S~4B?b>%zfobwDkEJM`qvCa)$a+eT;D{&%WSo$RYIuS0;_`D!|k;ynU4i> zzf<(PPd^Av5&O2KP@&uKV)5)FEY z9hi1_=s=5K?SAyst#1p~d=Q#U70oU!uR}j%8QzLLU}BQ4#8g#51>Jp8X|eV>_&lrd zGp|)rBvpGD;yclh*?6hh^5Q|c{hZ6sIzgmqnI~ra-sVU*KKZ5Br+!=Pbd0>Y!Lf(W zEb60zf-qCL?fij1hGc7NYo+-JQ%v=(r9hbL7K`ZV+1ZDJ0*jDN(4f3j#9G_%(uHr! zE1lN*+iL2}%7x9mqY#i7thNe^r8tp6bda)ajHu0Q%w0EUd-(JwDYQEW;o=e`hr_Q_ z>J$oOF8eZ_d*Q|d8G7c^wfA}x_L~PC`lH8WDx^ehxsS(muPqQ24<5X0uY=j_GWKm8 z_IDCi7+IJOks%AeOjcS1<%LcW%E$0{9DB%Jt&<&?O^r%Y)Y!~L9`A%P)BH?HvCI>z zb?X0p4!z~w_lb(I{%P&eWSN1FRKjBE;BuGt$2r?%&meD%n56nZI(aSD$f>F=>bW9S z_DvW3%ka^K8M$$F6!!u2q{NQ4k_EFvQuWL0vS zmO`m$jRd@oCom5thZM%5#$G?*Kqj`5?J9Xpr8u_wKkopxF4+Y6k)JFLoN3HH}l?~RdR3(>J=Qg|^Mx=Ev{grM7NZ602s)O;YvJQEv zbaDarxWx;D^`6Afm0ssc2Pf&;4C+5LCb{ATnKNNKf;1N9;`;L3iT>oP?=VlePTo=S zM2pEKRenA@yuMo@mpB-KL&9}$1X$3h?sF=h%`&_ zXJ=6i{VAL#Vow?r$+7rUDAu3_0;(lCKsccAHiqB3bE3RMP_tmvVR?&B z{HGVflmifuG>9~+B&}Yge-{~yL`#BMneRu%6pc4LmtT$BY?}xsn`FddD|v!X*`h?$ zu_%T~P|Q&KZC={9O=@?S!iY&>tXS0Oj)+LVH@#evp@ynnEYryP?u@70PYPdLREVij@i&~jJ675w_;ylftcoiR z3GS(bg;z&-Z}ja~gcq08*&NFQ{Sl-s4E|b1gKHh(iOg#ep-2hk>ds`@bivdohipd` z`W`2{MTq)FTI9mg5_M$NT^rfU-shxd=f_6TiCs-U_Ln~2xx5Mqu`ra4iqSiDQ{Q>| zSPz~VNFlvfcqj0^HTwkJk?2S9HT}3_bqeh8P?7?!U=G?4It~tz{x}b2r(W>}VCQ<2 z_u7ghXZ6Z{n+^)KG%WiqYsYK0*m0MFKcL!jLRLg1%=D{o z1@!6TovEQ9O7Gz08z8w@dVq%~%F4>h@!b%K@U~6*y4`2L+T;B(&D$3^Fv)?QIUS21 zCd9X`lFyZbjLmfi2nZRs@#tKs__2F#1nIwfCtx<$EM^yNX#(siYM(;B>hrRKiOK;2 zHf;q5#JX|xZ52m)G>B{gP zy@CUvUUIZ1=cW|Cc`9|K&c3}HjP{n#U%{2d2?a`Lmbm^fkZh4HV$w~I(V+uvI$r#B!7G_SAvH+sJ< zd*sAF_`ARo~zK0WtB*gbge6VG$r%$J6BAa&Kz@(HL`p#+o+pccj#)@Z_hdEz3-3o;n<#}toX%25M4tIb z{y|C%;VEtcCC&^Fau_vQX^J2_?$D?CZJ2_BLa#3UUPi0WR~UExP=KJX6GC4*7b{2| z$MwN+n!x#HTFbtK47g)(t?#m9Z`wP+>!WcHXoa6~w`?kI2dTq~1%{Or9<-+fkm z_u}H4orCWLGsZePT$y5HAR~?5mqNoOvuJPO`UR(ZGCxnRQR$b;=*e+A{8) zRF?jUeA~%mz9|Gz$ceNRr~LfaIf5VJ;b99rS9!GlF76pXxwvn7sjve-J+W9OeI*RC z9JJvoDmnE}0nF$&HbPSNjNk zRx9p$9BA*^VW_*0~ij!3_NTFE%inHE$`uqM0P(%da^ zd|X*cianM0p33Z;K{W^Z&ic}H-Q9yDD`6d-*zc>}7yD5nng&7ZYbSIO#0wJi3KYX$ zvni9MVrP~`=%Qoo^_QCk>RbjL=Z>pAzg|3X5FIOky&SnFP;Xh+Px8Yi;@D^pL4WI6 zTr9`Hz#x4x`z_G#=b<=aRFho%<@BOf4Xey-cYi-{<)hbVs@KDQEFbNfWNuCul_t&DU1Mg|OO_<3)I?I)n z=?@ns<}OZ)GSV6W`v@nbIshFLu;aLv!6tLw21?l1ES|0jiGJ15v1D!MnkCHz3iQwYhe)8m(w8FOLMxvcXUt61IK-+Y^Q>ydc ztT525Z?f5o@$9^R^hgz972)BC?3Zg*;j551D=d09 zSj@<__rC9!T7ha)l(kHQ&N`8RY{ge#ea&KR*L3<8U8Bl8bXNe!Wc15Ebfjc2r*iXs z@Tb^-3J3C;T1b#hN=h1syS1R&(PowD!SZX+zTt`yrCw#IC_Au!(E%zgamQ5#&Ve*R z^AUG>cVV#4Kz6fNCv)}l$$1x*5}k@31LK^@#O!VpY;xiTI_tZngGG#Enjem^gUtGN z>j$S6{k$%r+!T_g6Xju*AoY`BeU?4lZE^d1XUTA&>-6+2%w1lPC|!AHL%pIWJ2oDV zijWN_({727(85i~EYZ&y@zh$2w2WYPzqWQbCIDZwlx26KLfrj%${T|_Mpc|LANxmn z*&XFl`Oc;L{PL$HA~cAbW|>~+|C(tyBhYEN-KCKLHpY>b)uJ|_XmZDR8CFaq0l)j1 zoG)&uP+in8eExVxtAW+QY$YO`Oupp`srzV6g>kEr@KWquro(sHM7~?w=^=RW$|}Qe zczpzw^D=Z*x9M8v?aJ#Yd2hh?LD+Vq>-F#(g6`%_1!rgLqR8$$RDk^7?!Kh z*L(qB_*^Uq!-Uz5S099d{tW#6_Ywa*Y>F$(j0VA{qFR)hz6s&0hPTPKv0?b4FK)VH z%Hx?16!+Fp-FFAqiN<^iVd0f=U@Zr0IfP-A3k?Das{j4`ksNZ&t%k + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/site/resources/images/svg/diagrams-cli2.js b/src/site/resources/images/svg/diagrams-cli2.js new file mode 100644 index 000000000..9f1a9a277 --- /dev/null +++ b/src/site/resources/images/svg/diagrams-cli2.js @@ -0,0 +1,291 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var Option = new Interface("Option"); +Option.addMethod("process(...)"); +Option.addMethod("canProcess(...)"); +Option.addMethod("getTriggers()"); +Option.addMethod("getPrefixes()"); +Option.addMethod("validate(...)"); +Option.addMethod("helpLines(...)"); +Option.addMethod("appendUsage(...)"); +Option.addMethod("getPreferredName()"); +Option.addMethod("getDescription()"); +Option.addMethod("getId()"); +Option.addMethod("findOption(...)"); + +var Group = new Interface("Group"); +Group.addMethod("appendUsage(...)"); +Group.addNote("-a | -b | -c | -d | -e"); + +var Parent = new Interface("Parent"); +Parent.addMethod("processParent(...)"); +Parent.addNote("-f "); + +var Argument = new Interface("Argument"); +Argument.addMethod("getInitialSeparator()"); +Argument.addMethod("processValues(...)"); +Argument.addMethod("validate(...)"); +Argument.addNote(" [ ...]"); + +var CommandLine = new Interface("CommandLine"); +CommandLine.addMethod("hasOption(...)"); +CommandLine.addMethod("getOption(...)"); +CommandLine.addMethod("getValue(...)"); +CommandLine.addMethod("getValues(...)"); +CommandLine.addMethod("getSwitch(...)"); +CommandLine.addMethod("getProperty(...)"); +CommandLine.addMethod("getProperties()"); +CommandLine.addMethod("getOptionCount(...)"); +CommandLine.addMethod("getOptions()"); +CommandLine.addMethod("getOptionTriggers()"); + +var WriteableCommandLine = new Interface("WriteableCommandLine"); +WriteableCommandLine.addMethod("addOption(...)"); +WriteableCommandLine.addMethod("addValue(...)"); +WriteableCommandLine.addMethod("addSwitch(...)"); +WriteableCommandLine.addMethod("addProperty(...)"); +WriteableCommandLine.addMethod("looksLikeOption(...)"); + + + + + +var PropertyOption = new Class("PropertyOption"); +PropertyOption.addAttribute("optionString"); +PropertyOption.addAttribute("description"); +PropertyOption.addAttribute("prefixes"); +PropertyOption.addNote("-Dproperty=value"); + +var DefaultOption = new Class("DefaultOption"); +DefaultOption.addAttribute("optionString"); +DefaultOption.addAttribute("description"); +DefaultOption.addAttribute("prefixes"); +DefaultOption.addNote("-f (--file, --filelist)"); + +var Command = new Class("Command"); +Command.addAttribute("preferredName"); +Command.addAttribute("aliases"); +Command.addAttribute("required"); +Command.addAttribute("triggers"); +Command.addNote("update (up, upd)"); + +var Switch = new Class("Switch"); +Switch.addAttribute("enabledPrefix"); +Switch.addAttribute("disabledPrefix"); +Switch.addAttribute("preferredName"); +Switch.addAttribute("aliases"); +Switch.addAttribute("required"); +Switch.addAttribute("triggers"); +Switch.addAttribute("prefixes"); +Switch.addNote("+d|-d (+display|-display)"); + +var SourceDestArgument = new Class("SourceDestArgument"); +SourceDestArgument.addAttribute("preferredName"); +SourceDestArgument.addAttribute("aliases"); +SourceDestArgument.addAttribute("required"); +SourceDestArgument.addAttribute("triggers"); +SourceDestArgument.addNote(" ... "); + + + + +var Parser = new Class("Parser"); +Parser.addMethod("parse(...)"); +Parser.addMethod("parseAndHelp(...)"); +Parser.addMethod("setGroup(...)"); +Parser.addMethod("setHelpFormatter(...)"); +Parser.addMethod("setHelpOption(...)"); +Parser.addMethod("setHelpTrigger(...)"); + +var DefaultingCommandLine = new Class("DefaultingCommandLine"); +DefaultingCommandLine.addMethod("appendCommandLine(...)"); +DefaultingCommandLine.addMethod("insertCommandLine(...)"); +DefaultingCommandLine.addMethod("commandLines()"); + +var PropertiesCommandLine = new Class("PropertiesCommandLine"); +PropertiesCommandLine.addAttribute("properties"); +PropertiesCommandLine.addNote("java.util.Properties"); + +var PreferencesCommandLine = new Class("PreferencesCommandLine"); +PreferencesCommandLine.addAttribute("preferences"); +PreferencesCommandLine.addNote("java.util.prefs.Preferences"); + + + + + +var ArgumentBuilder = new Class("ArgumentBuilder"); +ArgumentBuilder.addMethod("withId(...)"); +ArgumentBuilder.addMethod("withName(...)"); +ArgumentBuilder.addMethod("withDescription(...)"); +ArgumentBuilder.addMethod("withConsumeRemaining(...)"); +ArgumentBuilder.addMethod("withValidator(...)"); +ArgumentBuilder.addMethod("withMinimum(...)"); +ArgumentBuilder.addMethod("withMaximum(...)"); +ArgumentBuilder.addMethod("withDefault(...)"); +ArgumentBuilder.addMethod("withDefaults(...)"); +ArgumentBuilder.addMethod("withInitialSeparator(...)"); +ArgumentBuilder.addMethod("withSubsequentSeparator(...)"); +ArgumentBuilder.addMethod("create()"); +ArgumentBuilder.addMethod("reset()"); + +var CommandBuilder = new Class("CommandBuilder"); +CommandBuilder.addMethod("withId(...)"); +CommandBuilder.addMethod("withName(...)"); +CommandBuilder.addMethod("withDescription(...)"); +CommandBuilder.addMethod("withArgument(...)"); +CommandBuilder.addMethod("withChildren(...)"); +CommandBuilder.addMethod("withRequired(...)"); +CommandBuilder.addMethod("create()"); +CommandBuilder.addMethod("reset()"); + +var DefaultOptionBuilder = new Class("DefaultOptionBuilder"); +DefaultOptionBuilder.addMethod("withId(...)"); +DefaultOptionBuilder.addMethod("withShortName(...)"); +DefaultOptionBuilder.addMethod("withLongName(...)"); +DefaultOptionBuilder.addMethod("withDescription(...)"); +DefaultOptionBuilder.addMethod("withArgument(...)"); +DefaultOptionBuilder.addMethod("withChildren(...)"); +DefaultOptionBuilder.addMethod("withRequired(...)"); +DefaultOptionBuilder.addMethod("create()"); +DefaultOptionBuilder.addMethod("reset()"); +DefaultOptionBuilder.addAttribute("shortPrefix"); +DefaultOptionBuilder.addAttribute("longPrefix"); +DefaultOptionBuilder.addAttribute("burstEnabled"); + +var DefaultOptionBuilder = new Class("DefaultOptionBuilder"); +DefaultOptionBuilder.addMethod("withId(...)"); +DefaultOptionBuilder.addMethod("withShortName(...)"); +DefaultOptionBuilder.addMethod("withLongName(...)"); +DefaultOptionBuilder.addMethod("withDescription(...)"); +DefaultOptionBuilder.addMethod("withArgument(...)"); +DefaultOptionBuilder.addMethod("withChildren(...)"); +DefaultOptionBuilder.addMethod("withRequired(...)"); +DefaultOptionBuilder.addMethod("create()"); +DefaultOptionBuilder.addMethod("reset()"); + +var GroupBuilder = new Class("GroupBuilder"); +GroupBuilder.addMethod("withName(...)"); +GroupBuilder.addMethod("withDescription(...)"); +GroupBuilder.addMethod("withOption(...)"); +GroupBuilder.addMethod("withMinimum(...)"); +GroupBuilder.addMethod("withMaximum(...)"); +GroupBuilder.addMethod("create()"); +GroupBuilder.addMethod("reset()"); + +var PatternBuilder = new Class("PatternBuilder"); +PatternBuilder.addMethod("withPattern(...)"); +PatternBuilder.addMethod("create()"); +PatternBuilder.addMethod("reset()"); +PatternBuilder.addAttribute("groupBuilder"); +PatternBuilder.addAttribute("optionBuilder"); +PatternBuilder.addAttribute("argumentBuilder"); + +var SwitchBuilder = new Class("SwitchBuilder"); +SwitchBuilder.addMethod("withId(...)"); +SwitchBuilder.addMethod("withName(...)"); +SwitchBuilder.addMethod("withDescription(...)"); +SwitchBuilder.addMethod("withArgument(...)"); +SwitchBuilder.addMethod("withChildren(...)"); +SwitchBuilder.addMethod("withRequired(...)"); +SwitchBuilder.addMethod("create()"); +SwitchBuilder.addMethod("reset()"); +SwitchBuilder.addAttribute("enabledPrefix"); +SwitchBuilder.addAttribute("disabledPrefix"); + + + +var Validator = new Class("Validator"); +Validator.addMethod("validate(...)"); + +var ClassValidator = new Class("ClassValidator"); +ClassValidator.addAttribute("classLoader"); +ClassValidator.addAttribute("instance"); +ClassValidator.addAttribute("loadable"); + +var DateValidator = new Class("DateValidator"); +DateValidator.addAttribute("formats"); +DateValidator.addAttribute("minimum"); +DateValidator.addAttribute("maximum"); + +var EnumValidator = new Class("EnumValidator"); +EnumValidator.addAttribute("validValues"); + +var FileValidator = new Class("FileValidator"); +FileValidator.addAttribute("directory"); +FileValidator.addAttribute("existing"); +FileValidator.addAttribute("file"); +FileValidator.addAttribute("hidden"); +FileValidator.addAttribute("readable"); +FileValidator.addAttribute("writable"); + +var FileValidator = new Class("FileValidator"); +FileValidator.addAttribute("format"); +FileValidator.addAttribute("minimum"); +FileValidator.addAttribute("maximum"); + +var UrlValidator = new Class("UrlValidator"); +UrlValidator.addAttribute("format"); +UrlValidator.addAttribute("minimum"); +UrlValidator.addAttribute("maximum"); + + + + +var Comparators = new Class("Comparators"); +Comparators.addMethod("chain(...)"); +Comparators.addMethod("commandFirst(...)"); +Comparators.addMethod("commandLast(...)"); +Comparators.addMethod("defaultOptionFirst(...)"); +Comparators.addMethod("defaultOptionLast(...)"); +Comparators.addMethod("groupFirst(...)"); +Comparators.addMethod("groupLast(...)"); +Comparators.addMethod("namedFirst(...)"); +Comparators.addMethod("namedLast(...)"); +Comparators.addMethod("preferredNameFirst(...)"); +Comparators.addMethod("preferredNameLast(...)"); +Comparators.addMethod("requiredFirst(...)"); +Comparators.addMethod("requiredLast(...)"); +Comparators.addMethod("switchFirst(...)"); +Comparators.addMethod("switchLast(...)"); + +var HelpFormatter = new Class("HelpFormatter"); +HelpFormatter.addMethod("print()"); +HelpFormatter.addMethod("printDivider()"); +HelpFormatter.addMethod("printException()"); +HelpFormatter.addMethod("printFooter()"); +HelpFormatter.addMethod("printGutterLeft()"); +HelpFormatter.addMethod("printGutterRight()"); +HelpFormatter.addMethod("printHeader()"); +HelpFormatter.addMethod("printHelp()"); +HelpFormatter.addMethod("printUsage()"); +HelpFormatter.addAttribute("comparator"); +HelpFormatter.addAttribute("displaySettings"); +HelpFormatter.addAttribute("divider"); +HelpFormatter.addAttribute("exception"); +HelpFormatter.addAttribute("footer"); +HelpFormatter.addAttribute("fullUsageSettings"); +HelpFormatter.addAttribute("group"); +HelpFormatter.addAttribute("gutterCenter"); +HelpFormatter.addAttribute("gutterLeft"); +HelpFormatter.addAttribute("gutterRight"); +HelpFormatter.addAttribute("header"); +HelpFormatter.addAttribute("lineUsageSettings"); +HelpFormatter.addAttribute("pageWidth"); +HelpFormatter.addAttribute("printWriter"); +HelpFormatter.addAttribute("shellCommand"); diff --git a/src/site/resources/images/svg/diagrams.css b/src/site/resources/images/svg/diagrams.css new file mode 100644 index 000000000..d8691da08 --- /dev/null +++ b/src/site/resources/images/svg/diagrams.css @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +.option .outline, .option polygon.note { + fill:rgb(191,255,255); +} +.group rect.outline, .group polygon.note { + fill:rgb(255,191,191); +} + +.parent rect.outline, .parent polygon.note { + fill:rgb(191,255,191); +} +.argument rect.outline, .argument polygon.note { + fill:rgb(191,191,255); +} +.property rect.outline, .property polygon.note { + fill:rgb(255,191,255); +} + +.package rect { + fill:rgb(255,255,191); +} + +.package rect.inner { + fill: rgb(255,255,255); + stroke: none; +} + +text.title { + text-anchor: middle; +} + +.type text { + fill: rgb(0,0,0); +} +rect, line, polygon, polyline { + stroke:rgb(0,0,0); + stroke-width:2; + stroke-linejoin: bevel; + stroke-linecap: round; +} + +.implements, .extends { + fill: none; + marker-end: url(util.svg#HollowArrow); +} + +.implements, .note.connect { + stroke-dasharray: 5; +} diff --git a/src/site/resources/images/svg/diagrams.js b/src/site/resources/images/svg/diagrams.js new file mode 100644 index 000000000..4e8a5a72e --- /dev/null +++ b/src/site/resources/images/svg/diagrams.js @@ -0,0 +1,368 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +var textHeight = 10; +var padding = 10; +var namespace = "http://www.w3.org/2000/svg"; + +var displayAttributes = true; +var displayMethods = true; +var displayNotes = true; + +function Type(name){ + this.width = 160; + this.style = "type"; + + this.insert = function(evt){ + y = 0; + y = this.insertOutline(evt,y); + y = this.insertName(evt,y); + if(displayAttributes==true){ + y = this.insertAttributes(evt,y); + } + if(displayMethods==true){ + y = this.insertMethods(evt,y); + } + if(displayNotes==true){ + y = this.insertNotes(evt,y); + } + } + + this.height = function(){ + height = 0; + height += this.heightName(); + if(displayAttributes==true){ + height += this.heightAttributes(); + } + if(displayMethods==true){ + height += this.heightMethods(); + } + return height; + } + + + + + + + this.insertOutline = function(evt,y){ + + style = evt.target.getAttributeNS(null, "class"); + evt.target.setAttributeNS(null,"class",style+" "+this.style); + + e = document.createElementNS(namespace, "rect"); + e.setAttributeNS(null, "x", 0); + e.setAttributeNS(null, "y", 0); + e.setAttributeNS(null, "width", this.width); + e.setAttributeNS(null, "height", this.height()); + e.setAttributeNS(null, "class", "outline"); + evt.target.appendChild(e); + + return y; + } + + + + + + + + this.name = name; + + this.heightName = function(){ + return padding * 2 + textHeight; + } + + this.insertName = function(evt,y){ + + y += padding; + y += textHeight; + + e = document.createElementNS(namespace, "text"); + e.setAttributeNS(null, "x", this.width/2); + e.setAttributeNS(null, "y", y); + e.setAttributeNS(null, "class", "title"); + e.appendChild(document.createTextNode(this.name)); + evt.target.appendChild(e); + + y += padding; + + return y; + } + + + + + + + + this.attributeList = new Array(); + this.attributeCount = 0; + + this.addAttribute = function(text){ + this.attributeList[this.attributeCount++]=text; + } + + this.heightAttributes = function(){ + if(this.attributeCount>0){ + return padding * 2 + this.attributeCount*textHeight; + } + else{ + return padding; + } + } + + this.insertAttributes = function(evt,y){ + + e = document.createElementNS(namespace, "line"); + e.setAttributeNS(null, "x1", 0); + e.setAttributeNS(null, "y1", y); + e.setAttributeNS(null, "x2", this.width); + e.setAttributeNS(null, "y2", y); + e.setAttributeNS(null, "class", "divider"); + evt.target.appendChild(e); + + y += padding; + + for(i=0;i0){ + y += padding; + } + + return y; + } + + + + + + this.methodList = new Array(); + this.methodCount = 0; + + this.addMethod = function(text){ + this.methodList[this.methodCount++]=text; + } + + this.heightMethods = function(){ + if(this.methodCount>0){ + return padding * 2 + this.methodCount*textHeight; + } + else{ + return padding; + } + } + + this.insertMethods = function(evt,y){ + + e = document.createElementNS(namespace, "line"); + e.setAttributeNS(null, "x1", 0); + e.setAttributeNS(null, "y1", y); + e.setAttributeNS(null, "x2", this.width); + e.setAttributeNS(null, "y2", y); + e.setAttributeNS(null, "class", "divider"); + evt.target.appendChild(e); + + y += padding; + + for(i=0;i0){ + y += padding; + } + + return y; + } + + + + + + this.noteList = new Array(); + this.noteCount = 0; + + this.addNote = function(text){ + this.noteList[this.noteCount++]=text; + } + + this.insertNotes = function(evt,y){ + if(this.noteCount>0){ + joinTop = y; + + y += padding; + + e = document.createElementNS(namespace, "line"); + e.setAttributeNS(null, "x1", this.width/2-padding*2); + e.setAttributeNS(null, "y1", y); + e.setAttributeNS(null, "x2", this.width/2+padding*2); + e.setAttributeNS(null, "y2", joinTop); + e.setAttributeNS(null, "class", "note connect"); + evt.target.appendChild(e); + + + + height = this.heightNotes(); + + e = document.createElementNS(namespace, "polygon"); + e.setAttributeNS(null, "points", "0,"+(y+padding)+" 0,"+(y+height)+" "+this.width+","+(y+height)+" "+this.width+","+y+" "+padding+","+y); + e.setAttributeNS(null, "class", "note"); + evt.target.appendChild(e); + + e = document.createElementNS(namespace, "polygon"); + e.setAttributeNS(null, "points", ""+padding+","+y+" 0,"+(y+padding)+" "+padding+","+(y+padding)); + e.setAttributeNS(null, "class", "note corner"); + evt.target.appendChild(e); + + y += padding; + + + for(i=0;i0){ + return padding*2 + this.noteCount*textHeight; + } + } +} + +function Interface(name){ + this.superclass = Type; + this.superclass(name); + delete this.superclass; + this.rounded = true; + + this.insertOutline = function(evt,y){ + + style = evt.target.getAttributeNS(null, "class"); + evt.target.setAttributeNS(null,"class",style+" "+this.style); + + e = document.createElementNS(namespace, "rect"); + e.setAttributeNS(null, "x", 0); + e.setAttributeNS(null, "y", 0); + e.setAttributeNS(null, "width", this.width); + e.setAttributeNS(null, "height", this.height()); + e.setAttributeNS(null, "rx", padding*1.5); + e.setAttributeNS(null, "ry", padding*1.5); + e.setAttributeNS(null, "class", "outline"); + evt.target.appendChild(e); + + return y; + } + + this.heightAttributes = function(){ + return 0; + } + + this.insertAttributes = function(evt,y){ + return y; + } + +} +Interface.prototype = new Type; + +function Class(name){ + this.superclass = Type; + this.superclass(name); + delete this.superclass; + this.rounded = false; +} +Class.prototype = new Type; + + + + +function PackageSymbol(name,width,height){ + this.name = name; + this.nameWidth = 150; + this.width = width; + this.height = height; + + this.insert = function(evt){ + + style = evt.target.getAttributeNS(null, "class"); + evt.target.setAttributeNS(null,"class",style+" package"); + + first = evt.target.getFirstChild(); + + e = document.createElementNS(namespace, "rect"); + e.setAttributeNS(null, "x", 0); + e.setAttributeNS(null, "y", 0); + e.setAttributeNS(null, "width", this.nameWidth); + e.setAttributeNS(null, "height", textHeight+padding); + e.setAttributeNS(null, "class", "outline"); + e.appendChild(document.createTextNode(this.name)); + evt.target.insertBefore(e,first); + + e = document.createElementNS(namespace, "text"); + e.setAttributeNS(null, "x", this.nameWidth/2); + e.setAttributeNS(null, "y", textHeight+padding/2); + e.setAttributeNS(null, "class", "title"); + e.appendChild(document.createTextNode(this.name)); + evt.target.insertBefore(e,first); + + e = document.createElementNS(namespace, "rect"); + e.setAttributeNS(null, "x", 0); + e.setAttributeNS(null, "y", textHeight+padding); + e.setAttributeNS(null, "width", this.width); + e.setAttributeNS(null, "height", this.height-textHeight-padding); + e.setAttributeNS(null, "class", "outline"); + e.appendChild(document.createTextNode(this.name)); + evt.target.insertBefore(e,first); + + e = document.createElementNS(namespace, "rect"); + e.setAttributeNS(null, "x", padding); + e.setAttributeNS(null, "y", textHeight+padding*2); + e.setAttributeNS(null, "width", this.width-padding*2); + e.setAttributeNS(null, "height", this.height-textHeight-padding*3); + e.setAttributeNS(null, "class", "inner"); + e.appendChild(document.createTextNode(this.name)); + evt.target.insertBefore(e,first); + + + } +} + diff --git a/src/site/resources/images/svg/options.svg b/src/site/resources/images/svg/options.svg new file mode 100644 index 000000000..cdb5160f9 --- /dev/null +++ b/src/site/resources/images/svg/options.svg @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/site/resources/images/svg/util.svg b/src/site/resources/images/svg/util.svg new file mode 100644 index 000000000..b86d760c4 --- /dev/null +++ b/src/site/resources/images/svg/util.svg @@ -0,0 +1,47 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/site/site.xml b/src/site/site.xml new file mode 100644 index 000000000..5663d9925 --- /dev/null +++ b/src/site/site.xml @@ -0,0 +1,53 @@ + + + + + Commons CLI + /images/logo.png + /index.html + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 19fe6dc11c328547156c8ab45d2da079eaff704a Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Mon, 7 Jan 2008 03:15:46 +0000 Subject: [PATCH 0060/1663] Upgrade to commons-parent version 6 release git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@609497 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7cb8ba100..d3815aebb 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.apache.commons commons-parent - 5 + 6 4.0.0 commons-cli From 419b0b9dddca7a398627b9de92804a71781b4fd8 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Tue, 15 Jan 2008 21:04:51 +0000 Subject: [PATCH 0061/1663] upgrade to commons-parent-7 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@612219 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d3815aebb..de830b637 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.apache.commons commons-parent - 6 + 7 4.0.0 commons-cli From 73276486b1f39510bf27cb6c0684da805b121f5d Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Tue, 29 Jan 2008 14:41:10 +0000 Subject: [PATCH 0062/1663] Remove unused dependency git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@616350 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 7 ------- project.xml | 7 ------- 2 files changed, 14 deletions(-) diff --git a/pom.xml b/pom.xml index de830b637..5cace853a 100644 --- a/pom.xml +++ b/pom.xml @@ -111,13 +111,6 @@ - - - commons-lang - commons-lang - 2.1 - - junit diff --git a/project.xml b/project.xml index 1d349ff6a..c7d9c028a 100644 --- a/project.xml +++ b/project.xml @@ -139,13 +139,6 @@ - - - commons-lang - commons-lang - 2.1 - - junit From 4ee0d6c4f1b553858aeabf3ee6fb37d764f263e2 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Thu, 21 Feb 2008 08:03:23 +0000 Subject: [PATCH 0063/1663] Applying Oliver Heger's patch for CLI-121, changing a HashSet to a LinkedHashSet so we pass tests on JDK 1.6. This moves us to a JDK 1.4+ dependency, but I don't think that's an issue. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@629710 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli2/builder/PatternBuilder.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/java/org/apache/commons/cli2/builder/PatternBuilder.java b/src/java/org/apache/commons/cli2/builder/PatternBuilder.java index 691001735..2b4c1b54d 100644 --- a/src/java/org/apache/commons/cli2/builder/PatternBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/PatternBuilder.java @@ -16,8 +16,8 @@ */ package org.apache.commons.cli2.builder; -import java.util.HashSet; import java.util.Iterator; +import java.util.LinkedHashSet; import java.util.Set; import org.apache.commons.cli2.Argument; @@ -64,7 +64,7 @@ public PatternBuilder( this.abuilder = abuilder; } - private final Set options = new HashSet(); + private final Set options = new LinkedHashSet(); /** * Creates a new Option instance. From f69f56f6d4f0c1001d0c3bb2f7edb363542f7abd Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Sun, 2 Mar 2008 19:37:56 +0000 Subject: [PATCH 0064/1663] Upgrade to commons-parent-8 and add configuration properties for OSGi (maven-bundle-plugin) and commons-build-plugin git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@632815 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 5cace853a..b591fd71a 100644 --- a/pom.xml +++ b/pom.xml @@ -22,9 +22,10 @@ org.apache.commons commons-parent - 7 + 8 4.0.0 + bundle commons-cli commons-cli 2.0-SNAPSHOT @@ -129,6 +130,15 @@ + + cli + org.apache.commons.cli2 + 1.1 + + CLI + 12310463 + + src/java src/test From a4824b4e0ac555283a1d3abc87ec8d846e17f62a Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Sun, 2 Mar 2008 19:46:00 +0000 Subject: [PATCH 0065/1663] Add Issue Tracking and Download pages generated by commons-build-plugin git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@632817 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/download_cli.xml | 145 +++++++++++++++++++++++++++++++++++++++ xdocs/issue-tracking.xml | 131 ++++++++++++++++++++++------------- 2 files changed, 228 insertions(+), 48 deletions(-) create mode 100644 xdocs/download_cli.xml diff --git a/xdocs/download_cli.xml b/xdocs/download_cli.xml new file mode 100644 index 000000000..169a0753c --- /dev/null +++ b/xdocs/download_cli.xml @@ -0,0 +1,145 @@ + + + + + + Download Commons CLI + Commons Documentation Team + + +
      +

      + We recommend you use a mirror to download our release + builds, but you must verify the integrity of + the downloaded files using signatures downloaded from our main + distribution directories. Recent releases (48 hours) may not yet + be available from the mirrors. +

      + +

      + You are currently using [preferred]. If you + encounter a problem with this mirror, please select another + mirror. If all mirrors are failing, there are backup + mirrors (at the end of the mirrors list) that should be + available. +

      + [if-any logo][end] +

      + +
      +

      + Other mirrors: + + +

      + + +

      + The KEYS link links to the code signing keys used to sign the product. + The PGP link downloads the OpenPGP compatible signature from our main site. + The MD5 link downloads the checksum from the main site. +

      + +

      + For more information concerning Commons CLI, see the + Commons CLI web site. +

      + +

      +

      + +

      +
      + +
      diff --git a/xdocs/issue-tracking.xml b/xdocs/issue-tracking.xml index d884a440a..c7e749c4a 100644 --- a/xdocs/issue-tracking.xml +++ b/xdocs/issue-tracking.xml @@ -15,53 +15,88 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> + - - Issue tracking - Commons Documentation Team - - - -
      -

      - Commons CLI uses the ASF JIRA for tracking issues. -

      -

      - To use JIRA you may need to create an account - (if you have previously created/updated Commons issues using Bugzilla an account will have been automatically - created and you can use the Forgot Password - page to get a new password). -

      -

      - If you would like to report a bug, or raise an enhancement request with - Commons CLI please do the following: -

        -
      1. Search existing open bugs. - If you find your issue listed then please add a comment with your details.
      2. -
      3. Search the mailing list archive. - You may find your issue or idea has already been discussed.
      4. -
      5. Decide if your issue is a bug or an enhancement.
      6. -
      7. Submit either a bug report - or enhancement request.
      8. -
      -

      -

      - Please also remember these points: -

        -
      • the more information you provide, the better we can help you
      • -
      • test cases are vital, particularly for any proposed enhancements
      • -
      • the developers of Commons CLI are all unpaid volunteers
      • -
      -

      -

      - You may also find these links useful: -

      -

      -
      - - + + Commons CLI Issue tracking + Commons Documentation Team + + + +
      +

      + Commons CLI uses ASF JIRA for tracking issues. + See the Commons CLI JIRA project page. +

      + +

      + To use JIRA you may need to create an account + (if you have previously created/updated Commons issues using Bugzilla an account will have been automatically + created and you can use the Forgot Password + page to get a new password). +

      + +

      + If you would like to report a bug, or raise an enhancement request with + Commons CLI please do the following: +

        +
      1. Search existing open bugs. + If you find your issue listed then please add a comment with your details.
      2. +
      3. Search the mailing list archive(s). + You may find your issue or idea has already been discussed.
      4. +
      5. Decide if your issue is a bug or an enhancement.
      6. +
      7. Submit either a bug report + or enhancement request.
      8. +
      +

      + +

      + Please also remember these points: +

        +
      • the more information you provide, the better we can help you
      • +
      • test cases are vital, particularly for any proposed enhancements
      • +
      • the developers of Commons CLI are all unpaid volunteers
      • +
      +

      + +

      + For more information on subversion and creating patches see the + Apache Contributors Guide. +

      + +

      + You may also find these links useful: +

      +

      +
      +
      From 8a8e6952fe4a2636d90e88d8fe4affccf85d8f87 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Sun, 9 Mar 2008 14:21:48 +0000 Subject: [PATCH 0066/1663] Upgrade to version 9 of commons-parent git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@635244 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index b591fd71a..6c3dc05dd 100644 --- a/pom.xml +++ b/pom.xml @@ -22,10 +22,9 @@ org.apache.commons commons-parent - 8 + 9 4.0.0 - bundle commons-cli commons-cli 2.0-SNAPSHOT From 52743cc9aec36a0674ee045cc73f983fcd79c6c5 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Fri, 14 Mar 2008 06:41:17 +0000 Subject: [PATCH 0067/1663] Fixing the assemblies to say project.version instead of version to stop '2.4.1' leaking through from the JVM properties. Also making it project.artifactId while I'm doing this. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@637007 13f79535-47bb-0310-9956-ffa450edef68 --- src/assembly/src.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/assembly/src.xml b/src/assembly/src.xml index a2262284f..58110f60f 100644 --- a/src/assembly/src.xml +++ b/src/assembly/src.xml @@ -20,7 +20,7 @@ tar.gz zip - ${artifactId}-${version}-src + ${project.artifactId}-${project.version}-src From 56ba9c6b01b0a05fef2c4731d7e6225e9c71ca30 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 22 Mar 2008 02:48:04 +0000 Subject: [PATCH 0068/1663] Fix bug pointed out by FindBugs - it was removing the Boolean from the options, not the option git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639940 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli2/commandline/WriteableCommandLineImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java index 4051d7642..bb1610e16 100644 --- a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java @@ -214,7 +214,7 @@ public void setDefaultValues(final Option option, public void setDefaultSwitch(final Option option, final Boolean defaultSwitch) { if (defaultSwitch == null) { - defaultSwitches.remove(defaultSwitch); + defaultSwitches.remove(option); } else { defaultSwitches.put(option, defaultSwitch); } From 4729315c88e18a531c151162f42544d525e36752 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 22 Mar 2008 02:49:41 +0000 Subject: [PATCH 0069/1663] Removing trailing spaces git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639941 13f79535-47bb-0310-9956-ffa450edef68 --- project.properties | 2 + .../org/apache/commons/cli2/Argument.java | 108 +-- .../org/apache/commons/cli2/CommandLine.java | 216 +----- .../apache/commons/cli2/DisplaySetting.java | 156 +---- src/java/org/apache/commons/cli2/Group.java | 66 +- .../org/apache/commons/cli2/HelpLine.java | 54 +- src/java/org/apache/commons/cli2/Option.java | 198 +----- .../apache/commons/cli2/OptionException.java | 108 +-- src/java/org/apache/commons/cli2/Parent.java | 42 +- .../commons/cli2/WriteableCommandLine.java | 77 +-- .../commons/cli2/builder/ArgumentBuilder.java | 287 +------- .../commons/cli2/builder/CommandBuilder.java | 188 +---- .../cli2/builder/DefaultOptionBuilder.java | 216 +----- .../commons/cli2/builder/GroupBuilder.java | 119 +--- .../commons/cli2/builder/PatternBuilder.java | 203 +----- .../commons/cli2/builder/SwitchBuilder.java | 195 +----- .../cli2/commandline/CommandLineImpl.java | 121 +--- .../commandline/DefaultingCommandLine.java | 173 +---- .../commons/cli2/commandline/Parser.java | 177 +---- .../commandline/PreferencesCommandLine.java | 171 +---- .../commandline/PropertiesCommandLine.java | 156 +---- .../commandline/WriteableCommandLineImpl.java | 227 +----- .../commons/cli2/option/ArgumentImpl.java | 375 +--------- .../apache/commons/cli2/option/Command.java | 176 +---- .../commons/cli2/option/DefaultOption.java | 222 +----- .../apache/commons/cli2/option/GroupImpl.java | 518 +------------- .../commons/cli2/option/HelpLineImpl.java | 111 +-- .../commons/cli2/option/OptionImpl.java | 160 +---- .../commons/cli2/option/ParentImpl.java | 258 +------ .../commons/cli2/option/PropertyOption.java | 168 +---- .../cli2/option/SourceDestArgument.java | 139 +--- .../apache/commons/cli2/option/Switch.java | 249 +------ .../cli2/resource/ResourceConstants.java | 71 +- .../commons/cli2/resource/ResourceHelper.java | 161 +---- .../apache/commons/cli2/util/Comparators.java | 457 +------------ .../commons/cli2/util/HelpFormatter.java | 639 +---------------- .../cli2/validation/ClassValidator.java | 202 +----- .../cli2/validation/DateValidator.java | 309 +-------- .../cli2/validation/EnumValidator.java | 121 +--- .../cli2/validation/FileValidator.java | 266 +------ .../validation/InvalidArgumentException.java | 35 +- .../cli2/validation/NumberValidator.java | 201 +----- .../commons/cli2/validation/UrlValidator.java | 116 +--- .../commons/cli2/validation/Validator.java | 44 +- .../org/apache/commons/cli2/CLITestCase.java | 86 +-- .../commons/cli2/CommandLineDefaultsTest.java | 252 +------ .../commons/cli2/CommandLineTestCase.java | 513 +------------- .../commons/cli2/DocumentationTest.java | 446 +----------- .../apache/commons/cli2/PrecedenceTest.java | 414 +---------- .../cli2/WriteableCommandLineTestCase.java | 93 +-- .../commons/cli2/application/AntTest.java | 199 +----- .../commons/cli2/application/CpTest.java | 472 +------------ .../commons/cli2/application/CvsTest.java | 313 +-------- .../commons/cli2/application/LsTest.java | 225 +----- .../apache/commons/cli2/bug/Bug13886Test.java | 90 +-- .../apache/commons/cli2/bug/Bug13935Test.java | 61 +- .../apache/commons/cli2/bug/Bug15046Test.java | 83 +-- .../apache/commons/cli2/bug/Bug15648Test.java | 61 +- .../apache/commons/cli2/bug/Bug27575Test.java | 42 +- .../apache/commons/cli2/bug/Bug28005Test.java | 80 +-- .../apache/commons/cli2/bug/Bug32533Test.java | 49 +- .../commons/cli2/bug/BugCLI122Test.java | 46 +- .../apache/commons/cli2/bug/BugCLI12Test.java | 58 +- .../apache/commons/cli2/bug/BugCLI18Test.java | 61 +- .../apache/commons/cli2/bug/BugCLI80Test.java | 68 +- .../bug/BugLoopingOptionLookAlikeTest.java | 80 +-- .../cli2/builder/ArgumentBuilderTest.java | 255 +------ .../builder/DefaultOptionBuilderTest.java | 201 +----- .../DefaultingCommandLineTest.java | 152 +--- .../commons/cli2/commandline/ParserTest.java | 141 +--- .../PreferencesCommandLineTest.java | 107 +-- .../PropertiesCommandLineTest.java | 102 +-- .../WriteableCommandLineImplTest.java | 37 +- .../commons/cli2/jdepend/JDependTest.java | 110 +-- .../commons/cli2/option/ArgumentTest.java | 647 +----------------- .../commons/cli2/option/ArgumentTestCase.java | 29 +- .../commons/cli2/option/CommandTest.java | 250 +------ .../cli2/option/DefaultOptionTest.java | 228 +----- .../apache/commons/cli2/option/GroupTest.java | 441 +----------- .../commons/cli2/option/GroupTestCase.java | 32 +- .../commons/cli2/option/NestedGroupTest.java | 193 +----- .../commons/cli2/option/OptionTestCase.java | 56 +- .../commons/cli2/option/ParentTest.java | 420 +----------- .../commons/cli2/option/ParentTestCase.java | 27 +- .../cli2/option/PropertyOptionTest.java | 234 +------ .../commons/cli2/option/SwitchTest.java | 309 +-------- .../cli2/resource/ResourceHelperTest.java | 85 +-- .../commons/cli2/util/ComparatorsTest.java | 222 +----- .../commons/cli2/util/HelpFormatterTest.java | 546 +-------------- .../cli2/validation/ClassValidatorTest.java | 249 +------ .../cli2/validation/DateValidatorTest.java | 221 +----- .../cli2/validation/EnumValidatorTest.java | 67 +- .../cli2/validation/FileValidatorTest.java | 197 +----- .../cli2/validation/NumberValidatorTest.java | 169 +---- .../cli2/validation/TimeZoneTestSuite.java | 47 +- .../cli2/validation/UrlValidatorTest.java | 94 +-- .../validation/protect/ProtectedClass.java | 24 +- 97 files changed, 98 insertions(+), 17844 deletions(-) diff --git a/project.properties b/project.properties index 67f6176e4..c4e10c2b0 100644 --- a/project.properties +++ b/project.properties @@ -3,6 +3,8 @@ # ------------------------------------------------------------------- maven.repo.remote=http://repo1.maven.org/maven +maven.checkstyle.properties=checkstyle.xml + maven.changelog.factory=org.apache.maven.svnlib.SvnChangeLogFactory maven.changes.issue.template=http://issues.apache.org/jira/browse/%ISSUE% diff --git a/src/java/org/apache/commons/cli2/Argument.java b/src/java/org/apache/commons/cli2/Argument.java index 49187da1e..6c239e5f9 100644 --- a/src/java/org/apache/commons/cli2/Argument.java +++ b/src/java/org/apache/commons/cli2/Argument.java @@ -1,107 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.ListIterator; - -/** - * An Option that can process values passed on the command line in the form - * "--file README". - */ -public interface Argument extends Option { - - /** - * Returns the initial separator character or - * '\0' if no character has been set. - * - * @return char the initial separator character - */ - char getInitialSeparator(); - - /** - * Processes the "README" style element of the argument. - * - * Values identified should be added to the CommandLine object in - * association with this Argument. - * - * @see WriteableCommandLine#addValue(Option,Object) - * - * @param commandLine The CommandLine object to store results in. - * @param args The arguments to process. - * @param option The option to register value against. - * @throws OptionException if any problems occur. - */ - void processValues( - final WriteableCommandLine commandLine, - final ListIterator args, - final Option option) - throws OptionException; - - /** - * Adds defaults to a CommandLine. - * - * @param commandLine - * The CommandLine object to store defaults in. - * @param option - * The Option to store the defaults against. - */ - void defaultValues(final WriteableCommandLine commandLine, final Option option); - - /** - * Performs any necessary validation on the values added to the - * CommandLine. - * - * Validation will typically involve using the - * CommandLine.getValues(option) method to retrieve the values - * and then either checking each value. Optionally the String - * value can be replaced by another Object such as a Number - * instance or a File instance. - * - * @see CommandLine#getValues(Option) - * - * @param commandLine The CommandLine object to query. - * @param option The option to lookup values with. - * @throws OptionException if any problems occur. - */ - void validate(final WriteableCommandLine commandLine, final Option option) - throws OptionException; - - /** - * Indicates whether argument values must be present for the CommandLine to - * be valid. - * - * @see #getMinimum() - * @see #getMaximum() - * @return true iff the CommandLine will be invalid without at least one - * value - */ - boolean isRequired(); - - /** - * Retrieves the minimum number of values required for a valid Argument - * - * @return the minimum number of values - */ - int getMinimum(); - - /** - * Retrieves the maximum number of values acceptable for a valid Argument - * - * @return the maximum number of values - */ - int getMaximum(); -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.ListIterator;/** * An Option that can process values passed on the command line in the form * "--file README". */public interface Argument extends Option { /** * Returns the initial separator character or * '\0' if no character has been set. * * @return char the initial separator character */ char getInitialSeparator(); /** * Processes the "README" style element of the argument. * * Values identified should be added to the CommandLine object in * association with this Argument. * * @see WriteableCommandLine#addValue(Option,Object) * * @param commandLine The CommandLine object to store results in. * @param args The arguments to process. * @param option The option to register value against. * @throws OptionException if any problems occur. */ void processValues( final WriteableCommandLine commandLine, final ListIterator args, final Option option) throws OptionException; /** * Adds defaults to a CommandLine. * * @param commandLine * The CommandLine object to store defaults in. * @param option * The Option to store the defaults against. */ void defaultValues(final WriteableCommandLine commandLine, final Option option); /** * Performs any necessary validation on the values added to the * CommandLine. * * Validation will typically involve using the * CommandLine.getValues(option) method to retrieve the values * and then either checking each value. Optionally the String * value can be replaced by another Object such as a Number * instance or a File instance. * * @see CommandLine#getValues(Option) * * @param commandLine The CommandLine object to query. * @param option The option to lookup values with. * @throws OptionException if any problems occur. */ void validate(final WriteableCommandLine commandLine, final Option option) throws OptionException; /** * Indicates whether argument values must be present for the CommandLine to * be valid. * * @see #getMinimum() * @see #getMaximum() * @return true iff the CommandLine will be invalid without at least one * value */ boolean isRequired(); /** * Retrieves the minimum number of values required for a valid Argument * * @return the minimum number of values */ int getMinimum(); /** * Retrieves the maximum number of values acceptable for a valid Argument * * @return the maximum number of values */ int getMaximum();} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/CommandLine.java b/src/java/org/apache/commons/cli2/CommandLine.java index 3c2eeba55..848fbce98 100644 --- a/src/java/org/apache/commons/cli2/CommandLine.java +++ b/src/java/org/apache/commons/cli2/CommandLine.java @@ -1,215 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.List; -import java.util.Set; - -/** - * Instances of CommandLine represent a command line that has been processed - * according to the definition supplied to the parser. - */ -public interface CommandLine { - - /** - * Detects the presence of an option with the specified trigger in this - * CommandLine. - * - * @param trigger the trigger to search for - * @return true iff an option with this trigger is present - */ - boolean hasOption(final String trigger); - - /** - * Detects the presence of an option in this CommandLine. - * - * @param option the Option to search for - * @return true iff the option is present - */ - boolean hasOption(final Option option); - - /** - * Finds the Option with the specified trigger - * - * @param trigger the name of the option to retrieve - * @return the Option matching the trigger or null if none exists - */ - Option getOption(final String trigger); - - /** - * Retrieves the Argument values associated with the specified Option - * - * @param trigger a trigger used to lookup the Option - * @return a list of values or an empty List if none are found - */ - List getValues(final String trigger); - - /** - * Retrieves the Argument values associated with the specified Option - * - * @param trigger a trigger used to lookup the Option - * @param defaultValues the result to return if no values are found - * @return a list of values or defaultValues if none are found - */ - List getValues(final String trigger, final List defaultValues); - - /** - * Retrieves the Argument values associated with the specified Option - * - * @param option the Option associated with the values - * @return a list of values or an empty List if none are found - */ - List getValues(final Option option); - - /** - * Retrieves the Argument values associated with the specified Option - * - * @param option the Option associated with the values - * @param defaultValues the result to return if no values are found - * @return a list of values or defaultValues if none are found - */ - List getValues(final Option option, final List defaultValues); - - /** - * Retrieves the single Argument value associated with the specified Option - * - * @param trigger a trigger used to lookup the Option - * @return the matching value or null if none exists - * @throws IllegalStateException if more than one values are found - */ - Object getValue(final String trigger) throws IllegalStateException; - - /** - * Retrieves the single Argument value associated with the specified Option - * - * @param trigger a trigger used to lookup the Option - * @param defaultValue the result to use if no values are found - * @return the matching value or defaultValue if none exists - * @throws IllegalStateException if more than one values are found - */ - Object getValue(final String trigger, final Object defaultValue) throws IllegalStateException; - - /** - * Retrieves the single Argument value associated with the specified Option - * - * @param option the Option associated with the value - * @return the matching value or null if none exists - * @throws IllegalStateException if more than one values are found - */ - Object getValue(final Option option) throws IllegalStateException; - - /** - * Retrieves the single Argument value associated with the specified Option - * - * @param option the Option associated with the value - * @param defaultValue the result to use if no values are found - * @return the matching value or defaultValue if none exists - * @throws IllegalStateException if more than one values are found - */ - Object getValue(final Option option, final Object defaultValue) throws IllegalStateException; - - /** - * Retrieves the Boolean value associated with the specified Switch - * - * @param trigger a trigger used to lookup the Option - * @return the Boolean associated with trigger or null if none exists - */ - Boolean getSwitch(final String trigger); - - /** - * Retrieves the Boolean value associated with the specified Switch - * - * @param trigger a trigger used to lookup the Option - * @param defaultValue the Boolean to use if none match - * @return the Boolean associated with trigger or defaultValue if none exists - */ - Boolean getSwitch(final String trigger, final Boolean defaultValue); - - /** - * Retrieves the Boolean value associated with the specified Switch - * - * @param option the Option associated with the value - * @return the Boolean associated with option or null if none exists - */ - Boolean getSwitch(final Option option); - - /** - * Retrieves the Boolean value associated with the specified Switch - * - * @param option the Option associated with the value - * @param defaultValue the Boolean to use if none match - * @return the Boolean associated with option or defaultValue if none exists - */ - Boolean getSwitch(final Option option, final Boolean defaultValue); - - - /** - * Retrieves the value associated with the specified property - * - * @param property the property name to lookup - * @return the value of the property or null - */ - String getProperty(final String property); - - /** - * Retrieves the value associated with the specified property - * - * @param property the property name to lookup - * @param defaultValue the value to use if no other is found - * @return the value of the property or defaultValue - */ - String getProperty(final String property, final String defaultValue); - - /** - * Retrieves the set of all property names associated with this CommandLine - * - * @return a none null set of property names - */ - Set getProperties(); - - /** - * Retrieves the number of times the specified Option appeared in this - * CommandLine - * - * @param trigger a trigger used to lookup the Option - * @return the number of occurrences of the option - */ - int getOptionCount(final String trigger); - - /** - * Retrieves the number of times the specified Option appeared in this - * CommandLine - * - * @param option the Option associated to check - * @return the number of occurrences of the option - */ - int getOptionCount(final Option option); - - /** - * Retrieves a list of all Options found in this CommandLine - * - * @return a none null list of Options - */ - List getOptions(); - - /** - * Retrieves a list of all Option triggers found in this CommandLine - * - * @return a none null list of Option triggers - */ - Set getOptionTriggers(); -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.List;import java.util.Set;/** * Instances of CommandLine represent a command line that has been processed * according to the definition supplied to the parser. */public interface CommandLine { /** * Detects the presence of an option with the specified trigger in this * CommandLine. * * @param trigger the trigger to search for * @return true iff an option with this trigger is present */ boolean hasOption(final String trigger); /** * Detects the presence of an option in this CommandLine. * * @param option the Option to search for * @return true iff the option is present */ boolean hasOption(final Option option); /** * Finds the Option with the specified trigger * * @param trigger the name of the option to retrieve * @return the Option matching the trigger or null if none exists */ Option getOption(final String trigger); /** * Retrieves the Argument values associated with the specified Option * * @param trigger a trigger used to lookup the Option * @return a list of values or an empty List if none are found */ List getValues(final String trigger); /** * Retrieves the Argument values associated with the specified Option * * @param trigger a trigger used to lookup the Option * @param defaultValues the result to return if no values are found * @return a list of values or defaultValues if none are found */ List getValues(final String trigger, final List defaultValues); /** * Retrieves the Argument values associated with the specified Option * * @param option the Option associated with the values * @return a list of values or an empty List if none are found */ List getValues(final Option option); /** * Retrieves the Argument values associated with the specified Option * * @param option the Option associated with the values * @param defaultValues the result to return if no values are found * @return a list of values or defaultValues if none are found */ List getValues(final Option option, final List defaultValues); /** * Retrieves the single Argument value associated with the specified Option * * @param trigger a trigger used to lookup the Option * @return the matching value or null if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final String trigger) throws IllegalStateException; /** * Retrieves the single Argument value associated with the specified Option * * @param trigger a trigger used to lookup the Option * @param defaultValue the result to use if no values are found * @return the matching value or defaultValue if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final String trigger, final Object defaultValue) throws IllegalStateException; /** * Retrieves the single Argument value associated with the specified Option * * @param option the Option associated with the value * @return the matching value or null if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final Option option) throws IllegalStateException; /** * Retrieves the single Argument value associated with the specified Option * * @param option the Option associated with the value * @param defaultValue the result to use if no values are found * @return the matching value or defaultValue if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final Option option, final Object defaultValue) throws IllegalStateException; /** * Retrieves the Boolean value associated with the specified Switch * * @param trigger a trigger used to lookup the Option * @return the Boolean associated with trigger or null if none exists */ Boolean getSwitch(final String trigger); /** * Retrieves the Boolean value associated with the specified Switch * * @param trigger a trigger used to lookup the Option * @param defaultValue the Boolean to use if none match * @return the Boolean associated with trigger or defaultValue if none exists */ Boolean getSwitch(final String trigger, final Boolean defaultValue); /** * Retrieves the Boolean value associated with the specified Switch * * @param option the Option associated with the value * @return the Boolean associated with option or null if none exists */ Boolean getSwitch(final Option option); /** * Retrieves the Boolean value associated with the specified Switch * * @param option the Option associated with the value * @param defaultValue the Boolean to use if none match * @return the Boolean associated with option or defaultValue if none exists */ Boolean getSwitch(final Option option, final Boolean defaultValue); /** * Retrieves the value associated with the specified property * * @param property the property name to lookup * @return the value of the property or null */ String getProperty(final String property); /** * Retrieves the value associated with the specified property * * @param property the property name to lookup * @param defaultValue the value to use if no other is found * @return the value of the property or defaultValue */ String getProperty(final String property, final String defaultValue); /** * Retrieves the set of all property names associated with this CommandLine * * @return a none null set of property names */ Set getProperties(); /** * Retrieves the number of times the specified Option appeared in this * CommandLine * * @param trigger a trigger used to lookup the Option * @return the number of occurrences of the option */ int getOptionCount(final String trigger); /** * Retrieves the number of times the specified Option appeared in this * CommandLine * * @param option the Option associated to check * @return the number of occurrences of the option */ int getOptionCount(final Option option); /** * Retrieves a list of all Options found in this CommandLine * * @return a none null list of Options */ List getOptions(); /** * Retrieves a list of all Option triggers found in this CommandLine * * @return a none null list of Option triggers */ Set getOptionTriggers();} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/DisplaySetting.java b/src/java/org/apache/commons/cli2/DisplaySetting.java index fc522067d..91b64532b 100644 --- a/src/java/org/apache/commons/cli2/DisplaySetting.java +++ b/src/java/org/apache/commons/cli2/DisplaySetting.java @@ -1,155 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -/** - * An enum of possible display settings. These settings are used to control the - * presence of various features in the String representations of options, - * CommandLines and usage strings. Usually a Set of DisplaySetting instances - * will be passed to a method that will lookup the presence of the values. - */ -public class DisplaySetting { - - private static final Set all = new HashSet(); - - /** - * A Set guarenteed to contain all possible DisplaySetting values - */ - public static final Set ALL = Collections.unmodifiableSet(all); - - /** - * A Set guarenteed to contain no DisplaySetting values - */ - public static final Set NONE = Collections.EMPTY_SET; - - /** - * Indicates that aliases should be included - */ - public static final DisplaySetting DISPLAY_ALIASES = - new DisplaySetting("DISPLAY_ALIASES"); - - /** - * Indicates that optionality should be included - */ - public static final DisplaySetting DISPLAY_OPTIONAL = - new DisplaySetting("DISPLAY_OPTIONAL"); - - /** - * Indicates that property options should be included - */ - public static final DisplaySetting DISPLAY_PROPERTY_OPTION = - new DisplaySetting("DISPLAY_PROPERTY_OPTION"); - - /** - * Indicates that switches should be included enabled - */ - public static final DisplaySetting DISPLAY_SWITCH_ENABLED = - new DisplaySetting("DISPLAY_SWITCH_ENABLED"); - - /** - * Indicates that switches should be included disabled - */ - public static final DisplaySetting DISPLAY_SWITCH_DISABLED = - new DisplaySetting("DISPLAY_SWITCH_DISABLED"); - - /** - * Indicates that group names should be included - */ - public static final DisplaySetting DISPLAY_GROUP_NAME = - new DisplaySetting("DISPLAY_GROUP_NAME"); - - /** - * Indicates that groups should be included expanded - */ - public static final DisplaySetting DISPLAY_GROUP_EXPANDED = - new DisplaySetting("DISPLAY_GROUP_EXPANDED"); - - /** - * Indicates that group arguments should be included - */ - public static final DisplaySetting DISPLAY_GROUP_ARGUMENT = - new DisplaySetting("DISPLAY_GROUP_ARGUMENT"); - - /** - * Indicates that group outer brackets should be included - */ - public static final DisplaySetting DISPLAY_GROUP_OUTER = - new DisplaySetting("DISPLAY_GROUP_OUTER"); - - /** - * Indicates that arguments should be included numbered - */ - public static final DisplaySetting DISPLAY_ARGUMENT_NUMBERED = - new DisplaySetting("DISPLAY_ARGUMENT_NUMBERED"); - - /** - * Indicates that arguments should be included bracketed - */ - public static final DisplaySetting DISPLAY_ARGUMENT_BRACKETED = - new DisplaySetting("DISPLAY_ARGUMENT_BRACKETED"); - - /** - * Indicates that arguments of Parents should be included - */ - public static final DisplaySetting DISPLAY_PARENT_ARGUMENT = - new DisplaySetting("DISPLAY_PARENT_ARGUMENT"); - - /** - * Indicates that children of Parents should be included - */ - public static final DisplaySetting DISPLAY_PARENT_CHILDREN = - new DisplaySetting("DISPLAY_PARENT_CHILDREN"); - - /** - * The name of the setting - */ - private final String name; - - /** - * The hashCode of the setting - */ - private final int hashCode; - - /** - * Creates a new DisplaySetting with the specified name - * @param name the name of the setting - */ - private DisplaySetting(final String name) { - this.name = name; - this.hashCode = name.hashCode(); - all.add(this); - } - - public int hashCode() { - return hashCode; - } - - public boolean equals(final Object that) { - if (that instanceof DisplaySetting) { - return name.compareTo(that.toString()) == 0; - } - return false; - } - - public String toString() { - return name; - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Collections;import java.util.HashSet;import java.util.Set;/** * An enum of possible display settings. These settings are used to control the * presence of various features in the String representations of options, * CommandLines and usage strings. Usually a Set of DisplaySetting instances * will be passed to a method that will lookup the presence of the values. */public class DisplaySetting { private static final Set all = new HashSet(); /** * A Set guarenteed to contain all possible DisplaySetting values */ public static final Set ALL = Collections.unmodifiableSet(all); /** * A Set guarenteed to contain no DisplaySetting values */ public static final Set NONE = Collections.EMPTY_SET; /** * Indicates that aliases should be included */ public static final DisplaySetting DISPLAY_ALIASES = new DisplaySetting("DISPLAY_ALIASES"); /** * Indicates that optionality should be included */ public static final DisplaySetting DISPLAY_OPTIONAL = new DisplaySetting("DISPLAY_OPTIONAL"); /** * Indicates that property options should be included */ public static final DisplaySetting DISPLAY_PROPERTY_OPTION = new DisplaySetting("DISPLAY_PROPERTY_OPTION"); /** * Indicates that switches should be included enabled */ public static final DisplaySetting DISPLAY_SWITCH_ENABLED = new DisplaySetting("DISPLAY_SWITCH_ENABLED"); /** * Indicates that switches should be included disabled */ public static final DisplaySetting DISPLAY_SWITCH_DISABLED = new DisplaySetting("DISPLAY_SWITCH_DISABLED"); /** * Indicates that group names should be included */ public static final DisplaySetting DISPLAY_GROUP_NAME = new DisplaySetting("DISPLAY_GROUP_NAME"); /** * Indicates that groups should be included expanded */ public static final DisplaySetting DISPLAY_GROUP_EXPANDED = new DisplaySetting("DISPLAY_GROUP_EXPANDED"); /** * Indicates that group arguments should be included */ public static final DisplaySetting DISPLAY_GROUP_ARGUMENT = new DisplaySetting("DISPLAY_GROUP_ARGUMENT"); /** * Indicates that group outer brackets should be included */ public static final DisplaySetting DISPLAY_GROUP_OUTER = new DisplaySetting("DISPLAY_GROUP_OUTER"); /** * Indicates that arguments should be included numbered */ public static final DisplaySetting DISPLAY_ARGUMENT_NUMBERED = new DisplaySetting("DISPLAY_ARGUMENT_NUMBERED"); /** * Indicates that arguments should be included bracketed */ public static final DisplaySetting DISPLAY_ARGUMENT_BRACKETED = new DisplaySetting("DISPLAY_ARGUMENT_BRACKETED"); /** * Indicates that arguments of Parents should be included */ public static final DisplaySetting DISPLAY_PARENT_ARGUMENT = new DisplaySetting("DISPLAY_PARENT_ARGUMENT"); /** * Indicates that children of Parents should be included */ public static final DisplaySetting DISPLAY_PARENT_CHILDREN = new DisplaySetting("DISPLAY_PARENT_CHILDREN"); /** * The name of the setting */ private final String name; /** * The hashCode of the setting */ private final int hashCode; /** * Creates a new DisplaySetting with the specified name * @param name the name of the setting */ private DisplaySetting(final String name) { this.name = name; this.hashCode = name.hashCode(); all.add(this); } public int hashCode() { return hashCode; } public boolean equals(final Object that) { if (that instanceof DisplaySetting) { return name.compareTo(that.toString()) == 0; } return false; } public String toString() { return name; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/Group.java b/src/java/org/apache/commons/cli2/Group.java index 3a3d4c752..d884a5269 100644 --- a/src/java/org/apache/commons/cli2/Group.java +++ b/src/java/org/apache/commons/cli2/Group.java @@ -1,65 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.Comparator; -import java.util.Set; - -/** - * An Option representing a choice or group of Options in the form "-a|-b|-c". - */ -public interface Group extends Option { - - /** - * Appends usage information to the specified StringBuffer - * - * @param buffer the buffer to append to - * @param helpSettings a set of display settings @see DisplaySetting - * @param comp a comparator used to sort the Options - * @param separator the String used to separate member Options - */ - void appendUsage( - final StringBuffer buffer, - final Set helpSettings, - final Comparator comp, - final String separator); - - /** - * Indicates whether group members must be present for the CommandLine to be - * valid. - * - * @see #getMinimum() - * @see #getMaximum() - * @return true iff the CommandLine will be invalid without at least one - * member option - */ - boolean isRequired(); - - /** - * Retrieves the minimum number of members required for a valid Group - * - * @return the minimum number of members - */ - int getMinimum(); - - /** - * Retrieves the maximum number of members acceptable for a valid Group - * - * @return the maximum number of members - */ - int getMaximum(); -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Comparator;import java.util.Set;/** * An Option representing a choice or group of Options in the form "-a|-b|-c". */public interface Group extends Option { /** * Appends usage information to the specified StringBuffer * * @param buffer the buffer to append to * @param helpSettings a set of display settings @see DisplaySetting * @param comp a comparator used to sort the Options * @param separator the String used to separate member Options */ void appendUsage( final StringBuffer buffer, final Set helpSettings, final Comparator comp, final String separator); /** * Indicates whether group members must be present for the CommandLine to be * valid. * * @see #getMinimum() * @see #getMaximum() * @return true iff the CommandLine will be invalid without at least one * member option */ boolean isRequired(); /** * Retrieves the minimum number of members required for a valid Group * * @return the minimum number of members */ int getMinimum(); /** * Retrieves the maximum number of members acceptable for a valid Group * * @return the maximum number of members */ int getMaximum();} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/HelpLine.java b/src/java/org/apache/commons/cli2/HelpLine.java index 2043a4841..def8d2fb7 100644 --- a/src/java/org/apache/commons/cli2/HelpLine.java +++ b/src/java/org/apache/commons/cli2/HelpLine.java @@ -1,53 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.Comparator; -import java.util.Set; - -/** - * Represents a line of help for a particular Option. - */ -public interface HelpLine { - - /** - * @return The description of the option - */ - String getDescription(); - - /** - * @return The level of indentation for this line - */ - int getIndent(); - - /** - * @return The Option that the help line relates to - */ - Option getOption(); - - /** - * Builds a usage string for the option using the specified settings and - * comparator. - * - * @param helpSettings - * the settings to apply - * @param comparator - * a comparator to sort options when applicable - * @return the usage string - */ - String usage(final Set helpSettings, final Comparator comparator); -} \ No newline at end of file +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Comparator;import java.util.Set;/** * Represents a line of help for a particular Option. */public interface HelpLine { /** * @return The description of the option */ String getDescription(); /** * @return The level of indentation for this line */ int getIndent(); /** * @return The Option that the help line relates to */ Option getOption(); /** * Builds a usage string for the option using the specified settings and * comparator. * * @param helpSettings * the settings to apply * @param comparator * a comparator to sort options when applicable * @return the usage string */ String usage(final Set helpSettings, final Comparator comparator);} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/Option.java b/src/java/org/apache/commons/cli2/Option.java index d0aaaa6c6..b33e8cd7e 100644 --- a/src/java/org/apache/commons/cli2/Option.java +++ b/src/java/org/apache/commons/cli2/Option.java @@ -1,197 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.Comparator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -/** - * The super type of all options representing a particular element of the - * command line interface. - */ -public interface Option { - - /** - * Processes String arguments into a CommandLine. - * - * The iterator will initially point at the first argument to be processed - * and at the end of the method should point to the first argument not - * processed. This method MUST process at least one argument from the - * ListIterator. - * - * @param commandLine - * The CommandLine object to store results in - * @param args - * The arguments to process - * @throws OptionException - * if any problems occur - */ - void process( - final WriteableCommandLine commandLine, - final ListIterator args) - throws OptionException; - - /** - * Adds defaults to a CommandLine. - * - * Any defaults for this option are applied as well as the defaults for - * any contained options - * - * @param commandLine - * The CommandLine object to store defaults in - */ - void defaults(final WriteableCommandLine commandLine); - - /** - * Indicates whether this Option will be able to process the particular - * argument. - * - * @param argument - * The argument to be tested - * @return true if the argument can be processed by this Option - */ - boolean canProcess(final WriteableCommandLine commandLine, final String argument); - - /** - * Indicates whether this Option will be able to process the particular - * argument. The ListIterator must be restored to the initial state before - * returning the boolean. - * - * @see #canProcess(WriteableCommandLine,String) - * @param arguments - * the ListIterator over String arguments - * @return true if the argument can be processed by this Option - */ - boolean canProcess(final WriteableCommandLine commandLine, final ListIterator arguments); - - /** - * Identifies the argument prefixes that should trigger this option. This - * is used to decide which of many Options should be tried when processing - * a given argument string. - * - * The returned Set must not be null. - * - * @return The set of triggers for this Option - */ - Set getTriggers(); - - /** - * Identifies the argument prefixes that should be considered options. This - * is used to identify whether a given string looks like an option or an - * argument value. Typically an option would return the set [--,-] while - * switches might offer [-,+]. - * - * The returned Set must not be null. - * - * @return The set of prefixes for this Option - */ - Set getPrefixes(); - - /** - * Checks that the supplied CommandLine is valid with respect to this - * option. - * - * @param commandLine - * The CommandLine to check. - * @throws OptionException - * if the CommandLine is not valid. - */ - void validate(final WriteableCommandLine commandLine) - throws OptionException; - - /** - * Builds up a list of HelpLineImpl instances to be presented by HelpFormatter. - * - * @see HelpLine - * @see org.apache.commons.cli2.util.HelpFormatter - * @param depth - * the initial indent depth - * @param helpSettings - * the HelpSettings that should be applied - * @param comp - * a comparator used to sort options when applicable. - * @return a List of HelpLineImpl objects - */ - List helpLines( - final int depth, - final Set helpSettings, - final Comparator comp); - - /** - * Appends usage information to the specified StringBuffer - * - * @param buffer the buffer to append to - * @param helpSettings a set of display settings @see DisplaySetting - * @param comp a comparator used to sort the Options - */ - void appendUsage( - final StringBuffer buffer, - final Set helpSettings, - final Comparator comp); - - /** - * The preferred name of an option is used for generating help and usage - * information. - * - * @return The preferred name of the option - */ - String getPreferredName(); - - /** - * Returns a description of the option. This string is used to build help - * messages as in the HelpFormatter. - * - * @see org.apache.commons.cli2.util.HelpFormatter - * @return a description of the option. - */ - String getDescription(); - - /** - * Returns the id of the option. This can be used in a loop and switch - * construct: - * - * - * for(Option o : cmd.getOptions()){ - * switch(o.getId()){ - * case POTENTIAL_OPTION: - * ... - * } - * } - * - * - * The returned value is not guarenteed to be unique. - * - * @return the id of the option. - */ - int getId(); - - /** - * Recursively searches for an option with the supplied trigger. - * - * @param trigger the trigger to search for. - * @return the matching option or null. - */ - Option findOption(final String trigger); - - /** - * Indicates whether this option is required to be present. - * @return true iff the CommandLine will be invalid without this Option - */ - boolean isRequired(); -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Comparator;import java.util.List;import java.util.ListIterator;import java.util.Set;/** * The super type of all options representing a particular element of the * command line interface. */public interface Option { /** * Processes String arguments into a CommandLine. * * The iterator will initially point at the first argument to be processed * and at the end of the method should point to the first argument not * processed. This method MUST process at least one argument from the * ListIterator. * * @param commandLine * The CommandLine object to store results in * @param args * The arguments to process * @throws OptionException * if any problems occur */ void process( final WriteableCommandLine commandLine, final ListIterator args) throws OptionException; /** * Adds defaults to a CommandLine. * * Any defaults for this option are applied as well as the defaults for * any contained options * * @param commandLine * The CommandLine object to store defaults in */ void defaults(final WriteableCommandLine commandLine); /** * Indicates whether this Option will be able to process the particular * argument. * * @param argument * The argument to be tested * @return true if the argument can be processed by this Option */ boolean canProcess(final WriteableCommandLine commandLine, final String argument); /** * Indicates whether this Option will be able to process the particular * argument. The ListIterator must be restored to the initial state before * returning the boolean. * * @see #canProcess(WriteableCommandLine,String) * @param arguments * the ListIterator over String arguments * @return true if the argument can be processed by this Option */ boolean canProcess(final WriteableCommandLine commandLine, final ListIterator arguments); /** * Identifies the argument prefixes that should trigger this option. This * is used to decide which of many Options should be tried when processing * a given argument string. * * The returned Set must not be null. * * @return The set of triggers for this Option */ Set getTriggers(); /** * Identifies the argument prefixes that should be considered options. This * is used to identify whether a given string looks like an option or an * argument value. Typically an option would return the set [--,-] while * switches might offer [-,+]. * * The returned Set must not be null. * * @return The set of prefixes for this Option */ Set getPrefixes(); /** * Checks that the supplied CommandLine is valid with respect to this * option. * * @param commandLine * The CommandLine to check. * @throws OptionException * if the CommandLine is not valid. */ void validate(final WriteableCommandLine commandLine) throws OptionException; /** * Builds up a list of HelpLineImpl instances to be presented by HelpFormatter. * * @see HelpLine * @see org.apache.commons.cli2.util.HelpFormatter * @param depth * the initial indent depth * @param helpSettings * the HelpSettings that should be applied * @param comp * a comparator used to sort options when applicable. * @return a List of HelpLineImpl objects */ List helpLines( final int depth, final Set helpSettings, final Comparator comp); /** * Appends usage information to the specified StringBuffer * * @param buffer the buffer to append to * @param helpSettings a set of display settings @see DisplaySetting * @param comp a comparator used to sort the Options */ void appendUsage( final StringBuffer buffer, final Set helpSettings, final Comparator comp); /** * The preferred name of an option is used for generating help and usage * information. * * @return The preferred name of the option */ String getPreferredName(); /** * Returns a description of the option. This string is used to build help * messages as in the HelpFormatter. * * @see org.apache.commons.cli2.util.HelpFormatter * @return a description of the option. */ String getDescription(); /** * Returns the id of the option. This can be used in a loop and switch * construct: * * * for(Option o : cmd.getOptions()){ * switch(o.getId()){ * case POTENTIAL_OPTION: * ... * } * } * * * The returned value is not guarenteed to be unique. * * @return the id of the option. */ int getId(); /** * Recursively searches for an option with the supplied trigger. * * @param trigger the trigger to search for. * @return the matching option or null. */ Option findOption(final String trigger); /** * Indicates whether this option is required to be present. * @return true iff the CommandLine will be invalid without this Option */ boolean isRequired();} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/OptionException.java b/src/java/org/apache/commons/cli2/OptionException.java index 15b408ba9..f431def95 100644 --- a/src/java/org/apache/commons/cli2/OptionException.java +++ b/src/java/org/apache/commons/cli2/OptionException.java @@ -1,107 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.Collections; -import java.util.Set; - -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * A problem found while dealing with command line options. - */ -public class OptionException - extends Exception { - /** - * The settings used when displaying the related Option. - * - * @see DisplaySetting - */ - public static final Set HELP_SETTINGS = - Collections.unmodifiableSet(Collections.singleton(DisplaySetting.DISPLAY_PROPERTY_OPTION)); - - /** resource helper instance */ - private static final ResourceHelper helper = ResourceHelper.getResourceHelper(); - - /** The Option the exception relates to */ - private final Option option; - - /** The message explaining the Exception */ - private final String message; - - /** - * Creates a new OptionException. - * - * @param option - * The Option the exception relates to - */ - public OptionException(final Option option) { - this(option, null, null); - } - - /** - * Creates a new OptionException. - * @param option the Option the exception relates to - * @param messageKey the id of the message to display - */ - public OptionException(final Option option, - final String messageKey) { - this(option, messageKey, null); - } - - /** - * Creates a new OptionException. - * @param option the Option the exception relates to - * @param messageKey the id of the message to display - * @param value a value to display with the message - */ - public OptionException(final Option option, - final String messageKey, - final String value) { - this.option = option; - - if (messageKey != null) { - final StringBuffer buffer = new StringBuffer(); - - if (value != null) { - buffer.append(helper.getMessage(messageKey, value)); - } else { - buffer.append(helper.getMessage(messageKey)); - } - - buffer.append(" "); - - option.appendUsage(buffer, HELP_SETTINGS, null); - message = buffer.toString(); - } else { - message = ""; - } - } - - /** - * Gets the Option the exception relates to - * - * @return The related Option - */ - public Option getOption() { - return option; - } - - public String getMessage() { - return message; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Collections;import java.util.Set;import org.apache.commons.cli2.resource.ResourceHelper;/** * A problem found while dealing with command line options. */public class OptionException extends Exception { /** * The settings used when displaying the related Option. * * @see DisplaySetting */ public static final Set HELP_SETTINGS = Collections.unmodifiableSet(Collections.singleton(DisplaySetting.DISPLAY_PROPERTY_OPTION)); /** resource helper instance */ private static final ResourceHelper helper = ResourceHelper.getResourceHelper(); /** The Option the exception relates to */ private final Option option; /** The message explaining the Exception */ private final String message; /** * Creates a new OptionException. * * @param option * The Option the exception relates to */ public OptionException(final Option option) { this(option, null, null); } /** * Creates a new OptionException. * @param option the Option the exception relates to * @param messageKey the id of the message to display */ public OptionException(final Option option, final String messageKey) { this(option, messageKey, null); } /** * Creates a new OptionException. * @param option the Option the exception relates to * @param messageKey the id of the message to display * @param value a value to display with the message */ public OptionException(final Option option, final String messageKey, final String value) { this.option = option; if (messageKey != null) { final StringBuffer buffer = new StringBuffer(); if (value != null) { buffer.append(helper.getMessage(messageKey, value)); } else { buffer.append(helper.getMessage(messageKey)); } buffer.append(" "); option.appendUsage(buffer, HELP_SETTINGS, null); message = buffer.toString(); } else { message = ""; } } /** * Gets the Option the exception relates to * * @return The related Option */ public Option getOption() { return option; } public String getMessage() { return message; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/Parent.java b/src/java/org/apache/commons/cli2/Parent.java index eafad2dc2..b8af44c59 100644 --- a/src/java/org/apache/commons/cli2/Parent.java +++ b/src/java/org/apache/commons/cli2/Parent.java @@ -1,41 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.ListIterator; - -/** - * An Option that can have an argument and/or group of child Options in the form - * "-f <arg> [-a|-b|-c]". - */ -public interface Parent extends Option { - - /** - * Processes the parent part of the Option. The combination of parent, - * argument and children is handled by the process method. - * @see Option#process(WriteableCommandLine, ListIterator) - * - * @param commandLine the CommandLine to write results to - * @param args a ListIterator over argument strings positioned at the next - * argument to process - * @throws OptionException if an error occurs while processing - */ - void processParent( - final WriteableCommandLine commandLine, - final ListIterator args) - throws OptionException; -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.ListIterator;/** * An Option that can have an argument and/or group of child Options in the form * "-f <arg> [-a|-b|-c]". */public interface Parent extends Option { /** * Processes the parent part of the Option. The combination of parent, * argument and children is handled by the process method. * @see Option#process(WriteableCommandLine, ListIterator) * * @param commandLine the CommandLine to write results to * @param args a ListIterator over argument strings positioned at the next * argument to process * @throws OptionException if an error occurs while processing */ void processParent( final WriteableCommandLine commandLine, final ListIterator args) throws OptionException;} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/WriteableCommandLine.java b/src/java/org/apache/commons/cli2/WriteableCommandLine.java index dae2a39b5..1189e10e9 100644 --- a/src/java/org/apache/commons/cli2/WriteableCommandLine.java +++ b/src/java/org/apache/commons/cli2/WriteableCommandLine.java @@ -1,76 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.List; - -/** - * A CommandLine that detected values and options can be written to. - */ -public interface WriteableCommandLine extends CommandLine { - - /** - * Adds an Option to the CommandLine - * @param option the Option to add - */ - void addOption(final Option option); - - /** - * Adds a value to an Option in the CommandLine. - * @param option the Option to add to - * @param value the value to add - */ - void addValue(final Option option, final Object value); - - /** - * Sets the default values for an Option in the CommandLine - * @param option the Option to add to - * @param defaultValues the defaults for the option - */ - void setDefaultValues(final Option option, final List defaultValues); - - /** - * Adds a switch value to an Option in the CommandLine. - * @param option the Option to add to - * @param value the switch value to add - * @throws IllegalStateException if the switch has already been added - */ - void addSwitch(final Option option, final boolean value) throws IllegalStateException; - - /** - * Sets the default state for a Switch in the CommandLine. - * @param option the Option to add to - * @param defaultSwitch the defaults state for ths switch - */ - void setDefaultSwitch(final Option option, final Boolean defaultSwitch); - - /** - * Adds a property value to a name in the CommandLine. - * Replaces any existing value for the property. - * - * @param property the name of the property - * @param value the value of the property - */ - void addProperty(final String property, final String value); - - /** - * Detects whether the argument looks like an Option trigger - * @param argument the argument to test - * @return true if the argument looks like an Option trigger - */ - boolean looksLikeOption(final String argument); -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.List;/** * A CommandLine that detected values and options can be written to. */public interface WriteableCommandLine extends CommandLine { /** * Adds an Option to the CommandLine * @param option the Option to add */ void addOption(final Option option); /** * Adds a value to an Option in the CommandLine. * @param option the Option to add to * @param value the value to add */ void addValue(final Option option, final Object value); /** * Sets the default values for an Option in the CommandLine * @param option the Option to add to * @param defaultValues the defaults for the option */ void setDefaultValues(final Option option, final List defaultValues); /** * Adds a switch value to an Option in the CommandLine. * @param option the Option to add to * @param value the switch value to add * @throws IllegalStateException if the switch has already been added */ void addSwitch(final Option option, final boolean value) throws IllegalStateException; /** * Sets the default state for a Switch in the CommandLine. * @param option the Option to add to * @param defaultSwitch the defaults state for ths switch */ void setDefaultSwitch(final Option option, final Boolean defaultSwitch); /** * Adds a property value to a name in the CommandLine. * Replaces any existing value for the property. * * @param property the name of the property * @param value the value of the property */ void addProperty(final String property, final String value); /** * Detects whether the argument looks like an Option trigger * @param argument the argument to test * @return true if the argument looks like an Option trigger */ boolean looksLikeOption(final String argument);} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java b/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java index 6c115d170..491106472 100644 --- a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java @@ -1,286 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.builder; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.option.ArgumentImpl; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; -import org.apache.commons.cli2.validation.Validator; - -/** - * Builds Argument instances. - */ -public class ArgumentBuilder { - - /** i18n */ - private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); - - /** name of the argument. Used for display and lookups in CommandLine */ - private String name; - - /** description of the argument. Used in the automated online help */ - private String description; - - /** minimum number of values required */ - private int minimum; - - /** maximum number of values permitted */ - private int maximum; - - /** character used to separate the values from the option */ - private char initialSeparator; - - /** character used to separate the values from each other */ - private char subsequentSeparator; - - /** object that should be used to ensure the values are valid */ - private Validator validator; - - /** used to identify the consume remaining option, typically "--" */ - private String consumeRemaining; - - /** default values for argument */ - private List defaultValues; - - /** id of the argument */ - private int id; - - /** - * Creates a new ArgumentBuilder instance - */ - public ArgumentBuilder() { - reset(); - } - - /** - * Creates a new Argument instance using the options specified in this - * ArgumentBuilder. - * - * @return A new Argument instance using the options specified in this - * ArgumentBuilder. - */ - public final Argument create() { - final Argument argument = - new ArgumentImpl( - name, - description, - minimum, - maximum, - initialSeparator, - subsequentSeparator, - validator, - consumeRemaining, - defaultValues, - id); - - reset(); - - return argument; - } - - /** - * Resets the ArgumentBuilder to the defaults for a new Argument. The - * method is called automatically at the end of a create() call. - */ - public final ArgumentBuilder reset() { - name = "arg"; - description = null; - minimum = 0; - maximum = Integer.MAX_VALUE; - initialSeparator = ArgumentImpl.DEFAULT_INITIAL_SEPARATOR; - subsequentSeparator = ArgumentImpl.DEFAULT_SUBSEQUENT_SEPARATOR; - validator = null; - consumeRemaining = "--"; - defaultValues = null; - id = 0; - return this; - } - - /** - * Sets the name of the argument. The name is used when displaying usage - * information and to allow lookups in the CommandLine object. - * - * @see org.apache.commons.cli2.CommandLine#getValue(String) - * - * @param newName the name of the argument - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withName(final String newName) { - if (newName == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME)); - } - if ("".equals(newName)) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME)); - } - this.name = newName; - return this; - } - - /** - * Sets the description of the argument. - * - * The description is used when displaying online help. - * - * @param newDescription a description of the argument - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withDescription(final String newDescription) { - this.description = newDescription; - return this; - } - - /** - * Sets the minimum number of values needed for the argument to be valid. - * - * @param newMinimum the number of values needed - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withMinimum(final int newMinimum) { - if (newMinimum < 0) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM)); - } - this.minimum = newMinimum; - return this; - } - - /** - * Sets the maximum number of values allowed for the argument to be valid. - * - * @param newMaximum the number of values allowed - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withMaximum(final int newMaximum) { - if (newMaximum < 0) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM)); - } - this.maximum = newMaximum; - return this; - } - - /** - * Sets the character used to separate the values from the option. When an - * argument is of the form -libs:dir1,dir2,dir3 the initialSeparator would - * be ':'. - * - * @param newInitialSeparator the character used to separate the values - * from the option - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withInitialSeparator( - final char newInitialSeparator) { - - this.initialSeparator = newInitialSeparator; - return this; - } - - /** - * Sets the character used to separate the values from each other. When an - * argument is of the form -libs:dir1,dir2,dir3 the subsequentSeparator - * would be ','. - * - * @param newSubsequentSeparator the character used to separate the values - * from each other - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withSubsequentSeparator( - final char newSubsequentSeparator) { - - this.subsequentSeparator = newSubsequentSeparator; - return this; - } - - /** - * Sets the validator instance used to perform validation on the Argument - * values. - * - * @param newValidator a Validator instance - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withValidator(final Validator newValidator) { - if (newValidator == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR)); - } - this.validator = newValidator; - return this; - } - - /** - * Sets the "consume remaining" option, defaults to "--". Use this if you - * want to allow values that might be confused with option strings. - * - * @param newConsumeRemaining the string to use for the consume - * remaining option - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withConsumeRemaining(final String newConsumeRemaining) { - if (newConsumeRemaining == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING)); - } - if ( "".equals(newConsumeRemaining)) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING)); - } - this.consumeRemaining = newConsumeRemaining; - return this; - } - - /** - * Sets the default value. - * - * @param defaultValue the default value for the Argument - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withDefault(final Object defaultValue) { - if (defaultValue == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT)); - } - - if (this.defaultValues == null) { - this.defaultValues = new ArrayList(1); - } - this.defaultValues.add(defaultValue); - return this; - } - - /** - * Sets the default values. - * - * @param newDefaultValues the default values for the Argument - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withDefaults(final List newDefaultValues) { - if (newDefaultValues == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS)); - } - this.defaultValues = newDefaultValues; - return this; - } - - /** - * Sets the id - * - * @param newId the id of the Argument - * @return this ArgumentBuilder - */ - public final ArgumentBuilder withId(final int newId) { - this.id = newId; - return this; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.ArrayList;import java.util.List;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.option.ArgumentImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;import org.apache.commons.cli2.validation.Validator;/** * Builds Argument instances. */public class ArgumentBuilder { /** i18n */ private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); /** name of the argument. Used for display and lookups in CommandLine */ private String name; /** description of the argument. Used in the automated online help */ private String description; /** minimum number of values required */ private int minimum; /** maximum number of values permitted */ private int maximum; /** character used to separate the values from the option */ private char initialSeparator; /** character used to separate the values from each other */ private char subsequentSeparator; /** object that should be used to ensure the values are valid */ private Validator validator; /** used to identify the consume remaining option, typically "--" */ private String consumeRemaining; /** default values for argument */ private List defaultValues; /** id of the argument */ private int id; /** * Creates a new ArgumentBuilder instance */ public ArgumentBuilder() { reset(); } /** * Creates a new Argument instance using the options specified in this * ArgumentBuilder. * * @return A new Argument instance using the options specified in this * ArgumentBuilder. */ public final Argument create() { final Argument argument = new ArgumentImpl( name, description, minimum, maximum, initialSeparator, subsequentSeparator, validator, consumeRemaining, defaultValues, id); reset(); return argument; } /** * Resets the ArgumentBuilder to the defaults for a new Argument. The * method is called automatically at the end of a create() call. */ public final ArgumentBuilder reset() { name = "arg"; description = null; minimum = 0; maximum = Integer.MAX_VALUE; initialSeparator = ArgumentImpl.DEFAULT_INITIAL_SEPARATOR; subsequentSeparator = ArgumentImpl.DEFAULT_SUBSEQUENT_SEPARATOR; validator = null; consumeRemaining = "--"; defaultValues = null; id = 0; return this; } /** * Sets the name of the argument. The name is used when displaying usage * information and to allow lookups in the CommandLine object. * * @see org.apache.commons.cli2.CommandLine#getValue(String) * * @param newName the name of the argument * @return this ArgumentBuilder */ public final ArgumentBuilder withName(final String newName) { if (newName == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME)); } if ("".equals(newName)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME)); } this.name = newName; return this; } /** * Sets the description of the argument. * * The description is used when displaying online help. * * @param newDescription a description of the argument * @return this ArgumentBuilder */ public final ArgumentBuilder withDescription(final String newDescription) { this.description = newDescription; return this; } /** * Sets the minimum number of values needed for the argument to be valid. * * @param newMinimum the number of values needed * @return this ArgumentBuilder */ public final ArgumentBuilder withMinimum(final int newMinimum) { if (newMinimum < 0) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM)); } this.minimum = newMinimum; return this; } /** * Sets the maximum number of values allowed for the argument to be valid. * * @param newMaximum the number of values allowed * @return this ArgumentBuilder */ public final ArgumentBuilder withMaximum(final int newMaximum) { if (newMaximum < 0) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM)); } this.maximum = newMaximum; return this; } /** * Sets the character used to separate the values from the option. When an * argument is of the form -libs:dir1,dir2,dir3 the initialSeparator would * be ':'. * * @param newInitialSeparator the character used to separate the values * from the option * @return this ArgumentBuilder */ public final ArgumentBuilder withInitialSeparator( final char newInitialSeparator) { this.initialSeparator = newInitialSeparator; return this; } /** * Sets the character used to separate the values from each other. When an * argument is of the form -libs:dir1,dir2,dir3 the subsequentSeparator * would be ','. * * @param newSubsequentSeparator the character used to separate the values * from each other * @return this ArgumentBuilder */ public final ArgumentBuilder withSubsequentSeparator( final char newSubsequentSeparator) { this.subsequentSeparator = newSubsequentSeparator; return this; } /** * Sets the validator instance used to perform validation on the Argument * values. * * @param newValidator a Validator instance * @return this ArgumentBuilder */ public final ArgumentBuilder withValidator(final Validator newValidator) { if (newValidator == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR)); } this.validator = newValidator; return this; } /** * Sets the "consume remaining" option, defaults to "--". Use this if you * want to allow values that might be confused with option strings. * * @param newConsumeRemaining the string to use for the consume * remaining option * @return this ArgumentBuilder */ public final ArgumentBuilder withConsumeRemaining(final String newConsumeRemaining) { if (newConsumeRemaining == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING)); } if ( "".equals(newConsumeRemaining)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING)); } this.consumeRemaining = newConsumeRemaining; return this; } /** * Sets the default value. * * @param defaultValue the default value for the Argument * @return this ArgumentBuilder */ public final ArgumentBuilder withDefault(final Object defaultValue) { if (defaultValue == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT)); } if (this.defaultValues == null) { this.defaultValues = new ArrayList(1); } this.defaultValues.add(defaultValue); return this; } /** * Sets the default values. * * @param newDefaultValues the default values for the Argument * @return this ArgumentBuilder */ public final ArgumentBuilder withDefaults(final List newDefaultValues) { if (newDefaultValues == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS)); } this.defaultValues = newDefaultValues; return this; } /** * Sets the id * * @param newId the id of the Argument * @return this ArgumentBuilder */ public final ArgumentBuilder withId(final int newId) { this.id = newId; return this; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/builder/CommandBuilder.java b/src/java/org/apache/commons/cli2/builder/CommandBuilder.java index 56c7eb21d..190f45590 100644 --- a/src/java/org/apache/commons/cli2/builder/CommandBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/CommandBuilder.java @@ -1,187 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.builder; - -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.option.Command; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * Builds Command instances - */ -public class CommandBuilder { - /** the preferred name of the command */ - private String preferredName; - - /** the description of the command */ - private String description; - - /** the aliases of the command */ - private Set aliases; - - /** whether the command is required or not */ - private boolean required; - - /** the argument of the command */ - private Argument argument; - - /** the children of the command */ - private Group children; - - /** the id of the command */ - private int id; - - /** - * Creates a new CommandBuilder instance. - */ - public CommandBuilder() { - reset(); - } - - /** - * Creates a new Command instance using the properties of the - * CommandBuilder. - * - * @return the new Command instance - */ - public Command create() { - // check we have a valid name - if (preferredName == null) { - throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME)); - } - - // build the command - final Command option = - new Command(preferredName, description, aliases, required, argument, children, id); - - // reset the builder - reset(); - - return option; - } - - /** - * Resets the CommandBuilder to the defaults for a new Command. - * - * This method is called automatically at the end of the - * {@link #create() create} method. - */ - public CommandBuilder reset() { - preferredName = null; - description = null; - aliases = new HashSet(); - required = false; - argument = null; - children = null; - id = 0; - - return this; - } - - /** - * Specifies the name for the next Command - * that is created. The first name is used as the preferred - * display name for the Command and then - * later names are used as aliases. - * - * @param name the name for the next Command - * that is created. - * @return this CommandBuilder. - */ - public CommandBuilder withName(final String name) { - if (preferredName == null) { - preferredName = name; - } else { - aliases.add(name); - } - - return this; - } - - /** - * Specifies the description for the next Command - * that is created. This description is used to produce - * help documentation for the Command. - * - * @param newDescription the description for the next - * Command that is created. - * @return this CommandBuilder. - */ - public CommandBuilder withDescription(final String newDescription) { - this.description = newDescription; - - return this; - } - - /** - * Specifies whether the next Command created is - * required or not. - * @param newRequired whether the next Command created is - * required or not. - * @return this CommandBuilder. - */ - public CommandBuilder withRequired(final boolean newRequired) { - this.required = newRequired; - - return this; - } - - /** - * Specifies the children for the next Command - * that is created. - * - * @param newChildren the child options for the next Command - * that is created. - * @return this CommandBuilder. - */ - public CommandBuilder withChildren(final Group newChildren) { - this.children = newChildren; - - return this; - } - - /** - * Specifies the argument for the next Command - * that is created. - * - * @param newArgument the argument for the next Command - * that is created. - * @return this CommandBuilder. - */ - public CommandBuilder withArgument(final Argument newArgument) { - this.argument = newArgument; - - return this; - } - - /** - * Specifies the id for the next Command that is created. - * - * @param newId the id for the next Command that is created. - * @return this CommandBuilder. - */ - public final CommandBuilder withId(final int newId) { - this.id = newId; - - return this; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.HashSet;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.option.Command;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Builds Command instances */public class CommandBuilder { /** the preferred name of the command */ private String preferredName; /** the description of the command */ private String description; /** the aliases of the command */ private Set aliases; /** whether the command is required or not */ private boolean required; /** the argument of the command */ private Argument argument; /** the children of the command */ private Group children; /** the id of the command */ private int id; /** * Creates a new CommandBuilder instance. */ public CommandBuilder() { reset(); } /** * Creates a new Command instance using the properties of the * CommandBuilder. * * @return the new Command instance */ public Command create() { // check we have a valid name if (preferredName == null) { throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME)); } // build the command final Command option = new Command(preferredName, description, aliases, required, argument, children, id); // reset the builder reset(); return option; } /** * Resets the CommandBuilder to the defaults for a new Command. * * This method is called automatically at the end of the * {@link #create() create} method. */ public CommandBuilder reset() { preferredName = null; description = null; aliases = new HashSet(); required = false; argument = null; children = null; id = 0; return this; } /** * Specifies the name for the next Command * that is created. The first name is used as the preferred * display name for the Command and then * later names are used as aliases. * * @param name the name for the next Command * that is created. * @return this CommandBuilder. */ public CommandBuilder withName(final String name) { if (preferredName == null) { preferredName = name; } else { aliases.add(name); } return this; } /** * Specifies the description for the next Command * that is created. This description is used to produce * help documentation for the Command. * * @param newDescription the description for the next * Command that is created. * @return this CommandBuilder. */ public CommandBuilder withDescription(final String newDescription) { this.description = newDescription; return this; } /** * Specifies whether the next Command created is * required or not. * @param newRequired whether the next Command created is * required or not. * @return this CommandBuilder. */ public CommandBuilder withRequired(final boolean newRequired) { this.required = newRequired; return this; } /** * Specifies the children for the next Command * that is created. * * @param newChildren the child options for the next Command * that is created. * @return this CommandBuilder. */ public CommandBuilder withChildren(final Group newChildren) { this.children = newChildren; return this; } /** * Specifies the argument for the next Command * that is created. * * @param newArgument the argument for the next Command * that is created. * @return this CommandBuilder. */ public CommandBuilder withArgument(final Argument newArgument) { this.argument = newArgument; return this; } /** * Specifies the id for the next Command that is created. * * @param newId the id for the next Command that is created. * @return this CommandBuilder. */ public final CommandBuilder withId(final int newId) { this.id = newId; return this; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java b/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java index cecfcf54c..4cc53bad1 100644 --- a/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java @@ -1,215 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.builder; - -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.option.DefaultOption; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * Builds DefaultOption instances. - */ -public class DefaultOptionBuilder { - private final String shortPrefix; - private final String longPrefix; - private final boolean burstEnabled; - private String preferredName; - private Set aliases; - private Set burstAliases; - private boolean required; - private String description; - private Argument argument; - private Group children; - private int id; - - /** - * Creates a new DefaultOptionBuilder using defaults - * @see DefaultOption#DEFAULT_SHORT_PREFIX - * @see DefaultOption#DEFAULT_LONG_PREFIX - * @see DefaultOption#DEFAULT_BURST_ENABLED - */ - public DefaultOptionBuilder() { - this(DefaultOption.DEFAULT_SHORT_PREFIX, DefaultOption.DEFAULT_LONG_PREFIX, - DefaultOption.DEFAULT_BURST_ENABLED); - } - - /** - * Creates a new DefaultOptionBuilder - * @param shortPrefix the prefix to use for short options - * @param longPrefix the prefix to use for long options - * @param burstEnabled whether to allow gnu style bursting - * @throws IllegalArgumentException if either prefix is less than on - * character long - */ - public DefaultOptionBuilder(final String shortPrefix, - final String longPrefix, - final boolean burstEnabled) - throws IllegalArgumentException { - if ((shortPrefix == null) || (shortPrefix.length() == 0)) { - throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX)); - } - - if ((longPrefix == null) || (longPrefix.length() == 0)) { - throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX)); - } - - this.shortPrefix = shortPrefix; - this.longPrefix = longPrefix; - this.burstEnabled = burstEnabled; - reset(); - } - - /** - * Creates a DefaultOption instance - * @return the new instance - * @throws IllegalStateException if no names have been supplied - */ - public DefaultOption create() - throws IllegalStateException { - if (preferredName == null) { - throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME)); - } - - final DefaultOption option = - new DefaultOption(shortPrefix, longPrefix, burstEnabled, preferredName, description, - aliases, burstAliases, required, argument, children, id); - - reset(); - - return option; - } - - /** - * Resets the builder - */ - public DefaultOptionBuilder reset() { - preferredName = null; - description = null; - aliases = new HashSet(); - burstAliases = new HashSet(); - required = false; - argument = null; - children = null; - id = 0; - - return this; - } - - /** - * Use this short option name. The first name is used as the preferred - * display name for the Command and then later names are used as aliases. - * - * @param shortName the name to use - * @return this builder - */ - public DefaultOptionBuilder withShortName(final String shortName) { - final String name = shortPrefix + shortName; - - if (preferredName == null) { - preferredName = name; - } else { - aliases.add(name); - } - - if (burstEnabled && (name.length() == (shortPrefix.length() + 1))) { - burstAliases.add(name); - } - - return this; - } - - /** - * Use this long option name. The first name is used as the preferred - * display name for the Command and then later names are used as aliases. - * - * @param longName the name to use - * @return this builder - */ - public DefaultOptionBuilder withLongName(final String longName) { - final String name = longPrefix + longName; - - if (preferredName == null) { - preferredName = name; - } else { - aliases.add(name); - } - - return this; - } - - /** - * Use this option description - * @param newDescription the description to use - * @return this builder - */ - public DefaultOptionBuilder withDescription(final String newDescription) { - this.description = newDescription; - - return this; - } - - /** - * Use this optionality - * @param newRequired true iff the Option is required - * @return this builder - */ - public DefaultOptionBuilder withRequired(final boolean newRequired) { - this.required = newRequired; - - return this; - } - - /** - * Use this child Group - * @param newChildren the child Group to use - * @return this builder - */ - public DefaultOptionBuilder withChildren(final Group newChildren) { - this.children = newChildren; - - return this; - } - - /** - * Use this Argument - * @param newArgument the argument to use - * @return this builder - */ - public DefaultOptionBuilder withArgument(final Argument newArgument) { - this.argument = newArgument; - - return this; - } - - /** - * Sets the id - * - * @param newId - * the id of the DefaultOption - * @return this DefaultOptionBuilder - */ - public final DefaultOptionBuilder withId(final int newId) { - this.id = newId; - - return this; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.HashSet;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.option.DefaultOption;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Builds DefaultOption instances. */public class DefaultOptionBuilder { private final String shortPrefix; private final String longPrefix; private final boolean burstEnabled; private String preferredName; private Set aliases; private Set burstAliases; private boolean required; private String description; private Argument argument; private Group children; private int id; /** * Creates a new DefaultOptionBuilder using defaults * @see DefaultOption#DEFAULT_SHORT_PREFIX * @see DefaultOption#DEFAULT_LONG_PREFIX * @see DefaultOption#DEFAULT_BURST_ENABLED */ public DefaultOptionBuilder() { this(DefaultOption.DEFAULT_SHORT_PREFIX, DefaultOption.DEFAULT_LONG_PREFIX, DefaultOption.DEFAULT_BURST_ENABLED); } /** * Creates a new DefaultOptionBuilder * @param shortPrefix the prefix to use for short options * @param longPrefix the prefix to use for long options * @param burstEnabled whether to allow gnu style bursting * @throws IllegalArgumentException if either prefix is less than on * character long */ public DefaultOptionBuilder(final String shortPrefix, final String longPrefix, final boolean burstEnabled) throws IllegalArgumentException { if ((shortPrefix == null) || (shortPrefix.length() == 0)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX)); } if ((longPrefix == null) || (longPrefix.length() == 0)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX)); } this.shortPrefix = shortPrefix; this.longPrefix = longPrefix; this.burstEnabled = burstEnabled; reset(); } /** * Creates a DefaultOption instance * @return the new instance * @throws IllegalStateException if no names have been supplied */ public DefaultOption create() throws IllegalStateException { if (preferredName == null) { throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME)); } final DefaultOption option = new DefaultOption(shortPrefix, longPrefix, burstEnabled, preferredName, description, aliases, burstAliases, required, argument, children, id); reset(); return option; } /** * Resets the builder */ public DefaultOptionBuilder reset() { preferredName = null; description = null; aliases = new HashSet(); burstAliases = new HashSet(); required = false; argument = null; children = null; id = 0; return this; } /** * Use this short option name. The first name is used as the preferred * display name for the Command and then later names are used as aliases. * * @param shortName the name to use * @return this builder */ public DefaultOptionBuilder withShortName(final String shortName) { final String name = shortPrefix + shortName; if (preferredName == null) { preferredName = name; } else { aliases.add(name); } if (burstEnabled && (name.length() == (shortPrefix.length() + 1))) { burstAliases.add(name); } return this; } /** * Use this long option name. The first name is used as the preferred * display name for the Command and then later names are used as aliases. * * @param longName the name to use * @return this builder */ public DefaultOptionBuilder withLongName(final String longName) { final String name = longPrefix + longName; if (preferredName == null) { preferredName = name; } else { aliases.add(name); } return this; } /** * Use this option description * @param newDescription the description to use * @return this builder */ public DefaultOptionBuilder withDescription(final String newDescription) { this.description = newDescription; return this; } /** * Use this optionality * @param newRequired true iff the Option is required * @return this builder */ public DefaultOptionBuilder withRequired(final boolean newRequired) { this.required = newRequired; return this; } /** * Use this child Group * @param newChildren the child Group to use * @return this builder */ public DefaultOptionBuilder withChildren(final Group newChildren) { this.children = newChildren; return this; } /** * Use this Argument * @param newArgument the argument to use * @return this builder */ public DefaultOptionBuilder withArgument(final Argument newArgument) { this.argument = newArgument; return this; } /** * Sets the id * * @param newId * the id of the DefaultOption * @return this DefaultOptionBuilder */ public final DefaultOptionBuilder withId(final int newId) { this.id = newId; return this; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/builder/GroupBuilder.java b/src/java/org/apache/commons/cli2/builder/GroupBuilder.java index 9d098464b..887aa2928 100644 --- a/src/java/org/apache/commons/cli2/builder/GroupBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/GroupBuilder.java @@ -1,118 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.builder; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.option.GroupImpl; - -/** - * Builds Group instances - */ -public class GroupBuilder { - - private String name; - private String description; - private List options; - private int minimum; - private int maximum; - - /** - * Creates a new GroupBuilder - */ - public GroupBuilder() { - reset(); - } - - /** - * Creates a new Group instance - * @return the new Group instance - */ - public Group create() { - final GroupImpl group = - new GroupImpl(options, name, description, minimum, maximum); - - reset(); - - return group; - } - - /** - * Resets the builder - */ - public GroupBuilder reset() { - name = null; - description = null; - options = new ArrayList(); - minimum = 0; - maximum = Integer.MAX_VALUE; - return this; - } - - /** - * Use this option description - * @param newDescription the description to use - * @return this builder - */ - public GroupBuilder withDescription(final String newDescription) { - this.description = newDescription; - return this; - } - - /** - * Use this option name - * @param newName the name to use - * @return this builder - */ - public GroupBuilder withName(final String newName) { - this.name = newName; - return this; - } - - /** - * A valid group requires at least this many options present - * @param newMinimum the minimum Options required - * @return this builder - */ - public GroupBuilder withMinimum(final int newMinimum) { - this.minimum = newMinimum; - return this; - } - - /** - * A valid group requires at most this many options present - * @param newMaximum the maximum Options allowed - * @return this builder - */ - public GroupBuilder withMaximum(final int newMaximum) { - this.maximum = newMaximum; - return this; - } - - /** - * Add this option to the group - * @param option the Option to add - * @return this builder - */ - public GroupBuilder withOption(final Option option) { - this.options.add(option); - return this; - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.ArrayList;import java.util.List;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.option.GroupImpl;/** * Builds Group instances */public class GroupBuilder { private String name; private String description; private List options; private int minimum; private int maximum; /** * Creates a new GroupBuilder */ public GroupBuilder() { reset(); } /** * Creates a new Group instance * @return the new Group instance */ public Group create() { final GroupImpl group = new GroupImpl(options, name, description, minimum, maximum); reset(); return group; } /** * Resets the builder */ public GroupBuilder reset() { name = null; description = null; options = new ArrayList(); minimum = 0; maximum = Integer.MAX_VALUE; return this; } /** * Use this option description * @param newDescription the description to use * @return this builder */ public GroupBuilder withDescription(final String newDescription) { this.description = newDescription; return this; } /** * Use this option name * @param newName the name to use * @return this builder */ public GroupBuilder withName(final String newName) { this.name = newName; return this; } /** * A valid group requires at least this many options present * @param newMinimum the minimum Options required * @return this builder */ public GroupBuilder withMinimum(final int newMinimum) { this.minimum = newMinimum; return this; } /** * A valid group requires at most this many options present * @param newMaximum the maximum Options allowed * @return this builder */ public GroupBuilder withMaximum(final int newMaximum) { this.maximum = newMaximum; return this; } /** * Add this option to the group * @param option the Option to add * @return this builder */ public GroupBuilder withOption(final Option option) { this.options.add(option); return this; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/builder/PatternBuilder.java b/src/java/org/apache/commons/cli2/builder/PatternBuilder.java index 2b4c1b54d..43ed77b4d 100644 --- a/src/java/org/apache/commons/cli2/builder/PatternBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/PatternBuilder.java @@ -1,202 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.builder; - -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.validation.ClassValidator; -import org.apache.commons.cli2.validation.DateValidator; -import org.apache.commons.cli2.validation.FileValidator; -import org.apache.commons.cli2.validation.NumberValidator; -import org.apache.commons.cli2.validation.UrlValidator; -import org.apache.commons.cli2.validation.Validator; - -/** - * Builds Options using a String pattern - */ -//TODO Document and link to the acceptable patterns -public class PatternBuilder { - - private final GroupBuilder gbuilder; - private final DefaultOptionBuilder obuilder; - private final ArgumentBuilder abuilder; - - /** - * Creates a new PatternBuilder - */ - public PatternBuilder() { - this( - new GroupBuilder(), - new DefaultOptionBuilder(), - new ArgumentBuilder()); - } - - /** - * Creates a new PatternBuilder - * @param gbuilder the GroupBuilder to use - * @param obuilder the DefaultOptionBuilder to use - * @param abuilder the ArgumentBuilder to use - */ - public PatternBuilder( - final GroupBuilder gbuilder, - final DefaultOptionBuilder obuilder, - final ArgumentBuilder abuilder) { - this.gbuilder = gbuilder; - this.obuilder = obuilder; - this.abuilder = abuilder; - } - - private final Set options = new LinkedHashSet(); - - /** - * Creates a new Option instance. - * @return a new Option instance - */ - public Option create() { - final Option option; - - if (options.size() == 1) { - option = (Option)options.iterator().next(); - } - else { - gbuilder.reset(); - for (final Iterator i = options.iterator(); i.hasNext();) { - gbuilder.withOption((Option)i.next()); - } - option = gbuilder.create(); - } - - reset(); - - return option; - } - - /** - * Resets this builder - */ - public PatternBuilder reset() { - options.clear(); - return this; - } - - private void createOption( - final char type, - final boolean required, - final char opt) { - final Argument argument; - if (type != ' ') { - abuilder.reset(); - abuilder.withValidator(validator(type)); - if (required) { - abuilder.withMinimum(1); - } - if (type != '*') { - abuilder.withMaximum(1); - } - argument = abuilder.create(); - } - else { - argument = null; - } - - obuilder.reset(); - obuilder.withArgument(argument); - obuilder.withShortName(String.valueOf(opt)); - obuilder.withRequired(required); - - options.add(obuilder.create()); - } - - /** - * Builds an Option using a pattern string. - * @param pattern the pattern to build from - */ - public void withPattern(final String pattern) { - int sz = pattern.length(); - - char opt = ' '; - char ch = ' '; - char type = ' '; - boolean required = false; - - for (int i = 0; i < sz; i++) { - ch = pattern.charAt(i); - - switch (ch) { - case '!' : - required = true; - break; - case '@' : - case ':' : - case '%' : - case '+' : - case '#' : - case '<' : - case '>' : - case '*' : - case '/' : - type = ch; - break; - default : - if (opt != ' ') { - createOption(type, required, opt); - required = false; - type = ' '; - } - - opt = ch; - } - } - - if (opt != ' ') { - createOption(type, required, opt); - } - } - - private static Validator validator(final char c) { - switch (c) { - case '@' : - final ClassValidator classv = new ClassValidator(); - classv.setInstance(true); - return classv; - case '+' : - final ClassValidator instancev = new ClassValidator(); - return instancev; - //case ':':// no validator needed for a string - case '%' : - return NumberValidator.getNumberInstance(); - case '#' : - return DateValidator.getDateInstance(); - case '<' : - final FileValidator existingv = new FileValidator(); - existingv.setExisting(true); - existingv.setFile(true); - return existingv; - case '>' : - case '*' : - return new FileValidator(); - case '/' : - return new UrlValidator(); - default : - return null; - } - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.Iterator;import java.util.LinkedHashSet;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.validation.ClassValidator;import org.apache.commons.cli2.validation.DateValidator;import org.apache.commons.cli2.validation.FileValidator;import org.apache.commons.cli2.validation.NumberValidator;import org.apache.commons.cli2.validation.UrlValidator;import org.apache.commons.cli2.validation.Validator;/** * Builds Options using a String pattern *///TODO Document and link to the acceptable patternspublic class PatternBuilder { private final GroupBuilder gbuilder; private final DefaultOptionBuilder obuilder; private final ArgumentBuilder abuilder; /** * Creates a new PatternBuilder */ public PatternBuilder() { this( new GroupBuilder(), new DefaultOptionBuilder(), new ArgumentBuilder()); } /** * Creates a new PatternBuilder * @param gbuilder the GroupBuilder to use * @param obuilder the DefaultOptionBuilder to use * @param abuilder the ArgumentBuilder to use */ public PatternBuilder( final GroupBuilder gbuilder, final DefaultOptionBuilder obuilder, final ArgumentBuilder abuilder) { this.gbuilder = gbuilder; this.obuilder = obuilder; this.abuilder = abuilder; } private final Set options = new LinkedHashSet(); /** * Creates a new Option instance. * @return a new Option instance */ public Option create() { final Option option; if (options.size() == 1) { option = (Option)options.iterator().next(); } else { gbuilder.reset(); for (final Iterator i = options.iterator(); i.hasNext();) { gbuilder.withOption((Option)i.next()); } option = gbuilder.create(); } reset(); return option; } /** * Resets this builder */ public PatternBuilder reset() { options.clear(); return this; } private void createOption( final char type, final boolean required, final char opt) { final Argument argument; if (type != ' ') { abuilder.reset(); abuilder.withValidator(validator(type)); if (required) { abuilder.withMinimum(1); } if (type != '*') { abuilder.withMaximum(1); } argument = abuilder.create(); } else { argument = null; } obuilder.reset(); obuilder.withArgument(argument); obuilder.withShortName(String.valueOf(opt)); obuilder.withRequired(required); options.add(obuilder.create()); } /** * Builds an Option using a pattern string. * @param pattern the pattern to build from */ public void withPattern(final String pattern) { int sz = pattern.length(); char opt = ' '; char ch = ' '; char type = ' '; boolean required = false; for (int i = 0; i < sz; i++) { ch = pattern.charAt(i); switch (ch) { case '!' : required = true; break; case '@' : case ':' : case '%' : case '+' : case '#' : case '<' : case '>' : case '*' : case '/' : type = ch; break; default : if (opt != ' ') { createOption(type, required, opt); required = false; type = ' '; } opt = ch; } } if (opt != ' ') { createOption(type, required, opt); } } private static Validator validator(final char c) { switch (c) { case '@' : final ClassValidator classv = new ClassValidator(); classv.setInstance(true); return classv; case '+' : final ClassValidator instancev = new ClassValidator(); return instancev; //case ':':// no validator needed for a string case '%' : return NumberValidator.getNumberInstance(); case '#' : return DateValidator.getDateInstance(); case '<' : final FileValidator existingv = new FileValidator(); existingv.setExisting(true); existingv.setFile(true); return existingv; case '>' : case '*' : return new FileValidator(); case '/' : return new UrlValidator(); default : return null; } }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java b/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java index fa88df359..da422aecf 100644 --- a/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java @@ -1,194 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.builder; - -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.option.Switch; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * Builds Switch instance. - */ -public class SwitchBuilder { - private final String enabledPrefix; - private final String disabledPrefix; - private String description; - private String preferredName; - private Set aliases; - private boolean required; - private Argument argument; - private Group children; - private int id; - private Boolean switchDefault; - - /** - * Creates a new SwitchBuilder using defaults. - * @see Switch#DEFAULT_ENABLED_PREFIX - * @see Switch#DEFAULT_DISABLED_PREFIX - */ - public SwitchBuilder() { - this(Switch.DEFAULT_ENABLED_PREFIX, Switch.DEFAULT_DISABLED_PREFIX); - } - - /** - * Creates a new SwitchBuilder - * @param enabledPrefix the prefix to use for enabling the option - * @param disabledPrefix the prefix to use for disabling the option - * @throws IllegalArgumentException if either prefix is less than 1 - * character long or the prefixes match - */ - public SwitchBuilder(final String enabledPrefix, - final String disabledPrefix) - throws IllegalArgumentException { - if ((enabledPrefix == null) || (enabledPrefix.length() < 1)) { - throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ILLEGAL_ENABLED_PREFIX)); - } - - if ((disabledPrefix == null) || (disabledPrefix.length() < 1)) { - throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ILLEGAL_DISABLED_PREFIX)); - } - - if (enabledPrefix.equals(disabledPrefix)) { - throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_IDENTICAL_PREFIXES)); - } - - this.enabledPrefix = enabledPrefix; - this.disabledPrefix = disabledPrefix; - reset(); - } - - /** - * Creates a new Switch instance - * @return a new Switch instance - */ - public Switch create() { - final Switch option = - new Switch(enabledPrefix, disabledPrefix, preferredName, aliases, description, - required, argument, children, id, switchDefault); - - reset(); - - return option; - } - - /** - * Resets the builder - */ - public SwitchBuilder reset() { - description = null; - preferredName = null; - required = false; - aliases = new HashSet(); - argument = null; - children = null; - id = 0; - switchDefault = null; - - return this; - } - - /** - * Use this option description - * @param newDescription the description to use - * @return this builder - */ - public SwitchBuilder withDescription(final String newDescription) { - this.description = newDescription; - - return this; - } - - /** - * Use this option name. The first name is used as the preferred - * display name for the Command and then later names are used as aliases. - * - * @param name the name to use - * @return this builder - */ - public SwitchBuilder withName(final String name) { - if (preferredName == null) { - preferredName = name; - } else { - aliases.add(name); - } - - return this; - } - - /** - * Use this optionality - * @param newRequired true iff the Option is required - * @return this builder - */ - public SwitchBuilder withRequired(final boolean newRequired) { - this.required = newRequired; - - return this; - } - - /** - * Use this Argument - * @param newArgument the argument to use - * @return this builder - */ - public SwitchBuilder withArgument(final Argument newArgument) { - this.argument = newArgument; - - return this; - } - - /** - * Use this child Group - * @param newChildren the child Group to use - * @return this builder - */ - public SwitchBuilder withChildren(final Group newChildren) { - this.children = newChildren; - - return this; - } - - /** - * Sets the id - * - * @param newId - * the id of the Switch - * @return this SwitchBuilder - */ - public final SwitchBuilder withId(final int newId) { - this.id = newId; - - return this; - } - - /** - * Sets the default state for this switch - * - * @param newSwitchDefault the default state - * @return this SwitchBuilder - */ - public final SwitchBuilder withSwitchDefault(final Boolean newSwitchDefault) { - this.switchDefault = newSwitchDefault; - - return this; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.HashSet;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.option.Switch;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Builds Switch instance. */public class SwitchBuilder { private final String enabledPrefix; private final String disabledPrefix; private String description; private String preferredName; private Set aliases; private boolean required; private Argument argument; private Group children; private int id; private Boolean switchDefault; /** * Creates a new SwitchBuilder using defaults. * @see Switch#DEFAULT_ENABLED_PREFIX * @see Switch#DEFAULT_DISABLED_PREFIX */ public SwitchBuilder() { this(Switch.DEFAULT_ENABLED_PREFIX, Switch.DEFAULT_DISABLED_PREFIX); } /** * Creates a new SwitchBuilder * @param enabledPrefix the prefix to use for enabling the option * @param disabledPrefix the prefix to use for disabling the option * @throws IllegalArgumentException if either prefix is less than 1 * character long or the prefixes match */ public SwitchBuilder(final String enabledPrefix, final String disabledPrefix) throws IllegalArgumentException { if ((enabledPrefix == null) || (enabledPrefix.length() < 1)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ILLEGAL_ENABLED_PREFIX)); } if ((disabledPrefix == null) || (disabledPrefix.length() < 1)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ILLEGAL_DISABLED_PREFIX)); } if (enabledPrefix.equals(disabledPrefix)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_IDENTICAL_PREFIXES)); } this.enabledPrefix = enabledPrefix; this.disabledPrefix = disabledPrefix; reset(); } /** * Creates a new Switch instance * @return a new Switch instance */ public Switch create() { final Switch option = new Switch(enabledPrefix, disabledPrefix, preferredName, aliases, description, required, argument, children, id, switchDefault); reset(); return option; } /** * Resets the builder */ public SwitchBuilder reset() { description = null; preferredName = null; required = false; aliases = new HashSet(); argument = null; children = null; id = 0; switchDefault = null; return this; } /** * Use this option description * @param newDescription the description to use * @return this builder */ public SwitchBuilder withDescription(final String newDescription) { this.description = newDescription; return this; } /** * Use this option name. The first name is used as the preferred * display name for the Command and then later names are used as aliases. * * @param name the name to use * @return this builder */ public SwitchBuilder withName(final String name) { if (preferredName == null) { preferredName = name; } else { aliases.add(name); } return this; } /** * Use this optionality * @param newRequired true iff the Option is required * @return this builder */ public SwitchBuilder withRequired(final boolean newRequired) { this.required = newRequired; return this; } /** * Use this Argument * @param newArgument the argument to use * @return this builder */ public SwitchBuilder withArgument(final Argument newArgument) { this.argument = newArgument; return this; } /** * Use this child Group * @param newChildren the child Group to use * @return this builder */ public SwitchBuilder withChildren(final Group newChildren) { this.children = newChildren; return this; } /** * Sets the id * * @param newId * the id of the Switch * @return this SwitchBuilder */ public final SwitchBuilder withId(final int newId) { this.id = newId; return this; } /** * Sets the default state for this switch * * @param newSwitchDefault the default state * @return this SwitchBuilder */ public final SwitchBuilder withSwitchDefault(final Boolean newSwitchDefault) { this.switchDefault = newSwitchDefault; return this; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java index 37f8b37b6..aff253d20 100644 --- a/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java @@ -1,120 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * Instances of CommandLine represent a command line that has been processed - * according to the definition supplied to the parser. - */ -public abstract class CommandLineImpl implements CommandLine { - public final boolean hasOption(final String trigger) { - return hasOption(getOption(trigger)); - } - - public final List getValues(final String trigger) { - return getValues(getOption(trigger), Collections.EMPTY_LIST); - } - - public final List getValues(final String trigger, - final List defaultValues) { - return getValues(getOption(trigger), defaultValues); - } - - public final List getValues(final Option option) { - return getValues(option, Collections.EMPTY_LIST); - } - - public final Object getValue(final String trigger) { - return getValue(getOption(trigger), null); - } - - public final Object getValue(final String trigger, - final Object defaultValue) { - return getValue(getOption(trigger), defaultValue); - } - - public final Object getValue(final Option option) { - return getValue(option, null); - } - - public final Object getValue(final Option option, - final Object defaultValue) { - final List values; - - if (defaultValue == null) { - values = getValues(option); - } else { - values = getValues(option, Collections.singletonList(defaultValue)); - } - - if (values.size() > 1) { - throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES)); - } - - if (values.isEmpty()) { - return defaultValue; - } - - return values.get(0); - } - - public final Boolean getSwitch(final String trigger) { - return getSwitch(getOption(trigger), null); - } - - public final Boolean getSwitch(final String trigger, - final Boolean defaultValue) { - return getSwitch(getOption(trigger), defaultValue); - } - - public final Boolean getSwitch(final Option option) { - return getSwitch(option, null); - } - - public final String getProperty(final String property) { - return getProperty(property, null); - } - - public final int getOptionCount(final String trigger) { - return getOptionCount(getOption(trigger)); - } - - public final int getOptionCount(final Option option) { - if (option == null) { - return 0; - } - - int count = 0; - - for (Iterator i = getOptions().iterator(); i.hasNext();) { - if (option.equals(i.next())) { - ++count; - } - } - - return count; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.Collections;import java.util.Iterator;import java.util.List;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Instances of CommandLine represent a command line that has been processed * according to the definition supplied to the parser. */public abstract class CommandLineImpl implements CommandLine { public final boolean hasOption(final String trigger) { return hasOption(getOption(trigger)); } public final List getValues(final String trigger) { return getValues(getOption(trigger), Collections.EMPTY_LIST); } public final List getValues(final String trigger, final List defaultValues) { return getValues(getOption(trigger), defaultValues); } public final List getValues(final Option option) { return getValues(option, Collections.EMPTY_LIST); } public final Object getValue(final String trigger) { return getValue(getOption(trigger), null); } public final Object getValue(final String trigger, final Object defaultValue) { return getValue(getOption(trigger), defaultValue); } public final Object getValue(final Option option) { return getValue(option, null); } public final Object getValue(final Option option, final Object defaultValue) { final List values; if (defaultValue == null) { values = getValues(option); } else { values = getValues(option, Collections.singletonList(defaultValue)); } if (values.size() > 1) { throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES)); } if (values.isEmpty()) { return defaultValue; } return values.get(0); } public final Boolean getSwitch(final String trigger) { return getSwitch(getOption(trigger), null); } public final Boolean getSwitch(final String trigger, final Boolean defaultValue) { return getSwitch(getOption(trigger), defaultValue); } public final Boolean getSwitch(final Option option) { return getSwitch(option, null); } public final String getProperty(final String property) { return getProperty(property, null); } public final int getOptionCount(final String trigger) { return getOptionCount(getOption(trigger)); } public final int getOptionCount(final Option option) { if (option == null) { return 0; } int count = 0; for (Iterator i = getOptions().iterator(); i.hasNext();) { if (option.equals(i.next())) { ++count; } } return count; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java b/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java index cb85e1fa7..1b887af8f 100644 --- a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java @@ -1,172 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Option; - -/** - * Manages a queue of default CommandLines. This CommandLine implementation is - * backed by a queue of CommandLine instances which are queried in turn until a - * suitable result is found. - * - * CommandLine instances can either be added to the back of the queue or can be - * pushed in at a specific position. - * - * @see #appendCommandLine(CommandLine) - * @see #insertCommandLine(int, CommandLine) - */ -public class DefaultingCommandLine extends CommandLineImpl { - - /** - * The list of default CommandLine instances - */ - private final List commandLines = new ArrayList(); - - /** - * Adds a CommandLine instance to the back of the queue. The supplied - * CommandLine will be used as defaults when all other CommandLines produce - * no result - * - * @param commandLine - * the default values to use if all CommandLines - */ - public void appendCommandLine(final CommandLine commandLine) { - commandLines.add(commandLine); - } - - /** - * Adds a CommandLine instance to a specified position in the queue. - * - * @param index ths position at which to insert - * @param commandLine the CommandLine to insert - */ - public void insertCommandLine( - final int index, - final CommandLine commandLine) { - commandLines.add(index, commandLine); - } - - /** - * Builds an iterator over the build in CommandLines. - * - * @return an unmodifiable iterator - */ - public Iterator commandLines(){ - return Collections.unmodifiableList(commandLines).iterator(); - } - - public Option getOption(String trigger) { - for (final Iterator i = commandLines.iterator(); i.hasNext();) { - final CommandLine commandLine = (CommandLine)i.next(); - final Option actual = commandLine.getOption(trigger); - if (actual != null) { - return actual; - } - } - return null; - } - - public List getOptions() { - final List options = new ArrayList(); - - final List temp = new ArrayList(); - for (final Iterator i = commandLines.iterator(); i.hasNext();) { - final CommandLine commandLine = (CommandLine)i.next(); - temp.clear(); - temp.addAll(commandLine.getOptions()); - temp.removeAll(options); - options.addAll(temp); - } - - return Collections.unmodifiableList(options); - } - - public Set getOptionTriggers() { - final Set all = new HashSet(); - for (final Iterator i = commandLines.iterator(); i.hasNext();) { - final CommandLine commandLine = (CommandLine)i.next(); - all.addAll(commandLine.getOptionTriggers()); - } - - return Collections.unmodifiableSet(all); - } - - public boolean hasOption(Option option) { - for (final Iterator i = commandLines.iterator(); i.hasNext();) { - final CommandLine commandLine = (CommandLine)i.next(); - if (commandLine.hasOption(option)) { - return true; - } - } - return false; - } - - public List getValues(Option option, List defaultValues) { - for (final Iterator i = commandLines.iterator(); i.hasNext();) { - final CommandLine commandLine = (CommandLine)i.next(); - final List actual = commandLine.getValues(option); - if (actual != null && !actual.isEmpty()) { - return actual; - } - } - if(defaultValues==null){ - return Collections.EMPTY_LIST; - } - else{ - return defaultValues; - } - } - - public Boolean getSwitch(Option option, Boolean defaultValue) { - for (final Iterator i = commandLines.iterator(); i.hasNext();) { - final CommandLine commandLine = (CommandLine)i.next(); - final Boolean actual = commandLine.getSwitch(option); - if (actual != null) { - return actual; - } - } - return defaultValue; - } - - public String getProperty(String property, String defaultValue) { - for (final Iterator i = commandLines.iterator(); i.hasNext();) { - final CommandLine commandLine = (CommandLine)i.next(); - final String actual = commandLine.getProperty(property); - if (actual != null) { - return actual; - } - } - return defaultValue; - } - - public Set getProperties() { - final Set all = new HashSet(); - for (final Iterator i = commandLines.iterator(); i.hasNext();) { - final CommandLine commandLine = (CommandLine)i.next(); - all.addAll(commandLine.getProperties()); - } - return Collections.unmodifiableSet(all); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Option;/** * Manages a queue of default CommandLines. This CommandLine implementation is * backed by a queue of CommandLine instances which are queried in turn until a * suitable result is found. * * CommandLine instances can either be added to the back of the queue or can be * pushed in at a specific position. * * @see #appendCommandLine(CommandLine) * @see #insertCommandLine(int, CommandLine) */public class DefaultingCommandLine extends CommandLineImpl { /** * The list of default CommandLine instances */ private final List commandLines = new ArrayList(); /** * Adds a CommandLine instance to the back of the queue. The supplied * CommandLine will be used as defaults when all other CommandLines produce * no result * * @param commandLine * the default values to use if all CommandLines */ public void appendCommandLine(final CommandLine commandLine) { commandLines.add(commandLine); } /** * Adds a CommandLine instance to a specified position in the queue. * * @param index ths position at which to insert * @param commandLine the CommandLine to insert */ public void insertCommandLine( final int index, final CommandLine commandLine) { commandLines.add(index, commandLine); } /** * Builds an iterator over the build in CommandLines. * * @return an unmodifiable iterator */ public Iterator commandLines(){ return Collections.unmodifiableList(commandLines).iterator(); } public Option getOption(String trigger) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); final Option actual = commandLine.getOption(trigger); if (actual != null) { return actual; } } return null; } public List getOptions() { final List options = new ArrayList(); final List temp = new ArrayList(); for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); temp.clear(); temp.addAll(commandLine.getOptions()); temp.removeAll(options); options.addAll(temp); } return Collections.unmodifiableList(options); } public Set getOptionTriggers() { final Set all = new HashSet(); for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); all.addAll(commandLine.getOptionTriggers()); } return Collections.unmodifiableSet(all); } public boolean hasOption(Option option) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); if (commandLine.hasOption(option)) { return true; } } return false; } public List getValues(Option option, List defaultValues) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); final List actual = commandLine.getValues(option); if (actual != null && !actual.isEmpty()) { return actual; } } if(defaultValues==null){ return Collections.EMPTY_LIST; } else{ return defaultValues; } } public Boolean getSwitch(Option option, Boolean defaultValue) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); final Boolean actual = commandLine.getSwitch(option); if (actual != null) { return actual; } } return defaultValue; } public String getProperty(String property, String defaultValue) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); final String actual = commandLine.getProperty(property); if (actual != null) { return actual; } } return defaultValue; } public Set getProperties() { final Set all = new HashSet(); for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); all.addAll(commandLine.getProperties()); } return Collections.unmodifiableSet(all); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/commandline/Parser.java b/src/java/org/apache/commons/cli2/commandline/Parser.java index 4dd3f9670..34229e368 100644 --- a/src/java/org/apache/commons/cli2/commandline/Parser.java +++ b/src/java/org/apache/commons/cli2/commandline/Parser.java @@ -1,176 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.util.HelpFormatter; - -/** - * A class that implements the Parser interface can parse a - * String array according to the {@link Group}specified and return a - * {@link CommandLine}. - * - * @author John Keyes (john at integralsource.com) - */ -public class Parser { - private HelpFormatter helpFormatter = new HelpFormatter(); - private Option helpOption = null; - private String helpTrigger = null; - private Group group = null; - - /** - * Parse the arguments according to the specified options and properties. - * - * @param arguments - * the command line arguments - * - * @return the list of atomic option and value tokens - * @throws OptionException - * if there are any problems encountered while parsing the - * command line tokens. - */ - public CommandLine parse(final String[] arguments) - throws OptionException { - // build a mutable list for the arguments - final List argumentList = new LinkedList(); - - // copy the arguments into the new list - for (int i = 0; i < arguments.length; i++) { - final String argument = arguments[i]; - - // ensure non intern'd strings are used - // so that == comparisons work as expected - argumentList.add(new String(argument)); - } - - // wet up a command line for this group - final WriteableCommandLine commandLine = new WriteableCommandLineImpl(group, argumentList); - - // pick up any defaults from the model - group.defaults(commandLine); - - // process the options as far as possible - final ListIterator iterator = argumentList.listIterator(); - Object previous = null; - - while (group.canProcess(commandLine, iterator)) { - // peek at the next item and backtrack - final Object next = iterator.next(); - iterator.previous(); - - // if we have just tried to process this instance - if (next == previous) { - // abort - break; - } - - // remember previous - previous = next; - - group.process(commandLine, iterator); - } - - // if there are more arguments we have a problem - if (iterator.hasNext()) { - final String arg = (String) iterator.next(); - throw new OptionException(group, ResourceConstants.UNEXPECTED_TOKEN, arg); - } - - // no need to validate if the help option is present - if (!commandLine.hasOption(helpOption) && !commandLine.hasOption(helpTrigger)) { - group.validate(commandLine); - } - - return commandLine; - } - - /** - * Parse the arguments according to the specified options and properties and - * displays the usage screen if the CommandLine is not valid or the help - * option was specified. - * - * @param arguments the command line arguments - * @return a valid CommandLine or null if the parse was unsuccessful - * @throws IOException if an error occurs while formatting help - */ - public CommandLine parseAndHelp(final String[] arguments) { - helpFormatter.setGroup(group); - - try { - // attempt to parse the command line - final CommandLine commandLine = parse(arguments); - - if (!commandLine.hasOption(helpOption) && !commandLine.hasOption(helpTrigger)) { - return commandLine; - } - } catch (final OptionException oe) { - // display help regarding the exception - helpFormatter.setException(oe); - } - - // print help - helpFormatter.print(); - - return null; - } - - /** - * Sets the Group of options to parse against - * @param group the group of options to parse against - */ - public void setGroup(final Group group) { - this.group = group; - } - - /** - * Sets the HelpFormatter to use with the simplified parsing. - * @see #parseAndHelp(String[]) - * @param helpFormatter the HelpFormatter to use with the simplified parsing - */ - public void setHelpFormatter(final HelpFormatter helpFormatter) { - this.helpFormatter = helpFormatter; - } - - /** - * Sets the help option to use with the simplified parsing. For example - * --help, -h and -? are often used. - * @see #parseAndHelp(String[]) - * @param helpOption the help Option - */ - public void setHelpOption(final Option helpOption) { - this.helpOption = helpOption; - } - - /** - * Sets the help option to use with the simplified parsing. For example - * --help, -h and -? are often used. - * @see #parseAndHelp(String[]) - * @param helpTrigger the trigger of the help Option - */ - public void setHelpTrigger(final String helpTrigger) { - this.helpTrigger = helpTrigger; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.LinkedList;import java.util.List;import java.util.ListIterator;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.util.HelpFormatter;/** * A class that implements the Parser interface can parse a * String array according to the {@link Group}specified and return a * {@link CommandLine}. * * @author John Keyes (john at integralsource.com) */public class Parser { private HelpFormatter helpFormatter = new HelpFormatter(); private Option helpOption = null; private String helpTrigger = null; private Group group = null; /** * Parse the arguments according to the specified options and properties. * * @param arguments * the command line arguments * * @return the list of atomic option and value tokens * @throws OptionException * if there are any problems encountered while parsing the * command line tokens. */ public CommandLine parse(final String[] arguments) throws OptionException { // build a mutable list for the arguments final List argumentList = new LinkedList(); // copy the arguments into the new list for (int i = 0; i < arguments.length; i++) { final String argument = arguments[i]; // ensure non intern'd strings are used // so that == comparisons work as expected argumentList.add(new String(argument)); } // wet up a command line for this group final WriteableCommandLine commandLine = new WriteableCommandLineImpl(group, argumentList); // pick up any defaults from the model group.defaults(commandLine); // process the options as far as possible final ListIterator iterator = argumentList.listIterator(); Object previous = null; while (group.canProcess(commandLine, iterator)) { // peek at the next item and backtrack final Object next = iterator.next(); iterator.previous(); // if we have just tried to process this instance if (next == previous) { // abort break; } // remember previous previous = next; group.process(commandLine, iterator); } // if there are more arguments we have a problem if (iterator.hasNext()) { final String arg = (String) iterator.next(); throw new OptionException(group, ResourceConstants.UNEXPECTED_TOKEN, arg); } // no need to validate if the help option is present if (!commandLine.hasOption(helpOption) && !commandLine.hasOption(helpTrigger)) { group.validate(commandLine); } return commandLine; } /** * Parse the arguments according to the specified options and properties and * displays the usage screen if the CommandLine is not valid or the help * option was specified. * * @param arguments the command line arguments * @return a valid CommandLine or null if the parse was unsuccessful * @throws IOException if an error occurs while formatting help */ public CommandLine parseAndHelp(final String[] arguments) { helpFormatter.setGroup(group); try { // attempt to parse the command line final CommandLine commandLine = parse(arguments); if (!commandLine.hasOption(helpOption) && !commandLine.hasOption(helpTrigger)) { return commandLine; } } catch (final OptionException oe) { // display help regarding the exception helpFormatter.setException(oe); } // print help helpFormatter.print(); return null; } /** * Sets the Group of options to parse against * @param group the group of options to parse against */ public void setGroup(final Group group) { this.group = group; } /** * Sets the HelpFormatter to use with the simplified parsing. * @see #parseAndHelp(String[]) * @param helpFormatter the HelpFormatter to use with the simplified parsing */ public void setHelpFormatter(final HelpFormatter helpFormatter) { this.helpFormatter = helpFormatter; } /** * Sets the help option to use with the simplified parsing. For example * --help, -h and -? are often used. * @see #parseAndHelp(String[]) * @param helpOption the help Option */ public void setHelpOption(final Option helpOption) { this.helpOption = helpOption; } /** * Sets the help option to use with the simplified parsing. For example * --help, -h and -? are often used. * @see #parseAndHelp(String[]) * @param helpTrigger the trigger of the help Option */ public void setHelpTrigger(final String helpTrigger) { this.helpTrigger = helpTrigger; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java b/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java index 5b74f5a09..2cc868cd6 100644 --- a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java @@ -1,170 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.prefs.BackingStoreException; -import java.util.prefs.Preferences; - -import org.apache.commons.cli2.Option; - -/** - * A CommandLine implementation using the Preferences API, useful when - * constructing a complex DefaultingCommandLine - * - * This implementation uses the children of a single preference node to populate - * the CommandLine. Options are keyed from their preferred name and presence in - * the Preferences object is taken as presence in the CommandLine. Argument - * values are taken from the Preference value and are optionally separated using - * the separator char defined, at construction time. Switch values can be - * specified using a simple value of true or false; - * obviously this means that Switches with Arguments are not supported by this - * implementation. - * - * @see java.util.prefs.Preferences - * @see org.apache.commons.cli2.commandline.DefaultingCommandLine - * @see org.apache.commons.cli2.Option#getPreferredName() - */ -public class PreferencesCommandLine extends CommandLineImpl { - - private static final char NUL = '\0'; - private final Preferences preferences; - private final Option root; - private final char separator; - - /** - * Creates a new PreferencesCommandLine using the specified root Option and - * Preferences node. Argument values will be separated using the char 0. - * - * @param root the CommandLine's root Option - * @param preferences the Preferences node to get values from - */ - public PreferencesCommandLine(final Option root, final Preferences preferences){ - this(root,preferences,NUL); - } - - /** - * Creates a new PreferencesCommandLine using the specified root Option, - * Preferences node and value separator. - * - * @param root the CommandLine's root Option - * @param preferences the Preferences node to get values from - * @param separator the character to split argument values - */ - public PreferencesCommandLine(final Option root, final Preferences preferences, final char separator){ - this.root = root; - this.preferences = preferences; - this.separator = separator; - } - - public boolean hasOption(Option option) { - if(option==null){ - return false; - } - else{ - try { - return Arrays.asList(preferences.keys()).contains(option.getPreferredName()); - } catch (BackingStoreException e) { - return false; - } - } - } - - public Option getOption(String trigger) { - return root.findOption(trigger); - } - - public List getValues(final Option option, final List defaultValues) { - final String value = preferences.get(option.getPreferredName(),null); - - if(value==null){ - return defaultValues; - } - else if(separator>NUL){ - final List values = new ArrayList(); - final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); - - while(tokens.hasMoreTokens()){ - values.add(tokens.nextToken()); - } - - return values; - } - else{ - return Collections.singletonList(value); - } - } - - public Boolean getSwitch(final Option option, final Boolean defaultValue) { - final String value = preferences.get(option.getPreferredName(),null); - if("true".equals(value)){ - return Boolean.TRUE; - } - else if("false".equals(value)){ - return Boolean.FALSE; - } - else{ - return defaultValue; - } - } - - public String getProperty(final String property, final String defaultValue) { - return preferences.get(property, defaultValue); - } - - public Set getProperties() { - try { - return new HashSet(Arrays.asList(preferences.keys())); - } catch (BackingStoreException e) { - return Collections.EMPTY_SET; - } - } - - public List getOptions() { - try { - final List options = new ArrayList(); - final Iterator keys = Arrays.asList(preferences.keys()).iterator(); - while (keys.hasNext()) { - final String trigger = (String) keys.next(); - final Option option = root.findOption(trigger); - if (option != null) { - options.add(option); - } - } - return Collections.unmodifiableList(options); - } catch (BackingStoreException e) { - return Collections.EMPTY_LIST; - } - } - - public Set getOptionTriggers() { - final Set triggers = new HashSet(); - final Iterator options = getOptions().iterator(); - while(options.hasNext()){ - final Option option = (Option)options.next(); - triggers.addAll(option.getTriggers()); - } - return Collections.unmodifiableSet(triggers); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;import java.util.StringTokenizer;import java.util.prefs.BackingStoreException;import java.util.prefs.Preferences;import org.apache.commons.cli2.Option;/** * A CommandLine implementation using the Preferences API, useful when * constructing a complex DefaultingCommandLine * * This implementation uses the children of a single preference node to populate * the CommandLine. Options are keyed from their preferred name and presence in * the Preferences object is taken as presence in the CommandLine. Argument * values are taken from the Preference value and are optionally separated using * the separator char defined, at construction time. Switch values can be * specified using a simple value of true or false; * obviously this means that Switches with Arguments are not supported by this * implementation. * * @see java.util.prefs.Preferences * @see org.apache.commons.cli2.commandline.DefaultingCommandLine * @see org.apache.commons.cli2.Option#getPreferredName() */public class PreferencesCommandLine extends CommandLineImpl { private static final char NUL = '\0'; private final Preferences preferences; private final Option root; private final char separator; /** * Creates a new PreferencesCommandLine using the specified root Option and * Preferences node. Argument values will be separated using the char 0. * * @param root the CommandLine's root Option * @param preferences the Preferences node to get values from */ public PreferencesCommandLine(final Option root, final Preferences preferences){ this(root,preferences,NUL); } /** * Creates a new PreferencesCommandLine using the specified root Option, * Preferences node and value separator. * * @param root the CommandLine's root Option * @param preferences the Preferences node to get values from * @param separator the character to split argument values */ public PreferencesCommandLine(final Option root, final Preferences preferences, final char separator){ this.root = root; this.preferences = preferences; this.separator = separator; } public boolean hasOption(Option option) { if(option==null){ return false; } else{ try { return Arrays.asList(preferences.keys()).contains(option.getPreferredName()); } catch (BackingStoreException e) { return false; } } } public Option getOption(String trigger) { return root.findOption(trigger); } public List getValues(final Option option, final List defaultValues) { final String value = preferences.get(option.getPreferredName(),null); if(value==null){ return defaultValues; } else if(separator>NUL){ final List values = new ArrayList(); final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); while(tokens.hasMoreTokens()){ values.add(tokens.nextToken()); } return values; } else{ return Collections.singletonList(value); } } public Boolean getSwitch(final Option option, final Boolean defaultValue) { final String value = preferences.get(option.getPreferredName(),null); if("true".equals(value)){ return Boolean.TRUE; } else if("false".equals(value)){ return Boolean.FALSE; } else{ return defaultValue; } } public String getProperty(final String property, final String defaultValue) { return preferences.get(property, defaultValue); } public Set getProperties() { try { return new HashSet(Arrays.asList(preferences.keys())); } catch (BackingStoreException e) { return Collections.EMPTY_SET; } } public List getOptions() { try { final List options = new ArrayList(); final Iterator keys = Arrays.asList(preferences.keys()).iterator(); while (keys.hasNext()) { final String trigger = (String) keys.next(); final Option option = root.findOption(trigger); if (option != null) { options.add(option); } } return Collections.unmodifiableList(options); } catch (BackingStoreException e) { return Collections.EMPTY_LIST; } } public Set getOptionTriggers() { final Set triggers = new HashSet(); final Iterator options = getOptions().iterator(); while(options.hasNext()){ final Option option = (Option)options.next(); triggers.addAll(option.getTriggers()); } return Collections.unmodifiableSet(triggers); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java b/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java index 6e04b6728..1c99983f0 100644 --- a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java @@ -1,155 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.StringTokenizer; - -import org.apache.commons.cli2.Option; - -/** - * A CommandLine implementation using a java Properties instance, useful for - * constructing a complex DefaultingCommandLine - * - * Options are keyed from their property name and presence in the Properties - * instance is taken as presence in the CommandLine. Argument values are taken - * from the property value and are optionally separated using the separator - * char, defined at construction time. Switch values can be specified using a - * simple value of true or false; obviously this means - * that Switches with Arguments are not supported by this implementation. - * - * @see java.util.Properties - * @see org.apache.commons.cli2.commandline.DefaultingCommandLine - * @see org.apache.commons.cli2.Option#getPreferredName() - */ -public class PropertiesCommandLine extends CommandLineImpl { - - private static final char NUL = '\0'; - private final Properties properties; - private final Option root; - private final char separator; - - /** - * Creates a new PropertiesCommandLine using the specified root Option, - * Properties instance. The character 0 is used as the value separator. - * - * @param root the CommandLine's root Option - * @param properties the Properties instance to get values from - */ - public PropertiesCommandLine(final Option root, final Properties properties){ - this(root,properties,NUL); - } - - /** - * Creates a new PropertiesCommandLine using the specified root Option, - * Properties instance and value separator. - * - * @param root the CommandLine's root Option - * @param properties the Properties instance to get values from - * @param separator the character to split argument values - */ - public PropertiesCommandLine(final Option root, final Properties properties, final char separator){ - this.root = root; - this.properties = properties; - this.separator = separator; - } - - - public boolean hasOption(Option option) { - if(option==null){ - return false; - } - else{ - return properties.containsKey(option.getPreferredName()); - } - } - - public Option getOption(String trigger) { - return root.findOption(trigger); - } - - public List getValues(final Option option, final List defaultValues) { - final String value = properties.getProperty(option.getPreferredName()); - - if(value==null){ - return defaultValues; - } - else if(separator>NUL){ - final List values = new ArrayList(); - final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); - - while(tokens.hasMoreTokens()){ - values.add(tokens.nextToken()); - } - - return values; - } - else{ - return Collections.singletonList(value); - } - } - - public Boolean getSwitch(final Option option, final Boolean defaultValue) { - final String value = properties.getProperty(option.getPreferredName()); - if("true".equals(value)){ - return Boolean.TRUE; - } - else if("false".equals(value)){ - return Boolean.FALSE; - } - else{ - return defaultValue; - } - } - - public String getProperty(final String property, final String defaultValue) { - return properties.getProperty(property,defaultValue); - } - - public Set getProperties() { - return properties.keySet(); - } - - public List getOptions() { - final List options = new ArrayList(); - final Iterator keys = properties.keySet().iterator(); - while(keys.hasNext()){ - final String trigger = (String)keys.next(); - final Option option = root.findOption(trigger); - if(option!=null){ - options.add(option); - } - } - return Collections.unmodifiableList(options); - } - - public Set getOptionTriggers() { - final Set triggers = new HashSet(); - final Iterator options = getOptions().iterator(); - while(options.hasNext()){ - final Option option = (Option)options.next(); - triggers.addAll(option.getTriggers()); - } - return Collections.unmodifiableSet(triggers); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Properties;import java.util.Set;import java.util.StringTokenizer;import org.apache.commons.cli2.Option;/** * A CommandLine implementation using a java Properties instance, useful for * constructing a complex DefaultingCommandLine * * Options are keyed from their property name and presence in the Properties * instance is taken as presence in the CommandLine. Argument values are taken * from the property value and are optionally separated using the separator * char, defined at construction time. Switch values can be specified using a * simple value of true or false; obviously this means * that Switches with Arguments are not supported by this implementation. * * @see java.util.Properties * @see org.apache.commons.cli2.commandline.DefaultingCommandLine * @see org.apache.commons.cli2.Option#getPreferredName() */public class PropertiesCommandLine extends CommandLineImpl { private static final char NUL = '\0'; private final Properties properties; private final Option root; private final char separator; /** * Creates a new PropertiesCommandLine using the specified root Option, * Properties instance. The character 0 is used as the value separator. * * @param root the CommandLine's root Option * @param properties the Properties instance to get values from */ public PropertiesCommandLine(final Option root, final Properties properties){ this(root,properties,NUL); } /** * Creates a new PropertiesCommandLine using the specified root Option, * Properties instance and value separator. * * @param root the CommandLine's root Option * @param properties the Properties instance to get values from * @param separator the character to split argument values */ public PropertiesCommandLine(final Option root, final Properties properties, final char separator){ this.root = root; this.properties = properties; this.separator = separator; } public boolean hasOption(Option option) { if(option==null){ return false; } else{ return properties.containsKey(option.getPreferredName()); } } public Option getOption(String trigger) { return root.findOption(trigger); } public List getValues(final Option option, final List defaultValues) { final String value = properties.getProperty(option.getPreferredName()); if(value==null){ return defaultValues; } else if(separator>NUL){ final List values = new ArrayList(); final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); while(tokens.hasMoreTokens()){ values.add(tokens.nextToken()); } return values; } else{ return Collections.singletonList(value); } } public Boolean getSwitch(final Option option, final Boolean defaultValue) { final String value = properties.getProperty(option.getPreferredName()); if("true".equals(value)){ return Boolean.TRUE; } else if("false".equals(value)){ return Boolean.FALSE; } else{ return defaultValue; } } public String getProperty(final String property, final String defaultValue) { return properties.getProperty(property,defaultValue); } public Set getProperties() { return properties.keySet(); } public List getOptions() { final List options = new ArrayList(); final Iterator keys = properties.keySet().iterator(); while(keys.hasNext()){ final String trigger = (String)keys.next(); final Option option = root.findOption(trigger); if(option!=null){ options.add(option); } } return Collections.unmodifiableList(options); } public Set getOptionTriggers() { final Set triggers = new HashSet(); final Iterator options = getOptions().iterator(); while(options.hasNext()){ final Option option = (Option)options.next(); triggers.addAll(option.getTriggers()); } return Collections.unmodifiableSet(triggers); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java index bb1610e16..85e3bfc5a 100644 --- a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java @@ -1,226 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * A WriteableCommandLine implementation allowing Options to write their - * processed information to a CommandLine. - */ -public class WriteableCommandLineImpl - extends CommandLineImpl implements WriteableCommandLine { - private final Properties properties = new Properties(); - private final List options = new ArrayList(); - private final Map nameToOption = new HashMap(); - private final Map values = new HashMap(); - private final Map switches = new HashMap(); - private final Map defaultValues = new HashMap(); - private final Map defaultSwitches = new HashMap(); - private final List normalised; - private final Set prefixes; - - /** - * Creates a new WriteableCommandLineImpl rooted on the specified Option, to - * hold the parsed arguments. - * - * @param rootOption the CommandLine's root Option - * @param arguments the arguments this CommandLine represents - */ - public WriteableCommandLineImpl(final Option rootOption, - final List arguments) { - this.prefixes = rootOption.getPrefixes(); - this.normalised = arguments; - } - - public void addOption(Option option) { - options.add(option); - nameToOption.put(option.getPreferredName(), option); - - for (Iterator i = option.getTriggers().iterator(); i.hasNext();) { - nameToOption.put(i.next(), option); - } - } - - public void addValue(final Option option, - final Object value) { - if (option instanceof Argument) { - addOption(option); - } - - List valueList = (List) values.get(option); - - if (valueList == null) { - valueList = new ArrayList(); - values.put(option, valueList); - } - - valueList.add(value); - } - - public void addSwitch(final Option option, - final boolean value) { - addOption(option); - - if (switches.containsKey(option)) { - throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ALREADY_SET)); - } else { - switches.put(option, value ? Boolean.TRUE : Boolean.FALSE); - } - } - - public boolean hasOption(final Option option) { - final boolean present = options.contains(option); - - return present; - } - - public Option getOption(final String trigger) { - return (Option) nameToOption.get(trigger); - } - - public List getValues(final Option option, - final List defaultValues) { - // First grab the command line values - List valueList = (List) values.get(option); - - // Secondly try the defaults supplied to the method - if ((valueList == null) || valueList.isEmpty()) { - valueList = defaultValues; - } - - // Thirdly try the option's default values - if ((valueList == null) || valueList.isEmpty()) { - valueList = (List) this.defaultValues.get(option); - } - - // Finally use an empty list - if (valueList == null) { - valueList = Collections.EMPTY_LIST; - } - - return valueList; - } - - public Boolean getSwitch(final Option option, - final Boolean defaultValue) { - // First grab the command line values - Boolean bool = (Boolean) switches.get(option); - - // Secondly try the defaults supplied to the method - if (bool == null) { - bool = defaultValue; - } - - // Thirdly try the option's default values - if (bool == null) { - bool = (Boolean) this.defaultSwitches.get(option); - } - - return bool; - } - - public void addProperty(final String property, - final String value) { - properties.setProperty(property, value); - } - - public String getProperty(final String property, - final String defaultValue) { - return properties.getProperty(property, defaultValue); - } - - public Set getProperties() { - return Collections.unmodifiableSet(properties.keySet()); - } - - public boolean looksLikeOption(final String trigger) { - for (final Iterator i = prefixes.iterator(); i.hasNext();) { - final String prefix = (String) i.next(); - - if (trigger.startsWith(prefix)) { - return true; - } - } - - return false; - } - - public String toString() { - final StringBuffer buffer = new StringBuffer(); - - // need to add group header - for (final Iterator i = normalised.iterator(); i.hasNext();) { - final String arg = (String) i.next(); - - if (arg.indexOf(' ') >= 0) { - buffer.append("\"").append(arg).append("\""); - } else { - buffer.append(arg); - } - - if (i.hasNext()) { - buffer.append(' '); - } - } - - return buffer.toString(); - } - - public List getOptions() { - return Collections.unmodifiableList(options); - } - - public Set getOptionTriggers() { - return Collections.unmodifiableSet(nameToOption.keySet()); - } - - public void setDefaultValues(final Option option, - final List defaults) { - if (defaults == null) { - defaultValues.remove(option); - } else { - defaultValues.put(option, defaults); - } - } - - public void setDefaultSwitch(final Option option, - final Boolean defaultSwitch) { - if (defaultSwitch == null) { - defaultSwitches.remove(option); - } else { - defaultSwitches.put(option, defaultSwitch); - } - } - - public List getNormalised() { - return Collections.unmodifiableList(normalised); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * A WriteableCommandLine implementation allowing Options to write their * processed information to a CommandLine. */public class WriteableCommandLineImpl extends CommandLineImpl implements WriteableCommandLine { private final Properties properties = new Properties(); private final List options = new ArrayList(); private final Map nameToOption = new HashMap(); private final Map values = new HashMap(); private final Map switches = new HashMap(); private final Map defaultValues = new HashMap(); private final Map defaultSwitches = new HashMap(); private final List normalised; private final Set prefixes; /** * Creates a new WriteableCommandLineImpl rooted on the specified Option, to * hold the parsed arguments. * * @param rootOption the CommandLine's root Option * @param arguments the arguments this CommandLine represents */ public WriteableCommandLineImpl(final Option rootOption, final List arguments) { this.prefixes = rootOption.getPrefixes(); this.normalised = arguments; } public void addOption(Option option) { options.add(option); nameToOption.put(option.getPreferredName(), option); for (Iterator i = option.getTriggers().iterator(); i.hasNext();) { nameToOption.put(i.next(), option); } } public void addValue(final Option option, final Object value) { if (option instanceof Argument) { addOption(option); } List valueList = (List) values.get(option); if (valueList == null) { valueList = new ArrayList(); values.put(option, valueList); } valueList.add(value); } public void addSwitch(final Option option, final boolean value) { addOption(option); if (switches.containsKey(option)) { throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ALREADY_SET)); } else { switches.put(option, value ? Boolean.TRUE : Boolean.FALSE); } } public boolean hasOption(final Option option) { final boolean present = options.contains(option); return present; } public Option getOption(final String trigger) { return (Option) nameToOption.get(trigger); } public List getValues(final Option option, final List defaultValues) { // First grab the command line values List valueList = (List) values.get(option); // Secondly try the defaults supplied to the method if ((valueList == null) || valueList.isEmpty()) { valueList = defaultValues; } // Thirdly try the option's default values if ((valueList == null) || valueList.isEmpty()) { valueList = (List) this.defaultValues.get(option); } // Finally use an empty list if (valueList == null) { valueList = Collections.EMPTY_LIST; } return valueList; } public Boolean getSwitch(final Option option, final Boolean defaultValue) { // First grab the command line values Boolean bool = (Boolean) switches.get(option); // Secondly try the defaults supplied to the method if (bool == null) { bool = defaultValue; } // Thirdly try the option's default values if (bool == null) { bool = (Boolean) this.defaultSwitches.get(option); } return bool; } public void addProperty(final String property, final String value) { properties.setProperty(property, value); } public String getProperty(final String property, final String defaultValue) { return properties.getProperty(property, defaultValue); } public Set getProperties() { return Collections.unmodifiableSet(properties.keySet()); } public boolean looksLikeOption(final String trigger) { for (final Iterator i = prefixes.iterator(); i.hasNext();) { final String prefix = (String) i.next(); if (trigger.startsWith(prefix)) { return true; } } return false; } public String toString() { final StringBuffer buffer = new StringBuffer(); // need to add group header for (final Iterator i = normalised.iterator(); i.hasNext();) { final String arg = (String) i.next(); if (arg.indexOf(' ') >= 0) { buffer.append("\"").append(arg).append("\""); } else { buffer.append(arg); } if (i.hasNext()) { buffer.append(' '); } } return buffer.toString(); } public List getOptions() { return Collections.unmodifiableList(options); } public Set getOptionTriggers() { return Collections.unmodifiableSet(nameToOption.keySet()); } public void setDefaultValues(final Option option, final List defaults) { if (defaults == null) { defaultValues.remove(option); } else { defaultValues.put(option, defaults); } } public void setDefaultSwitch(final Option option, final Boolean defaultSwitch) { if (defaultSwitch == null) { defaultSwitches.remove(option); } else { defaultSwitches.put(option, defaultSwitch); } } public List getNormalised() { return Collections.unmodifiableList(normalised); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java index 066a8ce82..e9d5f1f93 100644 --- a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java @@ -1,374 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; -import java.util.StringTokenizer; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.HelpLine; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; -import org.apache.commons.cli2.validation.InvalidArgumentException; -import org.apache.commons.cli2.validation.Validator; - -/** - * An implementation of an Argument. - */ -public class ArgumentImpl - extends OptionImpl implements Argument { - private static final char NUL = '\0'; - - /** - * The default value for the initial separator char. - */ - public static final char DEFAULT_INITIAL_SEPARATOR = NUL; - - /** - * The default value for the subsequent separator char. - */ - public static final char DEFAULT_SUBSEQUENT_SEPARATOR = NUL; - - /** - * The default token to indicate that remaining arguments should be consumed - * as values. - */ - public static final String DEFAULT_CONSUME_REMAINING = "--"; - private final String name; - private final String description; - private final int minimum; - private final int maximum; - private final char initialSeparator; - private final char subsequentSeparator; - private final boolean subsequentSplit; - private final Validator validator; - private final String consumeRemaining; - private final List defaultValues; - private final ResourceHelper resources = ResourceHelper.getResourceHelper(); - - /** - * Creates a new Argument instance. - * - * @param name - * The name of the argument - * @param description - * A description of the argument - * @param minimum - * The minimum number of values needed to be valid - * @param maximum - * The maximum number of values allowed to be valid - * @param initialSeparator - * The char separating option from value - * @param subsequentSeparator - * The char separating values from each other - * @param validator - * The object responsible for validating the values - * @param consumeRemaining - * The String used for the "consuming option" group - * @param valueDefaults - * The values to be used if none are specified. - * @param id - * The id of the option, 0 implies automatic assignment. - * - * @see OptionImpl#OptionImpl(int,boolean) - */ - public ArgumentImpl(final String name, - final String description, - final int minimum, - final int maximum, - final char initialSeparator, - final char subsequentSeparator, - final Validator validator, - final String consumeRemaining, - final List valueDefaults, - final int id) { - super(id, false); - - this.name = (name == null) ? "arg" : name; - this.description = description; - this.minimum = minimum; - this.maximum = maximum; - this.initialSeparator = initialSeparator; - this.subsequentSeparator = subsequentSeparator; - this.subsequentSplit = subsequentSeparator != NUL; - this.validator = validator; - this.consumeRemaining = consumeRemaining; - this.defaultValues = valueDefaults; - - if (minimum > maximum) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_MIN_EXCEEDS_MAX)); - } - - if ((valueDefaults != null) && (valueDefaults.size() > 0)) { - if (valueDefaults.size() < minimum) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_TOO_FEW_DEFAULTS)); - } - - if (valueDefaults.size() > maximum) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_DEFAULTS)); - } - } - } - - public String getPreferredName() { - return name; - } - - public void processValues(final WriteableCommandLine commandLine, - final ListIterator arguments, - final Option option) - throws OptionException { - int argumentCount = commandLine.getValues(option, Collections.EMPTY_LIST).size(); - - while (arguments.hasNext() && (argumentCount < maximum)) { - final String allValuesQuoted = (String) arguments.next(); - final String allValues = stripBoundaryQuotes(allValuesQuoted); - - // should we ignore things that look like options? - if (allValuesQuoted.equals(consumeRemaining)) { - while (arguments.hasNext() && (argumentCount < maximum)) { - ++argumentCount; - commandLine.addValue(option, arguments.next()); - } - } - // does it look like an option? - else if (commandLine.looksLikeOption(allValuesQuoted)) { - arguments.previous(); - - break; - } - // should we split the string up? - else if (subsequentSplit) { - final StringTokenizer values = - new StringTokenizer(allValues, String.valueOf(subsequentSeparator)); - - arguments.remove(); - - while (values.hasMoreTokens() && (argumentCount < maximum)) { - ++argumentCount; - - final String token = values.nextToken(); - commandLine.addValue(option, token); - arguments.add(token); - } - - if (values.hasMoreTokens()) { - throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, - values.nextToken()); - } - } - // it must be a value as it is - else { - ++argumentCount; - commandLine.addValue(option, allValues); - } - } - } - - public boolean canProcess(final WriteableCommandLine commandLine, - final String arg) { - return true; - } - - public Set getPrefixes() { - return Collections.EMPTY_SET; - } - - public void process(WriteableCommandLine commandLine, - ListIterator args) - throws OptionException { - processValues(commandLine, args, this); - } - - public char getInitialSeparator() { - return this.initialSeparator; - } - - public char getSubsequentSeparator() { - return this.subsequentSeparator; - } - - public Set getTriggers() { - return Collections.EMPTY_SET; - } - - public String getConsumeRemaining() { - return this.consumeRemaining; - } - - public List getDefaultValues() { - return this.defaultValues; - } - - public Validator getValidator() { - return this.validator; - } - - public void validate(final WriteableCommandLine commandLine) - throws OptionException { - validate(commandLine, this); - } - - public void validate(final WriteableCommandLine commandLine, - final Option option) - throws OptionException { - final List values = commandLine.getValues(option); - - if (values.size() < minimum) { - throw new OptionException(option, ResourceConstants.ARGUMENT_MISSING_VALUES); - } - - if (values.size() > maximum) { - throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, - (String) values.get(maximum)); - } - - if (validator != null) { - try { - validator.validate(values); - } catch (InvalidArgumentException ive) { - throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, - ive.getMessage()); - } - } - } - - public void appendUsage(final StringBuffer buffer, - final Set helpSettings, - final Comparator comp) { - // do we display the outer optionality - final boolean optional = helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); - - // allow numbering if multiple args - final boolean numbered = - (maximum > 1) && helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); - - final boolean bracketed = helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); - - // if infinite args are allowed then crop the list - final int max = (maximum == Integer.MAX_VALUE) ? 2 : maximum; - - int i = 0; - - // for each argument - while (i < max) { - // if we're past the first add a space - if (i > 0) { - buffer.append(' '); - } - - // if the next arg is optional - if ((i >= minimum) && (optional || (i > 0))) { - buffer.append('['); - } - - if (bracketed) { - buffer.append('<'); - } - - // add name - buffer.append(name); - ++i; - - // if numbering - if (numbered) { - buffer.append(i); - } - - if (bracketed) { - buffer.append('>'); - } - } - - // if infinite args are allowed - if (maximum == Integer.MAX_VALUE) { - // append elipsis - buffer.append(" ..."); - } - - // for each argument - while (i > 0) { - --i; - - // if the next arg is optional - if ((i >= minimum) && (optional || (i > 0))) { - buffer.append(']'); - } - } - } - - public String getDescription() { - return description; - } - - public List helpLines(final int depth, - final Set helpSettings, - final Comparator comp) { - final HelpLine helpLine = new HelpLineImpl(this, depth); - - return Collections.singletonList(helpLine); - } - - public int getMaximum() { - return maximum; - } - - public int getMinimum() { - return minimum; - } - - /** - * If there are any leading or trailing quotes remove them from the - * specified token. - * - * @param token - * the token to strip leading and trailing quotes - * - * @return String the possibly modified token - */ - public String stripBoundaryQuotes(String token) { - if (!token.startsWith("\"") || !token.endsWith("\"")) { - return token; - } - - token = token.substring(1, token.length() - 1); - - return token; - } - - public boolean isRequired() { - return getMinimum() > 0; - } - - public void defaults(final WriteableCommandLine commandLine) { - super.defaults(commandLine); - defaultValues(commandLine, this); - } - - public void defaultValues(final WriteableCommandLine commandLine, - final Option option) { - commandLine.setDefaultValues(option, defaultValues); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.ListIterator;import java.util.Set;import java.util.StringTokenizer;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;import org.apache.commons.cli2.validation.InvalidArgumentException;import org.apache.commons.cli2.validation.Validator;/** * An implementation of an Argument. */public class ArgumentImpl extends OptionImpl implements Argument { private static final char NUL = '\0'; /** * The default value for the initial separator char. */ public static final char DEFAULT_INITIAL_SEPARATOR = NUL; /** * The default value for the subsequent separator char. */ public static final char DEFAULT_SUBSEQUENT_SEPARATOR = NUL; /** * The default token to indicate that remaining arguments should be consumed * as values. */ public static final String DEFAULT_CONSUME_REMAINING = "--"; private final String name; private final String description; private final int minimum; private final int maximum; private final char initialSeparator; private final char subsequentSeparator; private final boolean subsequentSplit; private final Validator validator; private final String consumeRemaining; private final List defaultValues; private final ResourceHelper resources = ResourceHelper.getResourceHelper(); /** * Creates a new Argument instance. * * @param name * The name of the argument * @param description * A description of the argument * @param minimum * The minimum number of values needed to be valid * @param maximum * The maximum number of values allowed to be valid * @param initialSeparator * The char separating option from value * @param subsequentSeparator * The char separating values from each other * @param validator * The object responsible for validating the values * @param consumeRemaining * The String used for the "consuming option" group * @param valueDefaults * The values to be used if none are specified. * @param id * The id of the option, 0 implies automatic assignment. * * @see OptionImpl#OptionImpl(int,boolean) */ public ArgumentImpl(final String name, final String description, final int minimum, final int maximum, final char initialSeparator, final char subsequentSeparator, final Validator validator, final String consumeRemaining, final List valueDefaults, final int id) { super(id, false); this.name = (name == null) ? "arg" : name; this.description = description; this.minimum = minimum; this.maximum = maximum; this.initialSeparator = initialSeparator; this.subsequentSeparator = subsequentSeparator; this.subsequentSplit = subsequentSeparator != NUL; this.validator = validator; this.consumeRemaining = consumeRemaining; this.defaultValues = valueDefaults; if (minimum > maximum) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_MIN_EXCEEDS_MAX)); } if ((valueDefaults != null) && (valueDefaults.size() > 0)) { if (valueDefaults.size() < minimum) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_TOO_FEW_DEFAULTS)); } if (valueDefaults.size() > maximum) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_DEFAULTS)); } } } public String getPreferredName() { return name; } public void processValues(final WriteableCommandLine commandLine, final ListIterator arguments, final Option option) throws OptionException { int argumentCount = commandLine.getValues(option, Collections.EMPTY_LIST).size(); while (arguments.hasNext() && (argumentCount < maximum)) { final String allValuesQuoted = (String) arguments.next(); final String allValues = stripBoundaryQuotes(allValuesQuoted); // should we ignore things that look like options? if (allValuesQuoted.equals(consumeRemaining)) { while (arguments.hasNext() && (argumentCount < maximum)) { ++argumentCount; commandLine.addValue(option, arguments.next()); } } // does it look like an option? else if (commandLine.looksLikeOption(allValuesQuoted)) { arguments.previous(); break; } // should we split the string up? else if (subsequentSplit) { final StringTokenizer values = new StringTokenizer(allValues, String.valueOf(subsequentSeparator)); arguments.remove(); while (values.hasMoreTokens() && (argumentCount < maximum)) { ++argumentCount; final String token = values.nextToken(); commandLine.addValue(option, token); arguments.add(token); } if (values.hasMoreTokens()) { throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, values.nextToken()); } } // it must be a value as it is else { ++argumentCount; commandLine.addValue(option, allValues); } } } public boolean canProcess(final WriteableCommandLine commandLine, final String arg) { return true; } public Set getPrefixes() { return Collections.EMPTY_SET; } public void process(WriteableCommandLine commandLine, ListIterator args) throws OptionException { processValues(commandLine, args, this); } public char getInitialSeparator() { return this.initialSeparator; } public char getSubsequentSeparator() { return this.subsequentSeparator; } public Set getTriggers() { return Collections.EMPTY_SET; } public String getConsumeRemaining() { return this.consumeRemaining; } public List getDefaultValues() { return this.defaultValues; } public Validator getValidator() { return this.validator; } public void validate(final WriteableCommandLine commandLine) throws OptionException { validate(commandLine, this); } public void validate(final WriteableCommandLine commandLine, final Option option) throws OptionException { final List values = commandLine.getValues(option); if (values.size() < minimum) { throw new OptionException(option, ResourceConstants.ARGUMENT_MISSING_VALUES); } if (values.size() > maximum) { throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, (String) values.get(maximum)); } if (validator != null) { try { validator.validate(values); } catch (InvalidArgumentException ive) { throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, ive.getMessage()); } } } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { // do we display the outer optionality final boolean optional = helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); // allow numbering if multiple args final boolean numbered = (maximum > 1) && helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); final boolean bracketed = helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); // if infinite args are allowed then crop the list final int max = (maximum == Integer.MAX_VALUE) ? 2 : maximum; int i = 0; // for each argument while (i < max) { // if we're past the first add a space if (i > 0) { buffer.append(' '); } // if the next arg is optional if ((i >= minimum) && (optional || (i > 0))) { buffer.append('['); } if (bracketed) { buffer.append('<'); } // add name buffer.append(name); ++i; // if numbering if (numbered) { buffer.append(i); } if (bracketed) { buffer.append('>'); } } // if infinite args are allowed if (maximum == Integer.MAX_VALUE) { // append elipsis buffer.append(" ..."); } // for each argument while (i > 0) { --i; // if the next arg is optional if ((i >= minimum) && (optional || (i > 0))) { buffer.append(']'); } } } public String getDescription() { return description; } public List helpLines(final int depth, final Set helpSettings, final Comparator comp) { final HelpLine helpLine = new HelpLineImpl(this, depth); return Collections.singletonList(helpLine); } public int getMaximum() { return maximum; } public int getMinimum() { return minimum; } /** * If there are any leading or trailing quotes remove them from the * specified token. * * @param token * the token to strip leading and trailing quotes * * @return String the possibly modified token */ public String stripBoundaryQuotes(String token) { if (!token.startsWith("\"") || !token.endsWith("\"")) { return token; } token = token.substring(1, token.length() - 1); return token; } public boolean isRequired() { return getMinimum() > 0; } public void defaults(final WriteableCommandLine commandLine) { super.defaults(commandLine); defaultValues(commandLine, this); } public void defaultValues(final WriteableCommandLine commandLine, final Option option) { commandLine.setDefaultValues(option, defaultValues); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/option/Command.java b/src/java/org/apache/commons/cli2/option/Command.java index 99f8c721a..a76b82c6c 100644 --- a/src/java/org/apache/commons/cli2/option/Command.java +++ b/src/java/org/apache/commons/cli2/option/Command.java @@ -1,175 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * Represents a cvs "update" style command line option. - * - * Like all Parents, Commands can have child options and can be part of - * Arguments - */ -public class Command - extends ParentImpl { - /** The display name for the command */ - private final String preferredName; - - /** The aliases for this command */ - private final Set aliases; - - /** All the names for this command */ - private final Set triggers; - - /** - * Creates a new Command instance. - * - * @param preferredName - * The name normally used to refer to the Command - * @param description - * A description of the Command - * @param aliases - * Alternative names for the Command - * @param required - * Whether the Command is required - * @param argument - * An Argument that the command takes - * @param children - * The Group of child options for this Command - * @param id - * A unique id for the Command - * - * @see ParentImpl#ParentImpl(Argument, Group, String, int, boolean) - */ - public Command(final String preferredName, - final String description, - final Set aliases, - final boolean required, - final Argument argument, - final Group children, - final int id) { - super(argument, children, description, id, required); - - // check the preferred name is valid - if ((preferredName == null) || (preferredName.length() < 1)) { - throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT)); - } - - this.preferredName = preferredName; - - // gracefully and defensively handle aliases - this.aliases = - (aliases == null) ? Collections.EMPTY_SET - : Collections.unmodifiableSet(new HashSet(aliases)); - - // populate the triggers Set - final Set newTriggers = new HashSet(); - newTriggers.add(preferredName); - newTriggers.addAll(this.aliases); - this.triggers = Collections.unmodifiableSet(newTriggers); - } - - public void processParent(final WriteableCommandLine commandLine, - final ListIterator arguments) - throws OptionException { - // grab the argument to process - final String arg = (String) arguments.next(); - - // if we can process it - if (canProcess(commandLine, arg)) { - // then note the option - commandLine.addOption(this); - - // normalise the argument list - arguments.set(preferredName); - } else { - throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); - } - } - - public Set getTriggers() { - return triggers; - } - - public void validate(WriteableCommandLine commandLine) - throws OptionException { - if (isRequired() && !commandLine.hasOption(this)) { - throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, - getPreferredName()); - } - - super.validate(commandLine); - } - - public void appendUsage(final StringBuffer buffer, - final Set helpSettings, - final Comparator comp) { - // do we display optionality - final boolean optional = - !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); - final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); - - if (optional) { - buffer.append('['); - } - - buffer.append(preferredName); - - if (displayAliases && !aliases.isEmpty()) { - buffer.append(" ("); - - final List list = new ArrayList(aliases); - Collections.sort(list); - - for (final Iterator i = list.iterator(); i.hasNext();) { - final String alias = (String) i.next(); - buffer.append(alias); - - if (i.hasNext()) { - buffer.append(','); - } - } - - buffer.append(')'); - } - - super.appendUsage(buffer, helpSettings, comp); - - if (optional) { - buffer.append(']'); - } - } - - public String getPreferredName() { - return preferredName; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Represents a cvs "update" style command line option. * * Like all Parents, Commands can have child options and can be part of * Arguments */public class Command extends ParentImpl { /** The display name for the command */ private final String preferredName; /** The aliases for this command */ private final Set aliases; /** All the names for this command */ private final Set triggers; /** * Creates a new Command instance. * * @param preferredName * The name normally used to refer to the Command * @param description * A description of the Command * @param aliases * Alternative names for the Command * @param required * Whether the Command is required * @param argument * An Argument that the command takes * @param children * The Group of child options for this Command * @param id * A unique id for the Command * * @see ParentImpl#ParentImpl(Argument, Group, String, int, boolean) */ public Command(final String preferredName, final String description, final Set aliases, final boolean required, final Argument argument, final Group children, final int id) { super(argument, children, description, id, required); // check the preferred name is valid if ((preferredName == null) || (preferredName.length() < 1)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT)); } this.preferredName = preferredName; // gracefully and defensively handle aliases this.aliases = (aliases == null) ? Collections.EMPTY_SET : Collections.unmodifiableSet(new HashSet(aliases)); // populate the triggers Set final Set newTriggers = new HashSet(); newTriggers.add(preferredName); newTriggers.addAll(this.aliases); this.triggers = Collections.unmodifiableSet(newTriggers); } public void processParent(final WriteableCommandLine commandLine, final ListIterator arguments) throws OptionException { // grab the argument to process final String arg = (String) arguments.next(); // if we can process it if (canProcess(commandLine, arg)) { // then note the option commandLine.addOption(this); // normalise the argument list arguments.set(preferredName); } else { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); } } public Set getTriggers() { return triggers; } public void validate(WriteableCommandLine commandLine) throws OptionException { if (isRequired() && !commandLine.hasOption(this)) { throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, getPreferredName()); } super.validate(commandLine); } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { // do we display optionality final boolean optional = !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); if (optional) { buffer.append('['); } buffer.append(preferredName); if (displayAliases && !aliases.isEmpty()) { buffer.append(" ("); final List list = new ArrayList(aliases); Collections.sort(list); for (final Iterator i = list.iterator(); i.hasNext();) { final String alias = (String) i.next(); buffer.append(alias); if (i.hasNext()) { buffer.append(','); } } buffer.append(')'); } super.appendUsage(buffer, helpSettings, comp); if (optional) { buffer.append(']'); } } public String getPreferredName() { return preferredName; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/option/DefaultOption.java b/src/java/org/apache/commons/cli2/option/DefaultOption.java index d5246e1b7..5e18ea79c 100644 --- a/src/java/org/apache/commons/cli2/option/DefaultOption.java +++ b/src/java/org/apache/commons/cli2/option/DefaultOption.java @@ -1,221 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.resource.ResourceConstants; - -/** - * A Parent implementation representing normal options. - */ -public class DefaultOption - extends ParentImpl { - /** - * The default token used to prefix a short option - */ - public static final String DEFAULT_SHORT_PREFIX = "-"; - - /** - * The default token used to prefix a long option - */ - public static final String DEFAULT_LONG_PREFIX = "--"; - - /** - * The default value for the burstEnabled constructor parameter - */ - public static final boolean DEFAULT_BURST_ENABLED = true; - private final String preferredName; - private final Set aliases; - private final Set burstAliases; - private final Set triggers; - private final Set prefixes; - private final String shortPrefix; - private final boolean burstEnabled; - private final int burstLength; - - /** - * Creates a new DefaultOption - * - * @param shortPrefix the prefix used for short options - * @param longPrefix the prefix used for long options - * @param burstEnabled should option bursting be enabled - * @param preferredName the preferred name for this Option, this should begin with either shortPrefix or longPrefix - * @param description a description of this Option - * @param aliases the alternative names for this Option - * @param burstAliases the aliases that can be burst - * @param required whether the Option is strictly required - * @param argument the Argument belonging to this Parent, or null - * @param children the Group children belonging to this Parent, ot null - * @param id the unique identifier for this Option - * @throws IllegalArgumentException if the preferredName or an alias isn't - * prefixed with shortPrefix or longPrefix - */ - public DefaultOption(final String shortPrefix, - final String longPrefix, - final boolean burstEnabled, - final String preferredName, - final String description, - final Set aliases, - final Set burstAliases, - final boolean required, - final Argument argument, - final Group children, - final int id) { - super(argument, children, description, id, required); - - this.shortPrefix = shortPrefix; - this.burstEnabled = burstEnabled; - - this.burstLength = shortPrefix.length() + 1; - - this.preferredName = preferredName; - this.aliases = - (aliases == null) ? Collections.EMPTY_SET - : Collections.unmodifiableSet(new HashSet(aliases)); - - this.burstAliases = - (burstAliases == null) ? Collections.EMPTY_SET - : Collections.unmodifiableSet(new HashSet(burstAliases)); - - final Set newTriggers = new HashSet(); - newTriggers.add(preferredName); - newTriggers.addAll(this.aliases); - newTriggers.addAll(this.burstAliases); - this.triggers = Collections.unmodifiableSet(newTriggers); - - final Set newPrefixes = new HashSet(super.getPrefixes()); - newPrefixes.add(shortPrefix); - newPrefixes.add(longPrefix); - this.prefixes = Collections.unmodifiableSet(newPrefixes); - - checkPrefixes(newPrefixes); - } - - public boolean canProcess(final WriteableCommandLine commandLine, - final String argument) { - return (argument != null) && - (super.canProcess(commandLine, argument) || - ((argument.length() >= burstLength) && - burstAliases.contains(argument.substring(0, burstLength)))); - } - - public void processParent(WriteableCommandLine commandLine, - ListIterator arguments) - throws OptionException { - final String argument = (String) arguments.next(); - - if (triggers.contains(argument)) { - commandLine.addOption(this); - arguments.set(preferredName); - } else if (burstEnabled && (argument.length() >= burstLength)) { - final String burst = argument.substring(0, burstLength); - - if (burstAliases.contains(burst)) { - commandLine.addOption(this); - - //HMM test bursting all vs bursting one by one. - arguments.set(preferredName); - - if (getArgument() == null) { - arguments.add(shortPrefix + argument.substring(burstLength)); - } else { - arguments.add(argument.substring(burstLength)); - } - - arguments.previous(); - } else { - throw new OptionException(this, ResourceConstants.CANNOT_BURST, argument); - } - } else { - throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, argument); - } - } - - public Set getTriggers() { - return triggers; - } - - public Set getPrefixes() { - return prefixes; - } - - public void validate(WriteableCommandLine commandLine) - throws OptionException { - if (isRequired() && !commandLine.hasOption(this)) { - throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, - getPreferredName()); - } - - super.validate(commandLine); - } - - public void appendUsage(final StringBuffer buffer, - final Set helpSettings, - final Comparator comp) { - // do we display optionality - final boolean optional = - !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); - final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); - - if (optional) { - buffer.append('['); - } - - buffer.append(preferredName); - - if (displayAliases && !aliases.isEmpty()) { - buffer.append(" ("); - - final List list = new ArrayList(aliases); - Collections.sort(list); - - for (final Iterator i = list.iterator(); i.hasNext();) { - final String alias = (String) i.next(); - buffer.append(alias); - - if (i.hasNext()) { - buffer.append(','); - } - } - - buffer.append(')'); - } - - super.appendUsage(buffer, helpSettings, comp); - - if (optional) { - buffer.append(']'); - } - } - - public String getPreferredName() { - return preferredName; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;/** * A Parent implementation representing normal options. */public class DefaultOption extends ParentImpl { /** * The default token used to prefix a short option */ public static final String DEFAULT_SHORT_PREFIX = "-"; /** * The default token used to prefix a long option */ public static final String DEFAULT_LONG_PREFIX = "--"; /** * The default value for the burstEnabled constructor parameter */ public static final boolean DEFAULT_BURST_ENABLED = true; private final String preferredName; private final Set aliases; private final Set burstAliases; private final Set triggers; private final Set prefixes; private final String shortPrefix; private final boolean burstEnabled; private final int burstLength; /** * Creates a new DefaultOption * * @param shortPrefix the prefix used for short options * @param longPrefix the prefix used for long options * @param burstEnabled should option bursting be enabled * @param preferredName the preferred name for this Option, this should begin with either shortPrefix or longPrefix * @param description a description of this Option * @param aliases the alternative names for this Option * @param burstAliases the aliases that can be burst * @param required whether the Option is strictly required * @param argument the Argument belonging to this Parent, or null * @param children the Group children belonging to this Parent, ot null * @param id the unique identifier for this Option * @throws IllegalArgumentException if the preferredName or an alias isn't * prefixed with shortPrefix or longPrefix */ public DefaultOption(final String shortPrefix, final String longPrefix, final boolean burstEnabled, final String preferredName, final String description, final Set aliases, final Set burstAliases, final boolean required, final Argument argument, final Group children, final int id) { super(argument, children, description, id, required); this.shortPrefix = shortPrefix; this.burstEnabled = burstEnabled; this.burstLength = shortPrefix.length() + 1; this.preferredName = preferredName; this.aliases = (aliases == null) ? Collections.EMPTY_SET : Collections.unmodifiableSet(new HashSet(aliases)); this.burstAliases = (burstAliases == null) ? Collections.EMPTY_SET : Collections.unmodifiableSet(new HashSet(burstAliases)); final Set newTriggers = new HashSet(); newTriggers.add(preferredName); newTriggers.addAll(this.aliases); newTriggers.addAll(this.burstAliases); this.triggers = Collections.unmodifiableSet(newTriggers); final Set newPrefixes = new HashSet(super.getPrefixes()); newPrefixes.add(shortPrefix); newPrefixes.add(longPrefix); this.prefixes = Collections.unmodifiableSet(newPrefixes); checkPrefixes(newPrefixes); } public boolean canProcess(final WriteableCommandLine commandLine, final String argument) { return (argument != null) && (super.canProcess(commandLine, argument) || ((argument.length() >= burstLength) && burstAliases.contains(argument.substring(0, burstLength)))); } public void processParent(WriteableCommandLine commandLine, ListIterator arguments) throws OptionException { final String argument = (String) arguments.next(); if (triggers.contains(argument)) { commandLine.addOption(this); arguments.set(preferredName); } else if (burstEnabled && (argument.length() >= burstLength)) { final String burst = argument.substring(0, burstLength); if (burstAliases.contains(burst)) { commandLine.addOption(this); //HMM test bursting all vs bursting one by one. arguments.set(preferredName); if (getArgument() == null) { arguments.add(shortPrefix + argument.substring(burstLength)); } else { arguments.add(argument.substring(burstLength)); } arguments.previous(); } else { throw new OptionException(this, ResourceConstants.CANNOT_BURST, argument); } } else { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, argument); } } public Set getTriggers() { return triggers; } public Set getPrefixes() { return prefixes; } public void validate(WriteableCommandLine commandLine) throws OptionException { if (isRequired() && !commandLine.hasOption(this)) { throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, getPreferredName()); } super.validate(commandLine); } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { // do we display optionality final boolean optional = !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); if (optional) { buffer.append('['); } buffer.append(preferredName); if (displayAliases && !aliases.isEmpty()) { buffer.append(" ("); final List list = new ArrayList(aliases); Collections.sort(list); for (final Iterator i = list.iterator(); i.hasNext();) { final String alias = (String) i.next(); buffer.append(alias); if (i.hasNext()) { buffer.append(','); } } buffer.append(')'); } super.appendUsage(buffer, helpSettings, comp); if (optional) { buffer.append(']'); } } public String getPreferredName() { return preferredName; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/option/GroupImpl.java b/src/java/org/apache/commons/cli2/option/GroupImpl.java index e6a84dd51..b8bbffa5f 100644 --- a/src/java/org/apache/commons/cli2/option/GroupImpl.java +++ b/src/java/org/apache/commons/cli2/option/GroupImpl.java @@ -1,517 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.HelpLine; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.resource.ResourceConstants; - -/** - * An implementation of Group - */ -public class GroupImpl - extends OptionImpl implements Group { - private final String name; - private final String description; - private final List options; - private final int minimum; - private final int maximum; - private final List anonymous; - private final SortedMap optionMap; - private final Set prefixes; - - /** - * Creates a new GroupImpl using the specified parameters. - * - * @param options the Options and Arguments that make up the Group - * @param name the name of this Group, or null - * @param description a description of this Group - * @param minimum the minimum number of Options for a valid CommandLine - * @param maximum the maximum number of Options for a valid CommandLine - */ - public GroupImpl(final List options, - final String name, - final String description, - final int minimum, - final int maximum) { - super(0, false); - - this.name = name; - this.description = description; - this.minimum = minimum; - this.maximum = maximum; - - // store a copy of the options to be used by the - // help methods - this.options = Collections.unmodifiableList(options); - - // anonymous Argument temporary storage - final List newAnonymous = new ArrayList(); - - // map (key=trigger & value=Option) temporary storage - final SortedMap newOptionMap = new TreeMap(ReverseStringComparator.getInstance()); - - // prefixes temporary storage - final Set newPrefixes = new HashSet(); - - // process the options - for (final Iterator i = options.iterator(); i.hasNext();) { - final Option option = (Option) i.next(); - - if (option instanceof Argument) { - i.remove(); - newAnonymous.add(option); - } else { - final Set triggers = option.getTriggers(); - - for (Iterator j = triggers.iterator(); j.hasNext();) { - newOptionMap.put(j.next(), option); - } - - // store the prefixes - newPrefixes.addAll(option.getPrefixes()); - } - } - - this.anonymous = Collections.unmodifiableList(newAnonymous); - this.optionMap = Collections.unmodifiableSortedMap(newOptionMap); - this.prefixes = Collections.unmodifiableSet(newPrefixes); - } - - public boolean canProcess(final WriteableCommandLine commandLine, - final String arg) { - if (arg == null) { - return false; - } - - // if arg does not require bursting - if (optionMap.containsKey(arg)) { - return true; - } - - // filter - final Map tailMap = optionMap.tailMap(arg); - - // check if bursting is required - for (final Iterator iter = tailMap.values().iterator(); iter.hasNext();) { - final Option option = (Option) iter.next(); - - if (option.canProcess(commandLine, arg)) { - return true; - } - } - - if (commandLine.looksLikeOption(arg)) { - return false; - } - - // anonymous argument(s) means we can process it - if (anonymous.size() > 0) { - return true; - } - - return false; - } - - public Set getPrefixes() { - return prefixes; - } - - public Set getTriggers() { - return optionMap.keySet(); - } - - public void process(final WriteableCommandLine commandLine, - final ListIterator arguments) - throws OptionException { - String previous = null; - - // [START process each command line token - while (arguments.hasNext()) { - // grab the next argument - final String arg = (String) arguments.next(); - - // if we have just tried to process this instance - if (arg == previous) { - // rollback and abort - arguments.previous(); - - break; - } - - // remember last processed instance - previous = arg; - - final Option opt = (Option) optionMap.get(arg); - - // option found - if (opt != null) { - arguments.previous(); - opt.process(commandLine, arguments); - } - // [START option NOT found - else { - // it might be an anonymous argument continue search - // [START argument may be anonymous - if (commandLine.looksLikeOption(arg)) { - // narrow the search - final Collection values = optionMap.tailMap(arg).values(); - - boolean foundMemberOption = false; - - for (Iterator i = values.iterator(); i.hasNext() && !foundMemberOption;) { - final Option option = (Option) i.next(); - - if (option.canProcess(commandLine, arg)) { - foundMemberOption = true; - arguments.previous(); - option.process(commandLine, arguments); - } - } - - // back track and abort this group if necessary - if (!foundMemberOption) { - arguments.previous(); - - return; - } - } // [END argument may be anonymous - - // [START argument is NOT anonymous - else { - // move iterator back, current value not used - arguments.previous(); - - // if there are no anonymous arguments then this group can't - // process the argument - if (anonymous.isEmpty()) { - break; - } - - // TODO: why do we iterate over all anonymous arguments? - // canProcess will always return true? - for (final Iterator i = anonymous.iterator(); i.hasNext();) { - final Argument argument = (Argument) i.next(); - - if (argument.canProcess(commandLine, arguments)) { - argument.process(commandLine, arguments); - } - } - } // [END argument is NOT anonymous - } // [END option NOT found - } // [END process each command line token - } - - public void validate(final WriteableCommandLine commandLine) - throws OptionException { - // number of options found - int present = 0; - - // reference to first unexpected option - Option unexpected = null; - - for (final Iterator i = options.iterator(); i.hasNext();) { - final Option option = (Option) i.next(); - - // if the child option is required then validate it - if (option.isRequired()) { - option.validate(commandLine); - } - - if (option instanceof Group) { - option.validate(commandLine); - } - - // if the child option is present then validate it - if (commandLine.hasOption(option)) { - if (++present > maximum) { - unexpected = option; - - break; - } - - option.validate(commandLine); - } - } - - // too many options - if (unexpected != null) { - throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, - unexpected.getPreferredName()); - } - - // too few option - if (present < minimum) { - throw new OptionException(this, ResourceConstants.MISSING_OPTION); - } - - // validate each anonymous argument - for (final Iterator i = anonymous.iterator(); i.hasNext();) { - final Option option = (Option) i.next(); - option.validate(commandLine); - } - } - - public String getPreferredName() { - return name; - } - - public String getDescription() { - return description; - } - - public void appendUsage(final StringBuffer buffer, - final Set helpSettings, - final Comparator comp) { - appendUsage(buffer, helpSettings, comp, "|"); - } - - public void appendUsage(final StringBuffer buffer, - final Set helpSettings, - final Comparator comp, - final String separator) { - final Set helpSettingsCopy = new HashSet(helpSettings); - - final boolean optional = - (minimum == 0) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_OPTIONAL); - - final boolean expanded = - (name == null) || helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED); - - final boolean named = - !expanded || - ((name != null) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_NAME)); - - final boolean arguments = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT); - - final boolean outer = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_OUTER); - - helpSettingsCopy.remove(DisplaySetting.DISPLAY_GROUP_OUTER); - - final boolean both = named && expanded; - - if (optional) { - buffer.append('['); - } - - if (named) { - buffer.append(name); - } - - if (both) { - buffer.append(" ("); - } - - if (expanded) { - final Set childSettings; - - if (!helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) { - childSettings = DisplaySetting.NONE; - } else { - childSettings = new HashSet(helpSettingsCopy); - childSettings.remove(DisplaySetting.DISPLAY_OPTIONAL); - } - - // grab a list of the group's options. - final List list; - - if (comp == null) { - // default to using the initial order - list = options; - } else { - // sort options if comparator is supplied - list = new ArrayList(options); - Collections.sort(list, comp); - } - - // for each option. - for (final Iterator i = list.iterator(); i.hasNext();) { - final Option option = (Option) i.next(); - - // append usage information - option.appendUsage(buffer, childSettings, comp); - - // add separators as needed - if (i.hasNext()) { - buffer.append(separator); - } - } - } - - if (both) { - buffer.append(')'); - } - - if (optional && outer) { - buffer.append(']'); - } - - if (arguments) { - for (final Iterator i = anonymous.iterator(); i.hasNext();) { - buffer.append(' '); - - final Option option = (Option) i.next(); - option.appendUsage(buffer, helpSettingsCopy, comp); - } - } - - if (optional && !outer) { - buffer.append(']'); - } - } - - public List helpLines(final int depth, - final Set helpSettings, - final Comparator comp) { - final List helpLines = new ArrayList(); - - if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_NAME)) { - final HelpLine helpLine = new HelpLineImpl(this, depth); - helpLines.add(helpLine); - } - - if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) { - // grab a list of the group's options. - final List list; - - if (comp == null) { - // default to using the initial order - list = options; - } else { - // sort options if comparator is supplied - list = new ArrayList(options); - Collections.sort(list, comp); - } - - // for each option - for (final Iterator i = list.iterator(); i.hasNext();) { - final Option option = (Option) i.next(); - helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp)); - } - } - - if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT)) { - for (final Iterator i = anonymous.iterator(); i.hasNext();) { - final Option option = (Option) i.next(); - helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp)); - } - } - - return helpLines; - } - - /** - * Gets the member Options of thie Group. - * Note this does not include any Arguments - * @return only the non Argument Options of the Group - */ - public List getOptions() { - return options; - } - - /** - * Gets the anonymous Arguments of this Group. - * @return the Argument options of this Group - */ - public List getAnonymous() { - return anonymous; - } - - public Option findOption(final String trigger) { - final Iterator i = getOptions().iterator(); - - while (i.hasNext()) { - final Option option = (Option) i.next(); - final Option found = option.findOption(trigger); - - if (found != null) { - return found; - } - } - - return null; - } - - public int getMinimum() { - return minimum; - } - - public int getMaximum() { - return maximum; - } - - public boolean isRequired() { - return getMinimum() > 0; - } - - public void defaults(final WriteableCommandLine commandLine) { - super.defaults(commandLine); - - for (final Iterator i = options.iterator(); i.hasNext();) { - final Option option = (Option) i.next(); - option.defaults(commandLine); - } - - for (final Iterator i = anonymous.iterator(); i.hasNext();) { - final Option option = (Option) i.next(); - option.defaults(commandLine); - } - } -} - - -class ReverseStringComparator implements Comparator { - private static final Comparator instance = new ReverseStringComparator(); - - private ReverseStringComparator() { - // just making sure nobody else creates one - } - - /** - * Gets a singleton instance of a ReverseStringComparator - * @return the singleton instance - */ - public static final Comparator getInstance() { - return instance; - } - - public int compare(final Object o1, - final Object o2) { - final String s1 = (String) o1; - final String s2 = (String) o2; - - return -s1.compareTo(s2); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Map;import java.util.Set;import java.util.SortedMap;import java.util.TreeMap;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;/** * An implementation of Group */public class GroupImpl extends OptionImpl implements Group { private final String name; private final String description; private final List options; private final int minimum; private final int maximum; private final List anonymous; private final SortedMap optionMap; private final Set prefixes; /** * Creates a new GroupImpl using the specified parameters. * * @param options the Options and Arguments that make up the Group * @param name the name of this Group, or null * @param description a description of this Group * @param minimum the minimum number of Options for a valid CommandLine * @param maximum the maximum number of Options for a valid CommandLine */ public GroupImpl(final List options, final String name, final String description, final int minimum, final int maximum) { super(0, false); this.name = name; this.description = description; this.minimum = minimum; this.maximum = maximum; // store a copy of the options to be used by the // help methods this.options = Collections.unmodifiableList(options); // anonymous Argument temporary storage final List newAnonymous = new ArrayList(); // map (key=trigger & value=Option) temporary storage final SortedMap newOptionMap = new TreeMap(ReverseStringComparator.getInstance()); // prefixes temporary storage final Set newPrefixes = new HashSet(); // process the options for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); if (option instanceof Argument) { i.remove(); newAnonymous.add(option); } else { final Set triggers = option.getTriggers(); for (Iterator j = triggers.iterator(); j.hasNext();) { newOptionMap.put(j.next(), option); } // store the prefixes newPrefixes.addAll(option.getPrefixes()); } } this.anonymous = Collections.unmodifiableList(newAnonymous); this.optionMap = Collections.unmodifiableSortedMap(newOptionMap); this.prefixes = Collections.unmodifiableSet(newPrefixes); } public boolean canProcess(final WriteableCommandLine commandLine, final String arg) { if (arg == null) { return false; } // if arg does not require bursting if (optionMap.containsKey(arg)) { return true; } // filter final Map tailMap = optionMap.tailMap(arg); // check if bursting is required for (final Iterator iter = tailMap.values().iterator(); iter.hasNext();) { final Option option = (Option) iter.next(); if (option.canProcess(commandLine, arg)) { return true; } } if (commandLine.looksLikeOption(arg)) { return false; } // anonymous argument(s) means we can process it if (anonymous.size() > 0) { return true; } return false; } public Set getPrefixes() { return prefixes; } public Set getTriggers() { return optionMap.keySet(); } public void process(final WriteableCommandLine commandLine, final ListIterator arguments) throws OptionException { String previous = null; // [START process each command line token while (arguments.hasNext()) { // grab the next argument final String arg = (String) arguments.next(); // if we have just tried to process this instance if (arg == previous) { // rollback and abort arguments.previous(); break; } // remember last processed instance previous = arg; final Option opt = (Option) optionMap.get(arg); // option found if (opt != null) { arguments.previous(); opt.process(commandLine, arguments); } // [START option NOT found else { // it might be an anonymous argument continue search // [START argument may be anonymous if (commandLine.looksLikeOption(arg)) { // narrow the search final Collection values = optionMap.tailMap(arg).values(); boolean foundMemberOption = false; for (Iterator i = values.iterator(); i.hasNext() && !foundMemberOption;) { final Option option = (Option) i.next(); if (option.canProcess(commandLine, arg)) { foundMemberOption = true; arguments.previous(); option.process(commandLine, arguments); } } // back track and abort this group if necessary if (!foundMemberOption) { arguments.previous(); return; } } // [END argument may be anonymous // [START argument is NOT anonymous else { // move iterator back, current value not used arguments.previous(); // if there are no anonymous arguments then this group can't // process the argument if (anonymous.isEmpty()) { break; } // TODO: why do we iterate over all anonymous arguments? // canProcess will always return true? for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Argument argument = (Argument) i.next(); if (argument.canProcess(commandLine, arguments)) { argument.process(commandLine, arguments); } } } // [END argument is NOT anonymous } // [END option NOT found } // [END process each command line token } public void validate(final WriteableCommandLine commandLine) throws OptionException { // number of options found int present = 0; // reference to first unexpected option Option unexpected = null; for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); // if the child option is required then validate it if (option.isRequired()) { option.validate(commandLine); } if (option instanceof Group) { option.validate(commandLine); } // if the child option is present then validate it if (commandLine.hasOption(option)) { if (++present > maximum) { unexpected = option; break; } option.validate(commandLine); } } // too many options if (unexpected != null) { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, unexpected.getPreferredName()); } // too few option if (present < minimum) { throw new OptionException(this, ResourceConstants.MISSING_OPTION); } // validate each anonymous argument for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Option option = (Option) i.next(); option.validate(commandLine); } } public String getPreferredName() { return name; } public String getDescription() { return description; } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { appendUsage(buffer, helpSettings, comp, "|"); } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp, final String separator) { final Set helpSettingsCopy = new HashSet(helpSettings); final boolean optional = (minimum == 0) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_OPTIONAL); final boolean expanded = (name == null) || helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED); final boolean named = !expanded || ((name != null) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_NAME)); final boolean arguments = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT); final boolean outer = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_OUTER); helpSettingsCopy.remove(DisplaySetting.DISPLAY_GROUP_OUTER); final boolean both = named && expanded; if (optional) { buffer.append('['); } if (named) { buffer.append(name); } if (both) { buffer.append(" ("); } if (expanded) { final Set childSettings; if (!helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) { childSettings = DisplaySetting.NONE; } else { childSettings = new HashSet(helpSettingsCopy); childSettings.remove(DisplaySetting.DISPLAY_OPTIONAL); } // grab a list of the group's options. final List list; if (comp == null) { // default to using the initial order list = options; } else { // sort options if comparator is supplied list = new ArrayList(options); Collections.sort(list, comp); } // for each option. for (final Iterator i = list.iterator(); i.hasNext();) { final Option option = (Option) i.next(); // append usage information option.appendUsage(buffer, childSettings, comp); // add separators as needed if (i.hasNext()) { buffer.append(separator); } } } if (both) { buffer.append(')'); } if (optional && outer) { buffer.append(']'); } if (arguments) { for (final Iterator i = anonymous.iterator(); i.hasNext();) { buffer.append(' '); final Option option = (Option) i.next(); option.appendUsage(buffer, helpSettingsCopy, comp); } } if (optional && !outer) { buffer.append(']'); } } public List helpLines(final int depth, final Set helpSettings, final Comparator comp) { final List helpLines = new ArrayList(); if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_NAME)) { final HelpLine helpLine = new HelpLineImpl(this, depth); helpLines.add(helpLine); } if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) { // grab a list of the group's options. final List list; if (comp == null) { // default to using the initial order list = options; } else { // sort options if comparator is supplied list = new ArrayList(options); Collections.sort(list, comp); } // for each option for (final Iterator i = list.iterator(); i.hasNext();) { final Option option = (Option) i.next(); helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp)); } } if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT)) { for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Option option = (Option) i.next(); helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp)); } } return helpLines; } /** * Gets the member Options of thie Group. * Note this does not include any Arguments * @return only the non Argument Options of the Group */ public List getOptions() { return options; } /** * Gets the anonymous Arguments of this Group. * @return the Argument options of this Group */ public List getAnonymous() { return anonymous; } public Option findOption(final String trigger) { final Iterator i = getOptions().iterator(); while (i.hasNext()) { final Option option = (Option) i.next(); final Option found = option.findOption(trigger); if (found != null) { return found; } } return null; } public int getMinimum() { return minimum; } public int getMaximum() { return maximum; } public boolean isRequired() { return getMinimum() > 0; } public void defaults(final WriteableCommandLine commandLine) { super.defaults(commandLine); for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); option.defaults(commandLine); } for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Option option = (Option) i.next(); option.defaults(commandLine); } }}class ReverseStringComparator implements Comparator { private static final Comparator instance = new ReverseStringComparator(); private ReverseStringComparator() { // just making sure nobody else creates one } /** * Gets a singleton instance of a ReverseStringComparator * @return the singleton instance */ public static final Comparator getInstance() { return instance; } public int compare(final Object o1, final Object o2) { final String s1 = (String) o1; final String s2 = (String) o2; return -s1.compareTo(s2); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/option/HelpLineImpl.java b/src/java/org/apache/commons/cli2/option/HelpLineImpl.java index da938c89e..144076e5c 100644 --- a/src/java/org/apache/commons/cli2/option/HelpLineImpl.java +++ b/src/java/org/apache/commons/cli2/option/HelpLineImpl.java @@ -1,110 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.Comparator; -import java.util.Set; - -import org.apache.commons.cli2.HelpLine; -import org.apache.commons.cli2.Option; - -/** - * Represents a line in the help screen. - */ -public class HelpLineImpl implements HelpLine { - - /** The option that this HelpLineImpl describes */ - private final Option option; - - /** The level of indenting for this item */ - private final int indent; - - /** The help settings used to obtain the previous usage */ - private transient Set cachedHelpSettings; - - /** The comparator used to obtain the previous usage */ - private transient Comparator cachedComparator; - - /** The previously obtained usage */ - private transient String cachedUsage; - - /** - * Creates a new HelpLineImpl to represent a particular Option in the online - * help. - * - * @param option - * Option that the HelpLineImpl describes - * @param indent - * Level of indentation for this line - */ - public HelpLineImpl(final Option option, final int indent) { - this.option = option; - this.indent = indent; - } - - /** - * @return The description of the option - */ - public String getDescription() { - return option.getDescription(); - } - - /** - * @return The level of indentation for this line - */ - public int getIndent() { - return indent; - } - - /** - * @return The Option that the help line relates to - */ - public Option getOption() { - return option; - } - - /** - * Builds a usage string for the option using the specified settings and - * comparator. - * - * - * @param helpSettings the settings to apply - * @param comparator a comparator to sort options when applicable - * @return the usage string - */ - public String usage(final Set helpSettings, final Comparator comparator) { - if (cachedUsage == null - || cachedHelpSettings != helpSettings - || cachedComparator != comparator) { - - // cache the arguments to avoid redoing work - cachedHelpSettings = helpSettings; - cachedComparator = comparator; - - // build the new buffer - final StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < indent; ++i) { - buffer.append(" "); - } - option.appendUsage(buffer, helpSettings, comparator); - - // cache the usage string - cachedUsage = buffer.toString(); - } - return cachedUsage; - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Comparator;import java.util.Set;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;/** * Represents a line in the help screen. */public class HelpLineImpl implements HelpLine { /** The option that this HelpLineImpl describes */ private final Option option; /** The level of indenting for this item */ private final int indent; /** The help settings used to obtain the previous usage */ private transient Set cachedHelpSettings; /** The comparator used to obtain the previous usage */ private transient Comparator cachedComparator; /** The previously obtained usage */ private transient String cachedUsage; /** * Creates a new HelpLineImpl to represent a particular Option in the online * help. * * @param option * Option that the HelpLineImpl describes * @param indent * Level of indentation for this line */ public HelpLineImpl(final Option option, final int indent) { this.option = option; this.indent = indent; } /** * @return The description of the option */ public String getDescription() { return option.getDescription(); } /** * @return The level of indentation for this line */ public int getIndent() { return indent; } /** * @return The Option that the help line relates to */ public Option getOption() { return option; } /** * Builds a usage string for the option using the specified settings and * comparator. * * * @param helpSettings the settings to apply * @param comparator a comparator to sort options when applicable * @return the usage string */ public String usage(final Set helpSettings, final Comparator comparator) { if (cachedUsage == null || cachedHelpSettings != helpSettings || cachedComparator != comparator) { // cache the arguments to avoid redoing work cachedHelpSettings = helpSettings; cachedComparator = comparator; // build the new buffer final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < indent; ++i) { buffer.append(" "); } option.appendUsage(buffer, helpSettings, comparator); // cache the usage string cachedUsage = buffer.toString(); } return cachedUsage; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/option/OptionImpl.java b/src/java/org/apache/commons/cli2/option/OptionImpl.java index eab47a9bd..4a7f895c1 100644 --- a/src/java/org/apache/commons/cli2/option/OptionImpl.java +++ b/src/java/org/apache/commons/cli2/option/OptionImpl.java @@ -1,159 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.Iterator; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * A base implementation of Option providing limited ground work for further - * Option implementations. - */ -public abstract class OptionImpl implements Option { - private final int id; - private final boolean required; - - /** - * Creates an OptionImpl with the specified id - * @param id the unique id of this Option - * @param required true iff this Option must be present - */ - public OptionImpl(final int id, - final boolean required) { - this.id = id; - this.required = required; - } - - public boolean canProcess(final WriteableCommandLine commandLine, - final ListIterator arguments) { - if (arguments.hasNext()) { - final String argument = (String) arguments.next(); - arguments.previous(); - - return canProcess(commandLine, argument); - } else { - return false; - } - } - - public String toString() { - final StringBuffer buffer = new StringBuffer(); - appendUsage(buffer, DisplaySetting.ALL, null); - - return buffer.toString(); - } - - public int getId() { - return id; - } - - public boolean equals(final Object thatObj) { - if (thatObj instanceof OptionImpl) { - final OptionImpl that = (OptionImpl) thatObj; - - return (getId() == that.getId()) && - equals(getPreferredName(), that.getPreferredName()) && - equals(getDescription(), that.getDescription()) && - equals(getPrefixes(), that.getPrefixes()) && - equals(getTriggers(), that.getTriggers()); - } else { - return false; - } - } - - private boolean equals(Object left, - Object right) { - if ((left == null) && (right == null)) { - return true; - } else if ((left == null) || (right == null)) { - return false; - } else { - return left.equals(right); - } - } - - public int hashCode() { - int hashCode = getId(); - hashCode = (hashCode * 37) + getPreferredName().hashCode(); - - if (getDescription() != null) { - hashCode = (hashCode * 37) + getDescription().hashCode(); - } - - hashCode = (hashCode * 37) + getPrefixes().hashCode(); - hashCode = (hashCode * 37) + getTriggers().hashCode(); - - return hashCode; - } - - public Option findOption(String trigger) { - if (getTriggers().contains(trigger)) { - return this; - } else { - return null; - } - } - - public boolean isRequired() { - return required; - } - - public void defaults(final WriteableCommandLine commandLine) { - // nothing to do normally - } - - protected void checkPrefixes(final Set prefixes) { - // nothing to do if empty prefix list - if (prefixes.isEmpty()) { - return; - } - - // check preferred name - checkPrefix(prefixes, getPreferredName()); - - // check triggers - this.getTriggers(); - - for (final Iterator i = getTriggers().iterator(); i.hasNext();) { - checkPrefix(prefixes, (String) i.next()); - } - } - - private void checkPrefix(final Set prefixes, - final String trigger) { - for (final Iterator i = prefixes.iterator(); i.hasNext();) { - String prefix = (String) i.next(); - - if (trigger.startsWith(prefix)) { - return; - } - } - - final ResourceHelper helper = ResourceHelper.getResourceHelper(); - final String message = - helper.getMessage(ResourceConstants.OPTION_TRIGGER_NEEDS_PREFIX, trigger, - prefixes.toString()); - throw new IllegalArgumentException(message); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Iterator;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * A base implementation of Option providing limited ground work for further * Option implementations. */public abstract class OptionImpl implements Option { private final int id; private final boolean required; /** * Creates an OptionImpl with the specified id * @param id the unique id of this Option * @param required true iff this Option must be present */ public OptionImpl(final int id, final boolean required) { this.id = id; this.required = required; } public boolean canProcess(final WriteableCommandLine commandLine, final ListIterator arguments) { if (arguments.hasNext()) { final String argument = (String) arguments.next(); arguments.previous(); return canProcess(commandLine, argument); } else { return false; } } public String toString() { final StringBuffer buffer = new StringBuffer(); appendUsage(buffer, DisplaySetting.ALL, null); return buffer.toString(); } public int getId() { return id; } public boolean equals(final Object thatObj) { if (thatObj instanceof OptionImpl) { final OptionImpl that = (OptionImpl) thatObj; return (getId() == that.getId()) && equals(getPreferredName(), that.getPreferredName()) && equals(getDescription(), that.getDescription()) && equals(getPrefixes(), that.getPrefixes()) && equals(getTriggers(), that.getTriggers()); } else { return false; } } private boolean equals(Object left, Object right) { if ((left == null) && (right == null)) { return true; } else if ((left == null) || (right == null)) { return false; } else { return left.equals(right); } } public int hashCode() { int hashCode = getId(); hashCode = (hashCode * 37) + getPreferredName().hashCode(); if (getDescription() != null) { hashCode = (hashCode * 37) + getDescription().hashCode(); } hashCode = (hashCode * 37) + getPrefixes().hashCode(); hashCode = (hashCode * 37) + getTriggers().hashCode(); return hashCode; } public Option findOption(String trigger) { if (getTriggers().contains(trigger)) { return this; } else { return null; } } public boolean isRequired() { return required; } public void defaults(final WriteableCommandLine commandLine) { // nothing to do normally } protected void checkPrefixes(final Set prefixes) { // nothing to do if empty prefix list if (prefixes.isEmpty()) { return; } // check preferred name checkPrefix(prefixes, getPreferredName()); // check triggers this.getTriggers(); for (final Iterator i = getTriggers().iterator(); i.hasNext();) { checkPrefix(prefixes, (String) i.next()); } } private void checkPrefix(final Set prefixes, final String trigger) { for (final Iterator i = prefixes.iterator(); i.hasNext();) { String prefix = (String) i.next(); if (trigger.startsWith(prefix)) { return; } } final ResourceHelper helper = ResourceHelper.getResourceHelper(); final String message = helper.getMessage(ResourceConstants.OPTION_TRIGGER_NEEDS_PREFIX, trigger, prefixes.toString()); throw new IllegalArgumentException(message); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/option/ParentImpl.java b/src/java/org/apache/commons/cli2/option/ParentImpl.java index 064c80418..9ac08c9da 100644 --- a/src/java/org/apache/commons/cli2/option/ParentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ParentImpl.java @@ -1,257 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.Parent; -import org.apache.commons.cli2.WriteableCommandLine; - -/** - * A base implementation of Parent providing limited ground work for further - * Parent implementations. - */ -public abstract class ParentImpl - extends OptionImpl implements Parent { - private static final char NUL = '\0'; - private final Group children; - private final Argument argument; - private final String description; - - protected ParentImpl(final Argument argument, - final Group children, - final String description, - final int id, - final boolean required) { - super(id, required); - this.children = children; - this.argument = argument; - this.description = description; - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.Option#process(org.apache.commons.cli2.CommandLine, - * java.util.ListIterator) - */ - public void process(final WriteableCommandLine commandLine, - final ListIterator arguments) - throws OptionException { - if (argument != null) { - handleInitialSeparator(arguments, argument.getInitialSeparator()); - } - - processParent(commandLine, arguments); - - if (argument != null) { - argument.processValues(commandLine, arguments, this); - } - - if ((children != null) && children.canProcess(commandLine, arguments)) { - children.process(commandLine, arguments); - } - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.Option#canProcess(java.lang.String) - */ - public boolean canProcess(final WriteableCommandLine commandLine, - final String arg) { - final Set triggers = getTriggers(); - - if (argument != null) { - final char separator = argument.getInitialSeparator(); - - // if there is a valid separator character - if (separator != NUL) { - final int initialIndex = arg.indexOf(separator); - - // if there is a separator present - if (initialIndex > 0) { - return triggers.contains(arg.substring(0, initialIndex)); - } - } - } - - return triggers.contains(arg); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.Option#prefixes() - */ - public Set getPrefixes() { - return (children == null) ? Collections.EMPTY_SET : children.getPrefixes(); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.Option#validate(org.apache.commons.cli2.CommandLine) - */ - public void validate(WriteableCommandLine commandLine) - throws OptionException { - if (commandLine.hasOption(this)) { - if (argument != null) { - argument.validate(commandLine, this); - } - - if (children != null) { - children.validate(commandLine); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.Option#appendUsage(java.lang.StringBuffer, - * java.util.Set, java.util.Comparator) - */ - public void appendUsage(final StringBuffer buffer, - final Set helpSettings, - final Comparator comp) { - final boolean displayArgument = - (this.argument != null) && - helpSettings.contains(DisplaySetting.DISPLAY_PARENT_ARGUMENT); - final boolean displayChildren = - (this.children != null) && - helpSettings.contains(DisplaySetting.DISPLAY_PARENT_CHILDREN); - - if (displayArgument) { - buffer.append(' '); - argument.appendUsage(buffer, helpSettings, comp); - } - - if (displayChildren) { - buffer.append(' '); - children.appendUsage(buffer, helpSettings, comp); - } - } - - /** - * @return a description of this parent option - */ - public String getDescription() { - return description; - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.Option#helpLines(int, java.util.Set, - * java.util.Comparator) - */ - public List helpLines(final int depth, - final Set helpSettings, - final Comparator comp) { - final List helpLines = new ArrayList(); - helpLines.add(new HelpLineImpl(this, depth)); - - if (helpSettings.contains(DisplaySetting.DISPLAY_PARENT_ARGUMENT) && (argument != null)) { - helpLines.addAll(argument.helpLines(depth + 1, helpSettings, comp)); - } - - if (helpSettings.contains(DisplaySetting.DISPLAY_PARENT_CHILDREN) && (children != null)) { - helpLines.addAll(children.helpLines(depth + 1, helpSettings, comp)); - } - - return helpLines; - } - - /** - * @return Returns the argument. - */ - public Argument getArgument() { - return argument; - } - - /** - * @return Returns the children. - */ - public Group getChildren() { - return children; - } - - /** - * Split the token using the specified separator character. - * @param arguments the current position in the arguments iterator - * @param separator the separator char to split on - */ - private void handleInitialSeparator(final ListIterator arguments, - final char separator) { - // next token - final String newArgument = (String) arguments.next(); - - // split the token - final int initialIndex = newArgument.indexOf(separator); - - if (initialIndex > 0) { - arguments.remove(); - arguments.add(newArgument.substring(0, initialIndex)); - String value = newArgument.substring(initialIndex + 1); - // The value obviously isn't an option, so we need to quote it if looks like an option. - // The quotes will be removed later - if (value.startsWith("-")) { - value = '"' + value + '"'; - } - arguments.add(value); - arguments.previous(); - } - - arguments.previous(); - } - - /* - * @see org.apache.commons.cli2.Option#findOption(java.lang.String) - */ - public Option findOption(final String trigger) { - final Option found = super.findOption(trigger); - - if ((found == null) && (children != null)) { - return children.findOption(trigger); - } else { - return found; - } - } - - public void defaults(final WriteableCommandLine commandLine) { - super.defaults(commandLine); - - if (argument != null) { - argument.defaultValues(commandLine, this); - } - - if (children != null) { - children.defaults(commandLine); - } - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.Parent;import org.apache.commons.cli2.WriteableCommandLine;/** * A base implementation of Parent providing limited ground work for further * Parent implementations. */public abstract class ParentImpl extends OptionImpl implements Parent { private static final char NUL = '\0'; private final Group children; private final Argument argument; private final String description; protected ParentImpl(final Argument argument, final Group children, final String description, final int id, final boolean required) { super(id, required); this.children = children; this.argument = argument; this.description = description; } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#process(org.apache.commons.cli2.CommandLine, * java.util.ListIterator) */ public void process(final WriteableCommandLine commandLine, final ListIterator arguments) throws OptionException { if (argument != null) { handleInitialSeparator(arguments, argument.getInitialSeparator()); } processParent(commandLine, arguments); if (argument != null) { argument.processValues(commandLine, arguments, this); } if ((children != null) && children.canProcess(commandLine, arguments)) { children.process(commandLine, arguments); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#canProcess(java.lang.String) */ public boolean canProcess(final WriteableCommandLine commandLine, final String arg) { final Set triggers = getTriggers(); if (argument != null) { final char separator = argument.getInitialSeparator(); // if there is a valid separator character if (separator != NUL) { final int initialIndex = arg.indexOf(separator); // if there is a separator present if (initialIndex > 0) { return triggers.contains(arg.substring(0, initialIndex)); } } } return triggers.contains(arg); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#prefixes() */ public Set getPrefixes() { return (children == null) ? Collections.EMPTY_SET : children.getPrefixes(); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#validate(org.apache.commons.cli2.CommandLine) */ public void validate(WriteableCommandLine commandLine) throws OptionException { if (commandLine.hasOption(this)) { if (argument != null) { argument.validate(commandLine, this); } if (children != null) { children.validate(commandLine); } } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#appendUsage(java.lang.StringBuffer, * java.util.Set, java.util.Comparator) */ public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { final boolean displayArgument = (this.argument != null) && helpSettings.contains(DisplaySetting.DISPLAY_PARENT_ARGUMENT); final boolean displayChildren = (this.children != null) && helpSettings.contains(DisplaySetting.DISPLAY_PARENT_CHILDREN); if (displayArgument) { buffer.append(' '); argument.appendUsage(buffer, helpSettings, comp); } if (displayChildren) { buffer.append(' '); children.appendUsage(buffer, helpSettings, comp); } } /** * @return a description of this parent option */ public String getDescription() { return description; } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#helpLines(int, java.util.Set, * java.util.Comparator) */ public List helpLines(final int depth, final Set helpSettings, final Comparator comp) { final List helpLines = new ArrayList(); helpLines.add(new HelpLineImpl(this, depth)); if (helpSettings.contains(DisplaySetting.DISPLAY_PARENT_ARGUMENT) && (argument != null)) { helpLines.addAll(argument.helpLines(depth + 1, helpSettings, comp)); } if (helpSettings.contains(DisplaySetting.DISPLAY_PARENT_CHILDREN) && (children != null)) { helpLines.addAll(children.helpLines(depth + 1, helpSettings, comp)); } return helpLines; } /** * @return Returns the argument. */ public Argument getArgument() { return argument; } /** * @return Returns the children. */ public Group getChildren() { return children; } /** * Split the token using the specified separator character. * @param arguments the current position in the arguments iterator * @param separator the separator char to split on */ private void handleInitialSeparator(final ListIterator arguments, final char separator) { // next token final String newArgument = (String) arguments.next(); // split the token final int initialIndex = newArgument.indexOf(separator); if (initialIndex > 0) { arguments.remove(); arguments.add(newArgument.substring(0, initialIndex)); String value = newArgument.substring(initialIndex + 1); // The value obviously isn't an option, so we need to quote it if looks like an option. // The quotes will be removed later if (value.startsWith("-")) { value = '"' + value + '"'; } arguments.add(value); arguments.previous(); } arguments.previous(); } /* * @see org.apache.commons.cli2.Option#findOption(java.lang.String) */ public Option findOption(final String trigger) { final Option found = super.findOption(trigger); if ((found == null) && (children != null)) { return children.findOption(trigger); } else { return found; } } public void defaults(final WriteableCommandLine commandLine) { super.defaults(commandLine); if (argument != null) { argument.defaultValues(commandLine, this); } if (children != null) { children.defaults(commandLine); } }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/option/PropertyOption.java b/src/java/org/apache/commons/cli2/option/PropertyOption.java index 6c418eca0..83a5c5aea 100644 --- a/src/java/org/apache/commons/cli2/option/PropertyOption.java +++ b/src/java/org/apache/commons/cli2/option/PropertyOption.java @@ -1,167 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.HelpLine; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.resource.ResourceConstants; - -/** - * Handles the java style "-Dprop=value" opions - */ -public class PropertyOption - extends OptionImpl { - public static final String DEFAULT_OPTION_STRING = "-D"; - public static final String DEFAULT_DESCRIPTION = - "Passes properties and values to the application"; - - /** - * A default PropertyOption instance - */ - public static final PropertyOption INSTANCE = new PropertyOption(); - private final String optionString; - private final String description; - private final Set prefixes; - - /** - * Creates a new PropertyOption using the default settings of a "-D" trigger - * and an id of 'D' - */ - public PropertyOption() { - this(DEFAULT_OPTION_STRING, DEFAULT_DESCRIPTION, 'D'); - } - - /** - * Creates a new PropertyOption using the specified parameters - * @param optionString the trigger for the Option - * @param description the description of the Option - * @param id the id of the Option - */ - public PropertyOption(final String optionString, - final String description, - final int id) { - super(id, false); - this.optionString = optionString; - this.description = description; - this.prefixes = Collections.singleton(optionString); - } - - public boolean canProcess(final WriteableCommandLine commandLine, - final String argument) { - return (argument != null) && argument.startsWith(optionString) && - (argument.length() > optionString.length()); - } - - public Set getPrefixes() { - return prefixes; - } - - public void process(final WriteableCommandLine commandLine, - final ListIterator arguments) - throws OptionException { - final String arg = (String) arguments.next(); - - if (!canProcess(commandLine, arg)) { - throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); - } - - final int propertyStart = optionString.length(); - final int equalsIndex = arg.indexOf('=', propertyStart); - final String property; - final String value; - - if (equalsIndex < 0) { - property = arg.substring(propertyStart); - value = "true"; - } else { - property = arg.substring(propertyStart, equalsIndex); - value = arg.substring(equalsIndex + 1); - } - - commandLine.addProperty(property, value); - } - - public Set getTriggers() { - return Collections.singleton(optionString); - } - - public void validate(WriteableCommandLine commandLine) { - // PropertyOption needs no validation - } - - public void appendUsage(final StringBuffer buffer, - final Set helpSettings, - final Comparator comp) { - final boolean display = helpSettings.contains(DisplaySetting.DISPLAY_PROPERTY_OPTION); - - final boolean bracketed = helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); - - if (display) { - buffer.append(optionString); - - if (bracketed) { - buffer.append('<'); - } - - buffer.append("property"); - - if (bracketed) { - buffer.append('>'); - } - - buffer.append("="); - - if (bracketed) { - buffer.append('<'); - } - - buffer.append("value"); - - if (bracketed) { - buffer.append('>'); - } - } - } - - public String getPreferredName() { - return optionString; - } - - public String getDescription() { - return description; - } - - public List helpLines(final int depth, - final Set helpSettings, - final Comparator comp) { - if (helpSettings.contains(DisplaySetting.DISPLAY_PROPERTY_OPTION)) { - final HelpLine helpLine = new HelpLineImpl(this, depth); - - return Collections.singletonList(helpLine); - } else { - return Collections.EMPTY_LIST; - } - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;/** * Handles the java style "-Dprop=value" opions */public class PropertyOption extends OptionImpl { public static final String DEFAULT_OPTION_STRING = "-D"; public static final String DEFAULT_DESCRIPTION = "Passes properties and values to the application"; /** * A default PropertyOption instance */ public static final PropertyOption INSTANCE = new PropertyOption(); private final String optionString; private final String description; private final Set prefixes; /** * Creates a new PropertyOption using the default settings of a "-D" trigger * and an id of 'D' */ public PropertyOption() { this(DEFAULT_OPTION_STRING, DEFAULT_DESCRIPTION, 'D'); } /** * Creates a new PropertyOption using the specified parameters * @param optionString the trigger for the Option * @param description the description of the Option * @param id the id of the Option */ public PropertyOption(final String optionString, final String description, final int id) { super(id, false); this.optionString = optionString; this.description = description; this.prefixes = Collections.singleton(optionString); } public boolean canProcess(final WriteableCommandLine commandLine, final String argument) { return (argument != null) && argument.startsWith(optionString) && (argument.length() > optionString.length()); } public Set getPrefixes() { return prefixes; } public void process(final WriteableCommandLine commandLine, final ListIterator arguments) throws OptionException { final String arg = (String) arguments.next(); if (!canProcess(commandLine, arg)) { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); } final int propertyStart = optionString.length(); final int equalsIndex = arg.indexOf('=', propertyStart); final String property; final String value; if (equalsIndex < 0) { property = arg.substring(propertyStart); value = "true"; } else { property = arg.substring(propertyStart, equalsIndex); value = arg.substring(equalsIndex + 1); } commandLine.addProperty(property, value); } public Set getTriggers() { return Collections.singleton(optionString); } public void validate(WriteableCommandLine commandLine) { // PropertyOption needs no validation } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { final boolean display = helpSettings.contains(DisplaySetting.DISPLAY_PROPERTY_OPTION); final boolean bracketed = helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); if (display) { buffer.append(optionString); if (bracketed) { buffer.append('<'); } buffer.append("property"); if (bracketed) { buffer.append('>'); } buffer.append("="); if (bracketed) { buffer.append('<'); } buffer.append("value"); if (bracketed) { buffer.append('>'); } } } public String getPreferredName() { return optionString; } public String getDescription() { return description; } public List helpLines(final int depth, final Set helpSettings, final Comparator comp) { if (helpSettings.contains(DisplaySetting.DISPLAY_PROPERTY_OPTION)) { final HelpLine helpLine = new HelpLineImpl(this, depth); return Collections.singletonList(helpLine); } else { return Collections.EMPTY_LIST; } }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/option/SourceDestArgument.java b/src/java/org/apache/commons/cli2/option/SourceDestArgument.java index 52402fef9..2a346efd2 100644 --- a/src/java/org/apache/commons/cli2/option/SourceDestArgument.java +++ b/src/java/org/apache/commons/cli2/option/SourceDestArgument.java @@ -1,138 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * An Argument implementation that allows a variable size Argument to precede a - * fixed size argument. The canonical example of it's use is in the unix - * cp command where a number of source can be specified with - * exactly one destination specfied at the end. - */ -public class SourceDestArgument - extends ArgumentImpl { - private final Argument source; - private final Argument dest; - - /** - * Creates a SourceDestArgument using defaults where possible. - * - * @param source the variable size Argument - * @param dest the fixed size Argument - */ - public SourceDestArgument(final Argument source, - final Argument dest) { - this(source, dest, DEFAULT_INITIAL_SEPARATOR, DEFAULT_SUBSEQUENT_SEPARATOR, - DEFAULT_CONSUME_REMAINING, null); - } - - /** - * Creates a SourceDestArgument using the specified parameters. - * - * @param source the variable size Argument - * @param dest the fixed size Argument - * @param initialSeparator the inistial separator to use - * @param subsequentSeparator the subsequent separator to use - * @param consumeRemaining the token triggering consume remaining behaviour - * @param defaultValues the default values for the SourceDestArgument - */ - public SourceDestArgument(final Argument source, - final Argument dest, - final char initialSeparator, - final char subsequentSeparator, - final String consumeRemaining, - final List defaultValues) { - super("SourceDestArgument", null, sum(source.getMinimum(), dest.getMinimum()), - sum(source.getMaximum(), dest.getMaximum()), initialSeparator, subsequentSeparator, - null, consumeRemaining, defaultValues, 0); - - this.source = source; - this.dest = dest; - - if (dest.getMinimum() != dest.getMaximum()) { - throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SOURCE_DEST_MUST_ENFORCE_VALUES)); - } - } - - private static int sum(final int a, - final int b) { - return Math.max(a, Math.max(b, a + b)); - } - - public void appendUsage(final StringBuffer buffer, - final Set helpSettings, - final Comparator comp) { - final int length = buffer.length(); - - source.appendUsage(buffer, helpSettings, comp); - - if (buffer.length() != length) { - buffer.append(' '); - } - - dest.appendUsage(buffer, helpSettings, comp); - } - - public List helpLines(int depth, - Set helpSettings, - Comparator comp) { - final List helpLines = new ArrayList(); - helpLines.addAll(source.helpLines(depth, helpSettings, comp)); - helpLines.addAll(dest.helpLines(depth, helpSettings, comp)); - - return helpLines; - } - - public void validate(WriteableCommandLine commandLine, - Option option) - throws OptionException { - final List values = commandLine.getValues(option); - - final int limit = values.size() - dest.getMinimum(); - int count = 0; - - final Iterator i = values.iterator(); - - while (count++ < limit) { - commandLine.addValue(source, i.next()); - } - - while (i.hasNext()) { - commandLine.addValue(dest, i.next()); - } - - source.validate(commandLine, source); - dest.validate(commandLine, dest); - } - - public boolean canProcess(final WriteableCommandLine commandLine, - final String arg) { - return source.canProcess(commandLine, arg) || dest.canProcess(commandLine, arg); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Comparator;import java.util.Iterator;import java.util.List;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * An Argument implementation that allows a variable size Argument to precede a * fixed size argument. The canonical example of it's use is in the unix * cp command where a number of source can be specified with * exactly one destination specfied at the end. */public class SourceDestArgument extends ArgumentImpl { private final Argument source; private final Argument dest; /** * Creates a SourceDestArgument using defaults where possible. * * @param source the variable size Argument * @param dest the fixed size Argument */ public SourceDestArgument(final Argument source, final Argument dest) { this(source, dest, DEFAULT_INITIAL_SEPARATOR, DEFAULT_SUBSEQUENT_SEPARATOR, DEFAULT_CONSUME_REMAINING, null); } /** * Creates a SourceDestArgument using the specified parameters. * * @param source the variable size Argument * @param dest the fixed size Argument * @param initialSeparator the inistial separator to use * @param subsequentSeparator the subsequent separator to use * @param consumeRemaining the token triggering consume remaining behaviour * @param defaultValues the default values for the SourceDestArgument */ public SourceDestArgument(final Argument source, final Argument dest, final char initialSeparator, final char subsequentSeparator, final String consumeRemaining, final List defaultValues) { super("SourceDestArgument", null, sum(source.getMinimum(), dest.getMinimum()), sum(source.getMaximum(), dest.getMaximum()), initialSeparator, subsequentSeparator, null, consumeRemaining, defaultValues, 0); this.source = source; this.dest = dest; if (dest.getMinimum() != dest.getMaximum()) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SOURCE_DEST_MUST_ENFORCE_VALUES)); } } private static int sum(final int a, final int b) { return Math.max(a, Math.max(b, a + b)); } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { final int length = buffer.length(); source.appendUsage(buffer, helpSettings, comp); if (buffer.length() != length) { buffer.append(' '); } dest.appendUsage(buffer, helpSettings, comp); } public List helpLines(int depth, Set helpSettings, Comparator comp) { final List helpLines = new ArrayList(); helpLines.addAll(source.helpLines(depth, helpSettings, comp)); helpLines.addAll(dest.helpLines(depth, helpSettings, comp)); return helpLines; } public void validate(WriteableCommandLine commandLine, Option option) throws OptionException { final List values = commandLine.getValues(option); final int limit = values.size() - dest.getMinimum(); int count = 0; final Iterator i = values.iterator(); while (count++ < limit) { commandLine.addValue(source, i.next()); } while (i.hasNext()) { commandLine.addValue(dest, i.next()); } source.validate(commandLine, source); dest.validate(commandLine, dest); } public boolean canProcess(final WriteableCommandLine commandLine, final String arg) { return source.canProcess(commandLine, arg) || dest.canProcess(commandLine, arg); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/option/Switch.java b/src/java/org/apache/commons/cli2/option/Switch.java index 0781bb645..d4f68e3e2 100644 --- a/src/java/org/apache/commons/cli2/option/Switch.java +++ b/src/java/org/apache/commons/cli2/option/Switch.java @@ -1,248 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * A Parent implementation representing normal switch options. - * For example: +d|-d or --enable-x|--disable-x. - */ -public class Switch - extends ParentImpl { - /** i18n */ - public static final ResourceHelper resources = ResourceHelper.getResourceHelper(); - - /** - * The default prefix for enabled switches - */ - public static final String DEFAULT_ENABLED_PREFIX = "+"; - - /** - * The default prefix for disabled switches - */ - public static final String DEFAULT_DISABLED_PREFIX = "-"; - private final String enabledPrefix; - private final String disabledPrefix; - private final Set triggers; - private final String preferredName; - private final Set aliases; - private final Set prefixes; - private final Boolean defaultSwitch; - - /** - * Creates a new Switch with the specified parameters - * @param enabledPrefix the prefix used for enabled switches - * @param disabledPrefix the prefix used for disabled switches - * @param preferredName the preferred name of the switch - * @param aliases the aliases by which the Switch is known - * @param description a description of the Switch - * @param required whether the Option is strictly required - * @param argument the Argument belonging to this Parent, or null - * @param children the Group children belonging to this Parent, ot null - * @param id the unique identifier for this Option - * @throws IllegalArgumentException if the preferredName or an alias isn't - * prefixed with enabledPrefix or disabledPrefix - */ - public Switch(final String enabledPrefix, - final String disabledPrefix, - final String preferredName, - final Set aliases, - final String description, - final boolean required, - final Argument argument, - final Group children, - final int id, - final Boolean switchDefault) { - super(argument, children, description, id, required); - - if (enabledPrefix == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_NO_ENABLED_PREFIX)); - } - - if (disabledPrefix == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_NO_DISABLED_PREFIX)); - } - - if (enabledPrefix.startsWith(disabledPrefix)) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_ENABLED_STARTS_WITH_DISABLED)); - } - - if (disabledPrefix.startsWith(enabledPrefix)) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_DISABLED_STARTWS_WITH_ENABLED)); - } - - this.enabledPrefix = enabledPrefix; - this.disabledPrefix = disabledPrefix; - this.preferredName = preferredName; - - if ((preferredName == null) || (preferredName.length() < 1)) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT)); - } - - final Set newTriggers = new HashSet(); - newTriggers.add(enabledPrefix + preferredName); - newTriggers.add(disabledPrefix + preferredName); - this.triggers = Collections.unmodifiableSet(newTriggers); - - if (aliases == null) { - this.aliases = Collections.EMPTY_SET; - } else { - this.aliases = Collections.unmodifiableSet(new HashSet(aliases)); - - for (final Iterator i = aliases.iterator(); i.hasNext();) { - final String alias = (String) i.next(); - newTriggers.add(enabledPrefix + alias); - newTriggers.add(disabledPrefix + alias); - } - } - - final Set newPrefixes = new HashSet(super.getPrefixes()); - newPrefixes.add(enabledPrefix); - newPrefixes.add(disabledPrefix); - this.prefixes = Collections.unmodifiableSet(newPrefixes); - - this.defaultSwitch = switchDefault; - - checkPrefixes(newPrefixes); - } - - public void processParent(final WriteableCommandLine commandLine, - final ListIterator arguments) - throws OptionException { - final String arg = (String) arguments.next(); - - if (canProcess(commandLine, arg)) { - if (arg.startsWith(enabledPrefix)) { - commandLine.addSwitch(this, true); - arguments.set(enabledPrefix + preferredName); - } - - if (arg.startsWith(disabledPrefix)) { - commandLine.addSwitch(this, false); - arguments.set(disabledPrefix + preferredName); - } - } else { - throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); - } - } - - public Set getTriggers() { - return triggers; - } - - public Set getPrefixes() { - return prefixes; - } - - public void validate(WriteableCommandLine commandLine) - throws OptionException { - if (isRequired() && !commandLine.hasOption(this)) { - throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, - getPreferredName()); - } - - super.validate(commandLine); - } - - public void appendUsage(final StringBuffer buffer, - final Set helpSettings, - final Comparator comp) { - // do we display optionality - final boolean optional = - !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); - final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); - final boolean disabled = helpSettings.contains(DisplaySetting.DISPLAY_SWITCH_DISABLED); - final boolean enabled = - !disabled || helpSettings.contains(DisplaySetting.DISPLAY_SWITCH_ENABLED); - final boolean both = disabled && enabled; - - if (optional) { - buffer.append('['); - } - - if (enabled) { - buffer.append(enabledPrefix).append(preferredName); - } - - if (both) { - buffer.append('|'); - } - - if (disabled) { - buffer.append(disabledPrefix).append(preferredName); - } - - if (displayAliases && !aliases.isEmpty()) { - buffer.append(" ("); - - final List list = new ArrayList(aliases); - Collections.sort(list); - - for (final Iterator i = list.iterator(); i.hasNext();) { - final String alias = (String) i.next(); - - if (enabled) { - buffer.append(enabledPrefix).append(alias); - } - - if (both) { - buffer.append('|'); - } - - if (disabled) { - buffer.append(disabledPrefix).append(alias); - } - - if (i.hasNext()) { - buffer.append(','); - } - } - - buffer.append(')'); - } - - super.appendUsage(buffer, helpSettings, comp); - - if (optional) { - buffer.append(']'); - } - } - - public String getPreferredName() { - return enabledPrefix + preferredName; - } - - public void defaults(final WriteableCommandLine commandLine) { - commandLine.setDefaultSwitch(this, defaultSwitch); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * A Parent implementation representing normal switch options. * For example: +d|-d or --enable-x|--disable-x. */public class Switch extends ParentImpl { /** i18n */ public static final ResourceHelper resources = ResourceHelper.getResourceHelper(); /** * The default prefix for enabled switches */ public static final String DEFAULT_ENABLED_PREFIX = "+"; /** * The default prefix for disabled switches */ public static final String DEFAULT_DISABLED_PREFIX = "-"; private final String enabledPrefix; private final String disabledPrefix; private final Set triggers; private final String preferredName; private final Set aliases; private final Set prefixes; private final Boolean defaultSwitch; /** * Creates a new Switch with the specified parameters * @param enabledPrefix the prefix used for enabled switches * @param disabledPrefix the prefix used for disabled switches * @param preferredName the preferred name of the switch * @param aliases the aliases by which the Switch is known * @param description a description of the Switch * @param required whether the Option is strictly required * @param argument the Argument belonging to this Parent, or null * @param children the Group children belonging to this Parent, ot null * @param id the unique identifier for this Option * @throws IllegalArgumentException if the preferredName or an alias isn't * prefixed with enabledPrefix or disabledPrefix */ public Switch(final String enabledPrefix, final String disabledPrefix, final String preferredName, final Set aliases, final String description, final boolean required, final Argument argument, final Group children, final int id, final Boolean switchDefault) { super(argument, children, description, id, required); if (enabledPrefix == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_NO_ENABLED_PREFIX)); } if (disabledPrefix == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_NO_DISABLED_PREFIX)); } if (enabledPrefix.startsWith(disabledPrefix)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_ENABLED_STARTS_WITH_DISABLED)); } if (disabledPrefix.startsWith(enabledPrefix)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_DISABLED_STARTWS_WITH_ENABLED)); } this.enabledPrefix = enabledPrefix; this.disabledPrefix = disabledPrefix; this.preferredName = preferredName; if ((preferredName == null) || (preferredName.length() < 1)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT)); } final Set newTriggers = new HashSet(); newTriggers.add(enabledPrefix + preferredName); newTriggers.add(disabledPrefix + preferredName); this.triggers = Collections.unmodifiableSet(newTriggers); if (aliases == null) { this.aliases = Collections.EMPTY_SET; } else { this.aliases = Collections.unmodifiableSet(new HashSet(aliases)); for (final Iterator i = aliases.iterator(); i.hasNext();) { final String alias = (String) i.next(); newTriggers.add(enabledPrefix + alias); newTriggers.add(disabledPrefix + alias); } } final Set newPrefixes = new HashSet(super.getPrefixes()); newPrefixes.add(enabledPrefix); newPrefixes.add(disabledPrefix); this.prefixes = Collections.unmodifiableSet(newPrefixes); this.defaultSwitch = switchDefault; checkPrefixes(newPrefixes); } public void processParent(final WriteableCommandLine commandLine, final ListIterator arguments) throws OptionException { final String arg = (String) arguments.next(); if (canProcess(commandLine, arg)) { if (arg.startsWith(enabledPrefix)) { commandLine.addSwitch(this, true); arguments.set(enabledPrefix + preferredName); } if (arg.startsWith(disabledPrefix)) { commandLine.addSwitch(this, false); arguments.set(disabledPrefix + preferredName); } } else { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); } } public Set getTriggers() { return triggers; } public Set getPrefixes() { return prefixes; } public void validate(WriteableCommandLine commandLine) throws OptionException { if (isRequired() && !commandLine.hasOption(this)) { throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, getPreferredName()); } super.validate(commandLine); } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { // do we display optionality final boolean optional = !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); final boolean disabled = helpSettings.contains(DisplaySetting.DISPLAY_SWITCH_DISABLED); final boolean enabled = !disabled || helpSettings.contains(DisplaySetting.DISPLAY_SWITCH_ENABLED); final boolean both = disabled && enabled; if (optional) { buffer.append('['); } if (enabled) { buffer.append(enabledPrefix).append(preferredName); } if (both) { buffer.append('|'); } if (disabled) { buffer.append(disabledPrefix).append(preferredName); } if (displayAliases && !aliases.isEmpty()) { buffer.append(" ("); final List list = new ArrayList(aliases); Collections.sort(list); for (final Iterator i = list.iterator(); i.hasNext();) { final String alias = (String) i.next(); if (enabled) { buffer.append(enabledPrefix).append(alias); } if (both) { buffer.append('|'); } if (disabled) { buffer.append(disabledPrefix).append(alias); } if (i.hasNext()) { buffer.append(','); } } buffer.append(')'); } super.appendUsage(buffer, helpSettings, comp); if (optional) { buffer.append(']'); } } public String getPreferredName() { return enabledPrefix + preferredName; } public void defaults(final WriteableCommandLine commandLine) { commandLine.setDefaultSwitch(this, defaultSwitch); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/resource/ResourceConstants.java b/src/java/org/apache/commons/cli2/resource/ResourceConstants.java index c0b286f70..4bcc80077 100644 --- a/src/java/org/apache/commons/cli2/resource/ResourceConstants.java +++ b/src/java/org/apache/commons/cli2/resource/ResourceConstants.java @@ -1,70 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.commons.cli2.resource; - -public abstract class ResourceConstants { - public static final String CLASSVALIDATOR_BAD_CLASSNAME = "ClassValidator.bad.classname"; - public static final String CLASSVALIDATOR_CLASS_NOTFOUND = "ClassValidator.class.notfound"; - public static final String CLASSVALIDATOR_CLASS_ACCESS = "ClassValidator.class.access"; - public static final String CLASSVALIDATOR_CLASS_CREATE = "ClassValidator.class.create"; - public static final String DATEVALIDATOR_DATE_OUTOFRANGE = "DateValidator.date.OutOfRange"; - public static final String URLVALIDATOR_MALFORMED_URL = "URLValidator.malformed.URL"; - public static final String NUMBERVALIDATOR_NUMBER_OUTOFRANGE = - "NumberValidator.number.OutOfRange"; - public static final String ARGUMENT_UNEXPECTED_VALUE = "Argument.unexpected.value"; - public static final String ARGUMENT_MIN_EXCEEDS_MAX = "Argument.minimum.exceeds.maximum"; - public static final String ARGUMENT_TOO_FEW_DEFAULTS = "Argument.too.few.defaults"; - public static final String ARGUMENT_TOO_MANY_DEFAULTS = "Argument.too.many.defaults"; - public static final String ARGUMENT_MISSING_VALUES = "Argument.missing.values"; - public static final String ARGUMENT_TOO_MANY_VALUES = "Argument.too.many.values"; - public static final String OPTION_TRIGGER_NEEDS_PREFIX = "Option.trigger.needs.prefix"; - public static final String OPTION_MISSING_REQUIRED = "Option.missing.required"; - public static final String OPTION_NO_NAME = "Option.no.name"; - public static final String OPTION_ILLEGAL_LONG_PREFIX = "Option.illegal.long.prefix"; - public static final String OPTION_ILLEGAL_SHORT_PREFIX = "Option.illegal.short.prefix"; - public static final String UNEXPECTED_TOKEN = "Unexpected.token"; - public static final String MISSING_OPTION = "Missing.option"; - public static final String CANNOT_BURST = "Cannot.burst"; - public static final String COMMAND_PREFERRED_NAME_TOO_SHORT = "Command.preferredName.too.short"; - public static final String SWITCH_ILLEGAL_ENABLED_PREFIX = "Option.illegal.enabled.prefix"; - public static final String SWITCH_ILLEGAL_DISABLED_PREFIX = "Option.illegal.disabled.prefix"; - public static final String SWITCH_IDENTICAL_PREFIXES = "Option.identical.prefixes"; - public static final String SWITCH_ALREADY_SET = "Switch.already.set"; - public static final String SWITCH_NO_ENABLED_PREFIX = "Switch.no.enabledPrefix"; - public static final String SWITCH_NO_DISABLED_PREFIX = "Switch.no.disabledPrefix"; - public static final String SWITCH_ENABLED_STARTS_WITH_DISABLED = - "Switch.enabled.startsWith.disabled"; - public static final String SWITCH_DISABLED_STARTWS_WITH_ENABLED = - "Switch.disabled.startsWith.enabled"; - public static final String SWITCH_PREFERRED_NAME_TOO_SHORT = "Switch.preferredName.too.short"; - public static final String SOURCE_DEST_MUST_ENFORCE_VALUES = "SourceDest.must.enforce.values"; - public static final String HELPFORMATTER_GUTTER_TOO_LONG = "HelpFormatter.gutter.too.long"; - public static final String HELPFORMATTER_WIDTH_TOO_NARROW = "HelpFormatter.width.too.narrow"; - public static final String ENUM_ILLEGAL_VALUE = "Enum.illegal.value"; - public static final String ARGUMENT_BUILDER_NULL_CONSUME_REMAINING = "ArgumentBuilder.null.consume.remaining"; - public static final String ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING = "ArgumentBuilder.empty.consume.remaining"; - public static final String ARGUMENT_BUILDER_NULL_DEFAULT = "ArgumentBuilder.null.default"; - public static final String ARGUMENT_BUILDER_NULL_DEFAULTS = "ArgumentBuilder.null.defaults"; - public static final String ARGUMENT_BUILDER_NEGATIVE_MAXIMUM = "ArgumentBuilder.negative.maximum"; - public static final String ARGUMENT_BUILDER_NEGATIVE_MINIMUM = "ArgumentBuilder.negative.minimum"; - public static final String ARGUMENT_BUILDER_NULL_NAME = "ArgumentBuilder.null.name"; - public static final String ARGUMENT_BUILDER_EMPTY_NAME = "ArgumentBuilder.empty.name"; - public static final String ARGUMENT_BUILDER_NULL_VALIDATOR = "ArgumentBuilder.null.validator"; - -} +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.commons.cli2.resource;public abstract class ResourceConstants { public static final String CLASSVALIDATOR_BAD_CLASSNAME = "ClassValidator.bad.classname"; public static final String CLASSVALIDATOR_CLASS_NOTFOUND = "ClassValidator.class.notfound"; public static final String CLASSVALIDATOR_CLASS_ACCESS = "ClassValidator.class.access"; public static final String CLASSVALIDATOR_CLASS_CREATE = "ClassValidator.class.create"; public static final String DATEVALIDATOR_DATE_OUTOFRANGE = "DateValidator.date.OutOfRange"; public static final String URLVALIDATOR_MALFORMED_URL = "URLValidator.malformed.URL"; public static final String NUMBERVALIDATOR_NUMBER_OUTOFRANGE = "NumberValidator.number.OutOfRange"; public static final String ARGUMENT_UNEXPECTED_VALUE = "Argument.unexpected.value"; public static final String ARGUMENT_MIN_EXCEEDS_MAX = "Argument.minimum.exceeds.maximum"; public static final String ARGUMENT_TOO_FEW_DEFAULTS = "Argument.too.few.defaults"; public static final String ARGUMENT_TOO_MANY_DEFAULTS = "Argument.too.many.defaults"; public static final String ARGUMENT_MISSING_VALUES = "Argument.missing.values"; public static final String ARGUMENT_TOO_MANY_VALUES = "Argument.too.many.values"; public static final String OPTION_TRIGGER_NEEDS_PREFIX = "Option.trigger.needs.prefix"; public static final String OPTION_MISSING_REQUIRED = "Option.missing.required"; public static final String OPTION_NO_NAME = "Option.no.name"; public static final String OPTION_ILLEGAL_LONG_PREFIX = "Option.illegal.long.prefix"; public static final String OPTION_ILLEGAL_SHORT_PREFIX = "Option.illegal.short.prefix"; public static final String UNEXPECTED_TOKEN = "Unexpected.token"; public static final String MISSING_OPTION = "Missing.option"; public static final String CANNOT_BURST = "Cannot.burst"; public static final String COMMAND_PREFERRED_NAME_TOO_SHORT = "Command.preferredName.too.short"; public static final String SWITCH_ILLEGAL_ENABLED_PREFIX = "Option.illegal.enabled.prefix"; public static final String SWITCH_ILLEGAL_DISABLED_PREFIX = "Option.illegal.disabled.prefix"; public static final String SWITCH_IDENTICAL_PREFIXES = "Option.identical.prefixes"; public static final String SWITCH_ALREADY_SET = "Switch.already.set"; public static final String SWITCH_NO_ENABLED_PREFIX = "Switch.no.enabledPrefix"; public static final String SWITCH_NO_DISABLED_PREFIX = "Switch.no.disabledPrefix"; public static final String SWITCH_ENABLED_STARTS_WITH_DISABLED = "Switch.enabled.startsWith.disabled"; public static final String SWITCH_DISABLED_STARTWS_WITH_ENABLED = "Switch.disabled.startsWith.enabled"; public static final String SWITCH_PREFERRED_NAME_TOO_SHORT = "Switch.preferredName.too.short"; public static final String SOURCE_DEST_MUST_ENFORCE_VALUES = "SourceDest.must.enforce.values"; public static final String HELPFORMATTER_GUTTER_TOO_LONG = "HelpFormatter.gutter.too.long"; public static final String HELPFORMATTER_WIDTH_TOO_NARROW = "HelpFormatter.width.too.narrow"; public static final String ENUM_ILLEGAL_VALUE = "Enum.illegal.value"; public static final String ARGUMENT_BUILDER_NULL_CONSUME_REMAINING = "ArgumentBuilder.null.consume.remaining"; public static final String ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING = "ArgumentBuilder.empty.consume.remaining"; public static final String ARGUMENT_BUILDER_NULL_DEFAULT = "ArgumentBuilder.null.default"; public static final String ARGUMENT_BUILDER_NULL_DEFAULTS = "ArgumentBuilder.null.defaults"; public static final String ARGUMENT_BUILDER_NEGATIVE_MAXIMUM = "ArgumentBuilder.negative.maximum"; public static final String ARGUMENT_BUILDER_NEGATIVE_MINIMUM = "ArgumentBuilder.negative.minimum"; public static final String ARGUMENT_BUILDER_NULL_NAME = "ArgumentBuilder.null.name"; public static final String ARGUMENT_BUILDER_EMPTY_NAME = "ArgumentBuilder.empty.name"; public static final String ARGUMENT_BUILDER_NULL_VALIDATOR = "ArgumentBuilder.null.validator";} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/resource/ResourceHelper.java b/src/java/org/apache/commons/cli2/resource/ResourceHelper.java index eab71f9e1..6a0128d39 100644 --- a/src/java/org/apache/commons/cli2/resource/ResourceHelper.java +++ b/src/java/org/apache/commons/cli2/resource/ResourceHelper.java @@ -1,160 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.resource; - -import java.text.MessageFormat; - -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -/** - * A utility class used to provide internationalisation support. - * - * @author John Keyes - */ -public class ResourceHelper { - /** system property */ - private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle"; - - /** default package name */ - private static final String DEFAULT_BUNDLE = - "org.apache.commons.cli2.resource.CLIMessageBundle_en_US"; - private static ResourceHelper helper; - - /** resource bundle */ - private ResourceBundle bundle; - - private String prop; - - /** - * Create a new ResourceHelper for the current locale. - */ - private ResourceHelper() { - String bundleName = System.getProperty(PROP_LOCALE); - - if (bundleName == null) { - bundleName = DEFAULT_BUNDLE; - } - - this.prop = bundleName; - - int firstUnderscore = bundleName.indexOf('_'); - int secondUnderscore = bundleName.indexOf('_', firstUnderscore + 1); - - Locale locale; - if (firstUnderscore != -1) { - String language = bundleName.substring(firstUnderscore + 1, secondUnderscore); - String country = bundleName.substring(secondUnderscore + 1); - locale = new Locale(language, country); - } - else { - locale = Locale.getDefault(); - } - // initialize the bundle - try { - bundle = ResourceBundle.getBundle(bundleName, locale); - } catch (MissingResourceException exp) { - bundle = ResourceBundle.getBundle(DEFAULT_BUNDLE, locale); - } - } - - public String getBundleName() { - return this.prop; - } - - /** - * Gets the ResourceHelper appropriate to the current locale. - * @return a ResourceHelper - */ - public static ResourceHelper getResourceHelper() { - String bundleName = System.getProperty(PROP_LOCALE); - if (helper == null || !helper.getBundleName().equals(bundleName)) { - helper = new ResourceHelper(); - } - - return helper; - } - - /** - * Returns the message for the specified key. - * - * @param key the unique identifier of the message - * @return String the formatted String - */ - public String getMessage(final String key) { - return getMessage(key, new Object[] { }); - } - - /** - * Returns the message for the specified key and argument. - * - * @param key the unique identifier of the message - * @param value the argument value - * @return String the formatted String - */ - public String getMessage(final String key, - final Object value) { - return getMessage(key, new Object[] { value }); - } - - /** - * Returns the message for the specified key and arguments. - * - * @param key the unique identifier of the message - * @param value1 an argument value - * @param value2 an argument value - * @return String the formatted String - */ - public String getMessage(final String key, - final Object value1, - final Object value2) { - return getMessage(key, new Object[] { value1, value2 }); - } - - /** - * Returns the message for the specified key and arguments. - * - * @param key the unique identifier of the message - * @param value1 an argument value - * @param value2 an argument value - * @param value3 an argument value - * - * @return String the formatted String - */ - public String getMessage(final String key, - final Object value1, - final Object value2, - final Object value3) { - return getMessage(key, new Object[] { value1, value2, value3 }); - } - - /** - * Returns the message for the specified key and arguments. - * - * @param key the unique identifier of the message - * @param values argument values - * @return String the formatted String - */ - public String getMessage(final String key, - final Object[] values) { - final String msgFormatStr = bundle.getString(key); - final MessageFormat msgFormat = new MessageFormat(msgFormatStr); - - return msgFormat.format(values); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.resource;import java.text.MessageFormat;import java.util.Locale;import java.util.MissingResourceException;import java.util.ResourceBundle;/** * A utility class used to provide internationalisation support. * * @author John Keyes */public class ResourceHelper { /** system property */ private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle"; /** default package name */ private static final String DEFAULT_BUNDLE = "org.apache.commons.cli2.resource.CLIMessageBundle_en_US"; private static ResourceHelper helper; /** resource bundle */ private ResourceBundle bundle; private String prop; /** * Create a new ResourceHelper for the current locale. */ private ResourceHelper() { String bundleName = System.getProperty(PROP_LOCALE); if (bundleName == null) { bundleName = DEFAULT_BUNDLE; } this.prop = bundleName; int firstUnderscore = bundleName.indexOf('_'); int secondUnderscore = bundleName.indexOf('_', firstUnderscore + 1); Locale locale; if (firstUnderscore != -1) { String language = bundleName.substring(firstUnderscore + 1, secondUnderscore); String country = bundleName.substring(secondUnderscore + 1); locale = new Locale(language, country); } else { locale = Locale.getDefault(); } // initialize the bundle try { bundle = ResourceBundle.getBundle(bundleName, locale); } catch (MissingResourceException exp) { bundle = ResourceBundle.getBundle(DEFAULT_BUNDLE, locale); } } public String getBundleName() { return this.prop; } /** * Gets the ResourceHelper appropriate to the current locale. * @return a ResourceHelper */ public static ResourceHelper getResourceHelper() { String bundleName = System.getProperty(PROP_LOCALE); if (helper == null || !helper.getBundleName().equals(bundleName)) { helper = new ResourceHelper(); } return helper; } /** * Returns the message for the specified key. * * @param key the unique identifier of the message * @return String the formatted String */ public String getMessage(final String key) { return getMessage(key, new Object[] { }); } /** * Returns the message for the specified key and argument. * * @param key the unique identifier of the message * @param value the argument value * @return String the formatted String */ public String getMessage(final String key, final Object value) { return getMessage(key, new Object[] { value }); } /** * Returns the message for the specified key and arguments. * * @param key the unique identifier of the message * @param value1 an argument value * @param value2 an argument value * @return String the formatted String */ public String getMessage(final String key, final Object value1, final Object value2) { return getMessage(key, new Object[] { value1, value2 }); } /** * Returns the message for the specified key and arguments. * * @param key the unique identifier of the message * @param value1 an argument value * @param value2 an argument value * @param value3 an argument value * * @return String the formatted String */ public String getMessage(final String key, final Object value1, final Object value2, final Object value3) { return getMessage(key, new Object[] { value1, value2, value3 }); } /** * Returns the message for the specified key and arguments. * * @param key the unique identifier of the message * @param values argument values * @return String the formatted String */ public String getMessage(final String key, final Object[] values) { final String msgFormatStr = bundle.getString(key); final MessageFormat msgFormat = new MessageFormat(msgFormatStr); return msgFormat.format(values); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/util/Comparators.java b/src/java/org/apache/commons/cli2/util/Comparators.java index 3cc137e31..3cd7c68eb 100644 --- a/src/java/org/apache/commons/cli2/util/Comparators.java +++ b/src/java/org/apache/commons/cli2/util/Comparators.java @@ -1,456 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.util; - -import java.util.Comparator; -import java.util.List; - -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.option.Command; -import org.apache.commons.cli2.option.DefaultOption; -import org.apache.commons.cli2.option.Switch; - -/** - * A collection of Comparators suitable for use with Option instances. - */ -public class Comparators { - - private Comparators(){ - // constructor hiden from potential users - } - - - /** - * Chains comparators together. - * - * @see #chain(Comparator[]) - * @param c0 - * a comparator - * @param c1 - * a comparator - * @return a chained comparator - */ - public static Comparator chain(final Comparator c0, final Comparator c1) { - return chain(new Comparator[] { c0, c1 }); - } - - /** - * Chains comparators together. - * - * @see #chain(Comparator[]) - * @param c0 - * a comparator - * @param c1 - * a comparator - * @param c2 - * a comparator - * @return a chained comparator - */ - public static Comparator chain( - final Comparator c0, - final Comparator c1, - final Comparator c2) { - return chain(new Comparator[] { c0, c1, c2 }); - } - - /** - * Chains comparators together. - * - * @see #chain(Comparator[]) - * @param c0 - * a comparator - * @param c1 - * a comparator - * @param c2 - * a comparator - * @param c3 - * a comparator - * @return a chained comparator - */ - public static Comparator chain( - final Comparator c0, - final Comparator c1, - final Comparator c2, - final Comparator c3) { - return chain(new Comparator[] { c0, c1, c2, c3 }); - } - - /** - * Chains comparators together. - * - * @see #chain(Comparator[]) - * @param c0 - * a comparator - * @param c1 - * a comparator - * @param c2 - * a comparator - * @param c3 - * a comparator - * @param c4 - * a comparator - * @return a chained comparator - */ - public static Comparator chain( - final Comparator c0, - final Comparator c1, - final Comparator c2, - final Comparator c3, - final Comparator c4) { - return chain(new Comparator[] { c0, c1, c2, c3, c4 }); - } - - /** - * Chains comparators together. - * - * @see #chain(Comparator[]) - * @param comparators - * a List of comparators to chain together - * @return a chained comparator - */ - public static Comparator chain(final List comparators) { - return new Chain( - (Comparator[])comparators.toArray( - new Comparator[comparators.size()])); - } - - /** - * Chains an array of comparators together. Each Comparator will be called - * in turn until one of them return a non-zero value, this value will be - * returned. - * - * @param comparators - * the array of comparators - * @return a chained comparator - */ - public static Comparator chain(final Comparator[] comparators) { - return new Chain(comparators); - } - - /** - * Chains a series of Comparators together. - */ - private static class Chain implements Comparator { - - final Comparator[] chain; - - /** - * Creates a Comparator chain using the specified array of Comparators - * @param chain the Comparators in the chain - */ - public Chain(final Comparator[] chain) { - this.chain = new Comparator[chain.length]; - System.arraycopy(chain, 0, this.chain, 0, chain.length); - } - - public int compare(final Object left, final Object right) { - int result = 0; - for (int i = 0; result == 0 && i < chain.length; ++i) { - result = chain[i].compare(left, right); - } - return result; - } - } - - /** - * Reverses a comparator's logic. - * - * @param wrapped - * the Comparator to reverse the logic of - * @return a comparator with reverse logic - */ - private static Comparator reverse(final Comparator wrapped) { - return new Reverse(wrapped); - } - - private static class Reverse implements Comparator { - private final Comparator wrapped; - - /** - * Creates a Comparator with reverse logic - * @param wrapped the original logic - */ - public Reverse(final Comparator wrapped) { - this.wrapped = wrapped; - } - - public int compare(final Object left, final Object right) { - return -wrapped.compare(left, right); - } - } - - /** - * Forces Group instances to appear at the beginning of lists - * - * @see Group - * @return a new comparator - */ - public static Comparator groupFirst() { - return new GroupFirst(); - } - - /** - * Forces Group instances to appear at the end of lists - * - * @see Group - * @return a new comparator - */ - public static Comparator groupLast() { - return reverse(groupFirst()); - } - - private static class GroupFirst implements Comparator { - public int compare(final Object left, final Object right) { - final boolean l = left instanceof Group; - final boolean r = right instanceof Group; - - if (l ^ r) { - if (l) { - return -1; - } - return 1; - } - return 0; - } - } - - /** - * Forces Switch instances to appear at the beginning of lists - * - * @see Switch - * @return a new comparator - */ - public static Comparator switchFirst() { - return new SwitchFirst(); - } - - /** - * Forces Switch instances to appear at the end of lists - * - * @see Switch - * @return a new comparator - */ - public static Comparator switchLast() { - return reverse(switchFirst()); - } - - private static class SwitchFirst implements Comparator { - public int compare(final Object left, final Object right) { - final boolean l = left instanceof Switch; - final boolean r = right instanceof Switch; - - if (l ^ r) { - if (l) { - return -1; - } - return 1; - } - return 0; - } - } - - /** - * Forces Command instances to appear at the beginning of lists - * - * @see Command - * @return a new comparator - */ - public static Comparator commandFirst() { - return new CommandFirst(); - } - - /** - * Forces Command instances to appear at the end of lists - * - * @see Command - * @return a new comparator - */ - public static Comparator commandLast() { - return reverse(commandFirst()); - } - - private static class CommandFirst implements Comparator { - public int compare(final Object left, final Object right) { - final boolean l = left instanceof Command; - final boolean r = right instanceof Command; - - if (l ^ r) { - if (l) { - return -1; - } - return 1; - } - return 0; - } - } - - /** - * Forces DefaultOption instances to appear at the beginning of lists - * - * @see DefaultOption - * @return a new comparator - */ - public static Comparator defaultOptionFirst() { - return new DefaultOptionFirst(); - } - - /** - * Forces DefaultOption instances to appear at the end of lists - * - * @see DefaultOption - * @return a new comparator - */ - public static Comparator defaultOptionLast() { - return reverse(defaultOptionFirst()); - } - - private static class DefaultOptionFirst implements Comparator { - public int compare(final Object left, final Object right) { - final boolean l = left instanceof DefaultOption; - final boolean r = right instanceof DefaultOption; - - if (l ^ r) { - if (l) { - return -1; - } - return 1; - } - return 0; - } - } - - /** - * Forces Comparators with a particular trigger to appear at the beginning - * of lists - * - * @param name - * the trigger name to select - * @see Option#getTriggers() - * @return a new comparator - */ - public static Comparator namedFirst(final String name) { - return new Named(name); - } - - /** - * Forces Comparators with a particular trigger to appear at the end of - * lists - * - * @param name - * the trigger name to select - * @see Option#getTriggers() - * @return a new comparator - */ - public static Comparator namedLast(final String name) { - return reverse(new Named(name)); - } - - private static class Named implements Comparator { - private final String name; - - /** - * Creates a Comparator that sorts a particular name high in order - * @param name the trigger name to select - */ - public Named(final String name) { - this.name = name; - } - public int compare(final Object oleft, final Object oright) { - final Option left = (Option)oleft; - final Option right = (Option)oright; - - final boolean l = left.getTriggers().contains(name); - final boolean r = right.getTriggers().contains(name); - - if (l ^ r) { - if (l) { - return -1; - } - return 1; - } - return 0; - } - } - - /** - * Orders Options by preferredName - * - * @see Option#getPreferredName() - * @return a new comparator - */ - public static Comparator preferredNameFirst() { - return new PreferredName(); - } - - /** - * Orders Options by preferredName, reversed - * - * @see Option#getPreferredName() - * @return a new comparator - */ - public static Comparator preferredNameLast() { - return reverse(preferredNameFirst()); - } - - private static class PreferredName implements Comparator { - public int compare(final Object oleft, final Object oright) { - final Option left = (Option)oleft; - final Option right = (Option)oright; - - return left.getPreferredName().compareTo(right.getPreferredName()); - } - } - - /** - * Orders Options grouping required Options first - * - * @see Option#isRequired() - * @return a new comparator - */ - public static Comparator requiredFirst() { - return new Required(); - } - - /** - * Orders Options grouping required Options last - * - * @see Option#isRequired() - * @return a new comparator - */ - public static Comparator requiredLast() { - return reverse(requiredFirst()); - } - - private static class Required implements Comparator { - public int compare(final Object oleft, final Object oright) { - final Option left = (Option)oleft; - final Option right = (Option)oright; - - final boolean l = left.isRequired(); - final boolean r = right.isRequired(); - - if (l ^ r) { - if (l) { - return -1; - } - return 1; - } - return 0; - } - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.util;import java.util.Comparator;import java.util.List;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.option.Command;import org.apache.commons.cli2.option.DefaultOption;import org.apache.commons.cli2.option.Switch;/** * A collection of Comparators suitable for use with Option instances. */public class Comparators { private Comparators(){ // constructor hiden from potential users } /** * Chains comparators together. * * @see #chain(Comparator[]) * @param c0 * a comparator * @param c1 * a comparator * @return a chained comparator */ public static Comparator chain(final Comparator c0, final Comparator c1) { return chain(new Comparator[] { c0, c1 }); } /** * Chains comparators together. * * @see #chain(Comparator[]) * @param c0 * a comparator * @param c1 * a comparator * @param c2 * a comparator * @return a chained comparator */ public static Comparator chain( final Comparator c0, final Comparator c1, final Comparator c2) { return chain(new Comparator[] { c0, c1, c2 }); } /** * Chains comparators together. * * @see #chain(Comparator[]) * @param c0 * a comparator * @param c1 * a comparator * @param c2 * a comparator * @param c3 * a comparator * @return a chained comparator */ public static Comparator chain( final Comparator c0, final Comparator c1, final Comparator c2, final Comparator c3) { return chain(new Comparator[] { c0, c1, c2, c3 }); } /** * Chains comparators together. * * @see #chain(Comparator[]) * @param c0 * a comparator * @param c1 * a comparator * @param c2 * a comparator * @param c3 * a comparator * @param c4 * a comparator * @return a chained comparator */ public static Comparator chain( final Comparator c0, final Comparator c1, final Comparator c2, final Comparator c3, final Comparator c4) { return chain(new Comparator[] { c0, c1, c2, c3, c4 }); } /** * Chains comparators together. * * @see #chain(Comparator[]) * @param comparators * a List of comparators to chain together * @return a chained comparator */ public static Comparator chain(final List comparators) { return new Chain( (Comparator[])comparators.toArray( new Comparator[comparators.size()])); } /** * Chains an array of comparators together. Each Comparator will be called * in turn until one of them return a non-zero value, this value will be * returned. * * @param comparators * the array of comparators * @return a chained comparator */ public static Comparator chain(final Comparator[] comparators) { return new Chain(comparators); } /** * Chains a series of Comparators together. */ private static class Chain implements Comparator { final Comparator[] chain; /** * Creates a Comparator chain using the specified array of Comparators * @param chain the Comparators in the chain */ public Chain(final Comparator[] chain) { this.chain = new Comparator[chain.length]; System.arraycopy(chain, 0, this.chain, 0, chain.length); } public int compare(final Object left, final Object right) { int result = 0; for (int i = 0; result == 0 && i < chain.length; ++i) { result = chain[i].compare(left, right); } return result; } } /** * Reverses a comparator's logic. * * @param wrapped * the Comparator to reverse the logic of * @return a comparator with reverse logic */ private static Comparator reverse(final Comparator wrapped) { return new Reverse(wrapped); } private static class Reverse implements Comparator { private final Comparator wrapped; /** * Creates a Comparator with reverse logic * @param wrapped the original logic */ public Reverse(final Comparator wrapped) { this.wrapped = wrapped; } public int compare(final Object left, final Object right) { return -wrapped.compare(left, right); } } /** * Forces Group instances to appear at the beginning of lists * * @see Group * @return a new comparator */ public static Comparator groupFirst() { return new GroupFirst(); } /** * Forces Group instances to appear at the end of lists * * @see Group * @return a new comparator */ public static Comparator groupLast() { return reverse(groupFirst()); } private static class GroupFirst implements Comparator { public int compare(final Object left, final Object right) { final boolean l = left instanceof Group; final boolean r = right instanceof Group; if (l ^ r) { if (l) { return -1; } return 1; } return 0; } } /** * Forces Switch instances to appear at the beginning of lists * * @see Switch * @return a new comparator */ public static Comparator switchFirst() { return new SwitchFirst(); } /** * Forces Switch instances to appear at the end of lists * * @see Switch * @return a new comparator */ public static Comparator switchLast() { return reverse(switchFirst()); } private static class SwitchFirst implements Comparator { public int compare(final Object left, final Object right) { final boolean l = left instanceof Switch; final boolean r = right instanceof Switch; if (l ^ r) { if (l) { return -1; } return 1; } return 0; } } /** * Forces Command instances to appear at the beginning of lists * * @see Command * @return a new comparator */ public static Comparator commandFirst() { return new CommandFirst(); } /** * Forces Command instances to appear at the end of lists * * @see Command * @return a new comparator */ public static Comparator commandLast() { return reverse(commandFirst()); } private static class CommandFirst implements Comparator { public int compare(final Object left, final Object right) { final boolean l = left instanceof Command; final boolean r = right instanceof Command; if (l ^ r) { if (l) { return -1; } return 1; } return 0; } } /** * Forces DefaultOption instances to appear at the beginning of lists * * @see DefaultOption * @return a new comparator */ public static Comparator defaultOptionFirst() { return new DefaultOptionFirst(); } /** * Forces DefaultOption instances to appear at the end of lists * * @see DefaultOption * @return a new comparator */ public static Comparator defaultOptionLast() { return reverse(defaultOptionFirst()); } private static class DefaultOptionFirst implements Comparator { public int compare(final Object left, final Object right) { final boolean l = left instanceof DefaultOption; final boolean r = right instanceof DefaultOption; if (l ^ r) { if (l) { return -1; } return 1; } return 0; } } /** * Forces Comparators with a particular trigger to appear at the beginning * of lists * * @param name * the trigger name to select * @see Option#getTriggers() * @return a new comparator */ public static Comparator namedFirst(final String name) { return new Named(name); } /** * Forces Comparators with a particular trigger to appear at the end of * lists * * @param name * the trigger name to select * @see Option#getTriggers() * @return a new comparator */ public static Comparator namedLast(final String name) { return reverse(new Named(name)); } private static class Named implements Comparator { private final String name; /** * Creates a Comparator that sorts a particular name high in order * @param name the trigger name to select */ public Named(final String name) { this.name = name; } public int compare(final Object oleft, final Object oright) { final Option left = (Option)oleft; final Option right = (Option)oright; final boolean l = left.getTriggers().contains(name); final boolean r = right.getTriggers().contains(name); if (l ^ r) { if (l) { return -1; } return 1; } return 0; } } /** * Orders Options by preferredName * * @see Option#getPreferredName() * @return a new comparator */ public static Comparator preferredNameFirst() { return new PreferredName(); } /** * Orders Options by preferredName, reversed * * @see Option#getPreferredName() * @return a new comparator */ public static Comparator preferredNameLast() { return reverse(preferredNameFirst()); } private static class PreferredName implements Comparator { public int compare(final Object oleft, final Object oright) { final Option left = (Option)oleft; final Option right = (Option)oright; return left.getPreferredName().compareTo(right.getPreferredName()); } } /** * Orders Options grouping required Options first * * @see Option#isRequired() * @return a new comparator */ public static Comparator requiredFirst() { return new Required(); } /** * Orders Options grouping required Options last * * @see Option#isRequired() * @return a new comparator */ public static Comparator requiredLast() { return reverse(requiredFirst()); } private static class Required implements Comparator { public int compare(final Object oleft, final Object oright) { final Option left = (Option)oleft; final Option right = (Option)oright; final boolean l = left.isRequired(); final boolean r = right.isRequired(); if (l ^ r) { if (l) { return -1; } return 1; } return 0; } }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/util/HelpFormatter.java b/src/java/org/apache/commons/cli2/util/HelpFormatter.java index 8f6684f0a..12197653a 100644 --- a/src/java/org/apache/commons/cli2/util/HelpFormatter.java +++ b/src/java/org/apache/commons/cli2/util/HelpFormatter.java @@ -1,638 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.util; - -import java.io.PrintWriter; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.HelpLine; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * Presents on screen help based on the application's Options - */ -public class HelpFormatter { - /** - * The default screen width - */ - public static final int DEFAULT_FULL_WIDTH = 80; - - /** - * The default screen furniture left of screen - */ - public static final String DEFAULT_GUTTER_LEFT = ""; - - /** - * The default screen furniture right of screen - */ - public static final String DEFAULT_GUTTER_CENTER = " "; - - /** - * The default screen furniture between columns - */ - public static final String DEFAULT_GUTTER_RIGHT = ""; - - /** - * The default DisplaySettings used to select the elements to display in the - * displayed line of full usage information. - * - * @see DisplaySetting - */ - public static final Set DEFAULT_FULL_USAGE_SETTINGS; - - /** - * The default DisplaySettings used to select the elements of usage per help - * line in the main body of help - * - * @see DisplaySetting - */ - public static final Set DEFAULT_LINE_USAGE_SETTINGS; - - /** - * The default DisplaySettings used to select the help lines in the main - * body of help - */ - public static final Set DEFAULT_DISPLAY_USAGE_SETTINGS; - - static { - final Set fullUsage = new HashSet(DisplaySetting.ALL); - fullUsage.remove(DisplaySetting.DISPLAY_ALIASES); - fullUsage.remove(DisplaySetting.DISPLAY_GROUP_NAME); - DEFAULT_FULL_USAGE_SETTINGS = Collections.unmodifiableSet(fullUsage); - - final Set lineUsage = new HashSet(); - lineUsage.add(DisplaySetting.DISPLAY_ALIASES); - lineUsage.add(DisplaySetting.DISPLAY_GROUP_NAME); - lineUsage.add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); - DEFAULT_LINE_USAGE_SETTINGS = Collections.unmodifiableSet(lineUsage); - - final Set displayUsage = new HashSet(DisplaySetting.ALL); - displayUsage.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); - DEFAULT_DISPLAY_USAGE_SETTINGS = Collections.unmodifiableSet(displayUsage); - } - - private Set fullUsageSettings = new HashSet(DEFAULT_FULL_USAGE_SETTINGS); - private Set lineUsageSettings = new HashSet(DEFAULT_LINE_USAGE_SETTINGS); - private Set displaySettings = new HashSet(DEFAULT_DISPLAY_USAGE_SETTINGS); - private OptionException exception = null; - private Group group; - private Comparator comparator = null; - private String divider = null; - private String header = null; - private String footer = null; - private String shellCommand = ""; - private PrintWriter out = new PrintWriter(System.out); - - //or should this default to .err? - private final String gutterLeft; - private final String gutterCenter; - private final String gutterRight; - private final int pageWidth; - - /** - * Creates a new HelpFormatter using the defaults - */ - public HelpFormatter() { - this(DEFAULT_GUTTER_LEFT, DEFAULT_GUTTER_CENTER, DEFAULT_GUTTER_RIGHT, DEFAULT_FULL_WIDTH); - } - - /** - * Creates a new HelpFormatter using the specified parameters - * @param gutterLeft the string marking left of screen - * @param gutterCenter the string marking center of screen - * @param gutterRight the string marking right of screen - * @param fullWidth the width of the screen - */ - public HelpFormatter(final String gutterLeft, - final String gutterCenter, - final String gutterRight, - final int fullWidth) { - // default the left gutter to empty string - this.gutterLeft = (gutterLeft == null) ? DEFAULT_GUTTER_LEFT : gutterLeft; - - // default the center gutter to a single space - this.gutterCenter = (gutterCenter == null) ? DEFAULT_GUTTER_CENTER : gutterCenter; - - // default the right gutter to empty string - this.gutterRight = (gutterRight == null) ? DEFAULT_GUTTER_RIGHT : gutterRight; - - // calculate the available page width - this.pageWidth = fullWidth - this.gutterLeft.length() - this.gutterRight.length(); - - // check available page width is valid - int availableWidth = fullWidth - pageWidth + this.gutterCenter.length(); - - if (availableWidth < 2) { - throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.HELPFORMATTER_GUTTER_TOO_LONG)); - } - } - - /** - * Prints the Option help. - */ - public void print() { - printHeader(); - printException(); - printUsage(); - printHelp(); - printFooter(); - out.flush(); - } - - /** - * Prints any error message. - */ - public void printException() { - if (exception != null) { - printDivider(); - printWrapped(exception.getMessage()); - } - } - - /** - * Prints detailed help per option. - */ - public void printHelp() { - printDivider(); - - final Option option; - - if ((exception != null) && (exception.getOption() != null)) { - option = exception.getOption(); - } else { - option = group; - } - - // grab the HelpLines to display - final List helpLines = option.helpLines(0, displaySettings, comparator); - - // calculate the maximum width of the usage strings - int usageWidth = 0; - - for (final Iterator i = helpLines.iterator(); i.hasNext();) { - final HelpLine helpLine = (HelpLine) i.next(); - final String usage = helpLine.usage(lineUsageSettings, comparator); - usageWidth = Math.max(usageWidth, usage.length()); - } - - // build a blank string to pad wrapped descriptions - final StringBuffer blankBuffer = new StringBuffer(); - - for (int i = 0; i < usageWidth; i++) { - blankBuffer.append(' '); - } - - // determine the width available for descriptions - final int descriptionWidth = Math.max(1, pageWidth - gutterCenter.length() - usageWidth); - - // display each HelpLine - for (final Iterator i = helpLines.iterator(); i.hasNext();) { - // grab the HelpLine - final HelpLine helpLine = (HelpLine) i.next(); - - // wrap the description - final List descList = wrap(helpLine.getDescription(), descriptionWidth); - final Iterator descriptionIterator = descList.iterator(); - - // display usage + first line of description - printGutterLeft(); - pad(helpLine.usage(lineUsageSettings, comparator), usageWidth, out); - out.print(gutterCenter); - pad((String) descriptionIterator.next(), descriptionWidth, out); - printGutterRight(); - out.println(); - - // display padding + remaining lines of description - while (descriptionIterator.hasNext()) { - printGutterLeft(); - - //pad(helpLine.getUsage(),usageWidth,out); - out.print(blankBuffer); - out.print(gutterCenter); - pad((String) descriptionIterator.next(), descriptionWidth, out); - printGutterRight(); - out.println(); - } - } - - printDivider(); - } - - /** - * Prints a single line of usage information (wrapping if necessary) - */ - public void printUsage() { - printDivider(); - - final StringBuffer buffer = new StringBuffer("Usage:\n"); - buffer.append(shellCommand).append(' '); - group.appendUsage(buffer, fullUsageSettings, comparator, " "); - printWrapped(buffer.toString()); - } - - /** - * Prints a header string if necessary - */ - public void printHeader() { - if (header != null) { - printDivider(); - printWrapped(header); - } - } - - /** - * Prints a footer string if necessary - */ - public void printFooter() { - if (footer != null) { - printWrapped(footer); - printDivider(); - } - } - - /** - * Prints a string wrapped if necessary - * @param text the string to wrap - */ - public void printWrapped(final String text) { - for (final Iterator i = wrap(text, pageWidth).iterator(); i.hasNext();) { - printGutterLeft(); - pad((String) i.next(), pageWidth, out); - printGutterRight(); - out.println(); - } - - out.flush(); - } - - /** - * Prints the left gutter string - */ - public void printGutterLeft() { - if (gutterLeft != null) { - out.print(gutterLeft); - } - } - - /** - * Prints the right gutter string - */ - public void printGutterRight() { - if (gutterRight != null) { - out.print(gutterRight); - } - } - - /** - * Prints the divider text - */ - public void printDivider() { - if (divider != null) { - out.println(divider); - } - } - - protected static void pad(final String text, - final int width, - final PrintWriter writer) { - final int left; - - // write the text and record how many characters written - if (text == null) { - left = 0; - } else { - writer.write(text); - left = text.length(); - } - - // pad remainder with spaces - for (int i = left; i < width; ++i) { - writer.write(' '); - } - } - - protected static List wrap(final String text, - final int width) { - // check for valid width - if (width < 1) { - throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.HELPFORMATTER_WIDTH_TOO_NARROW, - new Object[] { - new Integer(width) - })); - } - - // handle degenerate case - if (text == null) { - return Collections.singletonList(""); - } - - final List lines = new ArrayList(); - final char[] chars = text.toCharArray(); - int left = 0; - - // for each character in the string - while (left < chars.length) { - // sync left and right indeces - int right = left; - - // move right until we run out of characters, width or find a newline - while ((right < chars.length) && (chars[right] != '\n') && - (right < (left + width + 1))) { - right++; - } - - // if a newline was found - if ((right < chars.length) && (chars[right] == '\n')) { - // record the substring - final String line = new String(chars, left, right - left); - lines.add(line); - - // move to the end of the substring - left = right + 1; - - if (left == chars.length) { - lines.add(""); - } - - // restart the loop - continue; - } - - // move to the next ideal wrap point - right = (left + width) - 1; - - // if we have run out of characters - if (chars.length <= right) { - // record the substring - final String line = new String(chars, left, chars.length - left); - lines.add(line); - - // abort the loop - break; - } - - // back track the substring end until a space is found - while ((right >= left) && (chars[right] != ' ')) { - right--; - } - - // if a space was found - if (right >= left) { - // record the substring to space - final String line = new String(chars, left, right - left); - lines.add(line); - - // absorb all the spaces before next substring - while ((right < chars.length) && (chars[right] == ' ')) { - right++; - } - - left = right; - - // restart the loop - continue; - } - - // move to the wrap position irrespective of spaces - right = Math.min(left + width, chars.length); - - // record the substring - final String line = new String(chars, left, right - left); - lines.add(line); - - // absorb any the spaces before next substring - while ((right < chars.length) && (chars[right] == ' ')) { - right++; - } - - left = right; - } - - return lines; - } - - /** - * The Comparator to use when sorting Options - * @param comparator Comparator to use when sorting Options - */ - public void setComparator(Comparator comparator) { - this.comparator = comparator; - } - - /** - * The DisplaySettings used to select the help lines in the main body of - * help - * - * @param displaySettings the settings to use - * @see DisplaySetting - */ - public void setDisplaySettings(Set displaySettings) { - this.displaySettings = displaySettings; - } - - /** - * Sets the string to use as a divider between sections of help - * @param divider the dividing string - */ - public void setDivider(String divider) { - this.divider = divider; - } - - /** - * Sets the exception to document - * @param exception the exception that occured - */ - public void setException(OptionException exception) { - this.exception = exception; - } - - /** - * Sets the footer text of the help screen - * @param footer the footer text - */ - public void setFooter(String footer) { - this.footer = footer; - } - - /** - * The DisplaySettings used to select the elements to display in the - * displayed line of full usage information. - * @see DisplaySetting - * @param fullUsageSettings - */ - public void setFullUsageSettings(Set fullUsageSettings) { - this.fullUsageSettings = fullUsageSettings; - } - - /** - * Sets the Group of Options to document - * @param group the options to document - */ - public void setGroup(Group group) { - this.group = group; - } - - /** - * Sets the footer text of the help screen - * @param header the footer text - */ - public void setHeader(String header) { - this.header = header; - } - - /** - * Sets the DisplaySettings used to select elements in the per helpline - * usage strings. - * @see DisplaySetting - * @param lineUsageSettings the DisplaySettings to use - */ - public void setLineUsageSettings(Set lineUsageSettings) { - this.lineUsageSettings = lineUsageSettings; - } - - /** - * Sets the command string used to invoke the application - * @param shellCommand the invokation command - */ - public void setShellCommand(String shellCommand) { - this.shellCommand = shellCommand; - } - - /** - * @return the Comparator used to sort the Group - */ - public Comparator getComparator() { - return comparator; - } - - /** - * @return the DisplaySettings used to select HelpLines - */ - public Set getDisplaySettings() { - return displaySettings; - } - - /** - * @return the String used as a horizontal section divider - */ - public String getDivider() { - return divider; - } - - /** - * @return the Exception being documented by this HelpFormatter - */ - public OptionException getException() { - return exception; - } - - /** - * @return the help screen footer text - */ - public String getFooter() { - return footer; - } - - /** - * @return the DisplaySettings used in the full usage string - */ - public Set getFullUsageSettings() { - return fullUsageSettings; - } - - /** - * @return the group documented by this HelpFormatter - */ - public Group getGroup() { - return group; - } - - /** - * @return the String used as the central gutter - */ - public String getGutterCenter() { - return gutterCenter; - } - - /** - * @return the String used as the left gutter - */ - public String getGutterLeft() { - return gutterLeft; - } - - /** - * @return the String used as the right gutter - */ - public String getGutterRight() { - return gutterRight; - } - - /** - * @return the help screen header text - */ - public String getHeader() { - return header; - } - - /** - * @return the DisplaySettings used in the per help line usage strings - */ - public Set getLineUsageSettings() { - return lineUsageSettings; - } - - /** - * @return the width of the screen in characters - */ - public int getPageWidth() { - return pageWidth; - } - - /** - * @return the command used to execute the application - */ - public String getShellCommand() { - return shellCommand; - } - - /** - * @param out the PrintWriter to write to - */ - public void setPrintWriter(PrintWriter out) { - this.out = out; - } - - /** - * @return the PrintWriter that will be written to - */ - public PrintWriter getPrintWriter() { - return out; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.util;import java.io.PrintWriter;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Presents on screen help based on the application's Options */public class HelpFormatter { /** * The default screen width */ public static final int DEFAULT_FULL_WIDTH = 80; /** * The default screen furniture left of screen */ public static final String DEFAULT_GUTTER_LEFT = ""; /** * The default screen furniture right of screen */ public static final String DEFAULT_GUTTER_CENTER = " "; /** * The default screen furniture between columns */ public static final String DEFAULT_GUTTER_RIGHT = ""; /** * The default DisplaySettings used to select the elements to display in the * displayed line of full usage information. * * @see DisplaySetting */ public static final Set DEFAULT_FULL_USAGE_SETTINGS; /** * The default DisplaySettings used to select the elements of usage per help * line in the main body of help * * @see DisplaySetting */ public static final Set DEFAULT_LINE_USAGE_SETTINGS; /** * The default DisplaySettings used to select the help lines in the main * body of help */ public static final Set DEFAULT_DISPLAY_USAGE_SETTINGS; static { final Set fullUsage = new HashSet(DisplaySetting.ALL); fullUsage.remove(DisplaySetting.DISPLAY_ALIASES); fullUsage.remove(DisplaySetting.DISPLAY_GROUP_NAME); DEFAULT_FULL_USAGE_SETTINGS = Collections.unmodifiableSet(fullUsage); final Set lineUsage = new HashSet(); lineUsage.add(DisplaySetting.DISPLAY_ALIASES); lineUsage.add(DisplaySetting.DISPLAY_GROUP_NAME); lineUsage.add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); DEFAULT_LINE_USAGE_SETTINGS = Collections.unmodifiableSet(lineUsage); final Set displayUsage = new HashSet(DisplaySetting.ALL); displayUsage.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); DEFAULT_DISPLAY_USAGE_SETTINGS = Collections.unmodifiableSet(displayUsage); } private Set fullUsageSettings = new HashSet(DEFAULT_FULL_USAGE_SETTINGS); private Set lineUsageSettings = new HashSet(DEFAULT_LINE_USAGE_SETTINGS); private Set displaySettings = new HashSet(DEFAULT_DISPLAY_USAGE_SETTINGS); private OptionException exception = null; private Group group; private Comparator comparator = null; private String divider = null; private String header = null; private String footer = null; private String shellCommand = ""; private PrintWriter out = new PrintWriter(System.out); //or should this default to .err? private final String gutterLeft; private final String gutterCenter; private final String gutterRight; private final int pageWidth; /** * Creates a new HelpFormatter using the defaults */ public HelpFormatter() { this(DEFAULT_GUTTER_LEFT, DEFAULT_GUTTER_CENTER, DEFAULT_GUTTER_RIGHT, DEFAULT_FULL_WIDTH); } /** * Creates a new HelpFormatter using the specified parameters * @param gutterLeft the string marking left of screen * @param gutterCenter the string marking center of screen * @param gutterRight the string marking right of screen * @param fullWidth the width of the screen */ public HelpFormatter(final String gutterLeft, final String gutterCenter, final String gutterRight, final int fullWidth) { // default the left gutter to empty string this.gutterLeft = (gutterLeft == null) ? DEFAULT_GUTTER_LEFT : gutterLeft; // default the center gutter to a single space this.gutterCenter = (gutterCenter == null) ? DEFAULT_GUTTER_CENTER : gutterCenter; // default the right gutter to empty string this.gutterRight = (gutterRight == null) ? DEFAULT_GUTTER_RIGHT : gutterRight; // calculate the available page width this.pageWidth = fullWidth - this.gutterLeft.length() - this.gutterRight.length(); // check available page width is valid int availableWidth = fullWidth - pageWidth + this.gutterCenter.length(); if (availableWidth < 2) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.HELPFORMATTER_GUTTER_TOO_LONG)); } } /** * Prints the Option help. */ public void print() { printHeader(); printException(); printUsage(); printHelp(); printFooter(); out.flush(); } /** * Prints any error message. */ public void printException() { if (exception != null) { printDivider(); printWrapped(exception.getMessage()); } } /** * Prints detailed help per option. */ public void printHelp() { printDivider(); final Option option; if ((exception != null) && (exception.getOption() != null)) { option = exception.getOption(); } else { option = group; } // grab the HelpLines to display final List helpLines = option.helpLines(0, displaySettings, comparator); // calculate the maximum width of the usage strings int usageWidth = 0; for (final Iterator i = helpLines.iterator(); i.hasNext();) { final HelpLine helpLine = (HelpLine) i.next(); final String usage = helpLine.usage(lineUsageSettings, comparator); usageWidth = Math.max(usageWidth, usage.length()); } // build a blank string to pad wrapped descriptions final StringBuffer blankBuffer = new StringBuffer(); for (int i = 0; i < usageWidth; i++) { blankBuffer.append(' '); } // determine the width available for descriptions final int descriptionWidth = Math.max(1, pageWidth - gutterCenter.length() - usageWidth); // display each HelpLine for (final Iterator i = helpLines.iterator(); i.hasNext();) { // grab the HelpLine final HelpLine helpLine = (HelpLine) i.next(); // wrap the description final List descList = wrap(helpLine.getDescription(), descriptionWidth); final Iterator descriptionIterator = descList.iterator(); // display usage + first line of description printGutterLeft(); pad(helpLine.usage(lineUsageSettings, comparator), usageWidth, out); out.print(gutterCenter); pad((String) descriptionIterator.next(), descriptionWidth, out); printGutterRight(); out.println(); // display padding + remaining lines of description while (descriptionIterator.hasNext()) { printGutterLeft(); //pad(helpLine.getUsage(),usageWidth,out); out.print(blankBuffer); out.print(gutterCenter); pad((String) descriptionIterator.next(), descriptionWidth, out); printGutterRight(); out.println(); } } printDivider(); } /** * Prints a single line of usage information (wrapping if necessary) */ public void printUsage() { printDivider(); final StringBuffer buffer = new StringBuffer("Usage:\n"); buffer.append(shellCommand).append(' '); group.appendUsage(buffer, fullUsageSettings, comparator, " "); printWrapped(buffer.toString()); } /** * Prints a header string if necessary */ public void printHeader() { if (header != null) { printDivider(); printWrapped(header); } } /** * Prints a footer string if necessary */ public void printFooter() { if (footer != null) { printWrapped(footer); printDivider(); } } /** * Prints a string wrapped if necessary * @param text the string to wrap */ public void printWrapped(final String text) { for (final Iterator i = wrap(text, pageWidth).iterator(); i.hasNext();) { printGutterLeft(); pad((String) i.next(), pageWidth, out); printGutterRight(); out.println(); } out.flush(); } /** * Prints the left gutter string */ public void printGutterLeft() { if (gutterLeft != null) { out.print(gutterLeft); } } /** * Prints the right gutter string */ public void printGutterRight() { if (gutterRight != null) { out.print(gutterRight); } } /** * Prints the divider text */ public void printDivider() { if (divider != null) { out.println(divider); } } protected static void pad(final String text, final int width, final PrintWriter writer) { final int left; // write the text and record how many characters written if (text == null) { left = 0; } else { writer.write(text); left = text.length(); } // pad remainder with spaces for (int i = left; i < width; ++i) { writer.write(' '); } } protected static List wrap(final String text, final int width) { // check for valid width if (width < 1) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.HELPFORMATTER_WIDTH_TOO_NARROW, new Object[] { new Integer(width) })); } // handle degenerate case if (text == null) { return Collections.singletonList(""); } final List lines = new ArrayList(); final char[] chars = text.toCharArray(); int left = 0; // for each character in the string while (left < chars.length) { // sync left and right indeces int right = left; // move right until we run out of characters, width or find a newline while ((right < chars.length) && (chars[right] != '\n') && (right < (left + width + 1))) { right++; } // if a newline was found if ((right < chars.length) && (chars[right] == '\n')) { // record the substring final String line = new String(chars, left, right - left); lines.add(line); // move to the end of the substring left = right + 1; if (left == chars.length) { lines.add(""); } // restart the loop continue; } // move to the next ideal wrap point right = (left + width) - 1; // if we have run out of characters if (chars.length <= right) { // record the substring final String line = new String(chars, left, chars.length - left); lines.add(line); // abort the loop break; } // back track the substring end until a space is found while ((right >= left) && (chars[right] != ' ')) { right--; } // if a space was found if (right >= left) { // record the substring to space final String line = new String(chars, left, right - left); lines.add(line); // absorb all the spaces before next substring while ((right < chars.length) && (chars[right] == ' ')) { right++; } left = right; // restart the loop continue; } // move to the wrap position irrespective of spaces right = Math.min(left + width, chars.length); // record the substring final String line = new String(chars, left, right - left); lines.add(line); // absorb any the spaces before next substring while ((right < chars.length) && (chars[right] == ' ')) { right++; } left = right; } return lines; } /** * The Comparator to use when sorting Options * @param comparator Comparator to use when sorting Options */ public void setComparator(Comparator comparator) { this.comparator = comparator; } /** * The DisplaySettings used to select the help lines in the main body of * help * * @param displaySettings the settings to use * @see DisplaySetting */ public void setDisplaySettings(Set displaySettings) { this.displaySettings = displaySettings; } /** * Sets the string to use as a divider between sections of help * @param divider the dividing string */ public void setDivider(String divider) { this.divider = divider; } /** * Sets the exception to document * @param exception the exception that occured */ public void setException(OptionException exception) { this.exception = exception; } /** * Sets the footer text of the help screen * @param footer the footer text */ public void setFooter(String footer) { this.footer = footer; } /** * The DisplaySettings used to select the elements to display in the * displayed line of full usage information. * @see DisplaySetting * @param fullUsageSettings */ public void setFullUsageSettings(Set fullUsageSettings) { this.fullUsageSettings = fullUsageSettings; } /** * Sets the Group of Options to document * @param group the options to document */ public void setGroup(Group group) { this.group = group; } /** * Sets the footer text of the help screen * @param header the footer text */ public void setHeader(String header) { this.header = header; } /** * Sets the DisplaySettings used to select elements in the per helpline * usage strings. * @see DisplaySetting * @param lineUsageSettings the DisplaySettings to use */ public void setLineUsageSettings(Set lineUsageSettings) { this.lineUsageSettings = lineUsageSettings; } /** * Sets the command string used to invoke the application * @param shellCommand the invokation command */ public void setShellCommand(String shellCommand) { this.shellCommand = shellCommand; } /** * @return the Comparator used to sort the Group */ public Comparator getComparator() { return comparator; } /** * @return the DisplaySettings used to select HelpLines */ public Set getDisplaySettings() { return displaySettings; } /** * @return the String used as a horizontal section divider */ public String getDivider() { return divider; } /** * @return the Exception being documented by this HelpFormatter */ public OptionException getException() { return exception; } /** * @return the help screen footer text */ public String getFooter() { return footer; } /** * @return the DisplaySettings used in the full usage string */ public Set getFullUsageSettings() { return fullUsageSettings; } /** * @return the group documented by this HelpFormatter */ public Group getGroup() { return group; } /** * @return the String used as the central gutter */ public String getGutterCenter() { return gutterCenter; } /** * @return the String used as the left gutter */ public String getGutterLeft() { return gutterLeft; } /** * @return the String used as the right gutter */ public String getGutterRight() { return gutterRight; } /** * @return the help screen header text */ public String getHeader() { return header; } /** * @return the DisplaySettings used in the per help line usage strings */ public Set getLineUsageSettings() { return lineUsageSettings; } /** * @return the width of the screen in characters */ public int getPageWidth() { return pageWidth; } /** * @return the command used to execute the application */ public String getShellCommand() { return shellCommand; } /** * @param out the PrintWriter to write to */ public void setPrintWriter(PrintWriter out) { this.out = out; } /** * @return the PrintWriter that will be written to */ public PrintWriter getPrintWriter() { return out; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/validation/ClassValidator.java b/src/java/org/apache/commons/cli2/validation/ClassValidator.java index a4770f2b6..930afa50a 100644 --- a/src/java/org/apache/commons/cli2/validation/ClassValidator.java +++ b/src/java/org/apache/commons/cli2/validation/ClassValidator.java @@ -1,201 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.util.List; -import java.util.ListIterator; - -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * The ClassValidator validates the string argument - * values are class names. - * - * The following example shows how to validate the 'logger' - * argument value is a class name, that can be instantiated. - * - *
      - * ...
      - * ClassValidator validator = new ClassValidator();
      - * validator.setInstance(true);
      - *
      - * ArgumentBuilder builder = new ArgumentBuilder();
      - * Argument logger =
      - *     builder.withName("logger");
      - *            .withValidator(validator);
      - * 
      - * - * @author John Keyes - */ -public class ClassValidator implements Validator { - /** i18n */ - private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); - - /** whether the class argument is loadable */ - private boolean loadable; - - /** whether to create an instance of the class */ - private boolean instance; - - /** the classloader to load classes from */ - private ClassLoader loader; - - /** - * Validate each argument value in the specified List against this instances - * permitted attributes. - * - * If a value is valid then it's String value in the list is - * replaced with it's Class value or instance. - * - * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) - */ - public void validate(final List values) - throws InvalidArgumentException { - for (final ListIterator i = values.listIterator(); i.hasNext();) { - final String name = (String) i.next(); - - if (!isPotentialClassName(name)) { - throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_BAD_CLASSNAME, - name)); - } - - if (loadable || instance) { - final ClassLoader theLoader = getClassLoader(); - - try { - final Class clazz = theLoader.loadClass(name); - - if (instance) { - i.set(clazz.newInstance()); - } else { - i.set(clazz); - } - } catch (final ClassNotFoundException exp) { - throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_NOTFOUND, - name)); - } catch (final IllegalAccessException exp) { - throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_ACCESS, - name, exp.getMessage())); - } catch (final InstantiationException exp) { - throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_CREATE, - name)); - } - } - } - } - - /** - * Returns whether the argument value must represent a - * class that is loadable. - * - * @return whether the argument value must represent a - * class that is loadable. - */ - public boolean isLoadable() { - return loadable; - } - - /** - * Specifies whether the argument value must represent a - * class that is loadable. - * - * @param loadable whether the argument value must - * represent a class that is loadable. - */ - public void setLoadable(boolean loadable) { - this.loadable = loadable; - } - - /** - * Returns the {@link ClassLoader} used to resolve and load - * the classes specified by the argument values. - * - * @return the {@link ClassLoader} used to resolve and load - * the classes specified by the argument values. - */ - public ClassLoader getClassLoader() { - if (loader == null) { - loader = getClass().getClassLoader(); - } - - return loader; - } - - /** - * Specifies the {@link ClassLoader} used to resolve and load - * the classes specified by the argument values. - * - * @param loader the {@link ClassLoader} used to resolve and load - * the classes specified by the argument values. - */ - public void setClassLoader(ClassLoader loader) { - this.loader = loader; - } - - /** - * Returns whether the argument value must represent a - * class that can be instantiated. - * - * @return whether the argument value must represent a - * class that can be instantiated. - */ - public boolean isInstance() { - return instance; - } - - /** - * Specifies whether the argument value must represent a - * class that can be instantiated. - * - * @param instance whether the argument value must - * represent a class that can be instantiated. - */ - public void setInstance(boolean instance) { - this.instance = instance; - } - - /** - * Returns whether the specified name is allowed as - * a Java class name. - */ - protected boolean isPotentialClassName(final String name) { - final char[] chars = name.toCharArray(); - - boolean expectingStart = true; - - for (int i = 0; i < chars.length; ++i) { - final char c = chars[i]; - - if (expectingStart) { - if (!Character.isJavaIdentifierStart(c)) { - return false; - } - - expectingStart = false; - } else { - if (c == '.') { - expectingStart = true; - } else if (!Character.isJavaIdentifierPart(c)) { - return false; - } - } - } - - return !expectingStart; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.util.List;import java.util.ListIterator;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * The ClassValidator validates the string argument * values are class names. * * The following example shows how to validate the 'logger' * argument value is a class name, that can be instantiated. * *
       * ... * ClassValidator validator = new ClassValidator(); * validator.setInstance(true); * * ArgumentBuilder builder = new ArgumentBuilder(); * Argument logger = *     builder.withName("logger"); *            .withValidator(validator); * 
      * * @author John Keyes */public class ClassValidator implements Validator { /** i18n */ private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); /** whether the class argument is loadable */ private boolean loadable; /** whether to create an instance of the class */ private boolean instance; /** the classloader to load classes from */ private ClassLoader loader; /** * Validate each argument value in the specified List against this instances * permitted attributes. * * If a value is valid then it's String value in the list is * replaced with it's Class value or instance. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { for (final ListIterator i = values.listIterator(); i.hasNext();) { final String name = (String) i.next(); if (!isPotentialClassName(name)) { throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_BAD_CLASSNAME, name)); } if (loadable || instance) { final ClassLoader theLoader = getClassLoader(); try { final Class clazz = theLoader.loadClass(name); if (instance) { i.set(clazz.newInstance()); } else { i.set(clazz); } } catch (final ClassNotFoundException exp) { throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_NOTFOUND, name)); } catch (final IllegalAccessException exp) { throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_ACCESS, name, exp.getMessage())); } catch (final InstantiationException exp) { throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_CREATE, name)); } } } } /** * Returns whether the argument value must represent a * class that is loadable. * * @return whether the argument value must represent a * class that is loadable. */ public boolean isLoadable() { return loadable; } /** * Specifies whether the argument value must represent a * class that is loadable. * * @param loadable whether the argument value must * represent a class that is loadable. */ public void setLoadable(boolean loadable) { this.loadable = loadable; } /** * Returns the {@link ClassLoader} used to resolve and load * the classes specified by the argument values. * * @return the {@link ClassLoader} used to resolve and load * the classes specified by the argument values. */ public ClassLoader getClassLoader() { if (loader == null) { loader = getClass().getClassLoader(); } return loader; } /** * Specifies the {@link ClassLoader} used to resolve and load * the classes specified by the argument values. * * @param loader the {@link ClassLoader} used to resolve and load * the classes specified by the argument values. */ public void setClassLoader(ClassLoader loader) { this.loader = loader; } /** * Returns whether the argument value must represent a * class that can be instantiated. * * @return whether the argument value must represent a * class that can be instantiated. */ public boolean isInstance() { return instance; } /** * Specifies whether the argument value must represent a * class that can be instantiated. * * @param instance whether the argument value must * represent a class that can be instantiated. */ public void setInstance(boolean instance) { this.instance = instance; } /** * Returns whether the specified name is allowed as * a Java class name. */ protected boolean isPotentialClassName(final String name) { final char[] chars = name.toCharArray(); boolean expectingStart = true; for (int i = 0; i < chars.length; ++i) { final char c = chars[i]; if (expectingStart) { if (!Character.isJavaIdentifierStart(c)) { return false; } expectingStart = false; } else { if (c == '.') { expectingStart = true; } else if (!Character.isJavaIdentifierPart(c)) { return false; } } } return !expectingStart; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/validation/DateValidator.java b/src/java/org/apache/commons/cli2/validation/DateValidator.java index 85fff682d..490bf476d 100644 --- a/src/java/org/apache/commons/cli2/validation/DateValidator.java +++ b/src/java/org/apache/commons/cli2/validation/DateValidator.java @@ -1,308 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.text.DateFormat; -import java.text.ParsePosition; - -import java.util.Date; -import java.util.List; -import java.util.ListIterator; - -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * The DateValidator validates the argument values - * are date or time value(s). - * - * The following example shows how to validate that - * an argument value(s) is a Date of the following - * type: d/M/yy (see {@link java.text.DateFormat}). - * - *
      - * DateFormat date = new SimpleDateFormat("d/M/yy");
      - * ...
      - * ArgumentBuilder builder = new ArgumentBuilder();
      - * Argument dateFormat =
      - *     builder.withName("date");
      - *            .withValidator(new DateValidator(dateFormat));
      - * 
      - * - * The following example shows how to validate that - * an argument value(s) is a time of the following - * type: HH:mm:ss (see {@link java.text.DateFormat}). - * - *
      - * DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
      - * ...
      - * ArgumentBuilder builder = new ArgumentBuilder();
      - * Argument time =
      - *     builder.withName("time");
      - *            .withValidator(new DateValidator(timeFormat));
      - * 
      - * - * @author John Keyes - * - * @see java.text.DateFormat - */ -public class DateValidator implements Validator { - /** i18n */ - private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); - - /** an array of permitted DateFormats */ - private DateFormat[] formats; - - /** minimum Date allowed i.e: a valid date occurs later than this date */ - private Date minimum; - - /** maximum Date allowed i.e: a valid date occurs earlier than this date */ - private Date maximum; - - /** leniant parsing */ - private boolean isLenient; - - /** - * Creates a Validator for the default date/time format - */ - public DateValidator() { - this(DateFormat.getInstance()); - } - - /** - * Creates a Validator for the specified DateFormat. - * - * @param format - * a DateFormat which dates must conform to - */ - public DateValidator(final DateFormat format) { - setFormat(format); - } - - /** - * Creates a Validator for the List of specified DateFormats. - * - * @param formats - * a List of DateFormats which dates must conform to - */ - public DateValidator(final List formats) { - setFormats(formats); - } - - /** - * Creates a Validator for dates. - * - * @return DateValidator a Validator for dates - */ - public static DateValidator getDateInstance() { - return new DateValidator(DateFormat.getDateInstance()); - } - - /** - * Creates a Validator for times. - * - * @return DateValidator a Validator for times - */ - public static DateValidator getTimeInstance() { - return new DateValidator(DateFormat.getTimeInstance()); - } - - /** - * Creates a Validator for date/times - * - * @return DateValidator a Validator for date/times - */ - public static DateValidator getDateTimeInstance() { - return new DateValidator(DateFormat.getDateTimeInstance()); - } - - /** - * Validate each String value in the specified List against this instances - * permitted DateFormats. - * - * If a value is valid then it's String value in the list is - * replaced with it's Date value. - * - * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) - */ - public void validate(final List values) - throws InvalidArgumentException { - // for each value - for (final ListIterator i = values.listIterator(); i.hasNext();) { - final String value = (String) i.next(); - - Date date = null; - - // create a resuable ParsePosition instance - final ParsePosition pp = new ParsePosition(0); - - // for each permitted DateFormat - for (int f = 0; (f < this.formats.length) && (date == null); ++f) { - // reset the parse position - pp.setIndex(0); - date = this.formats[f].parse(value, pp); - - // if the wrong number of characters have been parsed - if (pp.getIndex() < value.length()) { - date = null; - } - } - - // if date has not been set throw an InvalidArgumentException - if (date == null) { - throw new InvalidArgumentException(value); - } - - // if the date is outside the bounds - if (isDateEarlier(date) || isDateLater(date)) { - throw new InvalidArgumentException(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, - value)); - } - - // replace the value in the list with the actual Date - i.set(date); - } - } - - /** - * Sets whether this validator uses lenient parsing. - * - * @param lenient whether this validator uses lenient parsing - */ - public void setLenient(final boolean lenient) { - for (int i = 0; i < this.formats.length; i++) { - this.formats[i].setLenient(lenient); - } - - this.isLenient = lenient; - } - - /** - * Returns whether this validator uses lenient parsing. - * - * @return whether this validator uses lenient parsing - */ - public boolean isLenient() { - return this.isLenient; - } - - /** - * Returns the maximum date permitted. - * - * @return Date the maximum date permitted. If no maximum date has been - * specified then return null. - */ - public Date getMaximum() { - return maximum; - } - - /** - * Sets the maximum Date to the specified value. - * - * @param maximum - * the maximum Date permitted - */ - public void setMaximum(final Date maximum) { - this.maximum = maximum; - } - - /** - * Returns the minimum date permitted. - * - * @return Date the minimum date permitted. If no minimum date has been - * specified then return null. - */ - public Date getMinimum() { - return minimum; - } - - /** - * Sets the minimum Date to the specified value. - * - * @param minimum - * the minimum Date permitted - */ - public void setMinimum(Date minimum) { - this.minimum = minimum; - } - - /** - * Returns whether the specified Date is later than the maximum date. - * - * @param date - * the Date to evaluate - * - * @return boolean whether date is earlier than the maximum - * date - */ - private boolean isDateLater(Date date) { - return (maximum != null) && (date.getTime() > maximum.getTime()); - } - - /** - * Returns whether the specified Date is earlier than the minimum date. - * - * @param date - * the Date to evaluate - * - * @return boolean whether date is earlier than the minimum - * date - */ - private boolean isDateEarlier(Date date) { - return (minimum != null) && (date.getTime() < minimum.getTime()); - } - - /** - * Sets the date format permitted. - * - * @param format - * the format to use - */ - public void setFormat(final DateFormat format) { - setFormats(new DateFormat[] { format }); - } - - /** - * Sets the date formats permitted. - * - * @param formats - * the List of DateFormats to use - */ - public void setFormats(final List formats) { - setFormats((DateFormat[]) formats.toArray(new DateFormat[formats.size()])); - } - - /** - * Sets the date formats permitted. - * - * @param formats - * the array of DateFormats to use - */ - public void setFormats(final DateFormat[] formats) { - this.formats = formats; - setLenient(this.isLenient); - } - - /** - * Gets the date formats permitted. - * - * @return the permitted formats - */ - public DateFormat[] getFormats() { - return this.formats; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.text.DateFormat;import java.text.ParsePosition;import java.util.Date;import java.util.List;import java.util.ListIterator;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * The DateValidator validates the argument values * are date or time value(s). * * The following example shows how to validate that * an argument value(s) is a Date of the following * type: d/M/yy (see {@link java.text.DateFormat}). * *
       * DateFormat date = new SimpleDateFormat("d/M/yy"); * ... * ArgumentBuilder builder = new ArgumentBuilder(); * Argument dateFormat = *     builder.withName("date"); *            .withValidator(new DateValidator(dateFormat)); * 
      * * The following example shows how to validate that * an argument value(s) is a time of the following * type: HH:mm:ss (see {@link java.text.DateFormat}). * *
       * DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); * ... * ArgumentBuilder builder = new ArgumentBuilder(); * Argument time = *     builder.withName("time"); *            .withValidator(new DateValidator(timeFormat)); * 
      * * @author John Keyes * * @see java.text.DateFormat */public class DateValidator implements Validator { /** i18n */ private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); /** an array of permitted DateFormats */ private DateFormat[] formats; /** minimum Date allowed i.e: a valid date occurs later than this date */ private Date minimum; /** maximum Date allowed i.e: a valid date occurs earlier than this date */ private Date maximum; /** leniant parsing */ private boolean isLenient; /** * Creates a Validator for the default date/time format */ public DateValidator() { this(DateFormat.getInstance()); } /** * Creates a Validator for the specified DateFormat. * * @param format * a DateFormat which dates must conform to */ public DateValidator(final DateFormat format) { setFormat(format); } /** * Creates a Validator for the List of specified DateFormats. * * @param formats * a List of DateFormats which dates must conform to */ public DateValidator(final List formats) { setFormats(formats); } /** * Creates a Validator for dates. * * @return DateValidator a Validator for dates */ public static DateValidator getDateInstance() { return new DateValidator(DateFormat.getDateInstance()); } /** * Creates a Validator for times. * * @return DateValidator a Validator for times */ public static DateValidator getTimeInstance() { return new DateValidator(DateFormat.getTimeInstance()); } /** * Creates a Validator for date/times * * @return DateValidator a Validator for date/times */ public static DateValidator getDateTimeInstance() { return new DateValidator(DateFormat.getDateTimeInstance()); } /** * Validate each String value in the specified List against this instances * permitted DateFormats. * * If a value is valid then it's String value in the list is * replaced with it's Date value. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { // for each value for (final ListIterator i = values.listIterator(); i.hasNext();) { final String value = (String) i.next(); Date date = null; // create a resuable ParsePosition instance final ParsePosition pp = new ParsePosition(0); // for each permitted DateFormat for (int f = 0; (f < this.formats.length) && (date == null); ++f) { // reset the parse position pp.setIndex(0); date = this.formats[f].parse(value, pp); // if the wrong number of characters have been parsed if (pp.getIndex() < value.length()) { date = null; } } // if date has not been set throw an InvalidArgumentException if (date == null) { throw new InvalidArgumentException(value); } // if the date is outside the bounds if (isDateEarlier(date) || isDateLater(date)) { throw new InvalidArgumentException(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, value)); } // replace the value in the list with the actual Date i.set(date); } } /** * Sets whether this validator uses lenient parsing. * * @param lenient whether this validator uses lenient parsing */ public void setLenient(final boolean lenient) { for (int i = 0; i < this.formats.length; i++) { this.formats[i].setLenient(lenient); } this.isLenient = lenient; } /** * Returns whether this validator uses lenient parsing. * * @return whether this validator uses lenient parsing */ public boolean isLenient() { return this.isLenient; } /** * Returns the maximum date permitted. * * @return Date the maximum date permitted. If no maximum date has been * specified then return null. */ public Date getMaximum() { return maximum; } /** * Sets the maximum Date to the specified value. * * @param maximum * the maximum Date permitted */ public void setMaximum(final Date maximum) { this.maximum = maximum; } /** * Returns the minimum date permitted. * * @return Date the minimum date permitted. If no minimum date has been * specified then return null. */ public Date getMinimum() { return minimum; } /** * Sets the minimum Date to the specified value. * * @param minimum * the minimum Date permitted */ public void setMinimum(Date minimum) { this.minimum = minimum; } /** * Returns whether the specified Date is later than the maximum date. * * @param date * the Date to evaluate * * @return boolean whether date is earlier than the maximum * date */ private boolean isDateLater(Date date) { return (maximum != null) && (date.getTime() > maximum.getTime()); } /** * Returns whether the specified Date is earlier than the minimum date. * * @param date * the Date to evaluate * * @return boolean whether date is earlier than the minimum * date */ private boolean isDateEarlier(Date date) { return (minimum != null) && (date.getTime() < minimum.getTime()); } /** * Sets the date format permitted. * * @param format * the format to use */ public void setFormat(final DateFormat format) { setFormats(new DateFormat[] { format }); } /** * Sets the date formats permitted. * * @param formats * the List of DateFormats to use */ public void setFormats(final List formats) { setFormats((DateFormat[]) formats.toArray(new DateFormat[formats.size()])); } /** * Sets the date formats permitted. * * @param formats * the array of DateFormats to use */ public void setFormats(final DateFormat[] formats) { this.formats = formats; setLenient(this.isLenient); } /** * Gets the date formats permitted. * * @return the permitted formats */ public DateFormat[] getFormats() { return this.formats; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/validation/EnumValidator.java b/src/java/org/apache/commons/cli2/validation/EnumValidator.java index 12e376cbb..e67cb62fa 100644 --- a/src/java/org/apache/commons/cli2/validation/EnumValidator.java +++ b/src/java/org/apache/commons/cli2/validation/EnumValidator.java @@ -1,120 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * The EnumValidator validates the string argument - * values are valid. - * - * The following example shows how to limit the valid values - * for the color argument to 'red', 'green', or 'blue'. - * - *
      - * Set values = new HashSet();
      - * values.add("red");
      - * values.add("green");
      - * values.add("blue");
      - * ...
      - * ArgumentBuilder builder = new ArgumentBuilder();
      - * Argument color =
      - *     builder.withName("color");
      - *            .withValidator(new EnumValidator(values));
      - * 
      - * - * @author John Keyes - */ -public class EnumValidator implements Validator { - /** List of permitted values */ - private Set validValues; - - /** - * Creates a new EnumValidator for the specified values. - * - * @param values The list of permitted values - */ - public EnumValidator(final Set values) { - setValidValues(values); - } - - /** - * Validate the list of values against the list of permitted values. - * - * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) - */ - public void validate(final List values) - throws InvalidArgumentException { - for (final Iterator iter = values.iterator(); iter.hasNext();) { - final String value = (String) iter.next(); - - if (!this.validValues.contains(value)) { - throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ENUM_ILLEGAL_VALUE, - new Object[] { - value, - getValuesAsString() - })); - } - } - } - - /** - * Returns the permitted values in a comma separated String - * - * @return String formatted list of values - */ - String getValuesAsString() { - final StringBuffer buff = new StringBuffer(); - - buff.append("["); - - for (final Iterator iter = this.validValues.iterator(); iter.hasNext();) { - buff.append("'").append(iter.next()).append("'"); - - if (iter.hasNext()) { - buff.append(", "); - } - } - - buff.append("]"); - - return buff.toString(); - } - - /** - * Returns the Set of valid argument values. - * - * @return Returns the Set of valid argument values. - */ - public Set getValidValues() { - return validValues; - } - - /** - * Specifies the Set of valid argument values. - * - * @param validValues The Set of valid argument values. - */ - protected void setValidValues(Set validValues) { - this.validValues = validValues; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.util.Iterator;import java.util.List;import java.util.Set;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * The EnumValidator validates the string argument * values are valid. * * The following example shows how to limit the valid values * for the color argument to 'red', 'green', or 'blue'. * *
       * Set values = new HashSet(); * values.add("red"); * values.add("green"); * values.add("blue"); * ... * ArgumentBuilder builder = new ArgumentBuilder(); * Argument color = *     builder.withName("color"); *            .withValidator(new EnumValidator(values)); * 
      * * @author John Keyes */public class EnumValidator implements Validator { /** List of permitted values */ private Set validValues; /** * Creates a new EnumValidator for the specified values. * * @param values The list of permitted values */ public EnumValidator(final Set values) { setValidValues(values); } /** * Validate the list of values against the list of permitted values. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { for (final Iterator iter = values.iterator(); iter.hasNext();) { final String value = (String) iter.next(); if (!this.validValues.contains(value)) { throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ENUM_ILLEGAL_VALUE, new Object[] { value, getValuesAsString() })); } } } /** * Returns the permitted values in a comma separated String * * @return String formatted list of values */ String getValuesAsString() { final StringBuffer buff = new StringBuffer(); buff.append("["); for (final Iterator iter = this.validValues.iterator(); iter.hasNext();) { buff.append("'").append(iter.next()).append("'"); if (iter.hasNext()) { buff.append(", "); } } buff.append("]"); return buff.toString(); } /** * Returns the Set of valid argument values. * * @return Returns the Set of valid argument values. */ public Set getValidValues() { return validValues; } /** * Specifies the Set of valid argument values. * * @param validValues The Set of valid argument values. */ protected void setValidValues(Set validValues) { this.validValues = validValues; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/validation/FileValidator.java b/src/java/org/apache/commons/cli2/validation/FileValidator.java index aff1bc5f1..fdf996ad6 100644 --- a/src/java/org/apache/commons/cli2/validation/FileValidator.java +++ b/src/java/org/apache/commons/cli2/validation/FileValidator.java @@ -1,265 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.io.File; -import java.util.List; -import java.util.ListIterator; - -/** - * The FileValidator validates the string argument - * values are files. If the value is a file, the string value in - * the {@link java.util.List} of values is replaced with the - * {@link java.io.File} instance. - * - * The following attributes can also be specified using the - * appropriate settors: - *
        - *
      • writable
      • - *
      • readable
      • - *
      • hidden
      • - *
      • existing
      • - *
      • is a file
      • - *
      • is a directory
      • - *
      - * - * The following example shows how to limit the valid values - * for the config attribute to files that are readable, writeable, - * and that already existing. - * - *
      - * ...
      - * ArgumentBuilder builder = new ArgumentBuilder();
      - * FileValidator validator = FileValidator.getExistingFileInstance();
      - * validator.setReadable(true);
      - * validator.setWritable(true);
      - * 
      - * Argument age = 
      - *     builder.withName("config");
      - *            .withValidator(validator);
      - * 
      - * - * @author Rob Oxspring - * @author John Keyes - */ -public class FileValidator implements Validator { - - /** - * Returns a FileValidator for existing files/directories. - * - * @return a FileValidator for existing files/directories. - */ - public static FileValidator getExistingInstance() { - final FileValidator validator = new FileValidator(); - validator.setExisting(true); - return validator; - } - - /** - * Returns a FileValidator for existing files. - * - * @return a FileValidator for existing files. - */ - public static FileValidator getExistingFileInstance() { - final FileValidator validator = new FileValidator(); - validator.setExisting(true); - validator.setFile(true); - return validator; - } - - /** - * Returns a FileValidator for existing directories. - * - * @return a FileValidator for existing directories. - */ - public static FileValidator getExistingDirectoryInstance() { - final FileValidator validator = new FileValidator(); - validator.setExisting(true); - validator.setDirectory(true); - return validator; - } - - /** whether the argument value is readable */ - private boolean readable = false; - - /** whether the argument value is writable */ - private boolean writable = false; - - /** whether the argument value exists */ - private boolean existing = false; - - /** whether the argument value is a directory */ - private boolean directory = false; - - /** whether the argument value is a file */ - private boolean file = false; - - /** whether the argument value is a hidden file or directory */ - private boolean hidden = false; - - /** - * Validate the list of values against the list of permitted values. - * If a value is valid, replace the string in the values - * {@link java.util.List} with the {@link java.io.File} instance. - * - * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) - */ - public void validate(final List values) throws InvalidArgumentException { - for (final ListIterator i = values.listIterator(); i.hasNext();) { - final String name = (String)i.next(); - final File f = new File(name); - - if ((existing && !f.exists()) - || (file && !f.isFile()) - || (directory && !f.isDirectory()) - || (hidden && !f.isHidden()) - || (readable && !f.canRead()) - || (writable && !f.canWrite())) { - - throw new InvalidArgumentException(name); - } - - i.set(f); - } - } - - /** - * Returns whether the argument values must represent directories. - * - * @return whether the argument values must represent directories. - */ - public boolean isDirectory() { - return directory; - } - - /** - * Specifies whether the argument values must represent directories. - * - * @param directory specifies whether the argument values must - * represent directories. - */ - public void setDirectory(boolean directory) { - this.directory = directory; - } - - /** - * Returns whether the argument values must represent existing - * files/directories. - * - * @return whether the argument values must represent existing - * files/directories. - */ - public boolean isExisting() { - return existing; - } - - /** - * Specifies whether the argument values must represent existing - * files/directories. - * - * @param existing specifies whether the argument values must - * represent existing files/directories. - */ - public void setExisting(boolean existing) { - this.existing = existing; - } - - /** - * Returns whether the argument values must represent directories. - * - * @return whether the argument values must represent directories. - */ - public boolean isFile() { - return file; - } - - /** - * Specifies whether the argument values must represent files. - * - * @param file specifies whether the argument values must - * represent files. - */ - public void setFile(boolean file) { - this.file = file; - } - - /** - * Returns whether the argument values must represent hidden - * files/directories. - * - * @return whether the argument values must represent hidden - * files/directories. - */ - public boolean isHidden() { - return hidden; - } - - /** - * Specifies whether the argument values must represent hidden - * files/directories. - * - * @param hidden specifies whether the argument values must - * represent hidden files/directories. - */ - public void setHidden(boolean hidden) { - this.hidden = hidden; - } - - /** - * Returns whether the argument values must represent readable - * files/directories. - * - * @return whether the argument values must represent readable - * files/directories. - */ - public boolean isReadable() { - return readable; - } - - /** - * Specifies whether the argument values must represent readable - * files/directories. - * - * @param readable specifies whether the argument values must - * represent readable files/directories. - */ - public void setReadable(boolean readable) { - this.readable = readable; - } - - /** - * Returns whether the argument values must represent writable - * files/directories. - * - * @return whether the argument values must represent writable - * files/directories. - */ - public boolean isWritable() { - return writable; - } - - /** - * Specifies whether the argument values must represent writable - * files/directories. - * - * @param writable specifies whether the argument values must - * represent writable files/directories. - */ - public void setWritable(boolean writable) { - this.writable = writable; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.io.File;import java.util.List;import java.util.ListIterator;/** * The FileValidator validates the string argument * values are files. If the value is a file, the string value in * the {@link java.util.List} of values is replaced with the * {@link java.io.File} instance. * * The following attributes can also be specified using the * appropriate settors: *
        *
      • writable
      • *
      • readable
      • *
      • hidden
      • *
      • existing
      • *
      • is a file
      • *
      • is a directory
      • *
      * * The following example shows how to limit the valid values * for the config attribute to files that are readable, writeable, * and that already existing. * *
       * ... * ArgumentBuilder builder = new ArgumentBuilder(); * FileValidator validator = FileValidator.getExistingFileInstance(); * validator.setReadable(true); * validator.setWritable(true); * * Argument age = *     builder.withName("config"); *            .withValidator(validator); * 
      * * @author Rob Oxspring * @author John Keyes */public class FileValidator implements Validator { /** * Returns a FileValidator for existing files/directories. * * @return a FileValidator for existing files/directories. */ public static FileValidator getExistingInstance() { final FileValidator validator = new FileValidator(); validator.setExisting(true); return validator; } /** * Returns a FileValidator for existing files. * * @return a FileValidator for existing files. */ public static FileValidator getExistingFileInstance() { final FileValidator validator = new FileValidator(); validator.setExisting(true); validator.setFile(true); return validator; } /** * Returns a FileValidator for existing directories. * * @return a FileValidator for existing directories. */ public static FileValidator getExistingDirectoryInstance() { final FileValidator validator = new FileValidator(); validator.setExisting(true); validator.setDirectory(true); return validator; } /** whether the argument value is readable */ private boolean readable = false; /** whether the argument value is writable */ private boolean writable = false; /** whether the argument value exists */ private boolean existing = false; /** whether the argument value is a directory */ private boolean directory = false; /** whether the argument value is a file */ private boolean file = false; /** whether the argument value is a hidden file or directory */ private boolean hidden = false; /** * Validate the list of values against the list of permitted values. * If a value is valid, replace the string in the values * {@link java.util.List} with the {@link java.io.File} instance. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { for (final ListIterator i = values.listIterator(); i.hasNext();) { final String name = (String)i.next(); final File f = new File(name); if ((existing && !f.exists()) || (file && !f.isFile()) || (directory && !f.isDirectory()) || (hidden && !f.isHidden()) || (readable && !f.canRead()) || (writable && !f.canWrite())) { throw new InvalidArgumentException(name); } i.set(f); } } /** * Returns whether the argument values must represent directories. * * @return whether the argument values must represent directories. */ public boolean isDirectory() { return directory; } /** * Specifies whether the argument values must represent directories. * * @param directory specifies whether the argument values must * represent directories. */ public void setDirectory(boolean directory) { this.directory = directory; } /** * Returns whether the argument values must represent existing * files/directories. * * @return whether the argument values must represent existing * files/directories. */ public boolean isExisting() { return existing; } /** * Specifies whether the argument values must represent existing * files/directories. * * @param existing specifies whether the argument values must * represent existing files/directories. */ public void setExisting(boolean existing) { this.existing = existing; } /** * Returns whether the argument values must represent directories. * * @return whether the argument values must represent directories. */ public boolean isFile() { return file; } /** * Specifies whether the argument values must represent files. * * @param file specifies whether the argument values must * represent files. */ public void setFile(boolean file) { this.file = file; } /** * Returns whether the argument values must represent hidden * files/directories. * * @return whether the argument values must represent hidden * files/directories. */ public boolean isHidden() { return hidden; } /** * Specifies whether the argument values must represent hidden * files/directories. * * @param hidden specifies whether the argument values must * represent hidden files/directories. */ public void setHidden(boolean hidden) { this.hidden = hidden; } /** * Returns whether the argument values must represent readable * files/directories. * * @return whether the argument values must represent readable * files/directories. */ public boolean isReadable() { return readable; } /** * Specifies whether the argument values must represent readable * files/directories. * * @param readable specifies whether the argument values must * represent readable files/directories. */ public void setReadable(boolean readable) { this.readable = readable; } /** * Returns whether the argument values must represent writable * files/directories. * * @return whether the argument values must represent writable * files/directories. */ public boolean isWritable() { return writable; } /** * Specifies whether the argument values must represent writable * files/directories. * * @param writable specifies whether the argument values must * represent writable files/directories. */ public void setWritable(boolean writable) { this.writable = writable; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java b/src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java index 65c503e47..13d882fa0 100644 --- a/src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java +++ b/src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java @@ -1,34 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -/** - * An exception indicating validation failure. - * - * @author Rob Oxspring - * @author John Keyes - */ -public class InvalidArgumentException extends Exception { - - /** - * Creates a new exception - * @param message the reason for failure - */ - public InvalidArgumentException(final String message) { - super(message); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;/** * An exception indicating validation failure. * * @author Rob Oxspring * @author John Keyes */public class InvalidArgumentException extends Exception { /** * Creates a new exception * @param message the reason for failure */ public InvalidArgumentException(final String message) { super(message); }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/validation/NumberValidator.java b/src/java/org/apache/commons/cli2/validation/NumberValidator.java index 5761a71cd..b95b309dc 100644 --- a/src/java/org/apache/commons/cli2/validation/NumberValidator.java +++ b/src/java/org/apache/commons/cli2/validation/NumberValidator.java @@ -1,200 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.text.NumberFormat; -import java.text.ParsePosition; - -import java.util.List; -import java.util.ListIterator; - -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * The NumberValidator validates the string argument - * values are numbers. If the value is a number, the string value in - * the {@link java.util.List} of values is replaced with the - * {@link java.lang.Number} instance. - * - * A maximum and minimum value can also be specified using - * the {@link #setMaximum setMaximum}, and the - * {@link #setMinimum setMinimum} methods. - * - * The following example shows how to limit the valid values - * for the age attribute to integers less than 100. - * - *
      - * ...
      - * ArgumentBuilder builder = new ArgumentBuilder();
      - * NumberValidator validator = NumberValidator.getIntegerInstance();
      - * validator.setMaximum(new Integer(100));
      - *
      - * Argument age =
      - *     builder.withName("age");
      - *            .withValidator(validator);
      - * 
      - * - * @author Rob Oxspring - * @author John Keyes - */ -public class NumberValidator implements Validator { - /** the NumberFormat being used. */ - private NumberFormat format; - - /** the lower bound for argument values. */ - private Number minimum = null; - - /** the upper bound for argument values */ - private Number maximum = null; - - /** - * Creates a new NumberValidator based on the specified NumberFormat - * @param format the format of numbers to accept - */ - public NumberValidator(final NumberFormat format) { - setFormat(format); - } - - /** - * Returns a NumberValidator for a currency format - * for the current default locale. - * @return a NumberValidator for a currency format - * for the current default locale. - */ - public static NumberValidator getCurrencyInstance() { - return new NumberValidator(NumberFormat.getCurrencyInstance()); - } - - /** - * Returns a NumberValidator for an integer number format - * for the current default locale. - * @return a NumberValidator for an integer number format - * for the current default locale. - */ - public static NumberValidator getIntegerInstance() { - final NumberFormat format = NumberFormat.getNumberInstance(); - format.setParseIntegerOnly(true); - - return new NumberValidator(format); - } - - /** - * Returns a NumberValidator for a percentage format - * for the current default locale. - * @return a NumberValidator for a percentage format - * for the current default locale. - */ - public static NumberValidator getPercentInstance() { - return new NumberValidator(NumberFormat.getPercentInstance()); - } - - /** - * Returns a NumberValidator for a general-purpose - * number format for the current default locale. - * @return a NumberValidator for a general-purpose - * number format for the current default locale. - */ - public static NumberValidator getNumberInstance() { - return new NumberValidator(NumberFormat.getNumberInstance()); - } - - /** - * Validate the list of values against the list of permitted values. - * If a value is valid, replace the string in the values - * {@link java.util.List} with the {@link java.lang.Number} instance. - * - * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) - */ - public void validate(final List values) - throws InvalidArgumentException { - for (final ListIterator i = values.listIterator(); i.hasNext();) { - final String value = (String) i.next(); - - final ParsePosition pp = new ParsePosition(0); - final Number number = format.parse(value, pp); - - if (pp.getIndex() < value.length()) { - throw new InvalidArgumentException(value); - } - - if (((minimum != null) && (number.doubleValue() < minimum.doubleValue())) || - ((maximum != null) && (number.doubleValue() > maximum.doubleValue()))) { - throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, - new Object[] { - value - })); - } - - i.set(number); - } - } - - /** - * Return the format being used to validate argument values against. - * - * @return the format being used to validate argument values against. - */ - public NumberFormat getFormat() { - return format; - } - - /** - * Specify the format being used to validate argument values against. - * - * @param format the format being used to validate argument values against. - */ - protected void setFormat(NumberFormat format) { - this.format = format; - } - - /** - * Return the maximum value allowed for an argument value. - * - * @return the maximum value allowed for an argument value. - */ - public Number getMaximum() { - return maximum; - } - - /** - * Specify the maximum value allowed for an argument value. - * - * @param maximum the maximum value allowed for an argument value. - */ - public void setMaximum(Number maximum) { - this.maximum = maximum; - } - - /** - * Return the minimum value allowed for an argument value. - * - * @return the minimum value allowed for an argument value. - */ - public Number getMinimum() { - return minimum; - } - - /** - * Specify the minimum value allowed for an argument value. - * - * @param minimum the minimum value allowed for an argument value. - */ - public void setMinimum(Number minimum) { - this.minimum = minimum; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.text.NumberFormat;import java.text.ParsePosition;import java.util.List;import java.util.ListIterator;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * The NumberValidator validates the string argument * values are numbers. If the value is a number, the string value in * the {@link java.util.List} of values is replaced with the * {@link java.lang.Number} instance. * * A maximum and minimum value can also be specified using * the {@link #setMaximum setMaximum}, and the * {@link #setMinimum setMinimum} methods. * * The following example shows how to limit the valid values * for the age attribute to integers less than 100. * *
       * ... * ArgumentBuilder builder = new ArgumentBuilder(); * NumberValidator validator = NumberValidator.getIntegerInstance(); * validator.setMaximum(new Integer(100)); * * Argument age = *     builder.withName("age"); *            .withValidator(validator); * 
      * * @author Rob Oxspring * @author John Keyes */public class NumberValidator implements Validator { /** the NumberFormat being used. */ private NumberFormat format; /** the lower bound for argument values. */ private Number minimum = null; /** the upper bound for argument values */ private Number maximum = null; /** * Creates a new NumberValidator based on the specified NumberFormat * @param format the format of numbers to accept */ public NumberValidator(final NumberFormat format) { setFormat(format); } /** * Returns a NumberValidator for a currency format * for the current default locale. * @return a NumberValidator for a currency format * for the current default locale. */ public static NumberValidator getCurrencyInstance() { return new NumberValidator(NumberFormat.getCurrencyInstance()); } /** * Returns a NumberValidator for an integer number format * for the current default locale. * @return a NumberValidator for an integer number format * for the current default locale. */ public static NumberValidator getIntegerInstance() { final NumberFormat format = NumberFormat.getNumberInstance(); format.setParseIntegerOnly(true); return new NumberValidator(format); } /** * Returns a NumberValidator for a percentage format * for the current default locale. * @return a NumberValidator for a percentage format * for the current default locale. */ public static NumberValidator getPercentInstance() { return new NumberValidator(NumberFormat.getPercentInstance()); } /** * Returns a NumberValidator for a general-purpose * number format for the current default locale. * @return a NumberValidator for a general-purpose * number format for the current default locale. */ public static NumberValidator getNumberInstance() { return new NumberValidator(NumberFormat.getNumberInstance()); } /** * Validate the list of values against the list of permitted values. * If a value is valid, replace the string in the values * {@link java.util.List} with the {@link java.lang.Number} instance. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { for (final ListIterator i = values.listIterator(); i.hasNext();) { final String value = (String) i.next(); final ParsePosition pp = new ParsePosition(0); final Number number = format.parse(value, pp); if (pp.getIndex() < value.length()) { throw new InvalidArgumentException(value); } if (((minimum != null) && (number.doubleValue() < minimum.doubleValue())) || ((maximum != null) && (number.doubleValue() > maximum.doubleValue()))) { throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, new Object[] { value })); } i.set(number); } } /** * Return the format being used to validate argument values against. * * @return the format being used to validate argument values against. */ public NumberFormat getFormat() { return format; } /** * Specify the format being used to validate argument values against. * * @param format the format being used to validate argument values against. */ protected void setFormat(NumberFormat format) { this.format = format; } /** * Return the maximum value allowed for an argument value. * * @return the maximum value allowed for an argument value. */ public Number getMaximum() { return maximum; } /** * Specify the maximum value allowed for an argument value. * * @param maximum the maximum value allowed for an argument value. */ public void setMaximum(Number maximum) { this.maximum = maximum; } /** * Return the minimum value allowed for an argument value. * * @return the minimum value allowed for an argument value. */ public Number getMinimum() { return minimum; } /** * Specify the minimum value allowed for an argument value. * * @param minimum the minimum value allowed for an argument value. */ public void setMinimum(Number minimum) { this.minimum = minimum; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/validation/UrlValidator.java b/src/java/org/apache/commons/cli2/validation/UrlValidator.java index 4ce1d37f2..9c1da974c 100644 --- a/src/java/org/apache/commons/cli2/validation/UrlValidator.java +++ b/src/java/org/apache/commons/cli2/validation/UrlValidator.java @@ -1,115 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.net.MalformedURLException; -import java.net.URL; - -import java.util.List; -import java.util.ListIterator; - -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * The UrlValidator validates the string argument - * values are URLs. If the value is a URL, the string value in - * the {@link java.util.List} of values is replaced with the - * {@link java.net.URL} instance. - * - * URLs can also be validated based on their scheme by using - * the {@link #setProtocol setProtocol} method, or by using the specified - * {@link #UrlValidator(java.lang.String) constructor}. - * - * The following example shows how to limit the valid values - * for the site argument to 'https' URLs. - * - *
      - * ...
      - * ArgumentBuilder builder = new ArgumentBuilder();
      - * Argument site =
      - *     builder.withName("site");
      - *            .withValidator(new URLValidator("https"));
      - * 
      - * - * @author Rob Oxspring - * @author John Keyes - */ -public class UrlValidator implements Validator { - /** allowed protocol */ - private String protocol = null; - - /** - * Creates a UrlValidator. - */ - public UrlValidator() { - } - - /** - * Creates a UrlValidator for the specified protocol. - */ - public UrlValidator(final String protocol) { - setProtocol(protocol); - } - - /** - * Validate the list of values against the list of permitted values. - * If a value is valid, replace the string in the values - * {@link java.util.List} with the { java.net.URL} instance. - * - * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) - */ - public void validate(final List values) - throws InvalidArgumentException { - for (final ListIterator i = values.listIterator(); i.hasNext();) { - final String name = (String) i.next(); - - try { - final URL url = new URL(name); - - if ((protocol != null) && !protocol.equals(url.getProtocol())) { - throw new InvalidArgumentException(name); - } - - i.set(url); - } catch (final MalformedURLException mue) { - throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.URLVALIDATOR_MALFORMED_URL, - new Object[] { - name - })); - } - } - } - - /** - * Returns the protocol that must be used by a valid URL. - * - * @return the protocol that must be used by a valid URL. - */ - public String getProtocol() { - return protocol; - } - - /** - * Specifies the protocol that a URL must have to be valid. - * - * @param protocol the protocol that a URL must have to be valid. - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.net.MalformedURLException;import java.net.URL;import java.util.List;import java.util.ListIterator;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * The UrlValidator validates the string argument * values are URLs. If the value is a URL, the string value in * the {@link java.util.List} of values is replaced with the * {@link java.net.URL} instance. * * URLs can also be validated based on their scheme by using * the {@link #setProtocol setProtocol} method, or by using the specified * {@link #UrlValidator(java.lang.String) constructor}. * * The following example shows how to limit the valid values * for the site argument to 'https' URLs. * *
       * ... * ArgumentBuilder builder = new ArgumentBuilder(); * Argument site = *     builder.withName("site"); *            .withValidator(new URLValidator("https")); * 
      * * @author Rob Oxspring * @author John Keyes */public class UrlValidator implements Validator { /** allowed protocol */ private String protocol = null; /** * Creates a UrlValidator. */ public UrlValidator() { } /** * Creates a UrlValidator for the specified protocol. */ public UrlValidator(final String protocol) { setProtocol(protocol); } /** * Validate the list of values against the list of permitted values. * If a value is valid, replace the string in the values * {@link java.util.List} with the { java.net.URL} instance. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { for (final ListIterator i = values.listIterator(); i.hasNext();) { final String name = (String) i.next(); try { final URL url = new URL(name); if ((protocol != null) && !protocol.equals(url.getProtocol())) { throw new InvalidArgumentException(name); } i.set(url); } catch (final MalformedURLException mue) { throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.URLVALIDATOR_MALFORMED_URL, new Object[] { name })); } } } /** * Returns the protocol that must be used by a valid URL. * * @return the protocol that must be used by a valid URL. */ public String getProtocol() { return protocol; } /** * Specifies the protocol that a URL must have to be valid. * * @param protocol the protocol that a URL must have to be valid. */ public void setProtocol(String protocol) { this.protocol = protocol; }} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/validation/Validator.java b/src/java/org/apache/commons/cli2/validation/Validator.java index 2147dfd28..b0b7f4b92 100644 --- a/src/java/org/apache/commons/cli2/validation/Validator.java +++ b/src/java/org/apache/commons/cli2/validation/Validator.java @@ -1,43 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.util.List; - -/** - * The validation interface for validating argument values(s). - * - * A validator can replace the argument string value with a - * specific class instance e.g. the {@link UrlValidator} replaces - * the string value with a {@link java.net.URL} instance. - * - * @author Rob Oxspring - * @author John Keyes - */ -public interface Validator { - - /** - * Validate the specified values (List of Strings). - * - * @param values The values to validate. - * - * @throws InvalidArgumentException If any of the - * specified values are not valid. - */ - void validate(final List values) throws InvalidArgumentException; - -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.util.List;/** * The validation interface for validating argument values(s). * * A validator can replace the argument string value with a * specific class instance e.g. the {@link UrlValidator} replaces * the string value with a {@link java.net.URL} instance. * * @author Rob Oxspring * @author John Keyes */public interface Validator { /** * Validate the specified values (List of Strings). * * @param values The values to validate. * * @throws InvalidArgumentException If any of the * specified values are not valid. */ void validate(final List values) throws InvalidArgumentException;} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/CLITestCase.java b/src/test/org/apache/commons/cli2/CLITestCase.java index e2baf6913..59821ed27 100644 --- a/src/test/org/apache/commons/cli2/CLITestCase.java +++ b/src/test/org/apache/commons/cli2/CLITestCase.java @@ -1,85 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import junit.framework.TestCase; - -public abstract class CLITestCase extends TestCase { - - public static List list() { - return Collections.EMPTY_LIST; - } - - public static List list(final Object args[]) { - return new LinkedList(Arrays.asList(args)); - } - - public static List list(final Object arg0) { - return list(new Object[] { arg0 }); - } - - public static List list(final Object arg0, final Object arg1) { - return list(new Object[] { arg0, arg1 }); - } - - public static List list(final Object arg0, final Object arg1, final Object arg2) { - return list(new Object[] { arg0, arg1, arg2 }); - } - - public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3) { - return list(new Object[] { arg0, arg1, arg2, arg3 }); - } - - public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3, final Object arg4) { - return list(new Object[] { arg0, arg1, arg2, arg3, arg4 }); - } - - public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3, final Object arg4, final Object arg5) { - return list(new Object[] { arg0, arg1, arg2, arg3, arg4, arg5 }); - } - - public static void assertListContentsEqual(final List expected, final List found) { - - final Iterator e = expected.iterator(); - final Iterator f = found.iterator(); - - while (e.hasNext() && f.hasNext()) { - assertEquals(e.next(), f.next()); - } - - if (e.hasNext()) { - fail("Expected more elements"); - } - - if (f.hasNext()) { - fail("Found more elements"); - } - } - - public static void assertContentsEqual(final Collection expected, final Collection found) { - assertTrue(expected.containsAll(found)); - assertTrue(found.containsAll(expected)); - assertEquals(expected.size(), found.size()); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Arrays;import java.util.Collection;import java.util.Collections;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import junit.framework.TestCase;public abstract class CLITestCase extends TestCase { public static List list() { return Collections.EMPTY_LIST; } public static List list(final Object args[]) { return new LinkedList(Arrays.asList(args)); } public static List list(final Object arg0) { return list(new Object[] { arg0 }); } public static List list(final Object arg0, final Object arg1) { return list(new Object[] { arg0, arg1 }); } public static List list(final Object arg0, final Object arg1, final Object arg2) { return list(new Object[] { arg0, arg1, arg2 }); } public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3) { return list(new Object[] { arg0, arg1, arg2, arg3 }); } public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3, final Object arg4) { return list(new Object[] { arg0, arg1, arg2, arg3, arg4 }); } public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3, final Object arg4, final Object arg5) { return list(new Object[] { arg0, arg1, arg2, arg3, arg4, arg5 }); } public static void assertListContentsEqual(final List expected, final List found) { final Iterator e = expected.iterator(); final Iterator f = found.iterator(); while (e.hasNext() && f.hasNext()) { assertEquals(e.next(), f.next()); } if (e.hasNext()) { fail("Expected more elements"); } if (f.hasNext()) { fail("Found more elements"); } } public static void assertContentsEqual(final Collection expected, final Collection found) { assertTrue(expected.containsAll(found)); assertTrue(found.containsAll(expected)); assertEquals(expected.size(), found.size()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java b/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java index c4f1227cf..97e48fca3 100644 --- a/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java +++ b/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java @@ -1,251 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.SwitchBuilder; -import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; - -/** - * Tests the interaction of command line values and defaults supplied in different ways. - * - * Tests marked _Parsed involve values parsed from a command line. - * - * Tests marked _Method involve defaults supplied in the query method. - * - * Tests marked _Option involce defaults specified in the model. - * - * @author Rob Oxspring - */ -public class CommandLineDefaultsTest extends TestCase { - - /* - * utils to grab the default from the method - */ - - private Object methodSwitch(WriteableCommandLine cl, Option o, Boolean bool) { - return cl.getSwitch(o, bool); - } - - private Object methodSwitchNull(WriteableCommandLine cl, Option o) { - return methodSwitch(cl, o, null); - } - - private Object methodSwitchOff(WriteableCommandLine cl, Option o) { - return methodSwitch(cl, o, Boolean.FALSE); - } - - private Object methodSwitchOn(WriteableCommandLine cl, Option o) { - return methodSwitch(cl, o, Boolean.TRUE); - } - - private Object methodValueMissing(WriteableCommandLine cl, Option o) { - return cl.getValue(o); - } - - private Object methodValuePresent(WriteableCommandLine cl, Option o) { - return cl.getValue(o, "method"); - } - - /* - * utils to grab the default from the option model - */ - - private Option optionSwitch(Boolean bool) { - return new SwitchBuilder().withName("switch").withSwitchDefault(bool) - .create(); - } - - private Option optionSwitchNull() { - return optionSwitch(null); - } - - private Option optionSwitchOff() { - return optionSwitch(Boolean.FALSE); - } - - private Option optionSwitchOn() { - return optionSwitch(Boolean.TRUE); - } - - private Option optionValueMissing() { - return new ArgumentBuilder().create(); - } - - private Option optionValuePresent() { - return new ArgumentBuilder().withDefaults( - Arrays.asList(new String[] { "option" })).create(); - } - - /* - * utils to grab the input from the command line - */ - - private WriteableCommandLine parsedSwitch(Option o, Boolean bool) { - final List args; - if (bool == null) { - args = Collections.EMPTY_LIST; - } else { - args = Collections - .singletonList(String.valueOf(bool).toLowerCase()); - } - WriteableCommandLine cl = new WriteableCommandLineImpl(o, args); - o.defaults(cl); - if (bool != null) { - cl.addSwitch(o, bool.booleanValue()); - } - return cl; - } - - private WriteableCommandLine parsedSwitchNull(Option o) { - return parsedSwitch(o, null); - } - - private WriteableCommandLine parsedSwitchOn(Option o) { - return parsedSwitch(o, Boolean.TRUE); - } - - private WriteableCommandLine parsedValueMissing(Option o) { - WriteableCommandLine cl = new WriteableCommandLineImpl(o, - Collections.EMPTY_LIST); - o.defaults(cl); - return cl; - } - - private WriteableCommandLine parsedValuePresent(Option o) { - WriteableCommandLine cl = new WriteableCommandLineImpl(o, Arrays - .asList(new String[] { "parsed" })); - o.defaults(cl); - cl.addValue(o, "parsed"); - return cl; - } - - /* - * tests - */ - - public void testSwitch_Method() { - final Option o = optionSwitchNull(); - final WriteableCommandLine cl = parsedSwitchNull(o); - final Object v = methodSwitchOn(cl, o); - assertEquals(Boolean.TRUE, v); - } - - public void testSwitch_Method_Option() { - final Option o = optionSwitchOff(); - final WriteableCommandLine cl = parsedSwitchNull(o); - final Object v = methodSwitchOn(cl, o); - assertEquals(Boolean.TRUE, v); - } - - public void testSwitch_Option() { - final Option o = optionSwitchOn(); - final WriteableCommandLine cl = parsedSwitchNull(o); - final Object v = methodSwitchNull(cl, o); - assertEquals(Boolean.TRUE, v); - } - - public void testSwitch_Parsed() { - final Option o = optionSwitchNull(); - final WriteableCommandLine cl = parsedSwitchOn(o); - final Object v = methodSwitchNull(cl, o); - assertEquals(Boolean.TRUE, v); - } - - public void testSwitch_Parsed_Method() { - final Option o = optionSwitchOff(); - final WriteableCommandLine cl = parsedSwitchOn(o); - final Object v = methodSwitchNull(cl, o); - assertEquals(Boolean.TRUE, v); - } - - public void testSwitch_Parsed_Method_Option() { - final Option o = optionSwitchOff(); - final WriteableCommandLine cl = parsedSwitchOn(o); - final Object v = methodSwitchOff(cl, o); - assertEquals(Boolean.TRUE, v); - } - - public void testSwitch_Parsed_Option() { - final Option o = optionSwitchOff(); - final WriteableCommandLine cl = parsedSwitchOn(o); - final Object v = methodSwitchNull(cl, o); - assertEquals(Boolean.TRUE, v); - } - - public void testValues() { - final Option o = optionValueMissing(); - final WriteableCommandLine cl = parsedValueMissing(o); - final Object v = methodValueMissing(cl, o); - assertNull(v); - } - - public void testValues_Method() { - final Option o = optionValueMissing(); - final WriteableCommandLine cl = parsedValueMissing(o); - final Object v = methodValuePresent(cl, o); - assertEquals("method", v); - } - - public void testValues_Method_Option() { - final Option o = optionValuePresent(); - final WriteableCommandLine cl = parsedValueMissing(o); - final Object v = methodValuePresent(cl, o); - assertEquals("method", v); - } - - public void testValues_Option() { - final Option o = optionValuePresent(); - final WriteableCommandLine cl = parsedValueMissing(o); - final Object v = methodValueMissing(cl, o); - assertEquals("option", v); - } - - public void testValues_Parsed() { - final Option o = optionValueMissing(); - final WriteableCommandLine cl = parsedValuePresent(o); - final Object v = methodValueMissing(cl, o); - assertEquals("parsed", v); - } - - public void testValues_Parsed_Method() { - final Option o = optionValueMissing(); - final WriteableCommandLine cl = parsedValuePresent(o); - final Object v = methodValuePresent(cl, o); - assertEquals("parsed", v); - } - - public void testValues_Parsed_Method_Option() { - final Option o = optionValuePresent(); - final WriteableCommandLine cl = parsedValuePresent(o); - final Object v = methodValuePresent(cl, o); - assertEquals("parsed", v); - } - - public void testValues_Parsed_Option() { - final Option o = optionValuePresent(); - final WriteableCommandLine cl = parsedValuePresent(o); - final Object v = methodValueMissing(cl, o); - assertEquals("parsed", v); - } -} \ No newline at end of file +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Arrays;import java.util.Collections;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.SwitchBuilder;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;/** * Tests the interaction of command line values and defaults supplied in different ways. * * Tests marked _Parsed involve values parsed from a command line. * * Tests marked _Method involve defaults supplied in the query method. * * Tests marked _Option involce defaults specified in the model. * * @author Rob Oxspring */public class CommandLineDefaultsTest extends TestCase { /* * utils to grab the default from the method */ private Object methodSwitch(WriteableCommandLine cl, Option o, Boolean bool) { return cl.getSwitch(o, bool); } private Object methodSwitchNull(WriteableCommandLine cl, Option o) { return methodSwitch(cl, o, null); } private Object methodSwitchOff(WriteableCommandLine cl, Option o) { return methodSwitch(cl, o, Boolean.FALSE); } private Object methodSwitchOn(WriteableCommandLine cl, Option o) { return methodSwitch(cl, o, Boolean.TRUE); } private Object methodValueMissing(WriteableCommandLine cl, Option o) { return cl.getValue(o); } private Object methodValuePresent(WriteableCommandLine cl, Option o) { return cl.getValue(o, "method"); } /* * utils to grab the default from the option model */ private Option optionSwitch(Boolean bool) { return new SwitchBuilder().withName("switch").withSwitchDefault(bool) .create(); } private Option optionSwitchNull() { return optionSwitch(null); } private Option optionSwitchOff() { return optionSwitch(Boolean.FALSE); } private Option optionSwitchOn() { return optionSwitch(Boolean.TRUE); } private Option optionValueMissing() { return new ArgumentBuilder().create(); } private Option optionValuePresent() { return new ArgumentBuilder().withDefaults( Arrays.asList(new String[] { "option" })).create(); } /* * utils to grab the input from the command line */ private WriteableCommandLine parsedSwitch(Option o, Boolean bool) { final List args; if (bool == null) { args = Collections.EMPTY_LIST; } else { args = Collections .singletonList(String.valueOf(bool).toLowerCase()); } WriteableCommandLine cl = new WriteableCommandLineImpl(o, args); o.defaults(cl); if (bool != null) { cl.addSwitch(o, bool.booleanValue()); } return cl; } private WriteableCommandLine parsedSwitchNull(Option o) { return parsedSwitch(o, null); } private WriteableCommandLine parsedSwitchOn(Option o) { return parsedSwitch(o, Boolean.TRUE); } private WriteableCommandLine parsedValueMissing(Option o) { WriteableCommandLine cl = new WriteableCommandLineImpl(o, Collections.EMPTY_LIST); o.defaults(cl); return cl; } private WriteableCommandLine parsedValuePresent(Option o) { WriteableCommandLine cl = new WriteableCommandLineImpl(o, Arrays .asList(new String[] { "parsed" })); o.defaults(cl); cl.addValue(o, "parsed"); return cl; } /* * tests */ public void testSwitch_Method() { final Option o = optionSwitchNull(); final WriteableCommandLine cl = parsedSwitchNull(o); final Object v = methodSwitchOn(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Method_Option() { final Option o = optionSwitchOff(); final WriteableCommandLine cl = parsedSwitchNull(o); final Object v = methodSwitchOn(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Option() { final Option o = optionSwitchOn(); final WriteableCommandLine cl = parsedSwitchNull(o); final Object v = methodSwitchNull(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Parsed() { final Option o = optionSwitchNull(); final WriteableCommandLine cl = parsedSwitchOn(o); final Object v = methodSwitchNull(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Parsed_Method() { final Option o = optionSwitchOff(); final WriteableCommandLine cl = parsedSwitchOn(o); final Object v = methodSwitchNull(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Parsed_Method_Option() { final Option o = optionSwitchOff(); final WriteableCommandLine cl = parsedSwitchOn(o); final Object v = methodSwitchOff(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Parsed_Option() { final Option o = optionSwitchOff(); final WriteableCommandLine cl = parsedSwitchOn(o); final Object v = methodSwitchNull(cl, o); assertEquals(Boolean.TRUE, v); } public void testValues() { final Option o = optionValueMissing(); final WriteableCommandLine cl = parsedValueMissing(o); final Object v = methodValueMissing(cl, o); assertNull(v); } public void testValues_Method() { final Option o = optionValueMissing(); final WriteableCommandLine cl = parsedValueMissing(o); final Object v = methodValuePresent(cl, o); assertEquals("method", v); } public void testValues_Method_Option() { final Option o = optionValuePresent(); final WriteableCommandLine cl = parsedValueMissing(o); final Object v = methodValuePresent(cl, o); assertEquals("method", v); } public void testValues_Option() { final Option o = optionValuePresent(); final WriteableCommandLine cl = parsedValueMissing(o); final Object v = methodValueMissing(cl, o); assertEquals("option", v); } public void testValues_Parsed() { final Option o = optionValueMissing(); final WriteableCommandLine cl = parsedValuePresent(o); final Object v = methodValueMissing(cl, o); assertEquals("parsed", v); } public void testValues_Parsed_Method() { final Option o = optionValueMissing(); final WriteableCommandLine cl = parsedValuePresent(o); final Object v = methodValuePresent(cl, o); assertEquals("parsed", v); } public void testValues_Parsed_Method_Option() { final Option o = optionValuePresent(); final WriteableCommandLine cl = parsedValuePresent(o); final Object v = methodValuePresent(cl, o); assertEquals("parsed", v); } public void testValues_Parsed_Option() { final Option o = optionValuePresent(); final WriteableCommandLine cl = parsedValuePresent(o); final Object v = methodValueMissing(cl, o); assertEquals("parsed", v); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/CommandLineTestCase.java b/src/test/org/apache/commons/cli2/CommandLineTestCase.java index 07b2009b2..92398a00b 100644 --- a/src/test/org/apache/commons/cli2/CommandLineTestCase.java +++ b/src/test/org/apache/commons/cli2/CommandLineTestCase.java @@ -1,512 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import org.apache.commons.cli2.option.ArgumentTest; -import org.apache.commons.cli2.option.CommandTest; -import org.apache.commons.cli2.option.DefaultOptionTest; -import org.apache.commons.cli2.option.OptionTestCase; -import org.apache.commons.cli2.option.PropertyOption; -import org.apache.commons.cli2.option.SwitchTest; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -public abstract class CommandLineTestCase - extends CLITestCase { - private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); - public final Option present = - new DefaultOptionBuilder().withLongName("present").withLongName("alsopresent").create(); - public final Option missing = new DefaultOptionBuilder().withLongName("missing").create(); - public final Option multiple = new DefaultOptionBuilder().withLongName("multiple").create(); - public final Option bool = new DefaultOptionBuilder().withLongName("bool").create(); - public final Option root = - new GroupBuilder().withOption(present).withOption(missing).withOption(multiple) - .withOption(bool).create(); - private CommandLine commandLine; - - protected abstract CommandLine createCommandLine(); - - /* - * @see TestCase#setUp() - */ - public void setUp() - throws Exception { - super.setUp(); - commandLine = createCommandLine(); - } - - /* - * Class to test for boolean hasOption(String) - */ - public final void testHasOptionString() { - assertTrue(commandLine.hasOption("--present")); - assertTrue(commandLine.hasOption("--alsopresent")); - assertFalse(commandLine.hasOption("--missing")); - } - - /* - * Class to test for boolean hasOption(Option) - */ - public final void testHasOptionOption() { - assertTrue(commandLine.hasOption(present)); - assertFalse(commandLine.hasOption(missing)); - } - - public final void testGetOption() { - assertSame(present, commandLine.getOption("--present")); - assertSame(present, commandLine.getOption("--alsopresent")); - - //TODO decide whether the following assertion is valid - //assertSame(missing,commandLine.getOption("--missing")); - } - - /* - * Class to test for List getValues(String) - */ - public final void testGetValuesString() { - assertListContentsEqual(list("present value"), commandLine.getValues("--present")); - assertListContentsEqual(list("value 1", "value 2", "value 3"), - commandLine.getValues("--multiple")); - assertTrue(commandLine.getValues("--missing").isEmpty()); - } - - /* - * Class to test for List getValues(String, List) - */ - public final void testGetValuesStringList() { - assertListContentsEqual(list("present value"), commandLine.getValues("--present", null)); - assertListContentsEqual(list("present value"), commandLine.getValues("--alsopresent", null)); - assertSame(commandLine.getValues("--missing", Collections.EMPTY_LIST), - Collections.EMPTY_LIST); - - final List def = Collections.singletonList("default value"); - assertSame(def, commandLine.getValues("--missing", def)); - } - - /* - * Class to test for List getValues(Option) - */ - public final void testGetValuesOption() { - assertListContentsEqual(list("present value"), commandLine.getValues(present)); - assertTrue(commandLine.getValues(missing).isEmpty()); - } - - /* - * Class to test for List getValues(Option, List) - */ - public final void testGetValuesOptionList() { - assertListContentsEqual(list("present value"), commandLine.getValues(present)); - assertSame(commandLine.getValues(missing, Collections.EMPTY_LIST), Collections.EMPTY_LIST); - - final List defs = Collections.singletonList("custom default"); - assertSame(defs, commandLine.getValues(missing, defs)); - } - - /* - * Class to test for Object getValue(String) - */ - public final void testGetValueString() { - assertEquals("present value", commandLine.getValue("--present")); - assertEquals("present value", commandLine.getValue("--alsopresent")); - assertNull(commandLine.getValue("--missing")); - - try { - commandLine.getValue("--multiple"); - fail("expected IllegalStateException"); - } catch (IllegalStateException e) { - assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), - e.getMessage()); - } - } - - /* - * Class to test for Object getValue(String, Object) - */ - public final void testGetValueStringObject() { - assertEquals("present value", commandLine.getValue("--present", "default value")); - assertEquals("present value", commandLine.getValue("--alsopresent", "default value")); - assertEquals("default value", commandLine.getValue("--missing", "default value")); - - try { - commandLine.getValue("--multiple"); - fail("expected IllegalStateException"); - } catch (IllegalStateException e) { - assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), - e.getMessage()); - } - } - - /* - * Class to test for Object getValue(Option) - */ - public final void testGetValueOption() { - assertEquals("present value", commandLine.getValue(present)); - assertNull(commandLine.getValue(missing)); - - try { - commandLine.getValue(multiple); - fail("expected IllegalStateException"); - } catch (IllegalStateException e) { - assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), - e.getMessage()); - } - } - - /* - * Class to test for Object getValue(Option, Object) - */ - public final void testGetValueOptionObject() { - assertEquals("present value", commandLine.getValue(present, "default value")); - assertEquals("default value", commandLine.getValue(missing, "default value")); - - try { - commandLine.getValue(multiple); - fail("expected IllegalStateException"); - } catch (IllegalStateException e) { - assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), - e.getMessage()); - } - } - - /* - * Class to test for Boolean getSwitch(String) - */ - public final void testGetSwitchString() { - assertEquals(Boolean.TRUE, commandLine.getSwitch("--bool")); - assertNull(commandLine.getSwitch("--missing")); - } - - /* - * Class to test for Boolean getSwitch(String, Boolean) - */ - public final void testGetSwitchStringBoolean() { - assertEquals(Boolean.TRUE, commandLine.getSwitch("--bool", Boolean.FALSE)); - assertEquals(Boolean.FALSE, commandLine.getSwitch("--missing", Boolean.FALSE)); - } - - /* - * Class to test for Boolean getSwitch(Option) - */ - public final void testGetSwitchOption() { - assertEquals(Boolean.TRUE, commandLine.getSwitch(bool)); - assertNull(commandLine.getSwitch(missing)); - } - - /* - * Class to test for Boolean getSwitch(Option, Boolean) - */ - public final void testGetSwitchOptionBoolean() { - assertEquals(Boolean.TRUE, commandLine.getSwitch(bool, Boolean.FALSE)); - assertEquals(Boolean.FALSE, commandLine.getSwitch(missing, Boolean.FALSE)); - } - - /* - * Class to test for String getProperty(String) - */ - public final void testGetPropertyString() { - assertEquals("present property", commandLine.getProperty("present")); - assertNull(commandLine.getProperty("missing")); - } - - /* - * Class to test for String getProperty(String, String) - */ - public final void testGetPropertyStringString() { - assertEquals("present property", commandLine.getProperty("present", "default property")); - assertEquals("default property", commandLine.getProperty("missing", "default property")); - } - - public final void testGetProperties() { - assertTrue(commandLine.getProperties().containsAll(list("present"))); - } - - /* - * Class to test for int getOptionCount(String) - */ - public final void testGetOptionCountString() { - // one option, one switch - assertTrue(1 <= commandLine.getOptionCount("--present")); - assertTrue(1 <= commandLine.getOptionCount("--bool")); - assertEquals(0, commandLine.getOptionCount("--missing")); - } - - /* - * Class to test for int getOptionCount(Option) - */ - public final void testGetOptionCountOption() { - // one option, one switch - assertTrue(1 <= commandLine.getOptionCount(present)); - assertTrue(1 <= commandLine.getOptionCount(bool)); - assertEquals(0, commandLine.getOptionCount(missing)); - } - - public final void testGetOptions() { - //TODO Implement getOptions(). - } - - public final void testGetOptionTriggers() { - //TODO Implement getOptionTriggers(). - } - - // OLD TESTS FOLLOW - public final void testProperties() { - final Option option = new PropertyOption(); - final List args = CLITestCase.list(); - final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); - - assertTrue(writeable.getProperties().isEmpty()); - - writeable.addProperty("myprop", "myval"); - assertEquals(1, writeable.getProperties().size()); - assertEquals("myval", writeable.getProperty("myprop")); - - writeable.addProperty("myprop", "myval2"); - assertEquals(1, writeable.getProperties().size()); - assertEquals("myval2", writeable.getProperty("myprop")); - - writeable.addProperty("myprop2", "myval3"); - assertEquals(2, writeable.getProperties().size()); - assertEquals("myval3", writeable.getProperty("myprop2")); - } - - public final void testOptions() { - final Option option = new PropertyOption(); - final List args = CLITestCase.list(); - final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); - - final Option start = CommandTest.buildStartCommand(); - - assertFalse(writeable.hasOption(start)); - assertFalse(writeable.hasOption("start")); - assertFalse(writeable.hasOption("go")); - - writeable.addOption(start); - - assertTrue(writeable.hasOption(start)); - assertTrue(writeable.hasOption("start")); - assertTrue(writeable.hasOption("go")); - } - - public final void testValues() { - final Option option = new PropertyOption(); - final List args = CLITestCase.list(); - final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); - - final Option start = CommandTest.buildStartCommand(); - - assertNull(writeable.getValue(start)); - assertTrue(writeable.getValues(start).isEmpty()); - - writeable.addOption(start); - - assertTrue(writeable.getValues(start).isEmpty()); - - writeable.addValue(start, "file1"); - - assertEquals("file1", writeable.getValue(start)); - assertEquals("file1", writeable.getValue("start")); - assertEquals("file1", writeable.getValue("go")); - assertEquals(1, writeable.getValues(start).size()); - assertEquals(1, writeable.getValues("start").size()); - assertEquals(1, writeable.getValues("go").size()); - assertTrue(writeable.getValues(start).contains("file1")); - assertTrue(writeable.getValues("start").contains("file1")); - assertTrue(writeable.getValues("go").contains("file1")); - - writeable.addValue(start, "file2"); - - try { - writeable.getValue(start); - fail("Cannot get single value if multiple are present"); - } catch (IllegalStateException ise) { - assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), - ise.getMessage()); - } - - try { - writeable.getValue("start"); - fail("Cannot get single value if multiple are present"); - } catch (IllegalStateException ise) { - assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), - ise.getMessage()); - } - - writeable.getValues(start).add("file3"); - } - - public final void testSwitches() { - final Option option = new PropertyOption(); - final List args = CLITestCase.list(); - final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); - - final Option start = CommandTest.buildStartCommand(); - - assertNull(writeable.getSwitch(start)); - assertNull(writeable.getSwitch("start")); - assertNull(writeable.getSwitch("go")); - - writeable.addSwitch(start, true); - - try { - writeable.addSwitch(start, false); - fail("Switch cannot be changed"); - } catch (IllegalStateException ise) { - assertEquals(resources.getMessage(ResourceConstants.SWITCH_ALREADY_SET), - ise.getMessage()); - } - } - - public final void testSwitches_True() { - final Option option = new PropertyOption(); - final List args = CLITestCase.list(); - final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); - - final Option start = CommandTest.buildStartCommand(); - - writeable.addSwitch(start, true); - assertSame(Boolean.TRUE, writeable.getSwitch(start)); - } - - public final void testSwitches_False() { - final Option option = new PropertyOption(); - final List args = CLITestCase.list(); - final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); - - final Option start = CommandTest.buildStartCommand(); - - writeable.addSwitch(start, false); - assertSame(Boolean.FALSE, writeable.getSwitch(start)); - } - - // public final void testLooksLikeOption() { - // final Option option = new PropertyOption(); - // final List args = OptionTestCase.list(); - // final WriteableCommandLine commandLine = - // OptionTestCase.commandLine(option, args); - // - // assertTrue(commandLine.looksLikeOption("-D")); - // assertFalse(commandLine.looksLikeOption("--help")); - // assertFalse(commandLine.looksLikeOption("+display")); - // assertFalse(commandLine.looksLikeOption("myprefix")); - // assertFalse(commandLine.looksLikeOption("myprefix2")); - // assertFalse(commandLine.looksLikeOption("myprefference")); - // assertFalse(commandLine.looksLikeOption("/SCANDISK")); - // assertFalse(commandLine.looksLikeOption("update")); - // } - public final void testGetOptions_Order() - throws OptionException { - final Option help = DefaultOptionTest.buildHelpOption(); - final Option login = CommandTest.buildLoginCommand(); - final Option targets = ArgumentTest.buildTargetsArgument(); - - final Group group = - new GroupBuilder().withOption(help).withOption(login).withOption(targets).create(); - - final Parser parser = new Parser(); - parser.setGroup(group); - - final CommandLine cl = - parser.parse(new String[] { "login", "rob", "--help", "target1", "target2" }); - - final Iterator i = cl.getOptions().iterator(); - - assertSame(login, i.next()); - assertSame(help, i.next()); - assertSame(targets, i.next()); - assertSame(targets, i.next()); - assertFalse(i.hasNext()); - } - - public final void testGetOptionCount() - throws OptionException { - final Option help = DefaultOptionTest.buildHelpOption(); - final Option login = CommandTest.buildLoginCommand(); - final Option targets = ArgumentTest.buildTargetsArgument(); - final Option display = SwitchTest.buildDisplaySwitch(); - - final Group group = - new GroupBuilder().withOption(help).withOption(login).withOption(targets) - .withOption(display).create(); - - final Parser parser = new Parser(); - parser.setGroup(group); - - final CommandLine cl = - parser.parse(new String[] { - "--help", "login", "rob", "+display", "--help", "--help", "target1", - "target2" - }); - - assertEquals(1, cl.getOptionCount(login)); - assertEquals(3, cl.getOptionCount(help)); - assertEquals(2, cl.getOptionCount(targets)); - assertEquals(1, cl.getOptionCount(display)); - } - - public final void testGetOptionCount_Strings() - throws OptionException { - final Option help = DefaultOptionTest.buildHelpOption(); - final Option login = CommandTest.buildLoginCommand(); - final Option targets = ArgumentTest.buildTargetsArgument(); - final Option display = SwitchTest.buildDisplaySwitch(); - - final Group group = - new GroupBuilder().withOption(help).withOption(login).withOption(targets) - .withOption(display).create(); - - final Parser parser = new Parser(); - parser.setGroup(group); - - final CommandLine cl = - parser.parse(new String[] { - "--help", "login", "rob", "+display", "--help", "--help", "target1", - "target2" - }); - - assertEquals(1, cl.getOptionCount("login")); - assertEquals(3, cl.getOptionCount("-?")); - assertEquals(1, cl.getOptionCount("+display")); - } - - public final void testOptionAsArgument() - throws OptionException { - final Option p = new DefaultOptionBuilder().withShortName("p").create(); - final Argument argument = new ArgumentBuilder().create(); - final Option withArgument = - new DefaultOptionBuilder().withShortName("attr").withArgument(argument).create(); - - final Group group = new GroupBuilder().withOption(p).withOption(withArgument).create(); - - final Parser parser = new Parser(); - parser.setGroup(group); - - final CommandLine cl = parser.parse(new String[] { "-p", "-attr", "p" }); - - assertEquals(1, cl.getOptionCount("-p")); - assertTrue(cl.hasOption("-p")); - assertTrue(cl.hasOption("-attr")); - assertTrue(cl.getValue("-attr").equals("p")); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Collections;import java.util.Iterator;import java.util.List;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.option.ArgumentTest;import org.apache.commons.cli2.option.CommandTest;import org.apache.commons.cli2.option.DefaultOptionTest;import org.apache.commons.cli2.option.OptionTestCase;import org.apache.commons.cli2.option.PropertyOption;import org.apache.commons.cli2.option.SwitchTest;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;public abstract class CommandLineTestCase extends CLITestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); public final Option present = new DefaultOptionBuilder().withLongName("present").withLongName("alsopresent").create(); public final Option missing = new DefaultOptionBuilder().withLongName("missing").create(); public final Option multiple = new DefaultOptionBuilder().withLongName("multiple").create(); public final Option bool = new DefaultOptionBuilder().withLongName("bool").create(); public final Option root = new GroupBuilder().withOption(present).withOption(missing).withOption(multiple) .withOption(bool).create(); private CommandLine commandLine; protected abstract CommandLine createCommandLine(); /* * @see TestCase#setUp() */ public void setUp() throws Exception { super.setUp(); commandLine = createCommandLine(); } /* * Class to test for boolean hasOption(String) */ public final void testHasOptionString() { assertTrue(commandLine.hasOption("--present")); assertTrue(commandLine.hasOption("--alsopresent")); assertFalse(commandLine.hasOption("--missing")); } /* * Class to test for boolean hasOption(Option) */ public final void testHasOptionOption() { assertTrue(commandLine.hasOption(present)); assertFalse(commandLine.hasOption(missing)); } public final void testGetOption() { assertSame(present, commandLine.getOption("--present")); assertSame(present, commandLine.getOption("--alsopresent")); //TODO decide whether the following assertion is valid //assertSame(missing,commandLine.getOption("--missing")); } /* * Class to test for List getValues(String) */ public final void testGetValuesString() { assertListContentsEqual(list("present value"), commandLine.getValues("--present")); assertListContentsEqual(list("value 1", "value 2", "value 3"), commandLine.getValues("--multiple")); assertTrue(commandLine.getValues("--missing").isEmpty()); } /* * Class to test for List getValues(String, List) */ public final void testGetValuesStringList() { assertListContentsEqual(list("present value"), commandLine.getValues("--present", null)); assertListContentsEqual(list("present value"), commandLine.getValues("--alsopresent", null)); assertSame(commandLine.getValues("--missing", Collections.EMPTY_LIST), Collections.EMPTY_LIST); final List def = Collections.singletonList("default value"); assertSame(def, commandLine.getValues("--missing", def)); } /* * Class to test for List getValues(Option) */ public final void testGetValuesOption() { assertListContentsEqual(list("present value"), commandLine.getValues(present)); assertTrue(commandLine.getValues(missing).isEmpty()); } /* * Class to test for List getValues(Option, List) */ public final void testGetValuesOptionList() { assertListContentsEqual(list("present value"), commandLine.getValues(present)); assertSame(commandLine.getValues(missing, Collections.EMPTY_LIST), Collections.EMPTY_LIST); final List defs = Collections.singletonList("custom default"); assertSame(defs, commandLine.getValues(missing, defs)); } /* * Class to test for Object getValue(String) */ public final void testGetValueString() { assertEquals("present value", commandLine.getValue("--present")); assertEquals("present value", commandLine.getValue("--alsopresent")); assertNull(commandLine.getValue("--missing")); try { commandLine.getValue("--multiple"); fail("expected IllegalStateException"); } catch (IllegalStateException e) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), e.getMessage()); } } /* * Class to test for Object getValue(String, Object) */ public final void testGetValueStringObject() { assertEquals("present value", commandLine.getValue("--present", "default value")); assertEquals("present value", commandLine.getValue("--alsopresent", "default value")); assertEquals("default value", commandLine.getValue("--missing", "default value")); try { commandLine.getValue("--multiple"); fail("expected IllegalStateException"); } catch (IllegalStateException e) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), e.getMessage()); } } /* * Class to test for Object getValue(Option) */ public final void testGetValueOption() { assertEquals("present value", commandLine.getValue(present)); assertNull(commandLine.getValue(missing)); try { commandLine.getValue(multiple); fail("expected IllegalStateException"); } catch (IllegalStateException e) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), e.getMessage()); } } /* * Class to test for Object getValue(Option, Object) */ public final void testGetValueOptionObject() { assertEquals("present value", commandLine.getValue(present, "default value")); assertEquals("default value", commandLine.getValue(missing, "default value")); try { commandLine.getValue(multiple); fail("expected IllegalStateException"); } catch (IllegalStateException e) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), e.getMessage()); } } /* * Class to test for Boolean getSwitch(String) */ public final void testGetSwitchString() { assertEquals(Boolean.TRUE, commandLine.getSwitch("--bool")); assertNull(commandLine.getSwitch("--missing")); } /* * Class to test for Boolean getSwitch(String, Boolean) */ public final void testGetSwitchStringBoolean() { assertEquals(Boolean.TRUE, commandLine.getSwitch("--bool", Boolean.FALSE)); assertEquals(Boolean.FALSE, commandLine.getSwitch("--missing", Boolean.FALSE)); } /* * Class to test for Boolean getSwitch(Option) */ public final void testGetSwitchOption() { assertEquals(Boolean.TRUE, commandLine.getSwitch(bool)); assertNull(commandLine.getSwitch(missing)); } /* * Class to test for Boolean getSwitch(Option, Boolean) */ public final void testGetSwitchOptionBoolean() { assertEquals(Boolean.TRUE, commandLine.getSwitch(bool, Boolean.FALSE)); assertEquals(Boolean.FALSE, commandLine.getSwitch(missing, Boolean.FALSE)); } /* * Class to test for String getProperty(String) */ public final void testGetPropertyString() { assertEquals("present property", commandLine.getProperty("present")); assertNull(commandLine.getProperty("missing")); } /* * Class to test for String getProperty(String, String) */ public final void testGetPropertyStringString() { assertEquals("present property", commandLine.getProperty("present", "default property")); assertEquals("default property", commandLine.getProperty("missing", "default property")); } public final void testGetProperties() { assertTrue(commandLine.getProperties().containsAll(list("present"))); } /* * Class to test for int getOptionCount(String) */ public final void testGetOptionCountString() { // one option, one switch assertTrue(1 <= commandLine.getOptionCount("--present")); assertTrue(1 <= commandLine.getOptionCount("--bool")); assertEquals(0, commandLine.getOptionCount("--missing")); } /* * Class to test for int getOptionCount(Option) */ public final void testGetOptionCountOption() { // one option, one switch assertTrue(1 <= commandLine.getOptionCount(present)); assertTrue(1 <= commandLine.getOptionCount(bool)); assertEquals(0, commandLine.getOptionCount(missing)); } public final void testGetOptions() { //TODO Implement getOptions(). } public final void testGetOptionTriggers() { //TODO Implement getOptionTriggers(). } // OLD TESTS FOLLOW public final void testProperties() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); assertTrue(writeable.getProperties().isEmpty()); writeable.addProperty("myprop", "myval"); assertEquals(1, writeable.getProperties().size()); assertEquals("myval", writeable.getProperty("myprop")); writeable.addProperty("myprop", "myval2"); assertEquals(1, writeable.getProperties().size()); assertEquals("myval2", writeable.getProperty("myprop")); writeable.addProperty("myprop2", "myval3"); assertEquals(2, writeable.getProperties().size()); assertEquals("myval3", writeable.getProperty("myprop2")); } public final void testOptions() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); final Option start = CommandTest.buildStartCommand(); assertFalse(writeable.hasOption(start)); assertFalse(writeable.hasOption("start")); assertFalse(writeable.hasOption("go")); writeable.addOption(start); assertTrue(writeable.hasOption(start)); assertTrue(writeable.hasOption("start")); assertTrue(writeable.hasOption("go")); } public final void testValues() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); final Option start = CommandTest.buildStartCommand(); assertNull(writeable.getValue(start)); assertTrue(writeable.getValues(start).isEmpty()); writeable.addOption(start); assertTrue(writeable.getValues(start).isEmpty()); writeable.addValue(start, "file1"); assertEquals("file1", writeable.getValue(start)); assertEquals("file1", writeable.getValue("start")); assertEquals("file1", writeable.getValue("go")); assertEquals(1, writeable.getValues(start).size()); assertEquals(1, writeable.getValues("start").size()); assertEquals(1, writeable.getValues("go").size()); assertTrue(writeable.getValues(start).contains("file1")); assertTrue(writeable.getValues("start").contains("file1")); assertTrue(writeable.getValues("go").contains("file1")); writeable.addValue(start, "file2"); try { writeable.getValue(start); fail("Cannot get single value if multiple are present"); } catch (IllegalStateException ise) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), ise.getMessage()); } try { writeable.getValue("start"); fail("Cannot get single value if multiple are present"); } catch (IllegalStateException ise) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), ise.getMessage()); } writeable.getValues(start).add("file3"); } public final void testSwitches() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); final Option start = CommandTest.buildStartCommand(); assertNull(writeable.getSwitch(start)); assertNull(writeable.getSwitch("start")); assertNull(writeable.getSwitch("go")); writeable.addSwitch(start, true); try { writeable.addSwitch(start, false); fail("Switch cannot be changed"); } catch (IllegalStateException ise) { assertEquals(resources.getMessage(ResourceConstants.SWITCH_ALREADY_SET), ise.getMessage()); } } public final void testSwitches_True() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); final Option start = CommandTest.buildStartCommand(); writeable.addSwitch(start, true); assertSame(Boolean.TRUE, writeable.getSwitch(start)); } public final void testSwitches_False() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); final Option start = CommandTest.buildStartCommand(); writeable.addSwitch(start, false); assertSame(Boolean.FALSE, writeable.getSwitch(start)); } // public final void testLooksLikeOption() { // final Option option = new PropertyOption(); // final List args = OptionTestCase.list(); // final WriteableCommandLine commandLine = // OptionTestCase.commandLine(option, args); // // assertTrue(commandLine.looksLikeOption("-D")); // assertFalse(commandLine.looksLikeOption("--help")); // assertFalse(commandLine.looksLikeOption("+display")); // assertFalse(commandLine.looksLikeOption("myprefix")); // assertFalse(commandLine.looksLikeOption("myprefix2")); // assertFalse(commandLine.looksLikeOption("myprefference")); // assertFalse(commandLine.looksLikeOption("/SCANDISK")); // assertFalse(commandLine.looksLikeOption("update")); // } public final void testGetOptions_Order() throws OptionException { final Option help = DefaultOptionTest.buildHelpOption(); final Option login = CommandTest.buildLoginCommand(); final Option targets = ArgumentTest.buildTargetsArgument(); final Group group = new GroupBuilder().withOption(help).withOption(login).withOption(targets).create(); final Parser parser = new Parser(); parser.setGroup(group); final CommandLine cl = parser.parse(new String[] { "login", "rob", "--help", "target1", "target2" }); final Iterator i = cl.getOptions().iterator(); assertSame(login, i.next()); assertSame(help, i.next()); assertSame(targets, i.next()); assertSame(targets, i.next()); assertFalse(i.hasNext()); } public final void testGetOptionCount() throws OptionException { final Option help = DefaultOptionTest.buildHelpOption(); final Option login = CommandTest.buildLoginCommand(); final Option targets = ArgumentTest.buildTargetsArgument(); final Option display = SwitchTest.buildDisplaySwitch(); final Group group = new GroupBuilder().withOption(help).withOption(login).withOption(targets) .withOption(display).create(); final Parser parser = new Parser(); parser.setGroup(group); final CommandLine cl = parser.parse(new String[] { "--help", "login", "rob", "+display", "--help", "--help", "target1", "target2" }); assertEquals(1, cl.getOptionCount(login)); assertEquals(3, cl.getOptionCount(help)); assertEquals(2, cl.getOptionCount(targets)); assertEquals(1, cl.getOptionCount(display)); } public final void testGetOptionCount_Strings() throws OptionException { final Option help = DefaultOptionTest.buildHelpOption(); final Option login = CommandTest.buildLoginCommand(); final Option targets = ArgumentTest.buildTargetsArgument(); final Option display = SwitchTest.buildDisplaySwitch(); final Group group = new GroupBuilder().withOption(help).withOption(login).withOption(targets) .withOption(display).create(); final Parser parser = new Parser(); parser.setGroup(group); final CommandLine cl = parser.parse(new String[] { "--help", "login", "rob", "+display", "--help", "--help", "target1", "target2" }); assertEquals(1, cl.getOptionCount("login")); assertEquals(3, cl.getOptionCount("-?")); assertEquals(1, cl.getOptionCount("+display")); } public final void testOptionAsArgument() throws OptionException { final Option p = new DefaultOptionBuilder().withShortName("p").create(); final Argument argument = new ArgumentBuilder().create(); final Option withArgument = new DefaultOptionBuilder().withShortName("attr").withArgument(argument).create(); final Group group = new GroupBuilder().withOption(p).withOption(withArgument).create(); final Parser parser = new Parser(); parser.setGroup(group); final CommandLine cl = parser.parse(new String[] { "-p", "-attr", "p" }); assertEquals(1, cl.getOptionCount("-p")); assertTrue(cl.hasOption("-p")); assertTrue(cl.hasOption("-attr")); assertTrue(cl.getValue("-attr").equals("p")); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/DocumentationTest.java b/src/test/org/apache/commons/cli2/DocumentationTest.java index 4b8fe13a1..0ab509e16 100644 --- a/src/test/org/apache/commons/cli2/DocumentationTest.java +++ b/src/test/org/apache/commons/cli2/DocumentationTest.java @@ -1,445 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; -import org.apache.commons.cli2.option.DefaultOption; -import org.apache.commons.cli2.option.PropertyOption; -import org.apache.commons.cli2.util.HelpFormatter; - -/** - * @author Rob - */ -public class DocumentationTest extends TestCase { - - public void testBasicUsage() throws IOException, OptionException { - HelpFormatter helpFormatter = new HelpFormatter(); - //ignore all printed - helpFormatter.setPrintWriter(new PrintWriter(new StringWriter())); - - /* - * --version -? -h --help -log file -s|-q|-v|-d Bursting File/Num/Date - * validation Switches Commands Auto help Auto exception help - * - */ - DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - Option version = - obuilder - .withLongName("version") - .withDescription("Displays version information and then exits") - .create(); - - Option help = - obuilder - .withShortName("h") - .withShortName("?") - .withLongName("help") - .withDescription("Displays help on usage and then exits") - .create(); - - ArgumentBuilder abuilder = new ArgumentBuilder(); - Argument logFile = - abuilder - .withDescription("The log file to write to") - .withName("file") - .withMinimum(1) - .withMaximum(1) - .create(); - Option log = - obuilder - .withArgument(logFile) - .withShortName("log") - .withDescription("Log progress information to a file") - .create(); - - GroupBuilder gbuilder = new GroupBuilder(); - Group outputQuality = - gbuilder - .withName("quality") - .withDescription("Controls the quality of console output") - .withMaximum(1) - .withOption( - obuilder - .withShortName("s") - .withDescription("Silent") - .create()) - .withOption( - obuilder - .withShortName("q") - .withDescription("Quiet") - .create()) - .withOption( - obuilder - .withShortName("n") - .withDescription("Normal") - .create()) - .withOption( - obuilder - .withShortName("v") - .withDescription("Verbose") - .create()) - .withOption( - obuilder - .withShortName("d") - .withDescription("Debug") - .create()) - .create(); - - Group options = - new GroupBuilder() - .withName("options") - .withOption(version) - .withOption(help) - .withOption(log) - .withOption(outputQuality) - .create(); - - final String[] args = new String[] { "--bad-option" }; - - Parser parser = new Parser(); - parser.setHelpFormatter(helpFormatter); - parser.setGroup(options); - parser.setHelpOption(help); - CommandLine commandLine = parser.parseAndHelp(args); - if (commandLine != null) { - if (commandLine.hasOption(version)) { - System.out.println("MyApp ver 1.0"); - return; - } - if (commandLine.hasOption("-log")) { - String filename = (String)commandLine.getValue("-log"); - //... - } - } - - try { - commandLine = parser.parse(args); - fail("Unexpected Option!"); - } - catch (OptionException uoe) { - assertEquals( - "Unexpected --bad-option while processing options", - uoe.getMessage()); - } - } - - public void testManualIntroduction() { - - DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - ArgumentBuilder aBuilder = new ArgumentBuilder(); - GroupBuilder gBuilder = new GroupBuilder(); - - DefaultOption xmlOption = - oBuilder - .withLongName("xml") - .withDescription("Output using xml format") - .create(); - - Argument pathArgument = - aBuilder - .withName("path") - .withMinimum(1) - .withMaximum(1) - .create(); - - Group outputChildren = - gBuilder - .withOption(xmlOption) - .create(); - - Option outputOption = - oBuilder - .withLongName("output") - .withDescription("Outputs to a file") - .withArgument(pathArgument) - .withChildren(outputChildren) - .create(); - - /////////////////////////////////////////////////// - - Group options = outputChildren; - HelpFormatter hf = new HelpFormatter(); - - Parser p = new Parser(); - p.setGroup(options); - p.setHelpFormatter(hf); - p.setHelpTrigger("--help"); - CommandLine cl = p.parseAndHelp(new String[]{}); - if(cl==null) { - System.exit(-1); - } - - ////////////////////////////////////////////////// - - cl = new WriteableCommandLineImpl(outputChildren,new ArrayList()); - - // if we have --output option - if(cl.hasOption("--output")) { - // grab the path - String path = (String)cl.getValue("--output"); - // grab the format - boolean xml = cl.hasOption("--xml"); - // configure the application's output - configureOutput(path,xml); - } - - - - - } - - private void configureOutput(String path, boolean xml) { - // TODO Auto-generated method stub - - } - - public void testExampleAnt() throws IOException, OptionException { - // Apache Ant version 1.6.1 compiled on February 12 2004 - - final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - - Option help = - obuilder - .withShortName("help") - .withShortName("h") - .withDescription("print this message") - .create(); - Option projecthelp = - obuilder - .withShortName("projecthelp") - .withShortName("p") - .withDescription("print project help information") - .create(); - Option version = - obuilder - .withShortName("version") - .withDescription("print the version information and exit") - .create(); - Option diagnostics = - obuilder - .withShortName("diagnostics") - .withDescription("print information that might be helpful to diagnose or report problems.") - .create(); - Option quiet = - obuilder - .withShortName("quiet") - .withShortName("q") - .withDescription("be extra quiet") - .create(); - Option verbose = - obuilder - .withShortName("verbose") - .withShortName("v") - .withDescription("be extra verbose") - .create(); - Option debug = - obuilder - .withShortName("debug") - .withShortName("d") - .withDescription("print debugging information") - .create(); - Option emacs = - obuilder - .withShortName("emacs") - .withShortName("e") - .withDescription("produce logging information without adornments") - .create(); - Option lib = - obuilder - .withShortName("lib") - .withDescription("specifies a path to search for jars and classes") - .withArgument( - abuilder - .withName("path") - .withMinimum(1) - .withMaximum(1) - .create()) - .create(); - Option logfile = - obuilder - .withShortName("logfile") - .withShortName("l") - .withDescription("use given file for log") - .withArgument( - abuilder - .withName("file") - .withMinimum(1) - .withMaximum(1) - .create()) - .create(); - Option logger = - obuilder - .withShortName("logger") - .withDescription("the class which is to perform logging") - .withArgument( - abuilder - .withName("classname") - .withMinimum(1) - .withMaximum(1) - .create()) - .create(); - Option listener = - obuilder - .withShortName("listener") - .withDescription("add an instance of class as a project listener") - .withArgument( - abuilder - .withName("classname") - .withMinimum(1) - .withMaximum(1) - .create()) - .create(); - Option noinput = - obuilder - .withShortName("noinput") - .withDescription("do not allow interactive input") - .create(); - Option buildfile = - obuilder - .withShortName("buildfile") - .withShortName("file") - .withShortName("f") - .withDescription("use given buildfile") - .withArgument( - abuilder - .withName("file") - .withMinimum(1) - .withMaximum(1) - .create()) - .create(); - Option property = new PropertyOption(); - Option propertyfile = - obuilder - .withShortName("propertyfile") - .withDescription("load all properties from file with -D properties taking precedence") - .withArgument( - abuilder - .withName("name") - .withMinimum(1) - .withMaximum(1) - .create()) - .create(); - Option inputhandler = - obuilder - .withShortName("inputhandler") - .withDescription("the class which will handle input requests") - .withArgument( - abuilder - .withName("class") - .withMinimum(1) - .withMaximum(1) - .create()) - .create(); - Option find = - obuilder - .withShortName("find") - .withShortName("s") - .withDescription("search for buildfile towards the root of the filesystem and use it") - .withArgument( - abuilder - .withName("file") - .withMinimum(1) - .withMaximum(1) - .create()) - .create(); - Option targets = abuilder.withName("target").create(); - - Group options = - gbuilder - .withName("options") - .withOption(help) - .withOption(projecthelp) - .withOption(version) - .withOption(diagnostics) - .withOption(quiet) - .withOption(verbose) - .withOption(debug) - .withOption(emacs) - .withOption(lib) - .withOption(logfile) - .withOption(logger) - .withOption(listener) - .withOption(noinput) - .withOption(buildfile) - .withOption(property) - .withOption(propertyfile) - .withOption(inputhandler) - .withOption(find) - .withOption(targets) - .create(); - - ///////////////////////////////////// - String[] args = new String[]{}; - - Parser parser = new Parser(); - parser.setGroup(options); - CommandLine cl = parser.parse(args); - - if(cl.hasOption(help)) { - //displayHelp(); - return; - } - if(cl.hasOption("-version")) { - //displayVersion(); - return; - } - if(cl.hasOption(logfile)) { - String file = (String)cl.getValue(logfile); - //setLogFile(); - } - List targetList = cl.getValues(targets); - for (Iterator i = targetList.iterator(); i.hasNext();) { - String target = (String) i.next(); - //doTarget(target); - } - - ///////////////////////////////////// - - HelpFormatter hf = new HelpFormatter(); - hf.setShellCommand("ant"); - hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_NAME); - hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); - hf.getFullUsageSettings().remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); - - hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PROPERTY_OPTION); - hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); - hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); - - hf.getDisplaySettings().remove(DisplaySetting.DISPLAY_GROUP_ARGUMENT); - - hf.setGroup(options); - // redirect printed stuff to a string - hf.setPrintWriter(new PrintWriter(new StringWriter())); - hf.print(); - - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.io.IOException;import java.io.PrintWriter;import java.io.StringWriter;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;import org.apache.commons.cli2.option.DefaultOption;import org.apache.commons.cli2.option.PropertyOption;import org.apache.commons.cli2.util.HelpFormatter;/** * @author Rob */public class DocumentationTest extends TestCase { public void testBasicUsage() throws IOException, OptionException { HelpFormatter helpFormatter = new HelpFormatter(); //ignore all printed helpFormatter.setPrintWriter(new PrintWriter(new StringWriter())); /* * --version -? -h --help -log file -s|-q|-v|-d Bursting File/Num/Date * validation Switches Commands Auto help Auto exception help * */ DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); Option version = obuilder .withLongName("version") .withDescription("Displays version information and then exits") .create(); Option help = obuilder .withShortName("h") .withShortName("?") .withLongName("help") .withDescription("Displays help on usage and then exits") .create(); ArgumentBuilder abuilder = new ArgumentBuilder(); Argument logFile = abuilder .withDescription("The log file to write to") .withName("file") .withMinimum(1) .withMaximum(1) .create(); Option log = obuilder .withArgument(logFile) .withShortName("log") .withDescription("Log progress information to a file") .create(); GroupBuilder gbuilder = new GroupBuilder(); Group outputQuality = gbuilder .withName("quality") .withDescription("Controls the quality of console output") .withMaximum(1) .withOption( obuilder .withShortName("s") .withDescription("Silent") .create()) .withOption( obuilder .withShortName("q") .withDescription("Quiet") .create()) .withOption( obuilder .withShortName("n") .withDescription("Normal") .create()) .withOption( obuilder .withShortName("v") .withDescription("Verbose") .create()) .withOption( obuilder .withShortName("d") .withDescription("Debug") .create()) .create(); Group options = new GroupBuilder() .withName("options") .withOption(version) .withOption(help) .withOption(log) .withOption(outputQuality) .create(); final String[] args = new String[] { "--bad-option" }; Parser parser = new Parser(); parser.setHelpFormatter(helpFormatter); parser.setGroup(options); parser.setHelpOption(help); CommandLine commandLine = parser.parseAndHelp(args); if (commandLine != null) { if (commandLine.hasOption(version)) { System.out.println("MyApp ver 1.0"); return; } if (commandLine.hasOption("-log")) { String filename = (String)commandLine.getValue("-log"); //... } } try { commandLine = parser.parse(args); fail("Unexpected Option!"); } catch (OptionException uoe) { assertEquals( "Unexpected --bad-option while processing options", uoe.getMessage()); } } public void testManualIntroduction() { DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); ArgumentBuilder aBuilder = new ArgumentBuilder(); GroupBuilder gBuilder = new GroupBuilder(); DefaultOption xmlOption = oBuilder .withLongName("xml") .withDescription("Output using xml format") .create(); Argument pathArgument = aBuilder .withName("path") .withMinimum(1) .withMaximum(1) .create(); Group outputChildren = gBuilder .withOption(xmlOption) .create(); Option outputOption = oBuilder .withLongName("output") .withDescription("Outputs to a file") .withArgument(pathArgument) .withChildren(outputChildren) .create(); /////////////////////////////////////////////////// Group options = outputChildren; HelpFormatter hf = new HelpFormatter(); Parser p = new Parser(); p.setGroup(options); p.setHelpFormatter(hf); p.setHelpTrigger("--help"); CommandLine cl = p.parseAndHelp(new String[]{}); if(cl==null) { System.exit(-1); } ////////////////////////////////////////////////// cl = new WriteableCommandLineImpl(outputChildren,new ArrayList()); // if we have --output option if(cl.hasOption("--output")) { // grab the path String path = (String)cl.getValue("--output"); // grab the format boolean xml = cl.hasOption("--xml"); // configure the application's output configureOutput(path,xml); } } private void configureOutput(String path, boolean xml) { // TODO Auto-generated method stub } public void testExampleAnt() throws IOException, OptionException { // Apache Ant version 1.6.1 compiled on February 12 2004 final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); Option help = obuilder .withShortName("help") .withShortName("h") .withDescription("print this message") .create(); Option projecthelp = obuilder .withShortName("projecthelp") .withShortName("p") .withDescription("print project help information") .create(); Option version = obuilder .withShortName("version") .withDescription("print the version information and exit") .create(); Option diagnostics = obuilder .withShortName("diagnostics") .withDescription("print information that might be helpful to diagnose or report problems.") .create(); Option quiet = obuilder .withShortName("quiet") .withShortName("q") .withDescription("be extra quiet") .create(); Option verbose = obuilder .withShortName("verbose") .withShortName("v") .withDescription("be extra verbose") .create(); Option debug = obuilder .withShortName("debug") .withShortName("d") .withDescription("print debugging information") .create(); Option emacs = obuilder .withShortName("emacs") .withShortName("e") .withDescription("produce logging information without adornments") .create(); Option lib = obuilder .withShortName("lib") .withDescription("specifies a path to search for jars and classes") .withArgument( abuilder .withName("path") .withMinimum(1) .withMaximum(1) .create()) .create(); Option logfile = obuilder .withShortName("logfile") .withShortName("l") .withDescription("use given file for log") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create(); Option logger = obuilder .withShortName("logger") .withDescription("the class which is to perform logging") .withArgument( abuilder .withName("classname") .withMinimum(1) .withMaximum(1) .create()) .create(); Option listener = obuilder .withShortName("listener") .withDescription("add an instance of class as a project listener") .withArgument( abuilder .withName("classname") .withMinimum(1) .withMaximum(1) .create()) .create(); Option noinput = obuilder .withShortName("noinput") .withDescription("do not allow interactive input") .create(); Option buildfile = obuilder .withShortName("buildfile") .withShortName("file") .withShortName("f") .withDescription("use given buildfile") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create(); Option property = new PropertyOption(); Option propertyfile = obuilder .withShortName("propertyfile") .withDescription("load all properties from file with -D properties taking precedence") .withArgument( abuilder .withName("name") .withMinimum(1) .withMaximum(1) .create()) .create(); Option inputhandler = obuilder .withShortName("inputhandler") .withDescription("the class which will handle input requests") .withArgument( abuilder .withName("class") .withMinimum(1) .withMaximum(1) .create()) .create(); Option find = obuilder .withShortName("find") .withShortName("s") .withDescription("search for buildfile towards the root of the filesystem and use it") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create(); Option targets = abuilder.withName("target").create(); Group options = gbuilder .withName("options") .withOption(help) .withOption(projecthelp) .withOption(version) .withOption(diagnostics) .withOption(quiet) .withOption(verbose) .withOption(debug) .withOption(emacs) .withOption(lib) .withOption(logfile) .withOption(logger) .withOption(listener) .withOption(noinput) .withOption(buildfile) .withOption(property) .withOption(propertyfile) .withOption(inputhandler) .withOption(find) .withOption(targets) .create(); ///////////////////////////////////// String[] args = new String[]{}; Parser parser = new Parser(); parser.setGroup(options); CommandLine cl = parser.parse(args); if(cl.hasOption(help)) { //displayHelp(); return; } if(cl.hasOption("-version")) { //displayVersion(); return; } if(cl.hasOption(logfile)) { String file = (String)cl.getValue(logfile); //setLogFile(); } List targetList = cl.getValues(targets); for (Iterator i = targetList.iterator(); i.hasNext();) { String target = (String) i.next(); //doTarget(target); } ///////////////////////////////////// HelpFormatter hf = new HelpFormatter(); hf.setShellCommand("ant"); hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_NAME); hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); hf.getFullUsageSettings().remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PROPERTY_OPTION); hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); hf.getDisplaySettings().remove(DisplaySetting.DISPLAY_GROUP_ARGUMENT); hf.setGroup(options); // redirect printed stuff to a string hf.setPrintWriter(new PrintWriter(new StringWriter())); hf.print(); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/PrecedenceTest.java b/src/test/org/apache/commons/cli2/PrecedenceTest.java index f2114afc8..8928f9b66 100644 --- a/src/test/org/apache/commons/cli2/PrecedenceTest.java +++ b/src/test/org/apache/commons/cli2/PrecedenceTest.java @@ -1,413 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; - -/** - * @author Rob Oxspring - */ -public class PrecedenceTest extends TestCase { - private final String[] args = new String[] { "-file" }; - - public void testSimple() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - - final Group options = - new GroupBuilder() - .withOption(oBuilder.withShortName("file").create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-file" }, cl); - } - - public void testArgument() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final ArgumentBuilder aBuilder = new ArgumentBuilder(); - - final Group options = - new GroupBuilder() - .withOption( - oBuilder - .withShortName("f") - .withArgument(aBuilder.create()) - .create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f" }, cl); - } - - public void testBurst() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - final Group options = - gBuilder - .withOption(oBuilder.withShortName("f").create()) - .withOption(oBuilder.withShortName("i").create()) - .withOption(oBuilder.withShortName("l").create()) - .withOption(oBuilder.withShortName("e").create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); - } - - public void testChildren() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - - final Group children = - gBuilder - .withOption(oBuilder.withShortName("i").create()) - .withOption(oBuilder.withShortName("l").create()) - .withOption(oBuilder.withShortName("e").create()) - .create(); - final Group options = - gBuilder - .withOption( - oBuilder - .withShortName("f") - .withChildren(children) - .create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); - } - - public void XtestSimpleVsArgument() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - final ArgumentBuilder aBuilder = new ArgumentBuilder(); - - final Group options = - gBuilder - .withOption(oBuilder.withShortName("file").create()) - .withOption( - oBuilder - .withShortName("f") - .withArgument(aBuilder.create()) - .create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f" }, cl); - } - - public void XtestSimpleVsBurst() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - final Group options = - gBuilder - .withOption(oBuilder.withShortName("file").create()) - .withOption(oBuilder.withShortName("f").create()) - .withOption(oBuilder.withShortName("i").create()) - .withOption(oBuilder.withShortName("l").create()) - .withOption(oBuilder.withShortName("e").create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); - } - - public void XtestSimpleVsChildren() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - - final Group children = - gBuilder - .withOption( - oBuilder.withShortName("i").withLongName("ci").create()) - .withOption( - oBuilder.withShortName("l").withLongName("cl").create()) - .withOption( - oBuilder.withShortName("e").withLongName("ce").create()) - .create(); - - final Group options = - gBuilder - .withOption(oBuilder.withShortName("file").create()) - .withOption( - oBuilder - .withShortName("f") - .withChildren(children) - .create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals( - new String[] { "-f", "-i", "--ci", "-l", "--cl", "-e", "--ce" }, - cl); - } - - public void testArgumentVsBurst() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - final ArgumentBuilder aBuilder = new ArgumentBuilder(); - - final Group options = - gBuilder - .withOption( - oBuilder - .withShortName("f") - .withArgument(aBuilder.create()) - .create()) - .withOption(oBuilder.withShortName("i").create()) - .withOption(oBuilder.withShortName("l").create()) - .withOption(oBuilder.withShortName("e").create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f" }, cl); - } - - public void testArgumentVsChildren() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - final ArgumentBuilder aBuilder = new ArgumentBuilder(); - - final Group children = - gBuilder - .withOption(oBuilder.withShortName("i").create()) - .withOption(oBuilder.withShortName("l").create()) - .withOption(oBuilder.withShortName("e").create()) - .create(); - final Group options = - gBuilder - .withOption( - oBuilder - .withShortName("f") - .withChildren(children) - .withArgument(aBuilder.create()) - .create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f" }, cl); - } - - public void testBurstVsChildren() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - - final Group children = - gBuilder - .withOption( - oBuilder.withShortName("i").withLongName("ci").create()) - .withOption( - oBuilder.withShortName("l").withLongName("cl").create()) - .withOption( - oBuilder.withShortName("e").withLongName("ce").create()) - .create(); - - final Group options = - gBuilder - .withOption( - oBuilder - .withShortName("f") - .withChildren(children) - .create()) - .withOption( - oBuilder.withShortName("i").withLongName("bi").create()) - .withOption( - oBuilder.withShortName("l").withLongName("bl").create()) - .withOption( - oBuilder.withShortName("e").withLongName("be").create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals( - new String[] { "-f", "-i", "--ci", "-l", "--cl", "-e", "--ce" }, - cl); - } - - public void XtestSimpleVsArgumentVsBurst() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - final ArgumentBuilder aBuilder = new ArgumentBuilder(); - - final Group options = - gBuilder - .withOption(oBuilder.withShortName("file").create()) - .withOption( - oBuilder - .withShortName("f") - .withArgument(aBuilder.create()) - .create()) - .withOption(oBuilder.withShortName("i").create()) - .withOption(oBuilder.withShortName("l").create()) - .withOption(oBuilder.withShortName("e").create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f" }, cl); - } - - public void XtestSimpleVsArgumentVsChildren() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - final ArgumentBuilder aBuilder = new ArgumentBuilder(); - - final Group children = - gBuilder - .withOption( - oBuilder.withShortName("i").withLongName("ci").create()) - .withOption( - oBuilder.withShortName("l").withLongName("cl").create()) - .withOption( - oBuilder.withShortName("e").withLongName("ce").create()) - .create(); - - final Group options = - gBuilder - .withOption(oBuilder.withShortName("file").create()) - .withOption( - oBuilder - .withShortName("f") - .withChildren(children) - .withArgument(aBuilder.create()) - .create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f" }, cl); - } - - public void XtestSimpleVsBurstVsChildren() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - - final Group children = - gBuilder - .withOption( - oBuilder.withShortName("i").withLongName("ci").create()) - .withOption( - oBuilder.withShortName("l").withLongName("cl").create()) - .withOption( - oBuilder.withShortName("e").withLongName("ce").create()) - .create(); - - final Group options = - gBuilder - .withOption(oBuilder.withShortName("file").create()) - .withOption( - oBuilder - .withShortName("f") - .withChildren(children) - .create()) - .withOption(oBuilder.withShortName("i").create()) - .withOption(oBuilder.withShortName("l").create()) - .withOption(oBuilder.withShortName("e").create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); - } - - public void testArgumentVsBurstVsChildren() throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - final ArgumentBuilder aBuilder = new ArgumentBuilder(); - - final Group children = - gBuilder - .withOption( - oBuilder.withShortName("i").withLongName("ci").create()) - .withOption( - oBuilder.withShortName("l").withLongName("cl").create()) - .withOption( - oBuilder.withShortName("e").withLongName("ce").create()) - .create(); - - final Group options = - gBuilder - .withOption( - oBuilder - .withShortName("f") - .withChildren(children) - .withArgument(aBuilder.create()) - .create()) - .withOption(oBuilder.withShortName("i").create()) - .withOption(oBuilder.withShortName("l").create()) - .withOption(oBuilder.withShortName("e").create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f" }, cl); - } - - public void XtestSimpleVsArgumentVsBurstVsChildren() - throws OptionException { - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - final GroupBuilder gBuilder = new GroupBuilder(); - final ArgumentBuilder aBuilder = new ArgumentBuilder(); - - final Group children = - gBuilder - .withOption( - oBuilder.withShortName("i").withLongName("ci").create()) - .withOption( - oBuilder.withShortName("l").withLongName("cl").create()) - .withOption( - oBuilder.withShortName("e").withLongName("ce").create()) - .create(); - - final Group options = - gBuilder - .withOption(oBuilder.withShortName("file").create()) - .withOption( - oBuilder - .withShortName("f") - .withChildren(children) - .withArgument(aBuilder.create()) - .create()) - .withOption(oBuilder.withShortName("i").create()) - .withOption(oBuilder.withShortName("l").create()) - .withOption(oBuilder.withShortName("e").create()) - .create(); - - final CommandLine cl = buildCommandLine(options, args); - assertEquals(new String[] { "-f" }, cl); - } - - public CommandLine buildCommandLine(final Group group, final String[] arguments) - throws OptionException { - Parser p = new Parser(); - p.setGroup(group); - return p.parse(arguments); - } - - public void assertEquals(final String options[], final CommandLine line) { - final List expected = Arrays.asList(options); - final Set actual = line.getOptionTriggers(); - - assertTrue(expected.containsAll(actual)); - assertTrue(actual.containsAll(expected)); - } - -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Arrays;import java.util.List;import java.util.Set;import junit.framework.TestCase;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;/** * @author Rob Oxspring */public class PrecedenceTest extends TestCase { private final String[] args = new String[] { "-file" }; public void testSimple() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final Group options = new GroupBuilder() .withOption(oBuilder.withShortName("file").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-file" }, cl); } public void testArgument() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group options = new GroupBuilder() .withOption( oBuilder .withShortName("f") .withArgument(aBuilder.create()) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void testBurst() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group options = gBuilder .withOption(oBuilder.withShortName("f").create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); } public void testChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group children = gBuilder .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final Group options = gBuilder .withOption( oBuilder .withShortName("f") .withChildren(children) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); } public void XtestSimpleVsArgument() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withArgument(aBuilder.create()) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void XtestSimpleVsBurst() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption(oBuilder.withShortName("f").create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); } public void XtestSimpleVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withChildren(children) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals( new String[] { "-f", "-i", "--ci", "-l", "--cl", "-e", "--ce" }, cl); } public void testArgumentVsBurst() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group options = gBuilder .withOption( oBuilder .withShortName("f") .withArgument(aBuilder.create()) .create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void testArgumentVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group children = gBuilder .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final Group options = gBuilder .withOption( oBuilder .withShortName("f") .withChildren(children) .withArgument(aBuilder.create()) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void testBurstVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption( oBuilder .withShortName("f") .withChildren(children) .create()) .withOption( oBuilder.withShortName("i").withLongName("bi").create()) .withOption( oBuilder.withShortName("l").withLongName("bl").create()) .withOption( oBuilder.withShortName("e").withLongName("be").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals( new String[] { "-f", "-i", "--ci", "-l", "--cl", "-e", "--ce" }, cl); } public void XtestSimpleVsArgumentVsBurst() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withArgument(aBuilder.create()) .create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void XtestSimpleVsArgumentVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withChildren(children) .withArgument(aBuilder.create()) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void XtestSimpleVsBurstVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withChildren(children) .create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); } public void testArgumentVsBurstVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption( oBuilder .withShortName("f") .withChildren(children) .withArgument(aBuilder.create()) .create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void XtestSimpleVsArgumentVsBurstVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withChildren(children) .withArgument(aBuilder.create()) .create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public CommandLine buildCommandLine(final Group group, final String[] arguments) throws OptionException { Parser p = new Parser(); p.setGroup(group); return p.parse(arguments); } public void assertEquals(final String options[], final CommandLine line) { final List expected = Arrays.asList(options); final Set actual = line.getOptionTriggers(); assertTrue(expected.containsAll(actual)); assertTrue(actual.containsAll(expected)); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java b/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java index eac59b110..5e8f68624 100644 --- a/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java +++ b/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java @@ -1,92 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2; - -import org.apache.commons.cli2.option.ArgumentTest; - -/** - * @author Rob Oxspring - */ -public abstract class WriteableCommandLineTestCase extends CommandLineTestCase { - - private WriteableCommandLine writeable; - - protected abstract WriteableCommandLine createWriteableCommandLine(); - - /* (non-Javadoc) - * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() - */ - protected final CommandLine createCommandLine() { - final WriteableCommandLine cl = createWriteableCommandLine(); - cl.addOption(present); - cl.addProperty("present","present property"); - cl.addSwitch(bool,true); - cl.addValue(present,"present value"); - cl.addOption(multiple); - cl.addValue(multiple,"value 1"); - cl.addValue(multiple,"value 2"); - cl.addValue(multiple,"value 3"); - return cl; - } - - /* - * @see CommandLineTest#setUp() - */ - public void setUp() throws Exception { - super.setUp(); - writeable = createWriteableCommandLine(); - } - public final void testAddOption() { - assertFalse(writeable.hasOption(present)); - writeable.addOption(present); - assertTrue(writeable.hasOption(present)); - } - public final void testAddValue() { - assertFalse(writeable.hasOption(present)); - assertTrue(writeable.getValues(present).isEmpty()); - writeable.addValue(present,"value"); - assertContentsEqual(list("value"),writeable.getValues(present)); - - // most options shouldn't appear due to adding values - assertFalse(writeable.hasOption(present)); - - final Argument arg = ArgumentTest.buildHostArgument(); - - assertFalse(writeable.hasOption(arg)); - assertTrue(writeable.getValues(arg).isEmpty()); - writeable.addValue(arg,"value"); - assertContentsEqual(list("value"),writeable.getValues(arg)); - - // Arguments should force the option present - assertTrue(writeable.hasOption(arg)); - } - public final void testAddSwitch() { - assertFalse(writeable.hasOption(present)); - assertNull(writeable.getSwitch(present)); - writeable.addSwitch(present,true); - assertEquals(Boolean.TRUE,writeable.getSwitch(present)); - assertTrue(writeable.hasOption(present)); - } - public final void testAddProperty() { - assertNull(writeable.getProperty("present")); - writeable.addProperty("present","present value"); - assertEquals("present value",writeable.getProperty("present")); - } - public final void testLooksLikeOption() { - //TODO Implement looksLikeOption(). - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import org.apache.commons.cli2.option.ArgumentTest;/** * @author Rob Oxspring */public abstract class WriteableCommandLineTestCase extends CommandLineTestCase { private WriteableCommandLine writeable; protected abstract WriteableCommandLine createWriteableCommandLine(); /* (non-Javadoc) * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() */ protected final CommandLine createCommandLine() { final WriteableCommandLine cl = createWriteableCommandLine(); cl.addOption(present); cl.addProperty("present","present property"); cl.addSwitch(bool,true); cl.addValue(present,"present value"); cl.addOption(multiple); cl.addValue(multiple,"value 1"); cl.addValue(multiple,"value 2"); cl.addValue(multiple,"value 3"); return cl; } /* * @see CommandLineTest#setUp() */ public void setUp() throws Exception { super.setUp(); writeable = createWriteableCommandLine(); } public final void testAddOption() { assertFalse(writeable.hasOption(present)); writeable.addOption(present); assertTrue(writeable.hasOption(present)); } public final void testAddValue() { assertFalse(writeable.hasOption(present)); assertTrue(writeable.getValues(present).isEmpty()); writeable.addValue(present,"value"); assertContentsEqual(list("value"),writeable.getValues(present)); // most options shouldn't appear due to adding values assertFalse(writeable.hasOption(present)); final Argument arg = ArgumentTest.buildHostArgument(); assertFalse(writeable.hasOption(arg)); assertTrue(writeable.getValues(arg).isEmpty()); writeable.addValue(arg,"value"); assertContentsEqual(list("value"),writeable.getValues(arg)); // Arguments should force the option present assertTrue(writeable.hasOption(arg)); } public final void testAddSwitch() { assertFalse(writeable.hasOption(present)); assertNull(writeable.getSwitch(present)); writeable.addSwitch(present,true); assertEquals(Boolean.TRUE,writeable.getSwitch(present)); assertTrue(writeable.hasOption(present)); } public final void testAddProperty() { assertNull(writeable.getProperty("present")); writeable.addProperty("present","present value"); assertEquals("present value",writeable.getProperty("present")); } public final void testLooksLikeOption() { //TODO Implement looksLikeOption(). }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/application/AntTest.java b/src/test/org/apache/commons/cli2/application/AntTest.java index b9097ccc0..d9e655cfc 100644 --- a/src/test/org/apache/commons/cli2/application/AntTest.java +++ b/src/test/org/apache/commons/cli2/application/AntTest.java @@ -1,198 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.application; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import org.apache.commons.cli2.option.PropertyOption; - -//TODO Build up AntTest like CpTest -public class AntTest extends TestCase { - public void testAnt() throws OptionException { - final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - - final Group options = - gbuilder - .withName("ant") - .withOption( - obuilder - .withShortName("help") - .withDescription("print this message") - .create()) - .withOption( - obuilder - .withShortName("projecthelp") - .withDescription("print project help information") - .create()) - .withOption( - obuilder - .withShortName("version") - .withDescription("print the version information and exit") - .create()) - .withOption( - obuilder - .withShortName("diagnostics") - .withDescription("print information that might be helpful to diagnose or report problems.") - .create()) - .withOption( - obuilder - .withShortName("quiet") - .withShortName("q") - .withDescription("be extra quiet") - .create()) - .withOption( - obuilder - .withShortName("verbose") - .withShortName("v") - .withDescription("be extra verbose") - .create()) - .withOption( - obuilder - .withShortName("debug") - .withDescription("print debugging information") - .create()) - .withOption( - obuilder - .withShortName("emacs") - .withDescription("produce logging information without adornments") - .create()) - .withOption( - obuilder - .withShortName("logfile") - .withShortName("l") - .withDescription("use given file for log") - .withArgument( - abuilder - .withName("file") - .withMinimum(1) - .withMaximum(1) - .create()) - .create()) - .withOption( - obuilder - .withShortName("logger") - .withDescription("the class which is to perform logging") - .withArgument( - abuilder - .withName("classname") - .withMinimum(1) - .withMaximum(1) - .create()) - .create()) - .withOption( - obuilder - .withShortName("listener") - .withDescription("add an instance of class as a project listener") - .withArgument( - abuilder - .withName("classname") - .withMinimum(1) - .withMaximum(1) - .create()) - .create()) - .withOption( - obuilder - .withShortName("buildfile") - .withShortName("file") - .withShortName("f") - .withDescription("use given buildfile") - .withArgument( - abuilder - .withName("file") - .withMinimum(1) - .withMaximum(1) - .create()) - .create()) - .withOption(PropertyOption.INSTANCE) - .withOption( - obuilder - .withShortName("propertyfile") - .withDescription("load all properties from file with -D properties taking precedence") - .withArgument( - abuilder - .withName("name") - .withMinimum(1) - .withMaximum(1) - .create()) - .create()) - .withOption( - obuilder - .withShortName("inputhandler") - .withDescription("the class which will handle input requests") - .withArgument( - abuilder - .withName("class") - .withMinimum(1) - .withMaximum(1) - .create()) - .create()) - .withOption( - obuilder - .withShortName("find") - .withDescription("search for buildfile towards the root of the filesystem and use it") - .withArgument( - abuilder - .withName("file") - .withMinimum(1) - .withMaximum(1) - .create()) - .create()) - .withOption(abuilder.withName("target").create()) - .create(); - - Parser parser = new Parser(); - parser.setGroup(options); - CommandLine line = - parser.parse( - new String[] { - "-buildfile", - "mybuild.xml", - "-Dproperty=value", - "-Dproperty1=value1", - "-projecthelp", - "compile", - "docs" }); - - // check properties - assertEquals(2, line.getProperties().size()); - assertEquals("value", line.getProperty("property")); - assertEquals("value1", line.getProperty("property1")); - - // check single values - assertEquals("mybuild.xml", line.getValue("-buildfile")); - assertTrue(line.hasOption("-projecthelp")); - assertFalse(line.hasOption("-help")); - - assertTrue(line.hasOption("target")); - final List targets = new ArrayList(); - targets.add("compile"); - targets.add("docs"); - assertEquals(targets, line.getValues("target")); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.application;import java.util.ArrayList;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.option.PropertyOption;//TODO Build up AntTest like CpTestpublic class AntTest extends TestCase { public void testAnt() throws OptionException { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Group options = gbuilder .withName("ant") .withOption( obuilder .withShortName("help") .withDescription("print this message") .create()) .withOption( obuilder .withShortName("projecthelp") .withDescription("print project help information") .create()) .withOption( obuilder .withShortName("version") .withDescription("print the version information and exit") .create()) .withOption( obuilder .withShortName("diagnostics") .withDescription("print information that might be helpful to diagnose or report problems.") .create()) .withOption( obuilder .withShortName("quiet") .withShortName("q") .withDescription("be extra quiet") .create()) .withOption( obuilder .withShortName("verbose") .withShortName("v") .withDescription("be extra verbose") .create()) .withOption( obuilder .withShortName("debug") .withDescription("print debugging information") .create()) .withOption( obuilder .withShortName("emacs") .withDescription("produce logging information without adornments") .create()) .withOption( obuilder .withShortName("logfile") .withShortName("l") .withDescription("use given file for log") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption( obuilder .withShortName("logger") .withDescription("the class which is to perform logging") .withArgument( abuilder .withName("classname") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption( obuilder .withShortName("listener") .withDescription("add an instance of class as a project listener") .withArgument( abuilder .withName("classname") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption( obuilder .withShortName("buildfile") .withShortName("file") .withShortName("f") .withDescription("use given buildfile") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption(PropertyOption.INSTANCE) .withOption( obuilder .withShortName("propertyfile") .withDescription("load all properties from file with -D properties taking precedence") .withArgument( abuilder .withName("name") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption( obuilder .withShortName("inputhandler") .withDescription("the class which will handle input requests") .withArgument( abuilder .withName("class") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption( obuilder .withShortName("find") .withDescription("search for buildfile towards the root of the filesystem and use it") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption(abuilder.withName("target").create()) .create(); Parser parser = new Parser(); parser.setGroup(options); CommandLine line = parser.parse( new String[] { "-buildfile", "mybuild.xml", "-Dproperty=value", "-Dproperty1=value1", "-projecthelp", "compile", "docs" }); // check properties assertEquals(2, line.getProperties().size()); assertEquals("value", line.getProperty("property")); assertEquals("value1", line.getProperty("property1")); // check single values assertEquals("mybuild.xml", line.getValue("-buildfile")); assertTrue(line.hasOption("-projecthelp")); assertFalse(line.hasOption("-help")); assertTrue(line.hasOption("target")); final List targets = new ArrayList(); targets.add("compile"); targets.add("docs"); assertEquals(targets, line.getValues("target")); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/application/CpTest.java b/src/test/org/apache/commons/cli2/application/CpTest.java index bdcc9a5ba..457571c24 100644 --- a/src/test/org/apache/commons/cli2/application/CpTest.java +++ b/src/test/org/apache/commons/cli2/application/CpTest.java @@ -1,471 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.application; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; -import java.io.StringWriter; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import org.apache.commons.cli2.option.ArgumentImpl; -import org.apache.commons.cli2.option.SourceDestArgument; -import org.apache.commons.cli2.util.HelpFormatter; - -/** - *

      Test the cp command. Duplicated Option types are not - * tested e.g. -a and -d are the same Option type.

      - * - *

      The following is the man output for 'cp'. See - * http://www.rt.com/man/cp.1.html.

      - * - *
      - *  CP(1) FSF CP(1)
      - * 
      - *  NAME cp - copy files and directories
      - * 
      - *  SYNOPSIS cp [OPTION]... SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY
      - * 
      - *  DESCRIPTION Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.
      - * 
      - *  -a, --archive same as -dpR
      - * 
      - *  -b, --backup make backup before removal
      - * 
      - *  -d, --no-dereference preserve links
      - * 
      - *  -f, --force remove existing destinations, never prompt
      - * 
      - *  -i, --interactive prompt before overwrite
      - * 
      - *  -l, --link link files instead of copying
      - * 
      - *  -p, --preserve preserve file attributes if possible
      - * 
      - *  -P, --parents append source path to DIRECTORY
      - * -r copy recursively, non-directories as files
      - * 
      - *  --sparse=WHEN control creation of sparse files
      - * 
      - *  -R, --recursive copy directories recursively
      - * 
      - *  -s, --symbolic-link make symbolic links instead of copying
      - * 
      - *  -S, --suffix=SUFFIX override the usual backup suffix
      - * 
      - *  -u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing
      - * 
      - *  -v, --verbose explain what is being done
      - * 
      - *  -V, --version-control=WORD override the usual version control
      - * 
      - *  -x, --one-file-system stay on this file system
      - * 
      - *  --help display this help and exit
      - * 
      - *  --version output version information and exit
      - * 
      - *  By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file when- ever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files.
      - * 
      - *  The backup suffix is ~, unless set with SIMPLE_BACKUP_SUF- FIX. The version control may be set with VERSION_CONTROL, values are:
      - * t, numbered make numbered backups
      - * 
      - *  nil, existing numbered if numbered backups exist, simple other- wise
      - * 
      - *  never, simple always make simple backups
      - * 
      - *  As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. * 
      - *
      - * - * @author Rob Oxspring - * @author John Keyes - */ -public class CpTest extends TestCase { - - /** Option Builder */ - private static final DefaultOptionBuilder oBuilder = - new DefaultOptionBuilder(); - - /** Argument Builder */ - private static final ArgumentBuilder aBuilder = new ArgumentBuilder(); - - /** Group Builder */ - private static final GroupBuilder gBuilder = new GroupBuilder(); - - private Group options; - - public static Test suite() { - return new TestSuite(CpTest.class); - } - - private ArgumentImpl source; - private ArgumentImpl dest; - private Argument targets; - - private Option archive; - private Option backup; - private Option noDereference; - private Option force; - private Option interactive; - private Option link; - private Option preserve; - private Option parents; - private Option recursive1; - private Option sparse; - private Option recursive2; - private Option symbolicLink; - private Option suffix; - private Option update; - private Option verbose; - private Option versionControl; - private Option oneFileSystem; - private Option help; - private Option version; - - public void setUp() { - source = - (ArgumentImpl)aBuilder.withName("SOURCE").withMinimum(1).create(); - dest = - (ArgumentImpl)aBuilder - .withName("DEST") - .withMinimum(1) - .withMaximum(1) - .create(); - targets = new SourceDestArgument(source, dest); - - archive = - oBuilder - .withShortName("a") - .withLongName("archive") - .withDescription("same as -dpR") - .create(); - - backup = - oBuilder - .withShortName("b") - .withLongName("backup") - .withDescription("make backup before removal") - .create(); - - noDereference = - oBuilder - .withShortName("d") - .withLongName("no-dereference") - .withDescription("preserve links") - .create(); - - force = - oBuilder - .withShortName("f") - .withLongName("force") - .withDescription("remove existing destinations, never prompt") - .create(); - - interactive = - oBuilder - .withShortName("i") - .withLongName("interactive") - .withDescription("prompt before overwrite") - .create(); - - link = - oBuilder - .withShortName("l") - .withLongName("link") - .withDescription("link files instead of copying") - .create(); - - preserve = - oBuilder - .withShortName("p") - .withLongName("preserve") - .withDescription("preserve file attributes if possible") - .create(); - - parents = - oBuilder - .withShortName("P") - .withLongName("parents") - .withDescription("append source path to DIRECTORY") - .create(); - - recursive1 = - oBuilder - .withShortName("r") - .withDescription("copy recursively, non-directories as files") - .create(); - - sparse = - oBuilder - .withLongName("sparse") - .withDescription("control creation of sparse files") - .withArgument( - aBuilder - .withName("WHEN") - .withMinimum(1) - .withMaximum(1) - .withInitialSeparator('=') - .create()) - .create(); - - recursive2 = - oBuilder - .withShortName("R") - .withLongName("recursive") - .withDescription("copy directories recursively") - .create(); - - symbolicLink = - oBuilder - .withShortName("s") - .withLongName("symbolic-link") - .withDescription("make symbolic links instead of copying") - .create(); - - suffix = - oBuilder - .withShortName("S") - .withLongName("suffix") - .withDescription("override the usual backup suffix") - .withArgument( - aBuilder - .withName("SUFFIX") - .withMinimum(1) - .withMaximum(1) - .create()) - .create(); - - update = - oBuilder - .withShortName("u") - .withLongName("update") - .withDescription("copy only when the SOURCE file is newer than the destination file or when the destination file is missing") - .create(); - - verbose = - oBuilder - .withShortName("v") - .withLongName("verbose") - .withDescription("explain what is being done") - .create(); - - versionControl = - oBuilder - .withShortName("V") - .withLongName("version-contol") - .withDescription("explain what is being done") - .withArgument( - aBuilder - .withName("WORD") - .withInitialSeparator('=') - .withMinimum(1) - .withMaximum(1) - .create()) - .create(); - - oneFileSystem = - oBuilder - .withShortName("x") - .withLongName("one-file-system") - .withDescription("stay on this file system") - .create(); - - help = - oBuilder - .withLongName("help") - .withDescription("display this help and exit") - .create(); - - version = - oBuilder - .withLongName("version") - .withDescription("output version information and exit") - .create(); - - options = - gBuilder - .withOption(archive) - .withOption(backup) - .withOption(noDereference) - .withOption(force) - .withOption(interactive) - .withOption(link) - .withOption(preserve) - .withOption(parents) - .withOption(recursive1) - .withOption(sparse) - .withOption(recursive2) - .withOption(symbolicLink) - .withOption(suffix) - .withOption(update) - .withOption(verbose) - .withOption(versionControl) - .withOption(oneFileSystem) - .withOption(help) - .withOption(version) - .withOption(targets) - .withName("OPTIONS") - .create(); - } - - public void testNoSource() { - Parser parser = new Parser(); - parser.setGroup(options); - try { - parser.parse(new String[0]); - } - catch (OptionException mve) { - assertEquals( - "Missing value(s) SOURCE [SOURCE ...]", - mve.getMessage()); - } - } - - public void testOneSource() throws OptionException { - final String[] args = new String[] { "source1", "dest1" }; - final Parser parser = new Parser(); - parser.setGroup(options); - final CommandLine commandLine = parser.parse(args); - - assertTrue(commandLine.getValues(source).contains("source1")); - assertEquals(1, commandLine.getValues(source).size()); - assertTrue(commandLine.getValues(dest).contains("dest1")); - assertEquals(1, commandLine.getValues(dest).size()); - } - - public void testMultiSource() throws OptionException { - final String[] args = - new String[] { "source1", "source2", "source3", "dest1" }; - final Parser parser = new Parser(); - parser.setGroup(options); - final CommandLine commandLine = parser.parse(args); - - assertTrue(commandLine.getValues(source).contains("source1")); - assertTrue(commandLine.getValues(source).contains("source2")); - assertTrue(commandLine.getValues(source).contains("source3")); - assertEquals(3, commandLine.getValues(source).size()); - - assertTrue(commandLine.getValues(dest).contains("dest1")); - assertEquals(1, commandLine.getValues(dest).size()); - } - - public void testHelp() throws IOException { - final StringWriter out = new StringWriter(); - final HelpFormatter helpFormatter = new HelpFormatter(); - helpFormatter.setGroup(options); - helpFormatter.setPrintWriter(new PrintWriter(out)); - helpFormatter.print(); - - final BufferedReader in = - new BufferedReader(new StringReader(out.toString())); - assertEquals( - "Usage: ", - in.readLine()); - assertEquals( - " [-a -b -d -f -i -l -p -P -r --sparse -R -s -S -u -v -V ", - in.readLine()); - assertEquals( - "-x --help --version] [ ...] ", - in.readLine()); - assertEquals( - "OPTIONS ", - in.readLine()); - assertEquals( - " -a (--archive) same as -dpR ", - in.readLine()); - assertEquals( - " -b (--backup) make backup before removal ", - in.readLine()); - assertEquals( - " -d (--no-dereference) preserve links ", - in.readLine()); - assertEquals( - " -f (--force) remove existing destinations, never prompt ", - in.readLine()); - assertEquals( - " -i (--interactive) prompt before overwrite ", - in.readLine()); - assertEquals( - " -l (--link) link files instead of copying ", - in.readLine()); - assertEquals( - " -p (--preserve) preserve file attributes if possible ", - in.readLine()); - assertEquals( - " -P (--parents) append source path to DIRECTORY ", - in.readLine()); - assertEquals( - " -r copy recursively, non-directories as files ", - in.readLine()); - assertEquals( - " --sparse WHEN control creation of sparse files ", - in.readLine()); - assertEquals( - " -R (--recursive) copy directories recursively ", - in.readLine()); - assertEquals( - " -s (--symbolic-link) make symbolic links instead of copying ", - in.readLine()); - assertEquals( - " -S (--suffix) SUFFIX override the usual backup suffix ", - in.readLine()); - assertEquals( - " -u (--update) copy only when the SOURCE file is newer than ", - in.readLine()); - assertEquals( - " the destination file or when the destination ", - in.readLine()); - assertEquals( - " file is missing ", - in.readLine()); - assertEquals( - " -v (--verbose) explain what is being done ", - in.readLine()); - assertEquals( - " -V (--version-contol) WORD explain what is being done ", - in.readLine()); - assertEquals( - " -x (--one-file-system) stay on this file system ", - in.readLine()); - assertEquals( - " --help display this help and exit ", - in.readLine()); - assertEquals( - " --version output version information and exit ", - in.readLine()); - assertEquals( - " SOURCE [SOURCE ...] ", - in.readLine()); - assertEquals( - " DEST ", - in.readLine()); - assertNull(in.readLine()); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.application;import java.io.BufferedReader;import java.io.IOException;import java.io.PrintWriter;import java.io.StringReader;import java.io.StringWriter;import junit.framework.Test;import junit.framework.TestCase;import junit.framework.TestSuite;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.option.ArgumentImpl;import org.apache.commons.cli2.option.SourceDestArgument;import org.apache.commons.cli2.util.HelpFormatter;/** *

      Test the cp command. Duplicated Option types are not * tested e.g. -a and -d are the same Option type.

      * *

      The following is the man output for 'cp'. See * http://www.rt.com/man/cp.1.html.

      * *
       *  CP(1) FSF CP(1) * *  NAME cp - copy files and directories * *  SYNOPSIS cp [OPTION]... SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY * *  DESCRIPTION Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. * *  -a, --archive same as -dpR * *  -b, --backup make backup before removal * *  -d, --no-dereference preserve links * *  -f, --force remove existing destinations, never prompt * *  -i, --interactive prompt before overwrite * *  -l, --link link files instead of copying * *  -p, --preserve preserve file attributes if possible * *  -P, --parents append source path to DIRECTORY * -r copy recursively, non-directories as files * *  --sparse=WHEN control creation of sparse files * *  -R, --recursive copy directories recursively * *  -s, --symbolic-link make symbolic links instead of copying * *  -S, --suffix=SUFFIX override the usual backup suffix * *  -u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing * *  -v, --verbose explain what is being done * *  -V, --version-control=WORD override the usual version control * *  -x, --one-file-system stay on this file system * *  --help display this help and exit * *  --version output version information and exit * *  By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file when- ever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. * *  The backup suffix is ~, unless set with SIMPLE_BACKUP_SUF- FIX. The version control may be set with VERSION_CONTROL, values are: * t, numbered make numbered backups * *  nil, existing numbered if numbered backups exist, simple other- wise * *  never, simple always make simple backups * *  As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. * 
      *
      * * @author Rob Oxspring * @author John Keyes */public class CpTest extends TestCase { /** Option Builder */ private static final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); /** Argument Builder */ private static final ArgumentBuilder aBuilder = new ArgumentBuilder(); /** Group Builder */ private static final GroupBuilder gBuilder = new GroupBuilder(); private Group options; public static Test suite() { return new TestSuite(CpTest.class); } private ArgumentImpl source; private ArgumentImpl dest; private Argument targets; private Option archive; private Option backup; private Option noDereference; private Option force; private Option interactive; private Option link; private Option preserve; private Option parents; private Option recursive1; private Option sparse; private Option recursive2; private Option symbolicLink; private Option suffix; private Option update; private Option verbose; private Option versionControl; private Option oneFileSystem; private Option help; private Option version; public void setUp() { source = (ArgumentImpl)aBuilder.withName("SOURCE").withMinimum(1).create(); dest = (ArgumentImpl)aBuilder .withName("DEST") .withMinimum(1) .withMaximum(1) .create(); targets = new SourceDestArgument(source, dest); archive = oBuilder .withShortName("a") .withLongName("archive") .withDescription("same as -dpR") .create(); backup = oBuilder .withShortName("b") .withLongName("backup") .withDescription("make backup before removal") .create(); noDereference = oBuilder .withShortName("d") .withLongName("no-dereference") .withDescription("preserve links") .create(); force = oBuilder .withShortName("f") .withLongName("force") .withDescription("remove existing destinations, never prompt") .create(); interactive = oBuilder .withShortName("i") .withLongName("interactive") .withDescription("prompt before overwrite") .create(); link = oBuilder .withShortName("l") .withLongName("link") .withDescription("link files instead of copying") .create(); preserve = oBuilder .withShortName("p") .withLongName("preserve") .withDescription("preserve file attributes if possible") .create(); parents = oBuilder .withShortName("P") .withLongName("parents") .withDescription("append source path to DIRECTORY") .create(); recursive1 = oBuilder .withShortName("r") .withDescription("copy recursively, non-directories as files") .create(); sparse = oBuilder .withLongName("sparse") .withDescription("control creation of sparse files") .withArgument( aBuilder .withName("WHEN") .withMinimum(1) .withMaximum(1) .withInitialSeparator('=') .create()) .create(); recursive2 = oBuilder .withShortName("R") .withLongName("recursive") .withDescription("copy directories recursively") .create(); symbolicLink = oBuilder .withShortName("s") .withLongName("symbolic-link") .withDescription("make symbolic links instead of copying") .create(); suffix = oBuilder .withShortName("S") .withLongName("suffix") .withDescription("override the usual backup suffix") .withArgument( aBuilder .withName("SUFFIX") .withMinimum(1) .withMaximum(1) .create()) .create(); update = oBuilder .withShortName("u") .withLongName("update") .withDescription("copy only when the SOURCE file is newer than the destination file or when the destination file is missing") .create(); verbose = oBuilder .withShortName("v") .withLongName("verbose") .withDescription("explain what is being done") .create(); versionControl = oBuilder .withShortName("V") .withLongName("version-contol") .withDescription("explain what is being done") .withArgument( aBuilder .withName("WORD") .withInitialSeparator('=') .withMinimum(1) .withMaximum(1) .create()) .create(); oneFileSystem = oBuilder .withShortName("x") .withLongName("one-file-system") .withDescription("stay on this file system") .create(); help = oBuilder .withLongName("help") .withDescription("display this help and exit") .create(); version = oBuilder .withLongName("version") .withDescription("output version information and exit") .create(); options = gBuilder .withOption(archive) .withOption(backup) .withOption(noDereference) .withOption(force) .withOption(interactive) .withOption(link) .withOption(preserve) .withOption(parents) .withOption(recursive1) .withOption(sparse) .withOption(recursive2) .withOption(symbolicLink) .withOption(suffix) .withOption(update) .withOption(verbose) .withOption(versionControl) .withOption(oneFileSystem) .withOption(help) .withOption(version) .withOption(targets) .withName("OPTIONS") .create(); } public void testNoSource() { Parser parser = new Parser(); parser.setGroup(options); try { parser.parse(new String[0]); } catch (OptionException mve) { assertEquals( "Missing value(s) SOURCE [SOURCE ...]", mve.getMessage()); } } public void testOneSource() throws OptionException { final String[] args = new String[] { "source1", "dest1" }; final Parser parser = new Parser(); parser.setGroup(options); final CommandLine commandLine = parser.parse(args); assertTrue(commandLine.getValues(source).contains("source1")); assertEquals(1, commandLine.getValues(source).size()); assertTrue(commandLine.getValues(dest).contains("dest1")); assertEquals(1, commandLine.getValues(dest).size()); } public void testMultiSource() throws OptionException { final String[] args = new String[] { "source1", "source2", "source3", "dest1" }; final Parser parser = new Parser(); parser.setGroup(options); final CommandLine commandLine = parser.parse(args); assertTrue(commandLine.getValues(source).contains("source1")); assertTrue(commandLine.getValues(source).contains("source2")); assertTrue(commandLine.getValues(source).contains("source3")); assertEquals(3, commandLine.getValues(source).size()); assertTrue(commandLine.getValues(dest).contains("dest1")); assertEquals(1, commandLine.getValues(dest).size()); } public void testHelp() throws IOException { final StringWriter out = new StringWriter(); final HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setGroup(options); helpFormatter.setPrintWriter(new PrintWriter(out)); helpFormatter.print(); final BufferedReader in = new BufferedReader(new StringReader(out.toString())); assertEquals( "Usage: ", in.readLine()); assertEquals( " [-a -b -d -f -i -l -p -P -r --sparse -R -s -S -u -v -V ", in.readLine()); assertEquals( "-x --help --version] [ ...] ", in.readLine()); assertEquals( "OPTIONS ", in.readLine()); assertEquals( " -a (--archive) same as -dpR ", in.readLine()); assertEquals( " -b (--backup) make backup before removal ", in.readLine()); assertEquals( " -d (--no-dereference) preserve links ", in.readLine()); assertEquals( " -f (--force) remove existing destinations, never prompt ", in.readLine()); assertEquals( " -i (--interactive) prompt before overwrite ", in.readLine()); assertEquals( " -l (--link) link files instead of copying ", in.readLine()); assertEquals( " -p (--preserve) preserve file attributes if possible ", in.readLine()); assertEquals( " -P (--parents) append source path to DIRECTORY ", in.readLine()); assertEquals( " -r copy recursively, non-directories as files ", in.readLine()); assertEquals( " --sparse WHEN control creation of sparse files ", in.readLine()); assertEquals( " -R (--recursive) copy directories recursively ", in.readLine()); assertEquals( " -s (--symbolic-link) make symbolic links instead of copying ", in.readLine()); assertEquals( " -S (--suffix) SUFFIX override the usual backup suffix ", in.readLine()); assertEquals( " -u (--update) copy only when the SOURCE file is newer than ", in.readLine()); assertEquals( " the destination file or when the destination ", in.readLine()); assertEquals( " file is missing ", in.readLine()); assertEquals( " -v (--verbose) explain what is being done ", in.readLine()); assertEquals( " -V (--version-contol) WORD explain what is being done ", in.readLine()); assertEquals( " -x (--one-file-system) stay on this file system ", in.readLine()); assertEquals( " --help display this help and exit ", in.readLine()); assertEquals( " --version output version information and exit ", in.readLine()); assertEquals( " SOURCE [SOURCE ...] ", in.readLine()); assertEquals( " DEST ", in.readLine()); assertNull(in.readLine()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/application/CvsTest.java b/src/test/org/apache/commons/cli2/application/CvsTest.java index 47186e126..adc1e27e9 100644 --- a/src/test/org/apache/commons/cli2/application/CvsTest.java +++ b/src/test/org/apache/commons/cli2/application/CvsTest.java @@ -1,312 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.application; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.CommandBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.option.ArgumentTest; - -//TODO Build up CvsTest like CpTest -public class CvsTest extends TestCase { - public void testCVS() { - final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final CommandBuilder cbuilder = new CommandBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - - final Group commands = - gbuilder - .withName("commands") - .withOption( - cbuilder - .withName("add") - .withName("ad") - .withName("new") - .withDescription("Add a new file/directory to the repository") - .create()) - .withOption( - cbuilder - .withName("admin") - .withName("adm") - .withName("rcs") - .withDescription("Administration front end for rcs") - .create()) - .withOption( - cbuilder - .withName("annotate") - .withName("ann") - .withDescription("Show last revision where each line was modified") - .create()) - .withOption( - cbuilder - .withName("checkout") - .withName("co") - .withName("get") - .withDescription("Checkout sources for editing") - .create()) - .withOption( - cbuilder - .withName("commit") - .withName("ci") - .withName("com") - .withDescription("Check files into the repository") - .create()) - .withOption( - cbuilder - .withName("diff") - .withName("di") - .withName("dif") - .withDescription("Show differences between revisions") - .create()) - .withOption( - cbuilder - .withName("edit") - .withDescription("Get ready to edit a watched file") - .create()) - .withOption( - cbuilder - .withName("editors") - .withDescription("See who is editing a watched file") - .create()) - .withOption( - cbuilder - .withName("export") - .withName("exp") - .withName("ex") - .withDescription("Export sources from CVS, similar to checkout") - .create()) - .withOption( - cbuilder - .withName("history") - .withName("hi") - .withName("his") - .withDescription("Show repository access history") - .create()) - .withOption( - cbuilder - .withName("import") - .withName("im") - .withName("imp") - .withDescription("Import sources into CVS, using vendor branches") - .create()) - .withOption( - cbuilder - .withName("init") - .withDescription("Create a CVS repository if it doesn't exist") - .create()) - .withOption( - cbuilder - .withName("log") - .withName("lo") - .withName("rlog") - .withDescription("Print out history information for files") - .create()) - .withOption( - cbuilder - .withName("login") - .withName("logon") - .withName("lgn") - .withDescription("Prompt for password for authenticating server") - .create()) - .withOption( - cbuilder - .withName("logout") - .withDescription("Removes entry in .cvspass for remote repository") - .create()) - .withOption( - cbuilder - .withName("rdiff") - .withName("patch") - .withName("pa") - .withDescription("Create 'patch' format diffs between releases") - .create()) - .withOption( - cbuilder - .withName("release") - .withName("re") - .withName("rel") - .withDescription("Indicate that a Module is no longer in use") - .create()) - .withOption( - cbuilder - .withName("remove") - .withName("rm") - .withName("delete") - .withDescription("Remove an entry from the repository") - .create()) - .withOption( - cbuilder - .withName("rtag") - .withName("rt") - .withName("rfreeze") - .withDescription("Add a symbolic tag to a module") - .create()) - .withOption( - cbuilder - .withName("status") - .withName("st") - .withName("stat") - .withDescription("Display status information on checked out files") - .create()) - .withOption( - cbuilder - .withName("tag") - .withName("ta") - .withName("freeze") - .withDescription("Add a symbolic tag to checked out version of files") - .create()) - .withOption( - cbuilder - .withName("unedit") - .withDescription("Undo an edit command") - .create()) - .withOption( - cbuilder - .withName("update") - .withName("up") - .withName("upd") - .withDescription("Bring work tree in sync with repository") - .create()) - .withOption( - cbuilder - .withName("watch") - .withDescription("Set watches") - .create()) - .withOption( - cbuilder - .withName("watchers") - .withDescription("See who is watching a file") - .create()) - .withOption( - cbuilder - .withName("version") - .withName("ve") - .withName("ver") - .withDescription("????") - .create()) - .withOption(ArgumentTest.buildTargetsArgument()) - .create(); - - final Group cvsOptions = - new GroupBuilder() - .withName("cvs-options") - .withOption( - obuilder - .withShortName("H") - .withDescription("Displays usage information for command.") - .create()) - .withOption( - obuilder - .withShortName("Q") - .withDescription("Cause CVS to be really quiet.") - .create()) - .withOption( - obuilder - .withShortName("q") - .withDescription("Cause CVS to be somewhat quiet.") - .create()) - .withOption( - obuilder - .withShortName("r") - .withDescription("Make checked-out files read-only.") - .create()) - .withOption( - obuilder - .withShortName("w") - .withDescription("Make checked-out files read-write (default).") - .create()) - .withOption( - obuilder - .withShortName("l") - .withDescription("Turn history logging off.") - .create()) - .withOption( - obuilder - .withShortName("n") - .withDescription("Do not execute anything that will change the disk.") - .create()) - .withOption( - obuilder - .withShortName("t") - .withDescription("Show trace of program execution -- try with -n.") - .create()) - .withOption( - obuilder - .withShortName("v") - .withDescription("CVS version and copyright.") - .create()) - .withOption( - obuilder - .withLongName("crlf") - .withDescription("Use the Dos line feed for text files (default).") - .create()) - .withOption( - obuilder - .withLongName("lf") - .withDescription("Use the Unix line feed for text files.") - .create()) - .withOption( - obuilder - .withShortName("T") - .withDescription("Use 'tmpdir' for temporary files.") - .withArgument(abuilder.withName("tmpdir").create()) - .create()) - .withOption( - obuilder - .withShortName("e") - .withDescription("Use 'editor' for editing log information.") - .withArgument(abuilder.withName("editor").create()) - .create()) - .withOption( - obuilder - .withShortName("d") - .withDescription("Overrides $CVSROOT as the root of the CVS tree.") - .withArgument(abuilder.withName("CVS_root").create()) - .create()) - .withOption( - obuilder - .withShortName("f") - .withDescription("Do not use the ~/.cvsrc file.") - .create()) - .withOption( - obuilder - .withShortName("z") - .withDescription("Use compression level '#' for net traffic.") - .withArgument(abuilder.withName("#").create()) - .create()) - .withOption( - obuilder - .withShortName("a") - .withDescription("Authenticate all net traffic.") - .create()) - .withOption( - obuilder - .withShortName("s") - .withDescription("Set CVS user variable.") - .withArgument(abuilder.withName("VAR=VAL").create()) - .create()) - .withOption(commands) - .create(); - - assertNotNull(cvsOptions); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.application;import junit.framework.TestCase;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.CommandBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.option.ArgumentTest;//TODO Build up CvsTest like CpTestpublic class CvsTest extends TestCase { public void testCVS() { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final CommandBuilder cbuilder = new CommandBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Group commands = gbuilder .withName("commands") .withOption( cbuilder .withName("add") .withName("ad") .withName("new") .withDescription("Add a new file/directory to the repository") .create()) .withOption( cbuilder .withName("admin") .withName("adm") .withName("rcs") .withDescription("Administration front end for rcs") .create()) .withOption( cbuilder .withName("annotate") .withName("ann") .withDescription("Show last revision where each line was modified") .create()) .withOption( cbuilder .withName("checkout") .withName("co") .withName("get") .withDescription("Checkout sources for editing") .create()) .withOption( cbuilder .withName("commit") .withName("ci") .withName("com") .withDescription("Check files into the repository") .create()) .withOption( cbuilder .withName("diff") .withName("di") .withName("dif") .withDescription("Show differences between revisions") .create()) .withOption( cbuilder .withName("edit") .withDescription("Get ready to edit a watched file") .create()) .withOption( cbuilder .withName("editors") .withDescription("See who is editing a watched file") .create()) .withOption( cbuilder .withName("export") .withName("exp") .withName("ex") .withDescription("Export sources from CVS, similar to checkout") .create()) .withOption( cbuilder .withName("history") .withName("hi") .withName("his") .withDescription("Show repository access history") .create()) .withOption( cbuilder .withName("import") .withName("im") .withName("imp") .withDescription("Import sources into CVS, using vendor branches") .create()) .withOption( cbuilder .withName("init") .withDescription("Create a CVS repository if it doesn't exist") .create()) .withOption( cbuilder .withName("log") .withName("lo") .withName("rlog") .withDescription("Print out history information for files") .create()) .withOption( cbuilder .withName("login") .withName("logon") .withName("lgn") .withDescription("Prompt for password for authenticating server") .create()) .withOption( cbuilder .withName("logout") .withDescription("Removes entry in .cvspass for remote repository") .create()) .withOption( cbuilder .withName("rdiff") .withName("patch") .withName("pa") .withDescription("Create 'patch' format diffs between releases") .create()) .withOption( cbuilder .withName("release") .withName("re") .withName("rel") .withDescription("Indicate that a Module is no longer in use") .create()) .withOption( cbuilder .withName("remove") .withName("rm") .withName("delete") .withDescription("Remove an entry from the repository") .create()) .withOption( cbuilder .withName("rtag") .withName("rt") .withName("rfreeze") .withDescription("Add a symbolic tag to a module") .create()) .withOption( cbuilder .withName("status") .withName("st") .withName("stat") .withDescription("Display status information on checked out files") .create()) .withOption( cbuilder .withName("tag") .withName("ta") .withName("freeze") .withDescription("Add a symbolic tag to checked out version of files") .create()) .withOption( cbuilder .withName("unedit") .withDescription("Undo an edit command") .create()) .withOption( cbuilder .withName("update") .withName("up") .withName("upd") .withDescription("Bring work tree in sync with repository") .create()) .withOption( cbuilder .withName("watch") .withDescription("Set watches") .create()) .withOption( cbuilder .withName("watchers") .withDescription("See who is watching a file") .create()) .withOption( cbuilder .withName("version") .withName("ve") .withName("ver") .withDescription("????") .create()) .withOption(ArgumentTest.buildTargetsArgument()) .create(); final Group cvsOptions = new GroupBuilder() .withName("cvs-options") .withOption( obuilder .withShortName("H") .withDescription("Displays usage information for command.") .create()) .withOption( obuilder .withShortName("Q") .withDescription("Cause CVS to be really quiet.") .create()) .withOption( obuilder .withShortName("q") .withDescription("Cause CVS to be somewhat quiet.") .create()) .withOption( obuilder .withShortName("r") .withDescription("Make checked-out files read-only.") .create()) .withOption( obuilder .withShortName("w") .withDescription("Make checked-out files read-write (default).") .create()) .withOption( obuilder .withShortName("l") .withDescription("Turn history logging off.") .create()) .withOption( obuilder .withShortName("n") .withDescription("Do not execute anything that will change the disk.") .create()) .withOption( obuilder .withShortName("t") .withDescription("Show trace of program execution -- try with -n.") .create()) .withOption( obuilder .withShortName("v") .withDescription("CVS version and copyright.") .create()) .withOption( obuilder .withLongName("crlf") .withDescription("Use the Dos line feed for text files (default).") .create()) .withOption( obuilder .withLongName("lf") .withDescription("Use the Unix line feed for text files.") .create()) .withOption( obuilder .withShortName("T") .withDescription("Use 'tmpdir' for temporary files.") .withArgument(abuilder.withName("tmpdir").create()) .create()) .withOption( obuilder .withShortName("e") .withDescription("Use 'editor' for editing log information.") .withArgument(abuilder.withName("editor").create()) .create()) .withOption( obuilder .withShortName("d") .withDescription("Overrides $CVSROOT as the root of the CVS tree.") .withArgument(abuilder.withName("CVS_root").create()) .create()) .withOption( obuilder .withShortName("f") .withDescription("Do not use the ~/.cvsrc file.") .create()) .withOption( obuilder .withShortName("z") .withDescription("Use compression level '#' for net traffic.") .withArgument(abuilder.withName("#").create()) .create()) .withOption( obuilder .withShortName("a") .withDescription("Authenticate all net traffic.") .create()) .withOption( obuilder .withShortName("s") .withDescription("Set CVS user variable.") .withArgument(abuilder.withName("VAR=VAL").create()) .create()) .withOption(commands) .create(); assertNotNull(cvsOptions); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/application/LsTest.java b/src/test/org/apache/commons/cli2/application/LsTest.java index e68a248f5..887d56b95 100644 --- a/src/test/org/apache/commons/cli2/application/LsTest.java +++ b/src/test/org/apache/commons/cli2/application/LsTest.java @@ -1,224 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.application; - -import java.util.HashSet; -import java.util.Set; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import org.apache.commons.cli2.validation.EnumValidator; - -/** - *

      Test the ls command. Duplicated Option types are not - * tested e.g. -a and -d are the same Option type.

      - * - *

      The following is the man output for 'ls'. See - * http://www.rt.com/man/ls.1.html.

      - * - *
      - *  LS(1) FSF LS(1)
      - * 
      - *  NAME ls - list directory contents
      - * 
      - *  SYNOPSIS ls [OPTION]... [FILE]...
      - * 
      - *  DESCRIPTION List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuSUX nor --sort.
      - * 
      - *  -a, --all do not hide entries starting with .
      - * 
      - *  -A, --almost-all do not list implied . and ..
      - * 
      - *  -b, --escape print octal escapes for nongraphic characters
      - * 
      - *  --block-size=SIZE use SIZE-byte blocks
      - * 
      - *  -B, --ignore-backups do not list implied entries ending with ~ -c sort by change time; with -l: show ctime -C list entries by columns
      - * 
      - *  --color[=WHEN] control whether color is used to distinguish file types. WHEN may be `never', `always', or `auto'
      - * 
      - *  -d, --directory list directory entries instead of contents
      - * 
      - *  -D, --dired generate output designed for Emacs' dired mode -f do not sort, enable -aU, disable -lst
      - * 
      - *  -F, --classify append indicator (one of /=@|*) to entries
      - * 
      - *  --format=WORD across -x, commas -m, horizontal -x, long -l, sin- gle-column -1, verbose -l, vertical -C
      - * 
      - *  --full-time list both full date and full time -g (ignored)
      - * 
      - *  -G, --no-group inhibit display of group information
      - * 
      - *  -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)
      - * 
      - *  -H, --si likewise, but use powers of 1000 not 1024
      - * 
      - *  --indicator-style=WORD append indicator with style WORD to entry names: none (default), classify (-F), file-type (-p)
      - * 
      - *  -i, --inode print index number of each file
      - * 
      - *  -I, --ignore=PATTERN do not list implied entries matching shell PATTERN
      - * 
      - *  -k, --kilobytes like --block-size=1024 -l use a long listing format
      - * 
      - *  -L, --dereference list entries pointed to by symbolic links -m fill width with a comma separated list of entries
      - * 
      - *  -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names
      - * 
      - *  -N, --literal print raw entry names (don't treat e.g. control characters specially) -o use long listing format without group info
      - * 
      - *  -p, --file-type append indicator (one of /=@|) to entries
      - * 
      - *  -q, --hide-control-chars print ? instead of non graphic characters
      - * 
      - *  --show-control-chars show non graphic characters as-is (default)
      - * 
      - *  -Q, --quote-name enclose entry names in double quotes
      - * 
      - *  --quoting-style=WORD use quoting style WORD for entry names: literal, shell, shell-always, c, escape
      - * 
      - *  -r, --reverse reverse order while sorting
      - * 
      - *  -R, --recursive list subdirectories recursively
      - * 
      - *  -s, --size print size of each file, in blocks -S sort by file size
      - * 
      - *  --sort=WORD extension -X, none -U, size -S, time -t, version -v status -c, time -t, atime -u, access -u, use -u
      - * 
      - *  --time=WORD show time as WORD instead of modification time: atime, access, use, ctime or status; use specified time as sort key if --sort=time -t sort by modification time
      - * 
      - *  -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u sort by last access time; with -l: show atime -U do not sort; list entries in directory order -v sort by version
      - * 
      - *  -w, --width=COLS assume screen width instead of current value -x list entries by lines instead of by columns -X sort alphabetically by entry extension -1 list one file per line
      - * 
      - *  --help display this help and exit
      - * 
      - *  --version output version information and exit
      - * 
      - *  By default, color is not used to distinguish types of files. That is equivalent to using --color=none. Using the --color option without the optional WHEN argument is equivalent to using --color=always. With --color=auto, color codes are output only if standard output is con- nected to a terminal (tty).
      - * 
      - * - * @author Rob Oxspring - * @author John Keyes - */ -public class LsTest extends TestCase { - - /** Option Builder */ - private static final DefaultOptionBuilder oBuilder = - new DefaultOptionBuilder(); - - /** Argument Builder */ - private static final ArgumentBuilder aBuilder = new ArgumentBuilder(); - - /** Group Builder */ - private static final GroupBuilder gBuilder = new GroupBuilder(); - - private static Group options; - - public static Test suite() { - return new TestSuite(LsTest.class); - } - - /** - * Required ctor. - * - * @param name - * the name of the TestCase - */ - public LsTest(final String name) { - super(name); - } - - public void setUp() { - if (LsTest.options == null) { - final Option a = - oBuilder - .withShortName("a") - .withLongName("all") - .withDescription("do not hide entries starting with .") - .create(); - - final Option blockSize = - oBuilder - .withLongName("block-size") - .withRequired(false) - .withDescription("use SIZE-byte blocks") - .withArgument( - aBuilder - .withMaximum(1) - .withMinimum(1) - .withInitialSeparator('=') - .create()) - .create(); - - final Option c = - oBuilder - .withShortName("c") - .withRequired(false) - .withDescription("with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime") - .create(); - - final Set colors = new HashSet(); - colors.add("never"); - colors.add("always"); - colors.add("auto"); - final Option color = - oBuilder - .withLongName("color") - .withRequired(false) - .withDescription("control whether color is used to distinguish file types. WHEN may be `never', `always', or `auto'") - .withArgument( - aBuilder - .withMaximum(1) - .withMinimum(1) - .withInitialSeparator('=') - .withValidator(new EnumValidator(colors)) - .create()) - .create(); - - LsTest.options = - gBuilder - .withOption(a) - .withOption(blockSize) - .withOption(c) - .withOption(color) - .create(); - } - } - - public void testLs() throws OptionException { - // create the command line parser - Parser parser = new Parser(); - parser.setGroup(options); - CommandLine line = - parser.parse(new String[] { "--block-size=10", "--color=never" }); - - assertTrue(line.hasOption("--block-size")); - assertEquals(line.getValue("--block-size"), "10"); - assertFalse(line.hasOption("--ignore-backups")); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.application;import java.util.HashSet;import java.util.Set;import junit.framework.Test;import junit.framework.TestCase;import junit.framework.TestSuite;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.validation.EnumValidator;/** *

      Test the ls command. Duplicated Option types are not * tested e.g. -a and -d are the same Option type.

      * *

      The following is the man output for 'ls'. See * http://www.rt.com/man/ls.1.html.

      * *
       *  LS(1) FSF LS(1) * *  NAME ls - list directory contents * *  SYNOPSIS ls [OPTION]... [FILE]... * *  DESCRIPTION List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuSUX nor --sort. * *  -a, --all do not hide entries starting with . * *  -A, --almost-all do not list implied . and .. * *  -b, --escape print octal escapes for nongraphic characters * *  --block-size=SIZE use SIZE-byte blocks * *  -B, --ignore-backups do not list implied entries ending with ~ -c sort by change time; with -l: show ctime -C list entries by columns * *  --color[=WHEN] control whether color is used to distinguish file types. WHEN may be `never', `always', or `auto' * *  -d, --directory list directory entries instead of contents * *  -D, --dired generate output designed for Emacs' dired mode -f do not sort, enable -aU, disable -lst * *  -F, --classify append indicator (one of /=@|*) to entries * *  --format=WORD across -x, commas -m, horizontal -x, long -l, sin- gle-column -1, verbose -l, vertical -C * *  --full-time list both full date and full time -g (ignored) * *  -G, --no-group inhibit display of group information * *  -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G) * *  -H, --si likewise, but use powers of 1000 not 1024 * *  --indicator-style=WORD append indicator with style WORD to entry names: none (default), classify (-F), file-type (-p) * *  -i, --inode print index number of each file * *  -I, --ignore=PATTERN do not list implied entries matching shell PATTERN * *  -k, --kilobytes like --block-size=1024 -l use a long listing format * *  -L, --dereference list entries pointed to by symbolic links -m fill width with a comma separated list of entries * *  -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names * *  -N, --literal print raw entry names (don't treat e.g. control characters specially) -o use long listing format without group info * *  -p, --file-type append indicator (one of /=@|) to entries * *  -q, --hide-control-chars print ? instead of non graphic characters * *  --show-control-chars show non graphic characters as-is (default) * *  -Q, --quote-name enclose entry names in double quotes * *  --quoting-style=WORD use quoting style WORD for entry names: literal, shell, shell-always, c, escape * *  -r, --reverse reverse order while sorting * *  -R, --recursive list subdirectories recursively * *  -s, --size print size of each file, in blocks -S sort by file size * *  --sort=WORD extension -X, none -U, size -S, time -t, version -v status -c, time -t, atime -u, access -u, use -u * *  --time=WORD show time as WORD instead of modification time: atime, access, use, ctime or status; use specified time as sort key if --sort=time -t sort by modification time * *  -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u sort by last access time; with -l: show atime -U do not sort; list entries in directory order -v sort by version * *  -w, --width=COLS assume screen width instead of current value -x list entries by lines instead of by columns -X sort alphabetically by entry extension -1 list one file per line * *  --help display this help and exit * *  --version output version information and exit * *  By default, color is not used to distinguish types of files. That is equivalent to using --color=none. Using the --color option without the optional WHEN argument is equivalent to using --color=always. With --color=auto, color codes are output only if standard output is con- nected to a terminal (tty). * 
      * * @author Rob Oxspring * @author John Keyes */public class LsTest extends TestCase { /** Option Builder */ private static final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); /** Argument Builder */ private static final ArgumentBuilder aBuilder = new ArgumentBuilder(); /** Group Builder */ private static final GroupBuilder gBuilder = new GroupBuilder(); private static Group options; public static Test suite() { return new TestSuite(LsTest.class); } /** * Required ctor. * * @param name * the name of the TestCase */ public LsTest(final String name) { super(name); } public void setUp() { if (LsTest.options == null) { final Option a = oBuilder .withShortName("a") .withLongName("all") .withDescription("do not hide entries starting with .") .create(); final Option blockSize = oBuilder .withLongName("block-size") .withRequired(false) .withDescription("use SIZE-byte blocks") .withArgument( aBuilder .withMaximum(1) .withMinimum(1) .withInitialSeparator('=') .create()) .create(); final Option c = oBuilder .withShortName("c") .withRequired(false) .withDescription("with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime") .create(); final Set colors = new HashSet(); colors.add("never"); colors.add("always"); colors.add("auto"); final Option color = oBuilder .withLongName("color") .withRequired(false) .withDescription("control whether color is used to distinguish file types. WHEN may be `never', `always', or `auto'") .withArgument( aBuilder .withMaximum(1) .withMinimum(1) .withInitialSeparator('=') .withValidator(new EnumValidator(colors)) .create()) .create(); LsTest.options = gBuilder .withOption(a) .withOption(blockSize) .withOption(c) .withOption(color) .create(); } } public void testLs() throws OptionException { // create the command line parser Parser parser = new Parser(); parser.setGroup(options); CommandLine line = parser.parse(new String[] { "--block-size=10", "--color=never" }); assertTrue(line.hasOption("--block-size")); assertEquals(line.getValue("--block-size"), "10"); assertFalse(line.hasOption("--ignore-backups")); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/Bug13886Test.java b/src/test/org/apache/commons/cli2/bug/Bug13886Test.java index 9c2d97881..6c5cf7ee4 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug13886Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug13886Test.java @@ -1,89 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.bug; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; - -/** - * @author John Keyes - */ -public class Bug13886Test extends TestCase { - - public Bug13886Test(final String name) { - super(name); - } - - public void testMandatoryGroup() throws Exception { - final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - - final Option a = obuilder.withShortName("a").create(); - - final Option b = obuilder.withShortName("b").create(); - - final Group options = - gbuilder - .withOption(a) - .withOption(b) - .withMaximum(1) - .withMinimum(1) - .create(); - - final Parser parser = new Parser(); - parser.setGroup(options); - - try { - parser.parse(new String[] { - }); - fail("Expected MissingOptionException not caught"); - } - catch (final OptionException exp) { - assertEquals("Missing option -a|-b", exp.getMessage()); - } - - try { - parser.parse(new String[] { "-a" }); - } - catch (final OptionException exp) { - fail("Unexpected MissingOptionException caught"); - } - - try { - parser.parse(new String[] { "-b" }); - } - catch (final OptionException exp) { - fail("Unexpected MissingOptionException caught"); - } - - try { - parser.parse(new String[] { "-a", "-b" }); - fail("Expected UnexpectedOptionException not caught"); - } - catch (final OptionException exp) { - assertEquals( - "Unexpected -b while processing -a|-b", - exp.getMessage()); - } - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;/** * @author John Keyes */public class Bug13886Test extends TestCase { public Bug13886Test(final String name) { super(name); } public void testMandatoryGroup() throws Exception { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Option a = obuilder.withShortName("a").create(); final Option b = obuilder.withShortName("b").create(); final Group options = gbuilder .withOption(a) .withOption(b) .withMaximum(1) .withMinimum(1) .create(); final Parser parser = new Parser(); parser.setGroup(options); try { parser.parse(new String[] { }); fail("Expected MissingOptionException not caught"); } catch (final OptionException exp) { assertEquals("Missing option -a|-b", exp.getMessage()); } try { parser.parse(new String[] { "-a" }); } catch (final OptionException exp) { fail("Unexpected MissingOptionException caught"); } try { parser.parse(new String[] { "-b" }); } catch (final OptionException exp) { fail("Unexpected MissingOptionException caught"); } try { parser.parse(new String[] { "-a", "-b" }); fail("Expected UnexpectedOptionException not caught"); } catch (final OptionException exp) { assertEquals( "Unexpected -b while processing -a|-b", exp.getMessage()); } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/Bug13935Test.java b/src/test/org/apache/commons/cli2/bug/Bug13935Test.java index b76b91c0c..bc68397d8 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug13935Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug13935Test.java @@ -1,60 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.bug; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; - -/** - * @author John Keyes - */ -public class Bug13935Test extends TestCase { - - public Bug13935Test(final String name) { - super(name); - } - - public void testRequiredGroup() throws Exception { - final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - - final Option testOption = - obuilder - .withShortName("a") - .withArgument(abuilder.withName("quoted string").create()) - .create(); - - final Group options = gbuilder.withOption(testOption).create(); - - final Parser parser = new Parser(); - parser.setGroup(options); - - final CommandLine cmdLine = - parser.parse(new String[] { "-a", "\"two tokens\"" }); - - assertTrue(cmdLine.hasOption("-a")); - assertEquals("two tokens", cmdLine.getValue("-a")); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;/** * @author John Keyes */public class Bug13935Test extends TestCase { public Bug13935Test(final String name) { super(name); } public void testRequiredGroup() throws Exception { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Option testOption = obuilder .withShortName("a") .withArgument(abuilder.withName("quoted string").create()) .create(); final Group options = gbuilder.withOption(testOption).create(); final Parser parser = new Parser(); parser.setGroup(options); final CommandLine cmdLine = parser.parse(new String[] { "-a", "\"two tokens\"" }); assertTrue(cmdLine.hasOption("-a")); assertEquals("two tokens", cmdLine.getValue("-a")); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/Bug15046Test.java b/src/test/org/apache/commons/cli2/bug/Bug15046Test.java index cf4c324d4..41a36d498 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug15046Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug15046Test.java @@ -1,82 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.bug; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; - -/** - * @author John Keyes - */ -public class Bug15046Test extends TestCase { - - public Bug15046Test(String name) { - super(name); - } - - public void testParamNamedAsOption() throws Exception { - final String[] CLI_ARGS = new String[] { "-z", "c" }; - - DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - ArgumentBuilder abuilder = new ArgumentBuilder(); - - Option option = - obuilder - .withShortName("z") - .withLongName("timezone") - .withDescription("affected option") - .withArgument(abuilder.withName("timezone").create()) - .create(); - - GroupBuilder gbuilder = new GroupBuilder(); - Group options = - gbuilder.withName("bug15046").withOption(option).create(); - - Parser parser = new Parser(); - parser.setGroup(options); - CommandLine line = parser.parse(CLI_ARGS); - - assertEquals("c", line.getValue("-z")); - - Option c = - obuilder - .withShortName("c") - .withLongName("conflict") - .withDescription("conflicting option") - .withArgument(abuilder.withName("conflict").create()) - .create(); - - options = - gbuilder - .withName("bug15046") - .withOption(option) - .withOption(c) - .create(); - - parser.setGroup(options); - line = parser.parse(CLI_ARGS); - - assertEquals("c", line.getValue("-z")); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;/** * @author John Keyes */public class Bug15046Test extends TestCase { public Bug15046Test(String name) { super(name); } public void testParamNamedAsOption() throws Exception { final String[] CLI_ARGS = new String[] { "-z", "c" }; DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); Option option = obuilder .withShortName("z") .withLongName("timezone") .withDescription("affected option") .withArgument(abuilder.withName("timezone").create()) .create(); GroupBuilder gbuilder = new GroupBuilder(); Group options = gbuilder.withName("bug15046").withOption(option).create(); Parser parser = new Parser(); parser.setGroup(options); CommandLine line = parser.parse(CLI_ARGS); assertEquals("c", line.getValue("-z")); Option c = obuilder .withShortName("c") .withLongName("conflict") .withDescription("conflicting option") .withArgument(abuilder.withName("conflict").create()) .create(); options = gbuilder .withName("bug15046") .withOption(option) .withOption(c) .create(); parser.setGroup(options); line = parser.parse(CLI_ARGS); assertEquals("c", line.getValue("-z")); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/Bug15648Test.java b/src/test/org/apache/commons/cli2/bug/Bug15648Test.java index 1cc0da806..af905e1bf 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug15648Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug15648Test.java @@ -1,60 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.bug; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; - -/** - * @author John Keyes - */ -public class Bug15648Test extends TestCase { - - public Bug15648Test(final String name) { - super(name); - } - - public void testQuotedArgumentValue() throws Exception { - final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - - final Option testOption = - obuilder - .withShortName("a") - .withArgument(abuilder.withName("quoted string").create()) - .create(); - - final Group options = gbuilder.withOption(testOption).create(); - - final Parser parser = new Parser(); - parser.setGroup(options); - - final CommandLine cmdLine = - parser.parse(new String[] { "-a", "\"two tokens\"" }); - - assertTrue(cmdLine.hasOption("-a")); - assertEquals("two tokens", cmdLine.getValue("-a")); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;/** * @author John Keyes */public class Bug15648Test extends TestCase { public Bug15648Test(final String name) { super(name); } public void testQuotedArgumentValue() throws Exception { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Option testOption = obuilder .withShortName("a") .withArgument(abuilder.withName("quoted string").create()) .create(); final Group options = gbuilder.withOption(testOption).create(); final Parser parser = new Parser(); parser.setGroup(options); final CommandLine cmdLine = parser.parse(new String[] { "-a", "\"two tokens\"" }); assertTrue(cmdLine.hasOption("-a")); assertEquals("two tokens", cmdLine.getValue("-a")); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/Bug27575Test.java b/src/test/org/apache/commons/cli2/bug/Bug27575Test.java index fb7a5a900..368218039 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug27575Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug27575Test.java @@ -1,41 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.bug; - -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.builder.PatternBuilder; -import org.apache.commons.cli2.option.GroupImpl; - -public class Bug27575Test extends TestCase { - - public void testRequiredOptions(){ - PatternBuilder builder = new PatternBuilder(); - builder.withPattern("hc!<"); - Option option = builder.create(); - assertTrue(option instanceof GroupImpl); - - GroupImpl group = (GroupImpl)option; - Iterator i = group.getOptions().iterator(); - assertEquals("[-h]",i.next().toString()); - assertEquals("-c ",i.next().toString()); - assertFalse(i.hasNext()); - } -} \ No newline at end of file +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import java.util.Iterator;import junit.framework.TestCase;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.PatternBuilder;import org.apache.commons.cli2.option.GroupImpl;public class Bug27575Test extends TestCase { public void testRequiredOptions(){ PatternBuilder builder = new PatternBuilder(); builder.withPattern("hc!<"); Option option = builder.create(); assertTrue(option instanceof GroupImpl); GroupImpl group = (GroupImpl)option; Iterator i = group.getOptions().iterator(); assertEquals("[-h]",i.next().toString()); assertEquals("-c ",i.next().toString()); assertFalse(i.hasNext()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/Bug28005Test.java b/src/test/org/apache/commons/cli2/bug/Bug28005Test.java index 2c81ca302..5671ec5b6 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug28005Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug28005Test.java @@ -1,79 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.bug; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.CommandBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import junit.framework.TestCase; - -public class Bug28005Test extends TestCase { - public void testInfiniteLoop() { - final DefaultOptionBuilder optionBuilder = new DefaultOptionBuilder(); - final ArgumentBuilder argumentBuilder = new ArgumentBuilder(); - final GroupBuilder groupBuilder = new GroupBuilder(); - final CommandBuilder commandBuilder = new CommandBuilder(); - - final Option inputFormatOption = - optionBuilder - .withLongName("input-format") - //.withArgument(argumentBuilder.create()) - .create(); - - final Argument argument = - argumentBuilder - .withName("file") - .create(); - - final Group children = - groupBuilder - .withName("options") - .withOption(inputFormatOption) - .create(); - - final Option command = - commandBuilder - .withName("convert") - .withChildren(children) - .withArgument(argument) - .create(); - - final Group root = - groupBuilder - .withName("commands") - .withOption(command) - .create(); - - final Parser parser = new Parser(); - parser.setGroup(root); - final String[] args = new String[]{"convert", "test.txt", - "--input-format", "a"}; - - try { - parser.parse(args); - fail("a isn't valid!!"); - } catch (OptionException e) { - assertEquals("Unexpected a while processing commands",e.getMessage()); - } - } -} \ No newline at end of file +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.CommandBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import junit.framework.TestCase;public class Bug28005Test extends TestCase { public void testInfiniteLoop() { final DefaultOptionBuilder optionBuilder = new DefaultOptionBuilder(); final ArgumentBuilder argumentBuilder = new ArgumentBuilder(); final GroupBuilder groupBuilder = new GroupBuilder(); final CommandBuilder commandBuilder = new CommandBuilder(); final Option inputFormatOption = optionBuilder .withLongName("input-format") //.withArgument(argumentBuilder.create()) .create(); final Argument argument = argumentBuilder .withName("file") .create(); final Group children = groupBuilder .withName("options") .withOption(inputFormatOption) .create(); final Option command = commandBuilder .withName("convert") .withChildren(children) .withArgument(argument) .create(); final Group root = groupBuilder .withName("commands") .withOption(command) .create(); final Parser parser = new Parser(); parser.setGroup(root); final String[] args = new String[]{"convert", "test.txt", "--input-format", "a"}; try { parser.parse(args); fail("a isn't valid!!"); } catch (OptionException e) { assertEquals("Unexpected a while processing commands",e.getMessage()); } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/Bug32533Test.java b/src/test/org/apache/commons/cli2/bug/Bug32533Test.java index 56f337202..19547b0e5 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug32533Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug32533Test.java @@ -1,48 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.bug; - -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; - -import junit.framework.TestCase; - -/** - * @author roxspring - */ -public class Bug32533Test extends TestCase { - - public void testBlah() throws OptionException { - - Option a1 = new DefaultOptionBuilder().withLongName("a1").create(); - Option b1 = new DefaultOptionBuilder().withLongName("b1").create(); - Option c1 = new DefaultOptionBuilder().withLongName("c1").create(); - - Group b = new GroupBuilder().withOption(b1).create(); - Group c = new GroupBuilder().withOption(c1).create(); - Group a = new GroupBuilder().withOption(a1).withOption(b).withOption(c).create(); - - Parser parser = new Parser(); - parser.setGroup(a); - parser.parse(new String[]{"--a1","--b1"}); - } - -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import junit.framework.TestCase;/** * @author roxspring */public class Bug32533Test extends TestCase { public void testBlah() throws OptionException { Option a1 = new DefaultOptionBuilder().withLongName("a1").create(); Option b1 = new DefaultOptionBuilder().withLongName("b1").create(); Option c1 = new DefaultOptionBuilder().withLongName("c1").create(); Group b = new GroupBuilder().withOption(b1).create(); Group c = new GroupBuilder().withOption(c1).create(); Group a = new GroupBuilder().withOption(a1).withOption(b).withOption(c).create(); Parser parser = new Parser(); parser.setGroup(a); parser.parse(new String[]{"--a1","--b1"}); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java index 5e818e6f3..474954927 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java @@ -1,45 +1 @@ -package org.apache.commons.cli2.bug; - -import junit.framework.TestCase; -import org.apache.commons.cli2.*; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import org.apache.commons.cli2.validation.FileValidator; - -/** - * @author brianegge - */ -public class BugCLI122Test extends TestCase { - public void testArgumentWhichStartsWithDash() throws OptionException { - Argument wdArg = new ArgumentBuilder() - .withName("anything") - .withMaximum(1) - .withMinimum(1) - .withInitialSeparator('=') - .create(); - - Option wdOpt = new DefaultOptionBuilder().withArgument(wdArg) - .withDescription("anything, foo or -foo") - .withLongName("argument") - .withShortName("a") - .create(); - - Group group = new GroupBuilder().withOption(wdOpt).create(); - - Parser p = new Parser(); - p.setGroup(group); - CommandLine normal = p.parse (new String[]{"-a", "foo"}); - assertNotNull(normal); - assertEquals(normal.getValue(wdOpt), "foo"); - - CommandLine withDash = p.parse (new String[]{"--argument", "\"-foo\""}); - assertNotNull(withDash); - assertEquals("-foo", withDash.getValue(wdOpt)); - - CommandLine withDashAndEquals = p.parse (new String[]{"--argument=-foo"}); - assertNotNull(withDashAndEquals); - assertEquals("-foo", withDashAndEquals.getValue(wdOpt)); - } -} +package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.*;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.validation.FileValidator;/** * @author brianegge */public class BugCLI122Test extends TestCase { public void testArgumentWhichStartsWithDash() throws OptionException { Argument wdArg = new ArgumentBuilder() .withName("anything") .withMaximum(1) .withMinimum(1) .withInitialSeparator('=') .create(); Option wdOpt = new DefaultOptionBuilder().withArgument(wdArg) .withDescription("anything, foo or -foo") .withLongName("argument") .withShortName("a") .create(); Group group = new GroupBuilder().withOption(wdOpt).create(); Parser p = new Parser(); p.setGroup(group); CommandLine normal = p.parse (new String[]{"-a", "foo"}); assertNotNull(normal); assertEquals(normal.getValue(wdOpt), "foo"); CommandLine withDash = p.parse (new String[]{"--argument", "\"-foo\""}); assertNotNull(withDash); assertEquals("-foo", withDash.getValue(wdOpt)); CommandLine withDashAndEquals = p.parse (new String[]{"--argument=-foo"}); assertNotNull(withDashAndEquals); assertEquals("-foo", withDashAndEquals.getValue(wdOpt)); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java index fa1a09a16..8f7adae78 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java @@ -1,57 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.bug; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import org.apache.commons.cli2.option.PropertyOption; - -/** - * http://issues.apache.org/jira/browse/CLI-12 - */ -public class BugCLI12Test extends TestCase { - - public void testBug() { - Argument arg = new ArgumentBuilder().withName("file").create(); - - Option option = new PropertyOption(); - - Group group = new GroupBuilder().withOption(option).withOption(arg).create(); - - Parser p = new Parser(); - p.setGroup(group); - - CommandLine cl = p.parseAndHelp( new String[] { "-Dmyprop1=myval1", "-Dmyprop2=myval2", "myfile" } ); - if(cl == null) { - assertTrue("Couldn't parse valid commandLine", false); - } - - assertEquals( "myval1", cl.getProperty("myprop1")); - assertEquals( "myval2", cl.getProperty("myprop2")); - - String extraArgs = (String) cl.getValue(arg); - assertEquals( "myfile", extraArgs); - } - -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.option.PropertyOption;/** * http://issues.apache.org/jira/browse/CLI-12 */public class BugCLI12Test extends TestCase { public void testBug() { Argument arg = new ArgumentBuilder().withName("file").create(); Option option = new PropertyOption(); Group group = new GroupBuilder().withOption(option).withOption(arg).create(); Parser p = new Parser(); p.setGroup(group); CommandLine cl = p.parseAndHelp( new String[] { "-Dmyprop1=myval1", "-Dmyprop2=myval2", "myfile" } ); if(cl == null) { assertTrue("Couldn't parse valid commandLine", false); } assertEquals( "myval1", cl.getProperty("myprop1")); assertEquals( "myval2", cl.getProperty("myprop2")); String extraArgs = (String) cl.getValue(arg); assertEquals( "myfile", extraArgs); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI18Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI18Test.java index dda88aa61..331428907 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI18Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI18Test.java @@ -1,60 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.bug; - -import java.io.PrintWriter; -import java.io.StringWriter; - -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.util.HelpFormatter; - -import junit.framework.TestCase; - -/** - * http://issues.apache.org/jira/browse/CLI-18 - */ -public class BugCLI18Test extends TestCase { - - public BugCLI18Test() { - super(); - } - - - public void testBug() { - Option a = new DefaultOptionBuilder().withLongName("aaa").withShortName("a").withDescription("aaaaaaa").create(); - Option b = new DefaultOptionBuilder().withLongName("bbb").withDescription("bbbbbbbb dksh fkshd fkhs dkfhsdk fhskd hksdks dhfowehfsdhfkjshf skfhkshf sf jkshfk sfh skfh skf f").create(); - Option c = new DefaultOptionBuilder().withLongName("ccc").withShortName("c").withDescription("ccccccc").create(); - - Group g = new GroupBuilder().withOption(a).withOption(b).withOption(c).create(); - - HelpFormatter formatter = new HelpFormatter(); - StringWriter out = new StringWriter(); - - formatter.setPrintWriter(new PrintWriter(out)); - formatter.setHeader("dsfkfsh kdh hsd hsdh fkshdf ksdh fskdh fsdh fkshfk sfdkjhskjh fkjh fkjsh khsdkj hfskdhf skjdfh ksf khf s"); - formatter.setFooter("blort j jgj j jg jhghjghjgjhgjhg jgjhgj jhg jhg hjg jgjhghjg jhg hjg jhgjg jgjhghjg jg jgjhgjgjg jhg jhgjh" + '\r' + '\n' + "rarrr"); - formatter.setGroup(g); - formatter.setShellCommand("foobar"); - - formatter.print(); - - } -} - +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import java.io.PrintWriter;import java.io.StringWriter;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.util.HelpFormatter;import junit.framework.TestCase;/** * http://issues.apache.org/jira/browse/CLI-18 */public class BugCLI18Test extends TestCase { public BugCLI18Test() { super(); } public void testBug() { Option a = new DefaultOptionBuilder().withLongName("aaa").withShortName("a").withDescription("aaaaaaa").create(); Option b = new DefaultOptionBuilder().withLongName("bbb").withDescription("bbbbbbbb dksh fkshd fkhs dkfhsdk fhskd hksdks dhfowehfsdhfkjshf skfhkshf sf jkshfk sfh skfh skf f").create(); Option c = new DefaultOptionBuilder().withLongName("ccc").withShortName("c").withDescription("ccccccc").create(); Group g = new GroupBuilder().withOption(a).withOption(b).withOption(c).create(); HelpFormatter formatter = new HelpFormatter(); StringWriter out = new StringWriter(); formatter.setPrintWriter(new PrintWriter(out)); formatter.setHeader("dsfkfsh kdh hsd hsdh fkshdf ksdh fskdh fsdh fkshfk sfdkjhskjh fkjh fkjsh khsdkj hfskdhf skjdfh ksf khf s"); formatter.setFooter("blort j jgj j jg jhghjghjgjhgjhg jgjhgj jhg jhg hjg jgjhghjg jhg hjg jhgjg jgjhghjg jg jgjhgjgjg jhg jhgjh" + '\r' + '\n' + "rarrr"); formatter.setGroup(g); formatter.setShellCommand("foobar"); formatter.print(); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java index 13787100a..db94fbbd4 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java @@ -1,67 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.bug; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; - -import junit.framework.TestCase; - -/** - * http://issues.apache.org/jira/browse/CLI-80 - */ -public class BugCLI80Test extends TestCase { - - public void testBug() { - final String optName = "option"; - - Argument arg = new ArgumentBuilder().withName(optName) - .withMaximum(1) - .create(); - - Option option = new DefaultOptionBuilder().withArgument(arg) - .withDescription("singular option") - .withLongName(optName) - .withShortName("o") - .create(); - - Group group = new GroupBuilder().withOption(option).create(); - - Parser p = new Parser(); - p.setGroup(group); - - CommandLine cl = p.parseAndHelp( new String[] { "-o", "yes" } ); - assertNotNull("Couldn't parse valid commandLine", cl); - - assertEquals("Couldn't look up value by short name", "yes", cl.getValue("-o") ); - - try { - cl = p.parse( new String[] { "-o", "yes", "-o", "jam" } ); - fail("Parsed invalid commandLine"); - } catch(OptionException e) { - // ok - } - } - -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import junit.framework.TestCase;/** * http://issues.apache.org/jira/browse/CLI-80 */public class BugCLI80Test extends TestCase { public void testBug() { final String optName = "option"; Argument arg = new ArgumentBuilder().withName(optName) .withMaximum(1) .create(); Option option = new DefaultOptionBuilder().withArgument(arg) .withDescription("singular option") .withLongName(optName) .withShortName("o") .create(); Group group = new GroupBuilder().withOption(option).create(); Parser p = new Parser(); p.setGroup(group); CommandLine cl = p.parseAndHelp( new String[] { "-o", "yes" } ); assertNotNull("Couldn't parse valid commandLine", cl); assertEquals("Couldn't look up value by short name", "yes", cl.getValue("-o") ); try { cl = p.parse( new String[] { "-o", "yes", "-o", "jam" } ); fail("Parsed invalid commandLine"); } catch(OptionException e) { // ok } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java index f0e6d4d3a..57022582b 100644 --- a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java +++ b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java @@ -1,79 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.commons.cli2.bug; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import org.apache.commons.cli2.option.SourceDestArgument; - -/** - * The first is a loop in Parser.parse() if I set a non-declared option. This - * code goes into a loop in Parser.java method parse this “while” loop runs - * endless - * - * @author Steve Alberty - */ -public class BugLoopingOptionLookAlikeTest extends TestCase { - - public void testLoopingOptionLookAlike() { - final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - final Group options = gbuilder - .withName("ant") - .withOption(obuilder.withShortName("help").withDescription("print this message").create()) - .withOption(obuilder.withShortName("projecthelp").withDescription("print project help information").create()) - .withOption(abuilder.withName("target").create()) - .create(); - - final Parser parser = new Parser(); - parser.setGroup(options); - try { - parser.parse(new String[] { "-abcdef", - "testfile.txt ", }); - fail("OptionException"); - } catch (OptionException e) { - assertEquals("Unexpected -abcdef while processing ant",e.getMessage()); - } - } - - public void testLoopingOptionLookAlike2() { - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - final Argument inputfile_opt = abuilder.withName("input").withMinimum(1).withMaximum(1).create(); - final Argument outputfile_opt = abuilder.withName("output").withMinimum(1).withMaximum(1).create(); - final Argument targets = new SourceDestArgument(inputfile_opt, outputfile_opt); - final Group options = gbuilder.withOption(targets).create(); - final Parser parser = new Parser(); - parser.setGroup(options); - try { - parser.parse(new String[] { "testfile.txt", "testfile.txt", "testfile.txt", "testfile.txt" }); - fail("OptionException"); - } catch (OptionException e) { - assertEquals("Unexpected testfile.txt while processing ", e.getMessage()); - } - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.option.SourceDestArgument;/** * The first is a loop in Parser.parse() if I set a non-declared option. This * code goes into a loop in Parser.java method parse this “while” loop runs * endless * * @author Steve Alberty */public class BugLoopingOptionLookAlikeTest extends TestCase { public void testLoopingOptionLookAlike() { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Group options = gbuilder .withName("ant") .withOption(obuilder.withShortName("help").withDescription("print this message").create()) .withOption(obuilder.withShortName("projecthelp").withDescription("print project help information").create()) .withOption(abuilder.withName("target").create()) .create(); final Parser parser = new Parser(); parser.setGroup(options); try { parser.parse(new String[] { "-abcdef", "testfile.txt ", }); fail("OptionException"); } catch (OptionException e) { assertEquals("Unexpected -abcdef while processing ant",e.getMessage()); } } public void testLoopingOptionLookAlike2() { final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Argument inputfile_opt = abuilder.withName("input").withMinimum(1).withMaximum(1).create(); final Argument outputfile_opt = abuilder.withName("output").withMinimum(1).withMaximum(1).create(); final Argument targets = new SourceDestArgument(inputfile_opt, outputfile_opt); final Group options = gbuilder.withOption(targets).create(); final Parser parser = new Parser(); parser.setGroup(options); try { parser.parse(new String[] { "testfile.txt", "testfile.txt", "testfile.txt", "testfile.txt" }); fail("OptionException"); } catch (OptionException e) { assertEquals("Unexpected testfile.txt while processing ", e.getMessage()); } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java b/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java index 877523aaf..9761f4c03 100644 --- a/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java +++ b/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java @@ -1,254 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.commons.cli2.builder; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.option.ArgumentImpl; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; -import org.apache.commons.cli2.validation.DateValidator; -import org.apache.commons.cli2.validation.Validator; - -public class ArgumentBuilderTest - extends TestCase { - private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); - private ArgumentBuilder argumentBuilder; - - /* - * @see TestCase#setUp() - */ - protected void setUp() - throws Exception { - this.argumentBuilder = new ArgumentBuilder(); - } - - public void testConsumeRemaining() { - this.argumentBuilder.withConsumeRemaining("--"); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect consume remaining token", "--", arg.getConsumeRemaining()); - } - - public void testNullConsumeRemaining() { - try { - this.argumentBuilder.withConsumeRemaining(null); - fail("cannot use null consume remaining token"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING), - exp.getMessage()); - } - } - - public void testEmptyConsumeRemaining() { - try { - this.argumentBuilder.withConsumeRemaining(""); - fail("cannot use empty string consume remaining token"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING), - exp.getMessage()); - } - } - - public void testDefault() { - this.argumentBuilder.withDefault("defaultString"); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect number of default values", 1, arg.getDefaultValues().size()); - assertEquals("incorrect default value", "defaultString", arg.getDefaultValues().get(0)); - } - - public void testDefaultX2() { - this.argumentBuilder.withDefault("defaultString1"); - this.argumentBuilder.withDefault("defaultString2"); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); - assertEquals("incorrect default value-1", "defaultString1", arg.getDefaultValues().get(0)); - assertEquals("incorrect default value-2", "defaultString2", arg.getDefaultValues().get(1)); - } - - public void testNullDefault() { - try { - this.argumentBuilder.withDefault(null); - fail("cannot use null default"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT), - exp.getMessage()); - } - } - - public void testDefaults() { - final List defaults = new ArrayList(); - defaults.add("one"); - defaults.add("two"); - - this.argumentBuilder.withDefaults(defaults); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); - assertEquals("incorrect default value-1", "one", arg.getDefaultValues().get(0)); - assertEquals("incorrect default value-2", "two", arg.getDefaultValues().get(1)); - assertEquals("incorrect default values list", defaults, arg.getDefaultValues()); - - } - - public void testNullDefaults() { - try { - this.argumentBuilder.withDefaults(null); - fail("cannot use null defaults"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS), - exp.getMessage()); - } - } - - public void testId() { - this.argumentBuilder.withId(1); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect id", 1, arg.getId()); - } - - public void testInitialSeparator() { - this.argumentBuilder.withInitialSeparator(','); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect initial separator", ',', arg.getInitialSeparator()); - } - - public void testMaximum() { - this.argumentBuilder.withMaximum(1); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect maximum", 1, arg.getMaximum()); - } - - public void testNegativeMaximum() { - try { - this.argumentBuilder.withMaximum(-1); - fail("cannot use negative maximum"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM), - exp.getMessage()); - } - } - - public void testMinimum() { - this.argumentBuilder.withMinimum(1); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect maximum", 1, arg.getMinimum()); - } - - public void testNegativeMinimum() { - try { - this.argumentBuilder.withMinimum(-1); - fail("cannot use negative minimum"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM), - exp.getMessage()); - } - } - - public void testName() { - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect preferred name", "arg", arg.getPreferredName()); - } - - public void testNullName() { - try { - this.argumentBuilder.withName(null); - fail("cannot use null name"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME), - exp.getMessage()); - } - } - - public void testEmptyName() { - try { - this.argumentBuilder.withName(""); - fail("cannot use empty name"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME), - exp.getMessage()); - } - } - - public void testSubsequentSeparator() { - this.argumentBuilder.withSubsequentSeparator(':'); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect subsequent separator", ':', arg.getSubsequentSeparator()); - } - - public void testValidator() { - Validator validator = DateValidator.getDateInstance(); - this.argumentBuilder.withValidator(validator); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect validator", validator, arg.getValidator()); - } - - public void testNullValidator() { - try { - this.argumentBuilder.withValidator(null); - fail("cannot use null validator"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR), - exp.getMessage()); - } - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.commons.cli2.builder;import java.util.ArrayList;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.option.ArgumentImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;import org.apache.commons.cli2.validation.DateValidator;import org.apache.commons.cli2.validation.Validator;public class ArgumentBuilderTest extends TestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); private ArgumentBuilder argumentBuilder; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { this.argumentBuilder = new ArgumentBuilder(); } public void testConsumeRemaining() { this.argumentBuilder.withConsumeRemaining("--"); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect consume remaining token", "--", arg.getConsumeRemaining()); } public void testNullConsumeRemaining() { try { this.argumentBuilder.withConsumeRemaining(null); fail("cannot use null consume remaining token"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING), exp.getMessage()); } } public void testEmptyConsumeRemaining() { try { this.argumentBuilder.withConsumeRemaining(""); fail("cannot use empty string consume remaining token"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING), exp.getMessage()); } } public void testDefault() { this.argumentBuilder.withDefault("defaultString"); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect number of default values", 1, arg.getDefaultValues().size()); assertEquals("incorrect default value", "defaultString", arg.getDefaultValues().get(0)); } public void testDefaultX2() { this.argumentBuilder.withDefault("defaultString1"); this.argumentBuilder.withDefault("defaultString2"); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); assertEquals("incorrect default value-1", "defaultString1", arg.getDefaultValues().get(0)); assertEquals("incorrect default value-2", "defaultString2", arg.getDefaultValues().get(1)); } public void testNullDefault() { try { this.argumentBuilder.withDefault(null); fail("cannot use null default"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT), exp.getMessage()); } } public void testDefaults() { final List defaults = new ArrayList(); defaults.add("one"); defaults.add("two"); this.argumentBuilder.withDefaults(defaults); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); assertEquals("incorrect default value-1", "one", arg.getDefaultValues().get(0)); assertEquals("incorrect default value-2", "two", arg.getDefaultValues().get(1)); assertEquals("incorrect default values list", defaults, arg.getDefaultValues()); } public void testNullDefaults() { try { this.argumentBuilder.withDefaults(null); fail("cannot use null defaults"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS), exp.getMessage()); } } public void testId() { this.argumentBuilder.withId(1); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect id", 1, arg.getId()); } public void testInitialSeparator() { this.argumentBuilder.withInitialSeparator(','); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect initial separator", ',', arg.getInitialSeparator()); } public void testMaximum() { this.argumentBuilder.withMaximum(1); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect maximum", 1, arg.getMaximum()); } public void testNegativeMaximum() { try { this.argumentBuilder.withMaximum(-1); fail("cannot use negative maximum"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM), exp.getMessage()); } } public void testMinimum() { this.argumentBuilder.withMinimum(1); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect maximum", 1, arg.getMinimum()); } public void testNegativeMinimum() { try { this.argumentBuilder.withMinimum(-1); fail("cannot use negative minimum"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM), exp.getMessage()); } } public void testName() { this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect preferred name", "arg", arg.getPreferredName()); } public void testNullName() { try { this.argumentBuilder.withName(null); fail("cannot use null name"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME), exp.getMessage()); } } public void testEmptyName() { try { this.argumentBuilder.withName(""); fail("cannot use empty name"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME), exp.getMessage()); } } public void testSubsequentSeparator() { this.argumentBuilder.withSubsequentSeparator(':'); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect subsequent separator", ':', arg.getSubsequentSeparator()); } public void testValidator() { Validator validator = DateValidator.getDateInstance(); this.argumentBuilder.withValidator(validator); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect validator", validator, arg.getValidator()); } public void testNullValidator() { try { this.argumentBuilder.withValidator(null); fail("cannot use null validator"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR), exp.getMessage()); } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/builder/DefaultOptionBuilderTest.java b/src/test/org/apache/commons/cli2/builder/DefaultOptionBuilderTest.java index 36dcd64e8..c268798eb 100644 --- a/src/test/org/apache/commons/cli2/builder/DefaultOptionBuilderTest.java +++ b/src/test/org/apache/commons/cli2/builder/DefaultOptionBuilderTest.java @@ -1,200 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.builder; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.option.DefaultOption; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -public class DefaultOptionBuilderTest - extends TestCase { - private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); - private DefaultOptionBuilder defaultOptionBuilder; - - /* - * @see TestCase#setUp() - */ - protected void setUp() - throws Exception { - this.defaultOptionBuilder = new DefaultOptionBuilder(); - } - - /* - * Class to test for void DefaultOptionBuilder(String, String, boolean) - */ - public void testNew_NullShortPrefix() { - try { - new DefaultOptionBuilder(null, null, false); - fail("null short prefix is not permitted"); - } catch (IllegalArgumentException e) { - assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX), - e.getMessage()); - } - } - - /* - * Class to test for void DefaultOptionBuilder(String, String, boolean) - */ - public void testNew_EmptyShortPrefix() { - try { - new DefaultOptionBuilder("", null, false); - fail("empty short prefix is not permitted"); - } catch (IllegalArgumentException e) { - assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX), - e.getMessage()); - } - } - - /* - * Class to test for void DefaultOptionBuilder(String, String, boolean) - */ - public void testNew_NullLongPrefix() { - try { - new DefaultOptionBuilder("-", null, false); - fail("null long prefix is not permitted"); - } catch (IllegalArgumentException e) { - assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX), - e.getMessage()); - } - } - - /* - * Class to test for void DefaultOptionBuilder(String, String, boolean) - */ - public void testNew_EmptyLongPrefix() { - try { - new DefaultOptionBuilder("-", "", false); - fail("empty long prefix is not permitted"); - } catch (IllegalArgumentException e) { - assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX), - e.getMessage()); - } - } - - public void testCreate() { - try { - this.defaultOptionBuilder.create(); - fail("options must have a name"); - } catch (IllegalStateException e) { - assertEquals(resources.getMessage(ResourceConstants.OPTION_NO_NAME), e.getMessage()); - } - - this.defaultOptionBuilder.withShortName("j"); - this.defaultOptionBuilder.create(); - this.defaultOptionBuilder.withLongName("jkeyes"); - this.defaultOptionBuilder.create(); - - { - DefaultOptionBuilder builder = new DefaultOptionBuilder("-", "--", true); - builder.withShortName("mx"); - } - } - - public void testName() { - // withLongName && this.preferred != null - { - this.defaultOptionBuilder.withShortName("a"); - this.defaultOptionBuilder.withLongName("apples"); - } - // withShortName && this.preferred != null - { - this.defaultOptionBuilder.withLongName("apples"); - this.defaultOptionBuilder.withShortName("a"); - } - // withShortName && this.preferred != null - { - this.defaultOptionBuilder.withLongName("apples"); - this.defaultOptionBuilder.withShortName("a"); - } - } - - public void testWithDescription() { - String description = "desc"; - this.defaultOptionBuilder.withShortName("a"); - this.defaultOptionBuilder.withDescription(description); - - DefaultOption opt = this.defaultOptionBuilder.create(); - assertEquals("wrong description found", description, opt.getDescription()); - } - - public void testWithRequired() { - { - boolean required = false; - this.defaultOptionBuilder.withShortName("a"); - this.defaultOptionBuilder.withRequired(required); - - DefaultOption opt = this.defaultOptionBuilder.create(); - assertEquals("wrong required found", required, opt.isRequired()); - } - - { - boolean required = true; - this.defaultOptionBuilder.withShortName("a"); - this.defaultOptionBuilder.withRequired(required); - - DefaultOption opt = this.defaultOptionBuilder.create(); - assertEquals("wrong required found", required, opt.isRequired()); - } - } - - public void testWithChildren() { - GroupBuilder gbuilder = new GroupBuilder(); - - this.defaultOptionBuilder.withShortName("a"); - this.defaultOptionBuilder.withRequired(true); - - DefaultOption opt = this.defaultOptionBuilder.create(); - - Group group = gbuilder.withName("withchildren").withOption(opt).create(); - - { - this.defaultOptionBuilder.withShortName("b"); - this.defaultOptionBuilder.withChildren(group); - - DefaultOption option = this.defaultOptionBuilder.create(); - assertEquals("wrong children found", group, option.getChildren()); - } - } - - public void testWithArgument() { - ArgumentBuilder abuilder = new ArgumentBuilder(); - abuilder.withName("myarg"); - - Argument arg = abuilder.create(); - - this.defaultOptionBuilder.withShortName("a"); - this.defaultOptionBuilder.withRequired(true); - this.defaultOptionBuilder.withArgument(arg); - - DefaultOption opt = this.defaultOptionBuilder.create(); - - assertEquals("wrong argument found", arg, opt.getArgument()); - } - - public void testWithId() { - this.defaultOptionBuilder.withShortName("a"); - this.defaultOptionBuilder.withId(0); - - DefaultOption opt = this.defaultOptionBuilder.create(); - - assertEquals("wrong id found", 0, opt.getId()); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import junit.framework.TestCase;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.option.DefaultOption;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;public class DefaultOptionBuilderTest extends TestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); private DefaultOptionBuilder defaultOptionBuilder; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { this.defaultOptionBuilder = new DefaultOptionBuilder(); } /* * Class to test for void DefaultOptionBuilder(String, String, boolean) */ public void testNew_NullShortPrefix() { try { new DefaultOptionBuilder(null, null, false); fail("null short prefix is not permitted"); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX), e.getMessage()); } } /* * Class to test for void DefaultOptionBuilder(String, String, boolean) */ public void testNew_EmptyShortPrefix() { try { new DefaultOptionBuilder("", null, false); fail("empty short prefix is not permitted"); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX), e.getMessage()); } } /* * Class to test for void DefaultOptionBuilder(String, String, boolean) */ public void testNew_NullLongPrefix() { try { new DefaultOptionBuilder("-", null, false); fail("null long prefix is not permitted"); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX), e.getMessage()); } } /* * Class to test for void DefaultOptionBuilder(String, String, boolean) */ public void testNew_EmptyLongPrefix() { try { new DefaultOptionBuilder("-", "", false); fail("empty long prefix is not permitted"); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX), e.getMessage()); } } public void testCreate() { try { this.defaultOptionBuilder.create(); fail("options must have a name"); } catch (IllegalStateException e) { assertEquals(resources.getMessage(ResourceConstants.OPTION_NO_NAME), e.getMessage()); } this.defaultOptionBuilder.withShortName("j"); this.defaultOptionBuilder.create(); this.defaultOptionBuilder.withLongName("jkeyes"); this.defaultOptionBuilder.create(); { DefaultOptionBuilder builder = new DefaultOptionBuilder("-", "--", true); builder.withShortName("mx"); } } public void testName() { // withLongName && this.preferred != null { this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withLongName("apples"); } // withShortName && this.preferred != null { this.defaultOptionBuilder.withLongName("apples"); this.defaultOptionBuilder.withShortName("a"); } // withShortName && this.preferred != null { this.defaultOptionBuilder.withLongName("apples"); this.defaultOptionBuilder.withShortName("a"); } } public void testWithDescription() { String description = "desc"; this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withDescription(description); DefaultOption opt = this.defaultOptionBuilder.create(); assertEquals("wrong description found", description, opt.getDescription()); } public void testWithRequired() { { boolean required = false; this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withRequired(required); DefaultOption opt = this.defaultOptionBuilder.create(); assertEquals("wrong required found", required, opt.isRequired()); } { boolean required = true; this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withRequired(required); DefaultOption opt = this.defaultOptionBuilder.create(); assertEquals("wrong required found", required, opt.isRequired()); } } public void testWithChildren() { GroupBuilder gbuilder = new GroupBuilder(); this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withRequired(true); DefaultOption opt = this.defaultOptionBuilder.create(); Group group = gbuilder.withName("withchildren").withOption(opt).create(); { this.defaultOptionBuilder.withShortName("b"); this.defaultOptionBuilder.withChildren(group); DefaultOption option = this.defaultOptionBuilder.create(); assertEquals("wrong children found", group, option.getChildren()); } } public void testWithArgument() { ArgumentBuilder abuilder = new ArgumentBuilder(); abuilder.withName("myarg"); Argument arg = abuilder.create(); this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withRequired(true); this.defaultOptionBuilder.withArgument(arg); DefaultOption opt = this.defaultOptionBuilder.create(); assertEquals("wrong argument found", arg, opt.getArgument()); } public void testWithId() { this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withId(0); DefaultOption opt = this.defaultOptionBuilder.create(); assertEquals("wrong id found", 0, opt.getId()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java b/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java index 97be1fc96..4c4c64e53 100644 --- a/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java +++ b/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java @@ -1,151 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.Set; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.CommandLineTestCase; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; - -/** - * @author Rob Oxspring - */ -public class DefaultingCommandLineTest - extends CommandLineTestCase { - private CommandLine first; - private CommandLine second; - private Option inFirst = new DefaultOptionBuilder().withLongName("infirst").create(); - private Option inBoth = new DefaultOptionBuilder().withLongName("inboth").create(); - private Option inSecond = new DefaultOptionBuilder().withLongName("insecond").create(); - - /* (non-Javadoc) - * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() - */ - protected final CommandLine createCommandLine() { - final WriteableCommandLine writeable = new WriteableCommandLineImpl(root, new ArrayList()); - writeable.addOption(present); - writeable.addProperty("present", "present property"); - writeable.addSwitch(bool, true); - writeable.addValue(present, "present value"); - writeable.addOption(multiple); - writeable.addValue(multiple, "value 1"); - writeable.addValue(multiple, "value 2"); - writeable.addValue(multiple, "value 3"); - - final DefaultingCommandLine defaults = new DefaultingCommandLine(); - defaults.appendCommandLine(writeable); - - return defaults; - } - - public void setUp() - throws Exception { - super.setUp(); - - WriteableCommandLine writeable; - - writeable = new WriteableCommandLineImpl(root, new ArrayList()); - writeable.addOption(inFirst); - writeable.addOption(inBoth); - writeable.addProperty("infirst", "infirst first value"); - writeable.addProperty("inboth", "inboth first value"); - writeable.addSwitch(inFirst, true); - writeable.addSwitch(inBoth, true); - writeable.addValue(inFirst, "infirst first value 1"); - writeable.addValue(inFirst, "infirst first value 2"); - writeable.addValue(inBoth, "inboth first value 1"); - writeable.addValue(inBoth, "inboth first value 2"); - first = writeable; - - writeable = new WriteableCommandLineImpl(root, new ArrayList()); - writeable.addOption(inSecond); - writeable.addOption(inBoth); - writeable.addProperty("insecond", "insecond second value"); - writeable.addProperty("inboth", "inboth second value"); - writeable.addSwitch(inSecond, true); - writeable.addSwitch(inBoth, true); - writeable.addValue(inSecond, "insecond second value 1"); - writeable.addValue(inSecond, "insecond second value 2"); - writeable.addValue(inBoth, "inboth second value 1"); - writeable.addValue(inBoth, "inboth second value 2"); - second = writeable; - } - - public final void testAppendCommandLine() { - final DefaultingCommandLine defaults = new DefaultingCommandLine(); - Iterator i; - - i = defaults.commandLines(); - assertFalse(i.hasNext()); - - defaults.appendCommandLine(first); - i = defaults.commandLines(); - assertSame(first, i.next()); - assertFalse(i.hasNext()); - - defaults.appendCommandLine(second); - i = defaults.commandLines(); - assertSame(first, i.next()); - assertSame(second, i.next()); - assertFalse(i.hasNext()); - } - - public final void testInsertCommandLine() { - final DefaultingCommandLine defaults = new DefaultingCommandLine(); - Iterator i; - - i = defaults.commandLines(); - assertFalse(i.hasNext()); - - defaults.insertCommandLine(0, first); - i = defaults.commandLines(); - assertSame(first, i.next()); - assertFalse(i.hasNext()); - - defaults.insertCommandLine(0, second); - i = defaults.commandLines(); - assertSame(second, i.next()); - assertSame(first, i.next()); - assertFalse(i.hasNext()); - } - - public void testTriggers() { - final DefaultingCommandLine defaults = new DefaultingCommandLine(); - defaults.appendCommandLine(first); - defaults.appendCommandLine(second); - - Set set = defaults.getOptionTriggers(); - Iterator iter = set.iterator(); - assertEquals("wrong # of triggers", 3, set.size()); - assertTrue("cannot find trigger", set.contains("--insecond")); - assertTrue("cannot find trigger", set.contains("--inboth")); - assertTrue("cannot find trigger", set.contains("--infirst")); - } - - public void testDefaults() { - final DefaultingCommandLine defaults = new DefaultingCommandLine(); - - assertEquals("wrong # of defaults", 0, defaults.getValues("--insecond").size()); - assertEquals("wrong Set of defaults", Collections.EMPTY_LIST, defaults.getValues("--insecond", null)); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import java.util.Collections;import java.util.Iterator;import java.util.Set;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.CommandLineTestCase;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.builder.DefaultOptionBuilder;/** * @author Rob Oxspring */public class DefaultingCommandLineTest extends CommandLineTestCase { private CommandLine first; private CommandLine second; private Option inFirst = new DefaultOptionBuilder().withLongName("infirst").create(); private Option inBoth = new DefaultOptionBuilder().withLongName("inboth").create(); private Option inSecond = new DefaultOptionBuilder().withLongName("insecond").create(); /* (non-Javadoc) * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() */ protected final CommandLine createCommandLine() { final WriteableCommandLine writeable = new WriteableCommandLineImpl(root, new ArrayList()); writeable.addOption(present); writeable.addProperty("present", "present property"); writeable.addSwitch(bool, true); writeable.addValue(present, "present value"); writeable.addOption(multiple); writeable.addValue(multiple, "value 1"); writeable.addValue(multiple, "value 2"); writeable.addValue(multiple, "value 3"); final DefaultingCommandLine defaults = new DefaultingCommandLine(); defaults.appendCommandLine(writeable); return defaults; } public void setUp() throws Exception { super.setUp(); WriteableCommandLine writeable; writeable = new WriteableCommandLineImpl(root, new ArrayList()); writeable.addOption(inFirst); writeable.addOption(inBoth); writeable.addProperty("infirst", "infirst first value"); writeable.addProperty("inboth", "inboth first value"); writeable.addSwitch(inFirst, true); writeable.addSwitch(inBoth, true); writeable.addValue(inFirst, "infirst first value 1"); writeable.addValue(inFirst, "infirst first value 2"); writeable.addValue(inBoth, "inboth first value 1"); writeable.addValue(inBoth, "inboth first value 2"); first = writeable; writeable = new WriteableCommandLineImpl(root, new ArrayList()); writeable.addOption(inSecond); writeable.addOption(inBoth); writeable.addProperty("insecond", "insecond second value"); writeable.addProperty("inboth", "inboth second value"); writeable.addSwitch(inSecond, true); writeable.addSwitch(inBoth, true); writeable.addValue(inSecond, "insecond second value 1"); writeable.addValue(inSecond, "insecond second value 2"); writeable.addValue(inBoth, "inboth second value 1"); writeable.addValue(inBoth, "inboth second value 2"); second = writeable; } public final void testAppendCommandLine() { final DefaultingCommandLine defaults = new DefaultingCommandLine(); Iterator i; i = defaults.commandLines(); assertFalse(i.hasNext()); defaults.appendCommandLine(first); i = defaults.commandLines(); assertSame(first, i.next()); assertFalse(i.hasNext()); defaults.appendCommandLine(second); i = defaults.commandLines(); assertSame(first, i.next()); assertSame(second, i.next()); assertFalse(i.hasNext()); } public final void testInsertCommandLine() { final DefaultingCommandLine defaults = new DefaultingCommandLine(); Iterator i; i = defaults.commandLines(); assertFalse(i.hasNext()); defaults.insertCommandLine(0, first); i = defaults.commandLines(); assertSame(first, i.next()); assertFalse(i.hasNext()); defaults.insertCommandLine(0, second); i = defaults.commandLines(); assertSame(second, i.next()); assertSame(first, i.next()); assertFalse(i.hasNext()); } public void testTriggers() { final DefaultingCommandLine defaults = new DefaultingCommandLine(); defaults.appendCommandLine(first); defaults.appendCommandLine(second); Set set = defaults.getOptionTriggers(); Iterator iter = set.iterator(); assertEquals("wrong # of triggers", 3, set.size()); assertTrue("cannot find trigger", set.contains("--insecond")); assertTrue("cannot find trigger", set.contains("--inboth")); assertTrue("cannot find trigger", set.contains("--infirst")); } public void testDefaults() { final DefaultingCommandLine defaults = new DefaultingCommandLine(); assertEquals("wrong # of defaults", 0, defaults.getValues("--insecond").size()); assertEquals("wrong Set of defaults", Collections.EMPTY_LIST, defaults.getValues("--insecond", null)); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/commandline/ParserTest.java b/src/test/org/apache/commons/cli2/commandline/ParserTest.java index 0077f5df3..3145f5a0e 100644 --- a/src/test/org/apache/commons/cli2/commandline/ParserTest.java +++ b/src/test/org/apache/commons/cli2/commandline/ParserTest.java @@ -1,140 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; -import java.io.StringWriter; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.option.DefaultOption; -import org.apache.commons.cli2.util.HelpFormatter; - -import junit.framework.TestCase; - -public class ParserTest extends TestCase { - - private Parser parser; - private DefaultOption verboseOption; - private DefaultOption helpOption; - private Group options; - private HelpFormatter helpFormatter; - private StringWriter out; - private BufferedReader in; - - public void setUp() { - parser = new Parser(); - - final GroupBuilder gBuilder = new GroupBuilder(); - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - - helpOption = oBuilder.withLongName("help").withShortName("h").create(); - verboseOption = oBuilder.withLongName("verbose").withShortName("v").create(); - options = gBuilder.withOption(helpOption).withOption(verboseOption).create(); - parser.setGroup(options); - - helpFormatter = new HelpFormatter(); - out = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(out)); - parser.setHelpFormatter(helpFormatter); - } - - public void testParse_Successful() throws OptionException { - final CommandLine cl = parser.parse(new String[]{"-hv"}); - - assertTrue(cl.hasOption(helpOption)); - assertTrue(cl.hasOption(verboseOption)); - - assertEquals("--help --verbose",cl.toString()); - - final WriteableCommandLineImpl wcli = (WriteableCommandLineImpl)cl; - assertEquals("[--help, --verbose]",wcli.getNormalised().toString()); - } - - public void testParse_WithUnexpectedOption() { - try { - parser.parse(new String[]{"--unexpected"}); - fail("OptionException"); - } - catch(OptionException e) { - assertEquals(options,e.getOption()); - assertEquals("Unexpected --unexpected while processing --help|--verbose",e.getMessage()); - } - } - - public void testParseAndHelp_Successful() throws IOException { - final CommandLine cl = parser.parseAndHelp(new String[]{"-v"}); - - assertTrue(cl.hasOption(verboseOption)); - assertEquals("",out.getBuffer().toString()); - } - - public void testParseAndHelp_ByHelpOption() throws IOException { - parser.setHelpOption(helpOption); - - assertNull(parser.parseAndHelp(new String[]{"-hv"})); - - inReader(); - assertInReaderUsage(); - assertInReaderEOF(); - } - - public void testParseAndHelp_ByHelpTrigger() throws IOException { - parser.setHelpTrigger("--help"); - - assertNull(parser.parseAndHelp(new String[]{"-hv"})); - - inReader(); - assertInReaderUsage(); - assertInReaderEOF(); - } - - public void testParseAndHelp_WithUnexpectedOption() throws IOException { - assertNull(parser.parseAndHelp(new String[]{"--unexpected"})); - - inReader(); - assertInReaderLine("Unexpected --unexpected while processing --help|--verbose"); - assertInReaderUsage(); - assertInReaderEOF(); - } - - private void assertInReaderUsage() throws IOException { - assertInReaderLine("Usage:"); - assertInReaderLine("[--help --verbose]"); - assertInReaderLine("--help|--verbose"); - assertInReaderLine("--help (-h)"); - assertInReaderLine("--verbose (-v)"); - } - - private void assertInReaderLine(final String string) throws IOException { - assertEquals(string,in.readLine().trim()); - } - - private void assertInReaderEOF() throws IOException { - assertNull(in.readLine()); - } - - private void inReader() { - in = new BufferedReader(new StringReader(out.getBuffer().toString())); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.io.BufferedReader;import java.io.IOException;import java.io.PrintWriter;import java.io.StringReader;import java.io.StringWriter;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.option.DefaultOption;import org.apache.commons.cli2.util.HelpFormatter;import junit.framework.TestCase;public class ParserTest extends TestCase { private Parser parser; private DefaultOption verboseOption; private DefaultOption helpOption; private Group options; private HelpFormatter helpFormatter; private StringWriter out; private BufferedReader in; public void setUp() { parser = new Parser(); final GroupBuilder gBuilder = new GroupBuilder(); final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); helpOption = oBuilder.withLongName("help").withShortName("h").create(); verboseOption = oBuilder.withLongName("verbose").withShortName("v").create(); options = gBuilder.withOption(helpOption).withOption(verboseOption).create(); parser.setGroup(options); helpFormatter = new HelpFormatter(); out = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(out)); parser.setHelpFormatter(helpFormatter); } public void testParse_Successful() throws OptionException { final CommandLine cl = parser.parse(new String[]{"-hv"}); assertTrue(cl.hasOption(helpOption)); assertTrue(cl.hasOption(verboseOption)); assertEquals("--help --verbose",cl.toString()); final WriteableCommandLineImpl wcli = (WriteableCommandLineImpl)cl; assertEquals("[--help, --verbose]",wcli.getNormalised().toString()); } public void testParse_WithUnexpectedOption() { try { parser.parse(new String[]{"--unexpected"}); fail("OptionException"); } catch(OptionException e) { assertEquals(options,e.getOption()); assertEquals("Unexpected --unexpected while processing --help|--verbose",e.getMessage()); } } public void testParseAndHelp_Successful() throws IOException { final CommandLine cl = parser.parseAndHelp(new String[]{"-v"}); assertTrue(cl.hasOption(verboseOption)); assertEquals("",out.getBuffer().toString()); } public void testParseAndHelp_ByHelpOption() throws IOException { parser.setHelpOption(helpOption); assertNull(parser.parseAndHelp(new String[]{"-hv"})); inReader(); assertInReaderUsage(); assertInReaderEOF(); } public void testParseAndHelp_ByHelpTrigger() throws IOException { parser.setHelpTrigger("--help"); assertNull(parser.parseAndHelp(new String[]{"-hv"})); inReader(); assertInReaderUsage(); assertInReaderEOF(); } public void testParseAndHelp_WithUnexpectedOption() throws IOException { assertNull(parser.parseAndHelp(new String[]{"--unexpected"})); inReader(); assertInReaderLine("Unexpected --unexpected while processing --help|--verbose"); assertInReaderUsage(); assertInReaderEOF(); } private void assertInReaderUsage() throws IOException { assertInReaderLine("Usage:"); assertInReaderLine("[--help --verbose]"); assertInReaderLine("--help|--verbose"); assertInReaderLine("--help (-h)"); assertInReaderLine("--verbose (-v)"); } private void assertInReaderLine(final String string) throws IOException { assertEquals(string,in.readLine().trim()); } private void assertInReaderEOF() throws IOException { assertNull(in.readLine()); } private void inReader() { in = new BufferedReader(new StringReader(out.getBuffer().toString())); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java b/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java index 1526b9230..952b137ee 100644 --- a/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java +++ b/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java @@ -1,106 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.util.Iterator; -import java.util.Set; -import java.util.prefs.Preferences; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.CommandLineTestCase; - -/** - * @author Rob Oxspring - */ -public class PreferencesCommandLineTest extends CommandLineTestCase { - - /* (non-Javadoc) - * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() - */ - protected CommandLine createCommandLine() { - // TODO Auto-generated method stub - final Preferences props = Preferences.userNodeForPackage(PreferencesCommandLineTest.class); - props.put("--present","present value"); - props.put("--alsopresent",""); - props.put("--multiple","value 1|value 2|value 3"); - props.put("--bool","true"); - - props.put("present","present property"); - - return new PreferencesCommandLine(root,props,'|'); - } - - protected CommandLine createCommandLineNoSep() { - // TODO Auto-generated method stub - final Preferences props = Preferences.userNodeForPackage(PreferencesCommandLineTest.class); - props.put("--present","present value"); - props.put("--alsopresent",""); - props.put("--multiple","value 1|value 2|value 3"); - props.put("--bool","false"); - - props.put("present","present property"); - - return new PreferencesCommandLine(root,props); - } - - public void testPropertyValues() { - // nothing to test - CommandLine cmdline = createCommandLine(); - - assertEquals("wrong value", "present value", cmdline.getValue("--present")); - assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); - assertEquals("wrong # of values", 3, cmdline.getValues("--multiple").size()); - assertEquals("wrong value 1", "value 1", cmdline.getValues("--multiple").get(0)); - assertEquals("wrong value 2", "value 2", cmdline.getValues("--multiple").get(1)); - assertEquals("wrong value 3", "value 3", cmdline.getValues("--multiple").get(2)); - } - - public void testNoSeparator() { - // nothing to test - CommandLine cmdline = createCommandLineNoSep(); - - assertEquals("wrong value", "present value", cmdline.getValue("--present")); - assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); - assertEquals("wrong # of values", 1, cmdline.getValues("--multiple").size()); - assertEquals("wrong value", "value 1|value 2|value 3", cmdline.getValue("--multiple")); - assertFalse("expected a false", cmdline.getSwitch("--bool").booleanValue()); - } - - public void testNullOption() { - // nothing to test - CommandLine cmdline = createCommandLine(); - - assertFalse("should not find null option", cmdline.hasOption((String) null)); - assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); - } - - public void testPreferenceTriggers() { - // nothing to test - CommandLine cmdline = createCommandLine(); - - Set triggers = cmdline.getOptionTriggers(); - Iterator iter = triggers.iterator(); - assertEquals("wrong # of triggers", 4, triggers.size()); - assertTrue("cannot find trigger", triggers.contains("--bool")); - assertTrue("cannot find trigger", triggers.contains("--present")); - assertTrue("cannot find trigger", triggers.contains("--multiple")); - assertTrue("cannot find trigger", triggers.contains("--alsopresent")); - - assertFalse("should not find null option", cmdline.hasOption((String) null)); - assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.Iterator;import java.util.Set;import java.util.prefs.Preferences;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.CommandLineTestCase;/** * @author Rob Oxspring */public class PreferencesCommandLineTest extends CommandLineTestCase { /* (non-Javadoc) * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() */ protected CommandLine createCommandLine() { // TODO Auto-generated method stub final Preferences props = Preferences.userNodeForPackage(PreferencesCommandLineTest.class); props.put("--present","present value"); props.put("--alsopresent",""); props.put("--multiple","value 1|value 2|value 3"); props.put("--bool","true"); props.put("present","present property"); return new PreferencesCommandLine(root,props,'|'); } protected CommandLine createCommandLineNoSep() { // TODO Auto-generated method stub final Preferences props = Preferences.userNodeForPackage(PreferencesCommandLineTest.class); props.put("--present","present value"); props.put("--alsopresent",""); props.put("--multiple","value 1|value 2|value 3"); props.put("--bool","false"); props.put("present","present property"); return new PreferencesCommandLine(root,props); } public void testPropertyValues() { // nothing to test CommandLine cmdline = createCommandLine(); assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 3, cmdline.getValues("--multiple").size()); assertEquals("wrong value 1", "value 1", cmdline.getValues("--multiple").get(0)); assertEquals("wrong value 2", "value 2", cmdline.getValues("--multiple").get(1)); assertEquals("wrong value 3", "value 3", cmdline.getValues("--multiple").get(2)); } public void testNoSeparator() { // nothing to test CommandLine cmdline = createCommandLineNoSep(); assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 1, cmdline.getValues("--multiple").size()); assertEquals("wrong value", "value 1|value 2|value 3", cmdline.getValue("--multiple")); assertFalse("expected a false", cmdline.getSwitch("--bool").booleanValue()); } public void testNullOption() { // nothing to test CommandLine cmdline = createCommandLine(); assertFalse("should not find null option", cmdline.hasOption((String) null)); assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); } public void testPreferenceTriggers() { // nothing to test CommandLine cmdline = createCommandLine(); Set triggers = cmdline.getOptionTriggers(); Iterator iter = triggers.iterator(); assertEquals("wrong # of triggers", 4, triggers.size()); assertTrue("cannot find trigger", triggers.contains("--bool")); assertTrue("cannot find trigger", triggers.contains("--present")); assertTrue("cannot find trigger", triggers.contains("--multiple")); assertTrue("cannot find trigger", triggers.contains("--alsopresent")); assertFalse("should not find null option", cmdline.hasOption((String) null)); assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java b/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java index 664a2252a..aba69a1d9 100644 --- a/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java +++ b/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java @@ -1,101 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.util.Iterator; -import java.util.Properties; -import java.util.Set; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.CommandLineTestCase; - -/** - * @author Rob Oxspring - */ -public class PropertiesCommandLineTest - extends CommandLineTestCase { - private Properties props = null; - - protected CommandLine createCommandLine() { - props = new Properties(); - props.setProperty("--present", "present value"); - props.setProperty("--alsopresent", ""); - props.setProperty("--multiple", "value 1|value 2|value 3"); - props.setProperty("--bool", "true"); - - props.setProperty("present", "present property"); - return new PropertiesCommandLine(root, props, '|'); - } - - protected CommandLine createCommandLineNoSep() { - props = new Properties(); - props.setProperty("--present", "present value"); - props.setProperty("--alsopresent", ""); - props.setProperty("--multiple", "value 1|value 2|value 3"); - props.setProperty("--bool", "false"); - - props.setProperty("present", "present property"); - return new PropertiesCommandLine(root, props); - } - - public void testPropertyValues() { - // nothing to test - CommandLine cmdline = createCommandLine(); - - assertEquals("wrong value", "present value", cmdline.getValue("--present")); - assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); - assertEquals("wrong # of values", 3, cmdline.getValues("--multiple").size()); - assertEquals("wrong value 1", "value 1", cmdline.getValues("--multiple").get(0)); - assertEquals("wrong value 2", "value 2", cmdline.getValues("--multiple").get(1)); - assertEquals("wrong value 3", "value 3", cmdline.getValues("--multiple").get(2)); - } - - public void testNoSeparator() { - // nothing to test - CommandLine cmdline = createCommandLineNoSep(); - - assertEquals("wrong value", "present value", cmdline.getValue("--present")); - assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); - assertEquals("wrong # of values", 1, cmdline.getValues("--multiple").size()); - assertEquals("wrong value", "value 1|value 2|value 3", cmdline.getValue("--multiple")); - assertFalse("expected a false", cmdline.getSwitch("--bool").booleanValue()); - } - - public void testNullOption() { - // nothing to test - CommandLine cmdline = createCommandLine(); - - assertFalse("should not find null option", cmdline.hasOption((String) null)); - assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); - } - - public void testPropertyTriggers() { - // nothing to test - CommandLine cmdline = createCommandLine(); - - Set triggers = cmdline.getOptionTriggers(); - Iterator iter = triggers.iterator(); - assertEquals("wrong # of triggers", 4, triggers.size()); - assertTrue("cannot find trigger", triggers.contains("--bool")); - assertTrue("cannot find trigger", triggers.contains("--present")); - assertTrue("cannot find trigger", triggers.contains("--multiple")); - assertTrue("cannot find trigger", triggers.contains("--alsopresent")); - - assertFalse("should not find null option", cmdline.hasOption((String) null)); - assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.Iterator;import java.util.Properties;import java.util.Set;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.CommandLineTestCase;/** * @author Rob Oxspring */public class PropertiesCommandLineTest extends CommandLineTestCase { private Properties props = null; protected CommandLine createCommandLine() { props = new Properties(); props.setProperty("--present", "present value"); props.setProperty("--alsopresent", ""); props.setProperty("--multiple", "value 1|value 2|value 3"); props.setProperty("--bool", "true"); props.setProperty("present", "present property"); return new PropertiesCommandLine(root, props, '|'); } protected CommandLine createCommandLineNoSep() { props = new Properties(); props.setProperty("--present", "present value"); props.setProperty("--alsopresent", ""); props.setProperty("--multiple", "value 1|value 2|value 3"); props.setProperty("--bool", "false"); props.setProperty("present", "present property"); return new PropertiesCommandLine(root, props); } public void testPropertyValues() { // nothing to test CommandLine cmdline = createCommandLine(); assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 3, cmdline.getValues("--multiple").size()); assertEquals("wrong value 1", "value 1", cmdline.getValues("--multiple").get(0)); assertEquals("wrong value 2", "value 2", cmdline.getValues("--multiple").get(1)); assertEquals("wrong value 3", "value 3", cmdline.getValues("--multiple").get(2)); } public void testNoSeparator() { // nothing to test CommandLine cmdline = createCommandLineNoSep(); assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 1, cmdline.getValues("--multiple").size()); assertEquals("wrong value", "value 1|value 2|value 3", cmdline.getValue("--multiple")); assertFalse("expected a false", cmdline.getSwitch("--bool").booleanValue()); } public void testNullOption() { // nothing to test CommandLine cmdline = createCommandLine(); assertFalse("should not find null option", cmdline.hasOption((String) null)); assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); } public void testPropertyTriggers() { // nothing to test CommandLine cmdline = createCommandLine(); Set triggers = cmdline.getOptionTriggers(); Iterator iter = triggers.iterator(); assertEquals("wrong # of triggers", 4, triggers.size()); assertTrue("cannot find trigger", triggers.contains("--bool")); assertTrue("cannot find trigger", triggers.contains("--present")); assertTrue("cannot find trigger", triggers.contains("--multiple")); assertTrue("cannot find trigger", triggers.contains("--alsopresent")); assertFalse("should not find null option", cmdline.hasOption((String) null)); assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/commandline/WriteableCommandLineImplTest.java b/src/test/org/apache/commons/cli2/commandline/WriteableCommandLineImplTest.java index 73697fad6..afcaa64a2 100644 --- a/src/test/org/apache/commons/cli2/commandline/WriteableCommandLineImplTest.java +++ b/src/test/org/apache/commons/cli2/commandline/WriteableCommandLineImplTest.java @@ -1,36 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.util.ArrayList; - -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.WriteableCommandLineTestCase; - -public class WriteableCommandLineImplTest - extends WriteableCommandLineTestCase { - /* (non-Javadoc) - * @see org.apache.commons.cli2.WriteableCommandLineTest#createWriteableCommandLine() - */ - protected WriteableCommandLine createWriteableCommandLine() { - return new WriteableCommandLineImpl(root, new ArrayList()); - } - - public void testToMakeEclipseSpotTheTestCase() { - // nothing to test - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.WriteableCommandLineTestCase;public class WriteableCommandLineImplTest extends WriteableCommandLineTestCase { /* (non-Javadoc) * @see org.apache.commons.cli2.WriteableCommandLineTest#createWriteableCommandLine() */ protected WriteableCommandLine createWriteableCommandLine() { return new WriteableCommandLineImpl(root, new ArrayList()); } public void testToMakeEclipseSpotTheTestCase() { // nothing to test }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/jdepend/JDependTest.java b/src/test/org/apache/commons/cli2/jdepend/JDependTest.java index 45e5612b5..4451893dd 100644 --- a/src/test/org/apache/commons/cli2/jdepend/JDependTest.java +++ b/src/test/org/apache/commons/cli2/jdepend/JDependTest.java @@ -1,109 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.jdepend; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -import jdepend.framework.JDepend; -import jdepend.framework.JavaPackage; -import junit.framework.TestCase; - -/** - * @author Rob Oxspring - */ -public class JDependTest extends TestCase { - - private JDepend dependancies = null; - - public void setUp() throws IOException { - dependancies = new JDepend(); - dependancies.addDirectory("target/classes"); - dependancies.analyze(); - } - - public void testJUnitNotPresent() { - // if junit dependancy is found then jdepend has been poluted - // with test classes and all tests are meaningless - assertNull( - "JUnit dependancy found", - dependancies.getPackage("junit.framework")); - - // the same applies to jdepend - assertNull( - "JDepend dependancy found", - dependancies.getPackage("jdepend.framework")); - } - - public void testAcceptableDistance() { - Collection packages = dependancies.getPackages(); - // only interested in cli2 - packages = cli2Packages(packages); - // resources is well off the line - packages = - namedPackages(packages, "org.apache.commons.cli2.resource", false); - - for (final Iterator i = packages.iterator(); i.hasNext();) { - final JavaPackage pkg = (JavaPackage)i.next(); - final float distance = pkg.distance(); - final String message = pkg.getName() + " too far from line: " + distance; - assertTrue( - message, - distance < 0.21d); - } - } - - public void testNoCyclesPresent() { - assertEquals("Cycles exist", false, dependancies.containsCycles()); - } - - public void testApiIndependance() { - dependancies.analyze(); - - final JavaPackage apiPackage = - dependancies.getPackage("org.apache.commons.cli2"); - final Collection dependsUpon = cli2Packages(apiPackage.getEfferents()); - - assertEquals("Api should depend on one package", 1, dependsUpon.size()); - - JavaPackage pkg = (JavaPackage) dependsUpon.iterator().next(); - assertEquals( - "Wrong package name", - "org.apache.commons.cli2.resource", - pkg.getName()); - } - - private Collection cli2Packages(final Collection incoming) { - return namedPackages(incoming, "org.apache.commons.cli2", true); - } - - private Collection namedPackages( - final Collection incoming, - final String name, - final boolean include) { - final Collection outgoing = new ArrayList(); - for (final Iterator i = incoming.iterator(); i.hasNext();) { - final JavaPackage pkg = (JavaPackage)i.next(); - if (include ^ !pkg.getName().startsWith(name)) { - outgoing.add(pkg); - } - } - return outgoing; - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.jdepend;import java.io.IOException;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;import jdepend.framework.JDepend;import jdepend.framework.JavaPackage;import junit.framework.TestCase;/** * @author Rob Oxspring */public class JDependTest extends TestCase { private JDepend dependancies = null; public void setUp() throws IOException { dependancies = new JDepend(); dependancies.addDirectory("target/classes"); dependancies.analyze(); } public void testJUnitNotPresent() { // if junit dependancy is found then jdepend has been poluted // with test classes and all tests are meaningless assertNull( "JUnit dependancy found", dependancies.getPackage("junit.framework")); // the same applies to jdepend assertNull( "JDepend dependancy found", dependancies.getPackage("jdepend.framework")); } public void testAcceptableDistance() { Collection packages = dependancies.getPackages(); // only interested in cli2 packages = cli2Packages(packages); // resources is well off the line packages = namedPackages(packages, "org.apache.commons.cli2.resource", false); for (final Iterator i = packages.iterator(); i.hasNext();) { final JavaPackage pkg = (JavaPackage)i.next(); final float distance = pkg.distance(); final String message = pkg.getName() + " too far from line: " + distance; assertTrue( message, distance < 0.21d); } } public void testNoCyclesPresent() { assertEquals("Cycles exist", false, dependancies.containsCycles()); } public void testApiIndependance() { dependancies.analyze(); final JavaPackage apiPackage = dependancies.getPackage("org.apache.commons.cli2"); final Collection dependsUpon = cli2Packages(apiPackage.getEfferents()); assertEquals("Api should depend on one package", 1, dependsUpon.size()); JavaPackage pkg = (JavaPackage) dependsUpon.iterator().next(); assertEquals( "Wrong package name", "org.apache.commons.cli2.resource", pkg.getName()); } private Collection cli2Packages(final Collection incoming) { return namedPackages(incoming, "org.apache.commons.cli2", true); } private Collection namedPackages( final Collection incoming, final String name, final boolean include) { final Collection outgoing = new ArrayList(); for (final Iterator i = incoming.iterator(); i.hasNext();) { final JavaPackage pkg = (JavaPackage)i.next(); if (include ^ !pkg.getName().startsWith(name)) { outgoing.add(pkg); } } return outgoing; }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/ArgumentTest.java b/src/test/org/apache/commons/cli2/option/ArgumentTest.java index 4b6f92c0a..3e607482b 100644 --- a/src/test/org/apache/commons/cli2/option/ArgumentTest.java +++ b/src/test/org/apache/commons/cli2/option/ArgumentTest.java @@ -1,646 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.text.ParseException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.HelpLine; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; -import org.apache.commons.cli2.validation.DateValidator; -import org.apache.commons.cli2.validation.DateValidatorTest; - -/** - * @author Rob Oxspring - */ -public class ArgumentTest - extends ArgumentTestCase { - private ResourceHelper resources = ResourceHelper.getResourceHelper(); - - public static Argument buildUsernameArgument() { - return new ArgumentImpl("username", "The user to connect as", 1, 1, '\0', '\0', null, - ArgumentImpl.DEFAULT_CONSUME_REMAINING, null, 0); - } - - public static Argument buildHostArgument() { - return new ArgumentImpl("host", "The host name", 2, 3, '\0', ',', null, null, null, 0); - } - - public static Argument buildPathArgument() { - return new ArgumentImpl("path", "The place to look for files", 1, Integer.MAX_VALUE, '=', - ';', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, null, 0); - } - - public static Argument buildDateLimitArgument() { - return new ArgumentImpl("limit", "the last acceptable date", 0, 1, '=', '\0', - new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); - } - - public static Argument buildTargetsArgument() { - return new ArgumentImpl("target", "The targets ant should build", 0, Integer.MAX_VALUE, - '\0', ',', null, null, null, 0); - } - - public static Argument buildSizeArgument() { - List defaults = new ArrayList(); - defaults.add("10"); - - return new ArgumentImpl("size", "The number of units", 1, 1, '\0', '\0', null, - ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); - } - - public static Argument buildBoundsArgument() { - List defaults = new ArrayList(); - defaults.add("5"); - defaults.add("10"); - - return new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, - ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); - } - - public void testNew() { - try { - new ArgumentImpl("limit", "the last acceptable date", 10, 5, '=', '\0', - new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); - } catch (IllegalArgumentException e) { - assertEquals(resources.getMessage("Argument.minimum.exceeds.maximum"), e.getMessage()); - } - - { - ArgumentImpl arg = - new ArgumentImpl(null, "the last acceptable date", 5, 5, '=', '\0', - new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); - assertEquals("wrong arg name", "arg", arg.getPreferredName()); - } - - { - List defaults = new ArrayList(); - - try { - new ArgumentImpl(null, "the last acceptable date", 1, 1, '=', '\0', - new DateValidator(DateValidatorTest.YYYY_MM_DD), null, defaults, 0); - } catch (IllegalArgumentException exp) { - assertEquals(resources.getMessage("Argument.too.few.defaults"), exp.getMessage()); - } - } - - try { - List defaults = new ArrayList(); - defaults.add("1"); - defaults.add("2"); - - new ArgumentImpl(null, "the last acceptable date", 1, 1, '=', '\0', - new DateValidator(DateValidatorTest.YYYY_MM_DD), null, defaults, 0); - } catch (IllegalArgumentException exp) { - assertEquals(resources.getMessage("Argument.too.many.defaults"), exp.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.ArgumentTestCase#testProcessValues() - */ - public void testProcessValues() - throws OptionException { - final Argument option = buildUsernameArgument(); - final List args = list("rob"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processValues(commandLine, iterator, option); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("username")); - assertEquals("rob", commandLine.getValue(option)); - } - - public void testProcessValues_BoundaryQuotes() - throws OptionException { - final Argument option = buildUsernameArgument(); - final List args = list("\"rob\""); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processValues(commandLine, iterator, option); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("username")); - assertEquals("rob", commandLine.getValue(option)); - } - - public void testProcessValues_SpareValues() - throws OptionException { - final Argument option = buildUsernameArgument(); - final List args = list("rob", "secret"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processValues(commandLine, iterator, option); - - assertTrue(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("username")); - assertEquals("rob", commandLine.getValue(option)); - } - - public void testProcessValues_Optional() { - final Argument option = buildTargetsArgument(); - final List args = list(); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - try { - option.processValues(commandLine, iterator, option); - } catch (final OptionException mve) { - assertEquals(option, mve.getOption()); - assertEquals("Missing value(s) target [target ...]", mve.getMessage()); - } - - assertFalse(iterator.hasNext()); - assertFalse(commandLine.hasOption(option)); - assertFalse(commandLine.hasOption("username")); - assertTrue(commandLine.getValues(option).isEmpty()); - } - - public void testProcessValues_Multiple() - throws OptionException { - final Argument option = buildTargetsArgument(); - final List args = list("compile", "test", "docs"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processValues(commandLine, iterator, option); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("target")); - assertFalse(commandLine.getValues(option).isEmpty()); - assertListContentsEqual(args, commandLine.getValues(option)); - } - - public void testProcessValues_Contracted() - throws OptionException { - final Argument option = buildTargetsArgument(); - final List args = list("compile,test,javadoc", "checkstyle,jdepend"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processValues(commandLine, iterator, option); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("target")); - assertListContentsEqual(list("compile", "test", "javadoc", "checkstyle", "jdepend"), - commandLine.getValues(option)); - } - - public void testProcessValues_ContractedTooFew() { - final Argument option = buildHostArgument(); - final List args = list("box1"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - try { - option.processValues(commandLine, iterator, option); - option.validate(commandLine); - fail("Expected MissingValueException"); - } catch (OptionException mve) { - assertSame(option, mve.getOption()); - } - } - - public void testProcessValues_ContractedTooMany() { - final Argument option = buildHostArgument(); - final List args = list("box1,box2,box3,box4"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - try { - option.processValues(commandLine, iterator, option); - option.validate(commandLine); - fail("Expected MissingValueException"); - } catch (OptionException mve) { - assertSame(option, mve.getOption()); - } - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() - */ - public void testCanProcess() { - final Argument option = buildTargetsArgument(); - assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "any value")); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() - */ - public void testPrefixes() { - final Argument option = buildTargetsArgument(); - assertTrue(option.getPrefixes().isEmpty()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testProcess() - */ - public void testProcess() - throws OptionException { - final Argument option = buildPathArgument(); - final List args = list("-path=/lib;/usr/lib;/usr/local/lib"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.process(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("path")); - assertListContentsEqual(list("-path=/lib", "/usr/lib", "/usr/local/lib"), - commandLine.getValues(option)); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testTriggers() - */ - public void testTriggers() { - final Argument option = buildTargetsArgument(); - assertTrue(option.getTriggers().isEmpty()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testValidate() - */ - public void testValidate() - throws OptionException { - final Argument option = buildUsernameArgument(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - commandLine.addValue(option, "rob"); - - option.validate(commandLine); - } - - public void testValidate_Minimum() { - final Argument option = buildUsernameArgument(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - try { - option.validate(commandLine); - fail("UnexpectedValue"); - } catch (OptionException mve) { - assertEquals(option, mve.getOption()); - } - } - - public void testRequired() { - { - final Argument arg = buildBoundsArgument(); - - assertTrue("not required", arg.isRequired()); - } - - { - final Argument arg = buildTargetsArgument(); - - assertFalse("should not be required", arg.isRequired()); - } - } - - public void testValidate_Maximum() { - final Argument option = buildUsernameArgument(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - commandLine.addValue(option, "rob"); - commandLine.addValue(option, "oxspring"); - - try { - option.validate(commandLine); - fail("UnexpectedValue"); - } catch (OptionException uve) { - assertEquals(option, uve.getOption()); - } - } - - public void testValidate_Validator() - throws OptionException, ParseException { - final Argument option = buildDateLimitArgument(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - commandLine.addValue(option, "2004-01-01"); - - option.validate(commandLine, option); - assertContentsEqual(Arrays.asList(new Object[] { - DateValidatorTest.YYYY_MM_DD.parse("2004-01-01") - }), commandLine.getValues(option)); - } - - public void testValidate_ValidatorInvalidDate() - throws OptionException, ParseException { - final Argument option = buildDateLimitArgument(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - commandLine.addValue(option, "12-12-2004"); - - try { - option.validate(commandLine, option); - } catch (OptionException exp) { - OptionException e = - new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, - "12-12-2004"); - assertEquals("wrong exception message", e.getMessage(), exp.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() - */ - public void testAppendUsage() { - final Option option = buildUsernameArgument(); - final StringBuffer buffer = new StringBuffer(); - option.appendUsage(buffer, DisplaySetting.ALL, null); - - assertEquals("", buffer.toString()); - } - - public void testAppendUsage_Infinite() { - final Option option = buildTargetsArgument(); - final StringBuffer buffer = new StringBuffer(); - option.appendUsage(buffer, DisplaySetting.ALL, null); - - assertEquals("[ [ ...]]", buffer.toString()); - } - - public void testAppendUsage_InfiniteNoOptional() { - final Option option = buildTargetsArgument(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_OPTIONAL); - option.appendUsage(buffer, settings, null); - - assertEquals(" [ ...]", buffer.toString()); - } - - public void testAppendUsage_InfiniteNoNumbering() { - final Option option = buildTargetsArgument(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); - option.appendUsage(buffer, settings, null); - - assertEquals("[ [ ...]]", buffer.toString()); - } - - public void testAppendUsage_Minimum() { - final Option option = buildHostArgument(); - final StringBuffer buffer = new StringBuffer(); - option.appendUsage(buffer, DisplaySetting.ALL, null); - - assertEquals(" []", buffer.toString()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() - */ - public void testGetPreferredName() { - final Option option = buildPathArgument(); - assertEquals("path", option.getPreferredName()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() - */ - public void testGetDescription() { - final Option option = buildHostArgument(); - assertEquals("The host name", option.getDescription()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() - */ - public void testHelpLines() { - final Option option = buildHostArgument(); - final List lines = option.helpLines(0, DisplaySetting.ALL, null); - final Iterator i = lines.iterator(); - - final HelpLine line1 = (HelpLine) i.next(); - assertEquals(0, line1.getIndent()); - assertEquals(option, line1.getOption()); - - assertFalse(i.hasNext()); - } - - public void testCanProcess_ConsumeRemaining() { - final Option option = buildUsernameArgument(); - - assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "--")); - } - - public void testProcess_ConsumeRemaining() - throws OptionException { - final Option option = buildPathArgument(); - final List args = list("options", "--", "--ignored", "-Dprop=val"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - option.process(commandLine, iterator); - - final List values = commandLine.getValues(option); - assertTrue(values.contains("options")); - assertTrue(values.contains("--ignored")); - assertTrue(values.contains("-Dprop=val")); - assertEquals(3, values.size()); - assertFalse(iterator.hasNext()); - } - - public void testProcess_ConsumeNothing() { - final Option option = buildPathArgument(); - final List args = list("--"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - try { - option.process(commandLine, iterator); - option.validate(commandLine); - fail("Missing Value!"); - } catch (OptionException mve) { - assertEquals(option, mve.getOption()); - assertEquals("Missing value(s) path [path ...]", mve.getMessage()); - } - - assertTrue(commandLine.getValues(option).isEmpty()); - assertFalse(iterator.hasNext()); - } - - // public void testProcess_DefinedDefaultValue() throws OptionException { - // final Option size = buildSizeArgument(); - // final List args = list(); - // final WriteableCommandLine commandLine = commandLine(size, args); - // final ListIterator iterator = args.listIterator(); - // - // size.process(commandLine, iterator); - // - // assertEquals("10", commandLine.getValue(size)); - // } - // - // public void testProcess_DefinedDefaultValues() throws OptionException { - // final Option bounds = buildBoundsArgument(); - // final List args = list(); - // final WriteableCommandLine commandLine = commandLine(bounds, args); - // final ListIterator iterator = args.listIterator(); - // - // bounds.process(commandLine, iterator); - // - // List values = new ArrayList(); - // values.add("5"); - // values.add("10"); - // assertEquals(values, commandLine.getValues(bounds)); - // } - public void testProcess_InterrogatedDefaultValue() - throws OptionException { - final Option size = buildSizeArgument(); - final List args = list(); - final WriteableCommandLine commandLine = commandLine(size, args); - final ListIterator iterator = args.listIterator(); - - size.process(commandLine, iterator); - - assertEquals(new Integer(20), commandLine.getValue(size, new Integer(20))); - } - - public void testTooFewDefaults() { - List defaults = new ArrayList(); - defaults.add("5"); - - try { - new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, - ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_FEW_DEFAULTS), - exp.getMessage()); - } - } - - public void testTooManyDefaults() { - List defaults = new ArrayList(); - defaults.add("5"); - defaults.add("10"); - defaults.add("15"); - - try { - new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, - ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_MANY_DEFAULTS), - exp.getMessage()); - } - } - - public void testProcess_InterrogatedDefaultValues() - throws OptionException { - final Option bounds = buildBoundsArgument(); - final List args = list(); - final WriteableCommandLine commandLine = commandLine(bounds, args); - final ListIterator iterator = args.listIterator(); - - bounds.process(commandLine, iterator); - - // test with values - List values = new ArrayList(); - values.add("50"); - values.add("100"); - assertEquals(values, commandLine.getValues(bounds, values)); - - // test without values - assertEquals(Collections.EMPTY_LIST, commandLine.getValues(bounds, null)); - } - - public void testProcess_StripBoundaryQuotes() - throws OptionException { - final Option bounds = buildBoundsArgument(); - final List args = list(); - final WriteableCommandLine commandLine = commandLine(bounds, args); - final ListIterator iterator = args.listIterator(); - - bounds.process(commandLine, iterator); - - List values = new ArrayList(); - values.add("50\""); - values.add("\"100"); - assertEquals(values, commandLine.getValues(bounds, values)); - } - - public void testSourceDestArgument() { - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - final Argument inputfiles = - abuilder.withName("input").withMinimum(0).withMaximum(0).create(); - final Argument bad_outputfile = - abuilder.withName("output").withMinimum(1).withMaximum(2).create(); - - try { - final Argument targets = new SourceDestArgument(inputfiles, bad_outputfile); - } catch (final IllegalArgumentException exp) { - assertEquals("wrong exception message", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SOURCE_DEST_MUST_ENFORCE_VALUES), - exp.getMessage()); - } - - final Argument outputfile = - abuilder.withName("output").withMinimum(1).withMaximum(1).create(); - - final Argument targets = new SourceDestArgument(inputfiles, outputfile); - final StringBuffer buffer = new StringBuffer("test content"); - targets.appendUsage(buffer, Collections.EMPTY_SET, null); - - assertTrue("buffer not added", buffer.toString().startsWith("test content")); - assertFalse("space added", buffer.charAt(12) == ' '); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.text.ParseException;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;import org.apache.commons.cli2.validation.DateValidator;import org.apache.commons.cli2.validation.DateValidatorTest;/** * @author Rob Oxspring */public class ArgumentTest extends ArgumentTestCase { private ResourceHelper resources = ResourceHelper.getResourceHelper(); public static Argument buildUsernameArgument() { return new ArgumentImpl("username", "The user to connect as", 1, 1, '\0', '\0', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, null, 0); } public static Argument buildHostArgument() { return new ArgumentImpl("host", "The host name", 2, 3, '\0', ',', null, null, null, 0); } public static Argument buildPathArgument() { return new ArgumentImpl("path", "The place to look for files", 1, Integer.MAX_VALUE, '=', ';', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, null, 0); } public static Argument buildDateLimitArgument() { return new ArgumentImpl("limit", "the last acceptable date", 0, 1, '=', '\0', new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); } public static Argument buildTargetsArgument() { return new ArgumentImpl("target", "The targets ant should build", 0, Integer.MAX_VALUE, '\0', ',', null, null, null, 0); } public static Argument buildSizeArgument() { List defaults = new ArrayList(); defaults.add("10"); return new ArgumentImpl("size", "The number of units", 1, 1, '\0', '\0', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); } public static Argument buildBoundsArgument() { List defaults = new ArrayList(); defaults.add("5"); defaults.add("10"); return new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); } public void testNew() { try { new ArgumentImpl("limit", "the last acceptable date", 10, 5, '=', '\0', new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage("Argument.minimum.exceeds.maximum"), e.getMessage()); } { ArgumentImpl arg = new ArgumentImpl(null, "the last acceptable date", 5, 5, '=', '\0', new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); assertEquals("wrong arg name", "arg", arg.getPreferredName()); } { List defaults = new ArrayList(); try { new ArgumentImpl(null, "the last acceptable date", 1, 1, '=', '\0', new DateValidator(DateValidatorTest.YYYY_MM_DD), null, defaults, 0); } catch (IllegalArgumentException exp) { assertEquals(resources.getMessage("Argument.too.few.defaults"), exp.getMessage()); } } try { List defaults = new ArrayList(); defaults.add("1"); defaults.add("2"); new ArgumentImpl(null, "the last acceptable date", 1, 1, '=', '\0', new DateValidator(DateValidatorTest.YYYY_MM_DD), null, defaults, 0); } catch (IllegalArgumentException exp) { assertEquals(resources.getMessage("Argument.too.many.defaults"), exp.getMessage()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.ArgumentTestCase#testProcessValues() */ public void testProcessValues() throws OptionException { final Argument option = buildUsernameArgument(); final List args = list("rob"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processValues(commandLine, iterator, option); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("username")); assertEquals("rob", commandLine.getValue(option)); } public void testProcessValues_BoundaryQuotes() throws OptionException { final Argument option = buildUsernameArgument(); final List args = list("\"rob\""); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processValues(commandLine, iterator, option); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("username")); assertEquals("rob", commandLine.getValue(option)); } public void testProcessValues_SpareValues() throws OptionException { final Argument option = buildUsernameArgument(); final List args = list("rob", "secret"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processValues(commandLine, iterator, option); assertTrue(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("username")); assertEquals("rob", commandLine.getValue(option)); } public void testProcessValues_Optional() { final Argument option = buildTargetsArgument(); final List args = list(); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.processValues(commandLine, iterator, option); } catch (final OptionException mve) { assertEquals(option, mve.getOption()); assertEquals("Missing value(s) target [target ...]", mve.getMessage()); } assertFalse(iterator.hasNext()); assertFalse(commandLine.hasOption(option)); assertFalse(commandLine.hasOption("username")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcessValues_Multiple() throws OptionException { final Argument option = buildTargetsArgument(); final List args = list("compile", "test", "docs"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processValues(commandLine, iterator, option); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("target")); assertFalse(commandLine.getValues(option).isEmpty()); assertListContentsEqual(args, commandLine.getValues(option)); } public void testProcessValues_Contracted() throws OptionException { final Argument option = buildTargetsArgument(); final List args = list("compile,test,javadoc", "checkstyle,jdepend"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processValues(commandLine, iterator, option); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("target")); assertListContentsEqual(list("compile", "test", "javadoc", "checkstyle", "jdepend"), commandLine.getValues(option)); } public void testProcessValues_ContractedTooFew() { final Argument option = buildHostArgument(); final List args = list("box1"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.processValues(commandLine, iterator, option); option.validate(commandLine); fail("Expected MissingValueException"); } catch (OptionException mve) { assertSame(option, mve.getOption()); } } public void testProcessValues_ContractedTooMany() { final Argument option = buildHostArgument(); final List args = list("box1,box2,box3,box4"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.processValues(commandLine, iterator, option); option.validate(commandLine); fail("Expected MissingValueException"); } catch (OptionException mve) { assertSame(option, mve.getOption()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Argument option = buildTargetsArgument(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "any value")); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Argument option = buildTargetsArgument(); assertTrue(option.getPrefixes().isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { final Argument option = buildPathArgument(); final List args = list("-path=/lib;/usr/lib;/usr/local/lib"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("path")); assertListContentsEqual(list("-path=/lib", "/usr/lib", "/usr/local/lib"), commandLine.getValues(option)); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Argument option = buildTargetsArgument(); assertTrue(option.getTriggers().isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() throws OptionException { final Argument option = buildUsernameArgument(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addValue(option, "rob"); option.validate(commandLine); } public void testValidate_Minimum() { final Argument option = buildUsernameArgument(); final WriteableCommandLine commandLine = commandLine(option, list()); try { option.validate(commandLine); fail("UnexpectedValue"); } catch (OptionException mve) { assertEquals(option, mve.getOption()); } } public void testRequired() { { final Argument arg = buildBoundsArgument(); assertTrue("not required", arg.isRequired()); } { final Argument arg = buildTargetsArgument(); assertFalse("should not be required", arg.isRequired()); } } public void testValidate_Maximum() { final Argument option = buildUsernameArgument(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addValue(option, "rob"); commandLine.addValue(option, "oxspring"); try { option.validate(commandLine); fail("UnexpectedValue"); } catch (OptionException uve) { assertEquals(option, uve.getOption()); } } public void testValidate_Validator() throws OptionException, ParseException { final Argument option = buildDateLimitArgument(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addValue(option, "2004-01-01"); option.validate(commandLine, option); assertContentsEqual(Arrays.asList(new Object[] { DateValidatorTest.YYYY_MM_DD.parse("2004-01-01") }), commandLine.getValues(option)); } public void testValidate_ValidatorInvalidDate() throws OptionException, ParseException { final Argument option = buildDateLimitArgument(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addValue(option, "12-12-2004"); try { option.validate(commandLine, option); } catch (OptionException exp) { OptionException e = new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, "12-12-2004"); assertEquals("wrong exception message", e.getMessage(), exp.getMessage()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildUsernameArgument(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("", buffer.toString()); } public void testAppendUsage_Infinite() { final Option option = buildTargetsArgument(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("[ [ ...]]", buffer.toString()); } public void testAppendUsage_InfiniteNoOptional() { final Option option = buildTargetsArgument(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_OPTIONAL); option.appendUsage(buffer, settings, null); assertEquals(" [ ...]", buffer.toString()); } public void testAppendUsage_InfiniteNoNumbering() { final Option option = buildTargetsArgument(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); option.appendUsage(buffer, settings, null); assertEquals("[ [ ...]]", buffer.toString()); } public void testAppendUsage_Minimum() { final Option option = buildHostArgument(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals(" []", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildPathArgument(); assertEquals("path", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildHostArgument(); assertEquals("The host name", option.getDescription()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { final Option option = buildHostArgument(); final List lines = option.helpLines(0, DisplaySetting.ALL, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); assertFalse(i.hasNext()); } public void testCanProcess_ConsumeRemaining() { final Option option = buildUsernameArgument(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "--")); } public void testProcess_ConsumeRemaining() throws OptionException { final Option option = buildPathArgument(); final List args = list("options", "--", "--ignored", "-Dprop=val"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); final List values = commandLine.getValues(option); assertTrue(values.contains("options")); assertTrue(values.contains("--ignored")); assertTrue(values.contains("-Dprop=val")); assertEquals(3, values.size()); assertFalse(iterator.hasNext()); } public void testProcess_ConsumeNothing() { final Option option = buildPathArgument(); final List args = list("--"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.process(commandLine, iterator); option.validate(commandLine); fail("Missing Value!"); } catch (OptionException mve) { assertEquals(option, mve.getOption()); assertEquals("Missing value(s) path [path ...]", mve.getMessage()); } assertTrue(commandLine.getValues(option).isEmpty()); assertFalse(iterator.hasNext()); } // public void testProcess_DefinedDefaultValue() throws OptionException { // final Option size = buildSizeArgument(); // final List args = list(); // final WriteableCommandLine commandLine = commandLine(size, args); // final ListIterator iterator = args.listIterator(); // // size.process(commandLine, iterator); // // assertEquals("10", commandLine.getValue(size)); // } // // public void testProcess_DefinedDefaultValues() throws OptionException { // final Option bounds = buildBoundsArgument(); // final List args = list(); // final WriteableCommandLine commandLine = commandLine(bounds, args); // final ListIterator iterator = args.listIterator(); // // bounds.process(commandLine, iterator); // // List values = new ArrayList(); // values.add("5"); // values.add("10"); // assertEquals(values, commandLine.getValues(bounds)); // } public void testProcess_InterrogatedDefaultValue() throws OptionException { final Option size = buildSizeArgument(); final List args = list(); final WriteableCommandLine commandLine = commandLine(size, args); final ListIterator iterator = args.listIterator(); size.process(commandLine, iterator); assertEquals(new Integer(20), commandLine.getValue(size, new Integer(20))); } public void testTooFewDefaults() { List defaults = new ArrayList(); defaults.add("5"); try { new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_FEW_DEFAULTS), exp.getMessage()); } } public void testTooManyDefaults() { List defaults = new ArrayList(); defaults.add("5"); defaults.add("10"); defaults.add("15"); try { new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_MANY_DEFAULTS), exp.getMessage()); } } public void testProcess_InterrogatedDefaultValues() throws OptionException { final Option bounds = buildBoundsArgument(); final List args = list(); final WriteableCommandLine commandLine = commandLine(bounds, args); final ListIterator iterator = args.listIterator(); bounds.process(commandLine, iterator); // test with values List values = new ArrayList(); values.add("50"); values.add("100"); assertEquals(values, commandLine.getValues(bounds, values)); // test without values assertEquals(Collections.EMPTY_LIST, commandLine.getValues(bounds, null)); } public void testProcess_StripBoundaryQuotes() throws OptionException { final Option bounds = buildBoundsArgument(); final List args = list(); final WriteableCommandLine commandLine = commandLine(bounds, args); final ListIterator iterator = args.listIterator(); bounds.process(commandLine, iterator); List values = new ArrayList(); values.add("50\""); values.add("\"100"); assertEquals(values, commandLine.getValues(bounds, values)); } public void testSourceDestArgument() { final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Argument inputfiles = abuilder.withName("input").withMinimum(0).withMaximum(0).create(); final Argument bad_outputfile = abuilder.withName("output").withMinimum(1).withMaximum(2).create(); try { final Argument targets = new SourceDestArgument(inputfiles, bad_outputfile); } catch (final IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SOURCE_DEST_MUST_ENFORCE_VALUES), exp.getMessage()); } final Argument outputfile = abuilder.withName("output").withMinimum(1).withMaximum(1).create(); final Argument targets = new SourceDestArgument(inputfiles, outputfile); final StringBuffer buffer = new StringBuffer("test content"); targets.appendUsage(buffer, Collections.EMPTY_SET, null); assertTrue("buffer not added", buffer.toString().startsWith("test content")); assertFalse("space added", buffer.charAt(12) == ' '); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/ArgumentTestCase.java b/src/test/org/apache/commons/cli2/option/ArgumentTestCase.java index eab24f852..769a4af53 100644 --- a/src/test/org/apache/commons/cli2/option/ArgumentTestCase.java +++ b/src/test/org/apache/commons/cli2/option/ArgumentTestCase.java @@ -1,28 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import org.apache.commons.cli2.OptionException; - -/** - * @author Rob Oxspring - */ -public abstract class ArgumentTestCase extends OptionTestCase { - - public abstract void testProcessValues() throws OptionException; - -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import org.apache.commons.cli2.OptionException;/** * @author Rob Oxspring */public abstract class ArgumentTestCase extends OptionTestCase { public abstract void testProcessValues() throws OptionException;} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/CommandTest.java b/src/test/org/apache/commons/cli2/option/CommandTest.java index 2b78f1f91..75900de07 100644 --- a/src/test/org/apache/commons/cli2/option/CommandTest.java +++ b/src/test/org/apache/commons/cli2/option/CommandTest.java @@ -1,249 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.Parent; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * @author Rob Oxspring - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class CommandTest - extends ParentTestCase { - public static Command buildStartCommand() { - return new Command("start", "Begins the process", Collections.singleton("go"), false, null, - null, 0); - } - - public static Command buildCommitCommand() { - return new Command("commit", "Commit the changes to the database", null, true, null, null, 0); - } - - public static Command buildLoginCommand() { - return new Command("login", "Initiates a session for the user", null, false, - ArgumentTest.buildUsernameArgument(), null, 0); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() - */ - public void testProcessParent() - throws OptionException { - final Command option = buildStartCommand(); - final List args = list("go"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processParent(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("start")); - assertTrue(commandLine.hasOption("go")); - assertTrue(commandLine.getValues(option).isEmpty()); - } - - public void testProcessParent_Spare() - throws OptionException { - final Command option = buildLoginCommand(); - final List args = list("login", "rob"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processParent(commandLine, iterator); - - assertEquals("rob", iterator.next()); - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("login")); - assertTrue(commandLine.getValues(option).isEmpty()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() - */ - public void testCanProcess() { - final Command option = buildStartCommand(); - assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "start")); - } - - public void testCanProcess_BadMatch() { - final Command option = buildStartCommand(); - assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "stop")); - } - - public void testCanProcess_Alias() { - final Command option = buildStartCommand(); - assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "go")); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() - */ - public void testPrefixes() { - final Command option = buildStartCommand(); - assertTrue(option.getPrefixes().isEmpty()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testProcess() - */ - public void testProcess() - throws OptionException { - final Command option = buildLoginCommand(); - final List args = list("login", "rob"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.process(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("login")); - assertEquals("rob", commandLine.getValue(option)); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testTriggers() - */ - public void testTriggers() { - final Command option = buildStartCommand(); - final Set triggers = option.getTriggers(); - assertContentsEqual(list("start", "go"), triggers); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testValidate() - */ - public void testValidate() { - final Parent option = buildCommitCommand(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - try { - option.validate(commandLine); - fail("Missing an option"); - } catch (OptionException moe) { - assertSame(option, moe.getOption()); - } - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() - */ - public void testAppendUsage() { - final Option option = buildStartCommand(); - final StringBuffer buffer = new StringBuffer(); - option.appendUsage(buffer, DisplaySetting.ALL, null); - - assertEquals("[start (go)]", buffer.toString()); - } - - public void testNullPreferredName() { - try { - new Command(null, "", Collections.singleton("go"), false, null, null, 0); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception name", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT), - exp.getMessage()); - } - } - - public void testEmotyPreferredName() { - try { - new Command("", "", Collections.singleton("go"), false, null, null, 0); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception name", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT), - exp.getMessage()); - } - } - - public void testAppendUsage_NoOptional() { - final Option option = buildStartCommand(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_OPTIONAL); - option.appendUsage(buffer, settings, null); - - assertEquals("start (go)", buffer.toString()); - } - - public void testAppendUsage_NoAlias() { - final Option option = buildStartCommand(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_ALIASES); - option.appendUsage(buffer, settings, null); - - assertEquals("[start]", buffer.toString()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() - */ - public void testGetPreferredName() { - final Option option = buildStartCommand(); - assertEquals("start", option.getPreferredName()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() - */ - public void testGetDescription() { - final Option option = buildLoginCommand(); - assertEquals("Initiates a session for the user", option.getDescription()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() - */ - public void testHelpLines() { - // TODO Auto-generated method stub - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Collections;import java.util.HashSet;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.Parent;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * @author Rob Oxspring * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */public class CommandTest extends ParentTestCase { public static Command buildStartCommand() { return new Command("start", "Begins the process", Collections.singleton("go"), false, null, null, 0); } public static Command buildCommitCommand() { return new Command("commit", "Commit the changes to the database", null, true, null, null, 0); } public static Command buildLoginCommand() { return new Command("login", "Initiates a session for the user", null, false, ArgumentTest.buildUsernameArgument(), null, 0); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() */ public void testProcessParent() throws OptionException { final Command option = buildStartCommand(); final List args = list("go"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("start")); assertTrue(commandLine.hasOption("go")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcessParent_Spare() throws OptionException { final Command option = buildLoginCommand(); final List args = list("login", "rob"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertEquals("rob", iterator.next()); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("login")); assertTrue(commandLine.getValues(option).isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Command option = buildStartCommand(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "start")); } public void testCanProcess_BadMatch() { final Command option = buildStartCommand(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "stop")); } public void testCanProcess_Alias() { final Command option = buildStartCommand(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "go")); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Command option = buildStartCommand(); assertTrue(option.getPrefixes().isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { final Command option = buildLoginCommand(); final List args = list("login", "rob"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("login")); assertEquals("rob", commandLine.getValue(option)); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Command option = buildStartCommand(); final Set triggers = option.getTriggers(); assertContentsEqual(list("start", "go"), triggers); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() { final Parent option = buildCommitCommand(); final WriteableCommandLine commandLine = commandLine(option, list()); try { option.validate(commandLine); fail("Missing an option"); } catch (OptionException moe) { assertSame(option, moe.getOption()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildStartCommand(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("[start (go)]", buffer.toString()); } public void testNullPreferredName() { try { new Command(null, "", Collections.singleton("go"), false, null, null, 0); } catch (IllegalArgumentException exp) { assertEquals("wrong exception name", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT), exp.getMessage()); } } public void testEmotyPreferredName() { try { new Command("", "", Collections.singleton("go"), false, null, null, 0); } catch (IllegalArgumentException exp) { assertEquals("wrong exception name", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT), exp.getMessage()); } } public void testAppendUsage_NoOptional() { final Option option = buildStartCommand(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_OPTIONAL); option.appendUsage(buffer, settings, null); assertEquals("start (go)", buffer.toString()); } public void testAppendUsage_NoAlias() { final Option option = buildStartCommand(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_ALIASES); option.appendUsage(buffer, settings, null); assertEquals("[start]", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildStartCommand(); assertEquals("start", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildLoginCommand(); assertEquals("Initiates a session for the user", option.getDescription()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { // TODO Auto-generated method stub }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java b/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java index 2cdbe34b4..e4eb7a837 100644 --- a/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java +++ b/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java @@ -1,227 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.Parent; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; - -/** - * @author roberto - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class DefaultOptionTest extends ParentTestCase { - - public static DefaultOption buildHelpOption() { - final Set aliases = new HashSet(list("-h", "-?")); - return new DefaultOption( - "-", - "--", - true, - "--help", - "Displays the help", - aliases, - aliases, - false, - null, - null, - 'h'); - } - - public static DefaultOption buildXOption() { - return new DefaultOption( - "-", - "--", - true, - "-X", - "This is needed", - null, - null, - true, - null, - null, - 'X'); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() - */ - public void testProcessParent() throws OptionException { - final DefaultOption option = buildHelpOption(); - final List args = list("--help"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processParent(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("--help")); - assertTrue(commandLine.hasOption("-?")); - assertTrue(commandLine.getValues(option).isEmpty()); - } - - public void testProcessParent_Burst() throws OptionException { - final DefaultOption option = buildHelpOption(); - final List args = list("-help"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processParent(commandLine, iterator); - - assertEquals("-elp", iterator.next()); - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("--help")); - assertTrue(commandLine.hasOption("-?")); - assertTrue(commandLine.getValues(option).isEmpty()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() - */ - public void testCanProcess() { - final DefaultOption option = buildHelpOption(); - assertTrue(option.canProcess(new WriteableCommandLineImpl(option,null), "-?")); - } - - public void testCanProcess_BadMatch() { - final DefaultOption option = buildHelpOption(); - assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), "-H")); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() - */ - public void testPrefixes() { - final DefaultOption option = buildHelpOption(); - assertContentsEqual(list("-", "--"), option.getPrefixes()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testProcess() - */ - public void testProcess() { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testTriggers() - */ - public void testTriggers() { - final DefaultOption option = buildHelpOption(); - assertContentsEqual(list("-?", "-h", "--help"), option.getTriggers()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testValidate() - */ - public void testValidate() { - final Parent option = buildXOption(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - try { - option.validate(commandLine); - fail("Missing an option"); - } - catch (OptionException moe) { - assertSame(option, moe.getOption()); - } - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() - */ - public void testAppendUsage() { - final Option option = buildHelpOption(); - final StringBuffer buffer = new StringBuffer(); - option.appendUsage(buffer, DisplaySetting.ALL, null); - - assertEquals("[--help (-?,-h)]", buffer.toString()); - } - - public void testAppendUsage_NoOptional() { - final Option option = buildHelpOption(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_OPTIONAL); - option.appendUsage(buffer, settings, null); - - assertEquals("--help (-?,-h)", buffer.toString()); - } - - public void testAppendUsage_NoAlias() { - final Option option = buildHelpOption(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_ALIASES); - option.appendUsage(buffer, settings, null); - - assertEquals("[--help]", buffer.toString()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() - */ - public void testGetPreferredName() { - final Option option = buildHelpOption(); - assertEquals("--help", option.getPreferredName()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() - */ - public void testGetDescription() { - final Option option = buildHelpOption(); - assertEquals("Displays the help", option.getDescription()); - } - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() - */ - public void testHelpLines() { - // TODO Auto-generated method stub - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.HashSet;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.Parent;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;/** * @author roberto * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */public class DefaultOptionTest extends ParentTestCase { public static DefaultOption buildHelpOption() { final Set aliases = new HashSet(list("-h", "-?")); return new DefaultOption( "-", "--", true, "--help", "Displays the help", aliases, aliases, false, null, null, 'h'); } public static DefaultOption buildXOption() { return new DefaultOption( "-", "--", true, "-X", "This is needed", null, null, true, null, null, 'X'); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() */ public void testProcessParent() throws OptionException { final DefaultOption option = buildHelpOption(); final List args = list("--help"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("--help")); assertTrue(commandLine.hasOption("-?")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcessParent_Burst() throws OptionException { final DefaultOption option = buildHelpOption(); final List args = list("-help"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertEquals("-elp", iterator.next()); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("--help")); assertTrue(commandLine.hasOption("-?")); assertTrue(commandLine.getValues(option).isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final DefaultOption option = buildHelpOption(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option,null), "-?")); } public void testCanProcess_BadMatch() { final DefaultOption option = buildHelpOption(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), "-H")); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final DefaultOption option = buildHelpOption(); assertContentsEqual(list("-", "--"), option.getPrefixes()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final DefaultOption option = buildHelpOption(); assertContentsEqual(list("-?", "-h", "--help"), option.getTriggers()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() { final Parent option = buildXOption(); final WriteableCommandLine commandLine = commandLine(option, list()); try { option.validate(commandLine); fail("Missing an option"); } catch (OptionException moe) { assertSame(option, moe.getOption()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildHelpOption(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("[--help (-?,-h)]", buffer.toString()); } public void testAppendUsage_NoOptional() { final Option option = buildHelpOption(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_OPTIONAL); option.appendUsage(buffer, settings, null); assertEquals("--help (-?,-h)", buffer.toString()); } public void testAppendUsage_NoAlias() { final Option option = buildHelpOption(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_ALIASES); option.appendUsage(buffer, settings, null); assertEquals("[--help]", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildHelpOption(); assertEquals("--help", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildHelpOption(); assertEquals("Displays the help", option.getDescription()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { // TODO Auto-generated method stub }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/GroupTest.java b/src/test/org/apache/commons/cli2/option/GroupTest.java index 32cc36f48..379e7f5ff 100644 --- a/src/test/org/apache/commons/cli2/option/GroupTest.java +++ b/src/test/org/apache/commons/cli2/option/GroupTest.java @@ -1,440 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.HelpLine; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; - -/** - * @author Rob Oxspring - */ -public class GroupTest - extends GroupTestCase { - public static final Command COMMAND_START = - new Command("start", "Starts the server", null, false, null, null, 0); - public static final Command COMMAND_STOP = - new Command("stop", "Stops the server", null, false, null, null, 0); - public static final Command COMMAND_RESTART = - new Command("restart", "Stops and starts the server", null, false, null, null, 0); - public static final Command COMMAND_GRACEFUL = - new Command("graceful", "Restarts the server without interruption", null, false, null, - null, 0); - - public static Group buildApacheCommandGroup() { - final List options = new ArrayList(); - options.add(COMMAND_GRACEFUL); - options.add(COMMAND_RESTART); - options.add(COMMAND_START); - options.add(COMMAND_STOP); - - return new GroupImpl(options, "httpd-cmds", "The command to pass to the server", 1, 1); - } - - public static Group buildApachectlGroup() { - final List options = new ArrayList(); - options.add(DefaultOptionTest.buildHelpOption()); - options.add(ParentTest.buildKParent()); - - return new GroupImpl(options, "apachectl", "Controls the apache http deamon", 0, - Integer.MAX_VALUE); - } - - public static Group buildAntGroup() { - final List options = new ArrayList(); - options.add(DefaultOptionTest.buildHelpOption()); - options.add(ArgumentTest.buildTargetsArgument()); - - return new GroupImpl(options, "ant", "The options for ant", 0, Integer.MAX_VALUE); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.GroupTestCase#testProcessAnonymousArguments() - */ - public void testProcessAnonymousArguments() - throws OptionException { - final Group option = buildAntGroup(); - final List args = list("compile,test", "dist"); - final ListIterator iterator = args.listIterator(); - final WriteableCommandLine commandLine = commandLine(option, args); - option.process(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption("target")); - assertListContentsEqual(commandLine.getValues("target"), args); - assertListContentsEqual(list("compile", "test", "dist"), args); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.GroupTestCase#testProcessOptions() - */ - public void testProcessOptions() - throws OptionException { - final Group option = buildApachectlGroup(); - final List args = list("-?", "-k"); - final ListIterator iterator = args.listIterator(); - final WriteableCommandLine commandLine = commandLine(option, args); - option.process(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption("--help")); - assertTrue(commandLine.hasOption("-k")); - assertFalse(commandLine.hasOption("start")); - assertListContentsEqual(list("--help", "-k"), args); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() - */ - public void testCanProcess() { - final Group option = buildApacheCommandGroup(); - assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "start")); - } - - public void testCanProcess_BadMatch() { - final Group option = buildApacheCommandGroup(); - assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "begin")); - } - - public void testCanProcess_NullMatch() { - final Group option = buildApacheCommandGroup(); - assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), (String) null)); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() - */ - public void testPrefixes() { - final Group option = buildApachectlGroup(); - assertContentsEqual(list("-", "--"), option.getPrefixes()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testProcess() - */ - public void testProcess() - throws OptionException { - final Group option = buildAntGroup(); - final List args = list("--help", "compile,test", "dist"); - final ListIterator iterator = args.listIterator(); - final WriteableCommandLine commandLine = commandLine(option, args); - option.process(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption("-?")); - assertListContentsEqual(list("compile", "test", "dist"), commandLine.getValues("target")); - } - - public void testProcess_Nested() - throws OptionException { - final Group option = buildApachectlGroup(); - final List args = list("-h", "-k", "graceful"); - final ListIterator iterator = args.listIterator(); - final WriteableCommandLine commandLine = commandLine(option, args); - option.process(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption("-?")); - assertTrue(commandLine.hasOption("-k")); - assertTrue(commandLine.hasOption("graceful")); - assertFalse(commandLine.hasOption("stop")); - assertTrue(commandLine.getValues("start").isEmpty()); - assertListContentsEqual(list("--help", "-k", "graceful"), args); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testTriggers() - */ - public void testTriggers() { - final Group option = buildApachectlGroup(); - assertContentsEqual(list("--help", "-?", "-h", "-k"), option.getTriggers()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testValidate() - */ - public void testValidate() - throws OptionException { - final Group option = buildApacheCommandGroup(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - commandLine.addOption(COMMAND_RESTART); - - option.validate(commandLine); - } - - public void testValidate_UnexpectedOption() { - final Group option = buildApacheCommandGroup(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - commandLine.addOption(COMMAND_RESTART); - commandLine.addOption(COMMAND_GRACEFUL); - - try { - option.validate(commandLine); - fail("Too many options"); - } catch (OptionException uoe) { - assertEquals(option, uoe.getOption()); - } - } - - public void testValidate_MissingOption() { - final Group option = buildApacheCommandGroup(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - try { - option.validate(commandLine); - fail("Missing an option"); - } catch (OptionException moe) { - assertEquals(option, moe.getOption()); - } - } - - public void testValidate_RequiredChild() - throws OptionException { - final Option required = - new DefaultOptionBuilder().withLongName("required").withRequired(true).create(); - final Option optional = - new DefaultOptionBuilder().withLongName("optional").withRequired(false).create(); - final Group group = - new GroupBuilder().withOption(required).withOption(optional).withMinimum(1).create(); - - WriteableCommandLine commandLine; - - commandLine = commandLine(group, list()); - - try { - group.validate(commandLine); - fail("Missing option 'required'"); - } catch (OptionException moe) { - assertEquals(required, moe.getOption()); - } - - commandLine = commandLine(group, list()); - commandLine.addOption(optional); - - try { - group.validate(commandLine); - fail("Missing option 'required'"); - } catch (OptionException moe) { - assertEquals(required, moe.getOption()); - } - - commandLine = commandLine(group, list()); - commandLine.addOption(required); - group.validate(commandLine); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() - */ - public void testAppendUsage() { - final Option option = buildApacheCommandGroup(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - - //settings.remove(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); - option.appendUsage(buffer, settings, null); - - assertEquals("httpd-cmds (graceful|restart|start|stop)", buffer.toString()); - } - - public void testAppendUsage_NoOptional() { - final Option option = buildApacheCommandGroup(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_OPTIONAL); - option.appendUsage(buffer, settings, null); - - assertEquals("httpd-cmds (graceful|restart|start|stop)", buffer.toString()); - } - - public void testAppendUsage_NoExpand() { - final Option option = buildApacheCommandGroup(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); - option.appendUsage(buffer, settings, null); - - assertEquals("httpd-cmds", buffer.toString()); - } - - public void testAppendUsage_NoExpandOrName() { - final Option option = buildApacheCommandGroup(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); - settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); - option.appendUsage(buffer, settings, null); - - assertEquals("httpd-cmds", buffer.toString()); - } - - public void testAppendUsage_NoName() { - final Option option = buildApacheCommandGroup(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); - option.appendUsage(buffer, settings, null); - - assertEquals("graceful|restart|start|stop", buffer.toString()); - } - - public void testAppendUsage_WithArgs() { - final Option option = buildAntGroup(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); - option.appendUsage(buffer, settings, null); - - assertEquals("[ant (--help (-?,-h)) [ [ ...]]]", buffer.toString()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() - */ - public void testGetPreferredName() { - final Option option = buildAntGroup(); - assertEquals("ant", option.getPreferredName()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() - */ - public void testGetDescription() { - final Option option = buildApachectlGroup(); - assertEquals("Controls the apache http deamon", option.getDescription()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() - */ - public void testHelpLines() { - final Option option = buildApacheCommandGroup(); - final List lines = option.helpLines(0, DisplaySetting.ALL, null); - final Iterator i = lines.iterator(); - - final HelpLine line1 = (HelpLine) i.next(); - assertEquals(0, line1.getIndent()); - assertEquals(option, line1.getOption()); - - final HelpLine line2 = (HelpLine) i.next(); - assertEquals(1, line2.getIndent()); - assertEquals(COMMAND_GRACEFUL, line2.getOption()); - - final HelpLine line3 = (HelpLine) i.next(); - assertEquals(1, line3.getIndent()); - assertEquals(COMMAND_RESTART, line3.getOption()); - - final HelpLine line4 = (HelpLine) i.next(); - assertEquals(1, line4.getIndent()); - assertEquals(COMMAND_START, line4.getOption()); - - final HelpLine line5 = (HelpLine) i.next(); - assertEquals(1, line5.getIndent()); - assertEquals(COMMAND_STOP, line5.getOption()); - - assertFalse(i.hasNext()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() - */ - public void testHelpLines_NoExpanded() { - final Option option = buildApacheCommandGroup(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); - - final List lines = option.helpLines(0, settings, null); - final Iterator i = lines.iterator(); - - final HelpLine line1 = (HelpLine) i.next(); - assertEquals(0, line1.getIndent()); - assertEquals(option, line1.getOption()); - - assertFalse(i.hasNext()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() - */ - public void testHelpLines_NoName() { - final Option option = buildApacheCommandGroup(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); - - final List lines = option.helpLines(0, settings, null); - final Iterator i = lines.iterator(); - - final HelpLine line2 = (HelpLine) i.next(); - assertEquals(1, line2.getIndent()); - assertEquals(COMMAND_GRACEFUL, line2.getOption()); - - final HelpLine line3 = (HelpLine) i.next(); - assertEquals(1, line3.getIndent()); - assertEquals(COMMAND_RESTART, line3.getOption()); - - final HelpLine line4 = (HelpLine) i.next(); - assertEquals(1, line4.getIndent()); - assertEquals(COMMAND_START, line4.getOption()); - - final HelpLine line5 = (HelpLine) i.next(); - assertEquals(1, line5.getIndent()); - assertEquals(COMMAND_STOP, line5.getOption()); - - assertFalse(i.hasNext()); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;/** * @author Rob Oxspring */public class GroupTest extends GroupTestCase { public static final Command COMMAND_START = new Command("start", "Starts the server", null, false, null, null, 0); public static final Command COMMAND_STOP = new Command("stop", "Stops the server", null, false, null, null, 0); public static final Command COMMAND_RESTART = new Command("restart", "Stops and starts the server", null, false, null, null, 0); public static final Command COMMAND_GRACEFUL = new Command("graceful", "Restarts the server without interruption", null, false, null, null, 0); public static Group buildApacheCommandGroup() { final List options = new ArrayList(); options.add(COMMAND_GRACEFUL); options.add(COMMAND_RESTART); options.add(COMMAND_START); options.add(COMMAND_STOP); return new GroupImpl(options, "httpd-cmds", "The command to pass to the server", 1, 1); } public static Group buildApachectlGroup() { final List options = new ArrayList(); options.add(DefaultOptionTest.buildHelpOption()); options.add(ParentTest.buildKParent()); return new GroupImpl(options, "apachectl", "Controls the apache http deamon", 0, Integer.MAX_VALUE); } public static Group buildAntGroup() { final List options = new ArrayList(); options.add(DefaultOptionTest.buildHelpOption()); options.add(ArgumentTest.buildTargetsArgument()); return new GroupImpl(options, "ant", "The options for ant", 0, Integer.MAX_VALUE); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.GroupTestCase#testProcessAnonymousArguments() */ public void testProcessAnonymousArguments() throws OptionException { final Group option = buildAntGroup(); final List args = list("compile,test", "dist"); final ListIterator iterator = args.listIterator(); final WriteableCommandLine commandLine = commandLine(option, args); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption("target")); assertListContentsEqual(commandLine.getValues("target"), args); assertListContentsEqual(list("compile", "test", "dist"), args); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.GroupTestCase#testProcessOptions() */ public void testProcessOptions() throws OptionException { final Group option = buildApachectlGroup(); final List args = list("-?", "-k"); final ListIterator iterator = args.listIterator(); final WriteableCommandLine commandLine = commandLine(option, args); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption("--help")); assertTrue(commandLine.hasOption("-k")); assertFalse(commandLine.hasOption("start")); assertListContentsEqual(list("--help", "-k"), args); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Group option = buildApacheCommandGroup(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "start")); } public void testCanProcess_BadMatch() { final Group option = buildApacheCommandGroup(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "begin")); } public void testCanProcess_NullMatch() { final Group option = buildApacheCommandGroup(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), (String) null)); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Group option = buildApachectlGroup(); assertContentsEqual(list("-", "--"), option.getPrefixes()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { final Group option = buildAntGroup(); final List args = list("--help", "compile,test", "dist"); final ListIterator iterator = args.listIterator(); final WriteableCommandLine commandLine = commandLine(option, args); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption("-?")); assertListContentsEqual(list("compile", "test", "dist"), commandLine.getValues("target")); } public void testProcess_Nested() throws OptionException { final Group option = buildApachectlGroup(); final List args = list("-h", "-k", "graceful"); final ListIterator iterator = args.listIterator(); final WriteableCommandLine commandLine = commandLine(option, args); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption("-?")); assertTrue(commandLine.hasOption("-k")); assertTrue(commandLine.hasOption("graceful")); assertFalse(commandLine.hasOption("stop")); assertTrue(commandLine.getValues("start").isEmpty()); assertListContentsEqual(list("--help", "-k", "graceful"), args); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Group option = buildApachectlGroup(); assertContentsEqual(list("--help", "-?", "-h", "-k"), option.getTriggers()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() throws OptionException { final Group option = buildApacheCommandGroup(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addOption(COMMAND_RESTART); option.validate(commandLine); } public void testValidate_UnexpectedOption() { final Group option = buildApacheCommandGroup(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addOption(COMMAND_RESTART); commandLine.addOption(COMMAND_GRACEFUL); try { option.validate(commandLine); fail("Too many options"); } catch (OptionException uoe) { assertEquals(option, uoe.getOption()); } } public void testValidate_MissingOption() { final Group option = buildApacheCommandGroup(); final WriteableCommandLine commandLine = commandLine(option, list()); try { option.validate(commandLine); fail("Missing an option"); } catch (OptionException moe) { assertEquals(option, moe.getOption()); } } public void testValidate_RequiredChild() throws OptionException { final Option required = new DefaultOptionBuilder().withLongName("required").withRequired(true).create(); final Option optional = new DefaultOptionBuilder().withLongName("optional").withRequired(false).create(); final Group group = new GroupBuilder().withOption(required).withOption(optional).withMinimum(1).create(); WriteableCommandLine commandLine; commandLine = commandLine(group, list()); try { group.validate(commandLine); fail("Missing option 'required'"); } catch (OptionException moe) { assertEquals(required, moe.getOption()); } commandLine = commandLine(group, list()); commandLine.addOption(optional); try { group.validate(commandLine); fail("Missing option 'required'"); } catch (OptionException moe) { assertEquals(required, moe.getOption()); } commandLine = commandLine(group, list()); commandLine.addOption(required); group.validate(commandLine); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildApacheCommandGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); //settings.remove(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); option.appendUsage(buffer, settings, null); assertEquals("httpd-cmds (graceful|restart|start|stop)", buffer.toString()); } public void testAppendUsage_NoOptional() { final Option option = buildApacheCommandGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_OPTIONAL); option.appendUsage(buffer, settings, null); assertEquals("httpd-cmds (graceful|restart|start|stop)", buffer.toString()); } public void testAppendUsage_NoExpand() { final Option option = buildApacheCommandGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); option.appendUsage(buffer, settings, null); assertEquals("httpd-cmds", buffer.toString()); } public void testAppendUsage_NoExpandOrName() { final Option option = buildApacheCommandGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); option.appendUsage(buffer, settings, null); assertEquals("httpd-cmds", buffer.toString()); } public void testAppendUsage_NoName() { final Option option = buildApacheCommandGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); option.appendUsage(buffer, settings, null); assertEquals("graceful|restart|start|stop", buffer.toString()); } public void testAppendUsage_WithArgs() { final Option option = buildAntGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); option.appendUsage(buffer, settings, null); assertEquals("[ant (--help (-?,-h)) [ [ ...]]]", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildAntGroup(); assertEquals("ant", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildApachectlGroup(); assertEquals("Controls the apache http deamon", option.getDescription()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { final Option option = buildApacheCommandGroup(); final List lines = option.helpLines(0, DisplaySetting.ALL, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); final HelpLine line2 = (HelpLine) i.next(); assertEquals(1, line2.getIndent()); assertEquals(COMMAND_GRACEFUL, line2.getOption()); final HelpLine line3 = (HelpLine) i.next(); assertEquals(1, line3.getIndent()); assertEquals(COMMAND_RESTART, line3.getOption()); final HelpLine line4 = (HelpLine) i.next(); assertEquals(1, line4.getIndent()); assertEquals(COMMAND_START, line4.getOption()); final HelpLine line5 = (HelpLine) i.next(); assertEquals(1, line5.getIndent()); assertEquals(COMMAND_STOP, line5.getOption()); assertFalse(i.hasNext()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines_NoExpanded() { final Option option = buildApacheCommandGroup(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); final List lines = option.helpLines(0, settings, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); assertFalse(i.hasNext()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines_NoName() { final Option option = buildApacheCommandGroup(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); final List lines = option.helpLines(0, settings, null); final Iterator i = lines.iterator(); final HelpLine line2 = (HelpLine) i.next(); assertEquals(1, line2.getIndent()); assertEquals(COMMAND_GRACEFUL, line2.getOption()); final HelpLine line3 = (HelpLine) i.next(); assertEquals(1, line3.getIndent()); assertEquals(COMMAND_RESTART, line3.getOption()); final HelpLine line4 = (HelpLine) i.next(); assertEquals(1, line4.getIndent()); assertEquals(COMMAND_START, line4.getOption()); final HelpLine line5 = (HelpLine) i.next(); assertEquals(1, line5.getIndent()); assertEquals(COMMAND_STOP, line5.getOption()); assertFalse(i.hasNext()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/GroupTestCase.java b/src/test/org/apache/commons/cli2/option/GroupTestCase.java index 203a3a17b..2a8ca5733 100644 --- a/src/test/org/apache/commons/cli2/option/GroupTestCase.java +++ b/src/test/org/apache/commons/cli2/option/GroupTestCase.java @@ -1,31 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import org.apache.commons.cli2.OptionException; - -/** - * @author Rob Oxspring - */ -public abstract class GroupTestCase - extends OptionTestCase { - public abstract void testProcessOptions() - throws OptionException; - - public abstract void testProcessAnonymousArguments() - throws OptionException; -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import org.apache.commons.cli2.OptionException;/** * @author Rob Oxspring */public abstract class GroupTestCase extends OptionTestCase { public abstract void testProcessOptions() throws OptionException; public abstract void testProcessAnonymousArguments() throws OptionException;} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/NestedGroupTest.java b/src/test/org/apache/commons/cli2/option/NestedGroupTest.java index 5fd8219bb..13622f7bb 100644 --- a/src/test/org/apache/commons/cli2/option/NestedGroupTest.java +++ b/src/test/org/apache/commons/cli2/option/NestedGroupTest.java @@ -1,192 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import org.apache.commons.cli2.CLITestCase; -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import org.apache.commons.cli2.util.HelpFormatter; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; -import java.io.StringWriter; - -import java.util.ArrayList; -import java.util.List; - - -/** - * Test to exercise nested groups developed to demonstrate bug 32533 - */ -public class NestedGroupTest extends CLITestCase { - final static DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - final static ArgumentBuilder abuilder = new ArgumentBuilder(); - final static GroupBuilder gbuilder = new GroupBuilder(); - - static Group buildActionGroup() { - return gbuilder.withName("Action").withDescription("Action") - .withMinimum(1).withMaximum(1) - .withOption(obuilder.withId(5).withShortName("e") - .withLongName("encrypt") - .withDescription("Encrypt input") - .create()) - .withOption(obuilder.withId(6).withShortName("d") - .withLongName("decrypt") - .withDescription("Decrypt input") - .create()).create(); - } - - static Group buildAlgorithmGroup() { - return gbuilder.withName("Algorithm") - .withDescription("Encryption Algorithm").withMaximum(1) - .withOption(obuilder.withId(0).withShortName("b") - .withLongName("blowfish") - .withDescription("Blowfish").create()) - .withOption(obuilder.withId(1).withShortName("3") - .withLongName("3DES") - .withDescription("Triple DES") - .create()).create(); - } - - static Group buildInputGroup() { - return gbuilder.withName("Input").withDescription("Input").withMinimum(1) - .withMaximum(1) - .withOption(obuilder.withId(2).withShortName("f") - .withLongName("file") - .withDescription("Input file") - .withArgument(abuilder.withName( - "file").withMinimum(1).withMaximum(1).create()).create()) - .withOption(obuilder.withId(3).withShortName("s") - .withLongName("string") - .withDescription("Input string") - .withArgument(abuilder.withName( - "string").withMinimum(1).withMaximum(1).create()).create()) - .create(); - } - - static Group buildEncryptionServiceGroup(Group[] nestedGroups) { - gbuilder.withName("encryptionService") - .withOption(obuilder.withId(4).withShortName("h") - .withLongName("help") - .withDescription("Print this message") - .create()).withOption(obuilder.withShortName( - "k").withLongName("key").withDescription("Encryption key") - .create()); - - for (int i = 0; i < nestedGroups.length; i++) { - gbuilder.withOption(nestedGroups[i]); - } - - return gbuilder.create(); - } - - public void testNestedGroup() - throws OptionException { - final String[] args = { - "-eb", - "--file", - "/tmp/filename.txt" - }; - - Group[] nestedGroups = { - buildActionGroup(), - buildAlgorithmGroup(), - buildInputGroup() - }; - - Parser parser = new Parser(); - parser.setGroup(buildEncryptionServiceGroup(nestedGroups)); - - CommandLine commandLine = parser.parse(args); - - assertTrue("/tmp/filename.txt".equals(commandLine.getValue("-f"))); - assertTrue(commandLine.hasOption("-e")); - assertTrue(commandLine.hasOption("-b")); - assertFalse(commandLine.hasOption("-d")); - } - - public void testNestedGroupHelp() { - Group[] nestedGroups = { - buildActionGroup(), - buildAlgorithmGroup(), - buildInputGroup() - }; - - HelpFormatter helpFormatter = new HelpFormatter(); - helpFormatter.setGroup(buildEncryptionServiceGroup(nestedGroups)); - - final StringWriter out = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(out)); - - try { - helpFormatter.print(); - - final BufferedReader bufferedReader = new BufferedReader(new StringReader( - out.toString())); - final String[] expected = new String[] { - "Usage: ", - " [-h -k -e|-d -b|-3 -f |-s ] ", - "encryptionService ", - " -h (--help) Print this message ", - " -k (--key) Encryption key ", - " Action Action ", - " -e (--encrypt) Encrypt input ", - " -d (--decrypt) Decrypt input ", - " Algorithm Encryption Algorithm ", - " -b (--blowfish) Blowfish ", - " -3 (--3DES) Triple DES ", - " Input Input ", - " -f (--file) file Input file ", - " -s (--string) string Input string " - }; - - List actual = new ArrayList(expected.length); - String input; - - while ((input = bufferedReader.readLine()) != null) { - actual.add(input); - } - - // Show they are the same number of lines - assertEquals("Help text lines should be " + expected.length, - actual.size(), expected.length); - - for (int i = 0; i < expected.length; i++) { - if (!expected[i].equals(actual.get(i))) { - for (int x = 0; x < expected.length; i++) { - System.out.println(" " + expected[i]); - System.out.println((expected[i].equals(actual.get(i)) - ? "== " - : "!= ") + actual.get(i)); - } - } - - assertEquals(expected[i], actual.get(i)); - } - } - catch (IOException e) { - fail(e.getLocalizedMessage()); - } - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import org.apache.commons.cli2.CLITestCase;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.util.HelpFormatter;import java.io.BufferedReader;import java.io.IOException;import java.io.PrintWriter;import java.io.StringReader;import java.io.StringWriter;import java.util.ArrayList;import java.util.List;/** * Test to exercise nested groups developed to demonstrate bug 32533 */public class NestedGroupTest extends CLITestCase { final static DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final static ArgumentBuilder abuilder = new ArgumentBuilder(); final static GroupBuilder gbuilder = new GroupBuilder(); static Group buildActionGroup() { return gbuilder.withName("Action").withDescription("Action") .withMinimum(1).withMaximum(1) .withOption(obuilder.withId(5).withShortName("e") .withLongName("encrypt") .withDescription("Encrypt input") .create()) .withOption(obuilder.withId(6).withShortName("d") .withLongName("decrypt") .withDescription("Decrypt input") .create()).create(); } static Group buildAlgorithmGroup() { return gbuilder.withName("Algorithm") .withDescription("Encryption Algorithm").withMaximum(1) .withOption(obuilder.withId(0).withShortName("b") .withLongName("blowfish") .withDescription("Blowfish").create()) .withOption(obuilder.withId(1).withShortName("3") .withLongName("3DES") .withDescription("Triple DES") .create()).create(); } static Group buildInputGroup() { return gbuilder.withName("Input").withDescription("Input").withMinimum(1) .withMaximum(1) .withOption(obuilder.withId(2).withShortName("f") .withLongName("file") .withDescription("Input file") .withArgument(abuilder.withName( "file").withMinimum(1).withMaximum(1).create()).create()) .withOption(obuilder.withId(3).withShortName("s") .withLongName("string") .withDescription("Input string") .withArgument(abuilder.withName( "string").withMinimum(1).withMaximum(1).create()).create()) .create(); } static Group buildEncryptionServiceGroup(Group[] nestedGroups) { gbuilder.withName("encryptionService") .withOption(obuilder.withId(4).withShortName("h") .withLongName("help") .withDescription("Print this message") .create()).withOption(obuilder.withShortName( "k").withLongName("key").withDescription("Encryption key") .create()); for (int i = 0; i < nestedGroups.length; i++) { gbuilder.withOption(nestedGroups[i]); } return gbuilder.create(); } public void testNestedGroup() throws OptionException { final String[] args = { "-eb", "--file", "/tmp/filename.txt" }; Group[] nestedGroups = { buildActionGroup(), buildAlgorithmGroup(), buildInputGroup() }; Parser parser = new Parser(); parser.setGroup(buildEncryptionServiceGroup(nestedGroups)); CommandLine commandLine = parser.parse(args); assertTrue("/tmp/filename.txt".equals(commandLine.getValue("-f"))); assertTrue(commandLine.hasOption("-e")); assertTrue(commandLine.hasOption("-b")); assertFalse(commandLine.hasOption("-d")); } public void testNestedGroupHelp() { Group[] nestedGroups = { buildActionGroup(), buildAlgorithmGroup(), buildInputGroup() }; HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setGroup(buildEncryptionServiceGroup(nestedGroups)); final StringWriter out = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(out)); try { helpFormatter.print(); final BufferedReader bufferedReader = new BufferedReader(new StringReader( out.toString())); final String[] expected = new String[] { "Usage: ", " [-h -k -e|-d -b|-3 -f |-s ] ", "encryptionService ", " -h (--help) Print this message ", " -k (--key) Encryption key ", " Action Action ", " -e (--encrypt) Encrypt input ", " -d (--decrypt) Decrypt input ", " Algorithm Encryption Algorithm ", " -b (--blowfish) Blowfish ", " -3 (--3DES) Triple DES ", " Input Input ", " -f (--file) file Input file ", " -s (--string) string Input string " }; List actual = new ArrayList(expected.length); String input; while ((input = bufferedReader.readLine()) != null) { actual.add(input); } // Show they are the same number of lines assertEquals("Help text lines should be " + expected.length, actual.size(), expected.length); for (int i = 0; i < expected.length; i++) { if (!expected[i].equals(actual.get(i))) { for (int x = 0; x < expected.length; i++) { System.out.println(" " + expected[i]); System.out.println((expected[i].equals(actual.get(i)) ? "== " : "!= ") + actual.get(i)); } } assertEquals(expected[i], actual.get(i)); } } catch (IOException e) { fail(e.getLocalizedMessage()); } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/OptionTestCase.java b/src/test/org/apache/commons/cli2/option/OptionTestCase.java index 8555aae04..e0018e6e5 100644 --- a/src/test/org/apache/commons/cli2/option/OptionTestCase.java +++ b/src/test/org/apache/commons/cli2/option/OptionTestCase.java @@ -1,55 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.List; - -import org.apache.commons.cli2.CLITestCase; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; - -/** - * @author Rob Oxspring - */ -public abstract class OptionTestCase extends CLITestCase { - - public static WriteableCommandLine commandLine( - final Option option, - final List args) { - return new WriteableCommandLineImpl(option, args); - } - - public abstract void testTriggers(); - - public abstract void testPrefixes(); - - public abstract void testCanProcess(); - - public abstract void testProcess() throws OptionException; - - public abstract void testValidate() throws OptionException; - - public abstract void testAppendUsage() throws OptionException; - - public abstract void testGetPreferredName(); - - public abstract void testGetDescription(); - - public abstract void testHelpLines(); -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.List;import org.apache.commons.cli2.CLITestCase;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;/** * @author Rob Oxspring */public abstract class OptionTestCase extends CLITestCase { public static WriteableCommandLine commandLine( final Option option, final List args) { return new WriteableCommandLineImpl(option, args); } public abstract void testTriggers(); public abstract void testPrefixes(); public abstract void testCanProcess(); public abstract void testProcess() throws OptionException; public abstract void testValidate() throws OptionException; public abstract void testAppendUsage() throws OptionException; public abstract void testGetPreferredName(); public abstract void testGetDescription(); public abstract void testHelpLines();} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/ParentTest.java b/src/test/org/apache/commons/cli2/option/ParentTest.java index 94a8a83ad..8fa8d8ca0 100644 --- a/src/test/org/apache/commons/cli2/option/ParentTest.java +++ b/src/test/org/apache/commons/cli2/option/ParentTest.java @@ -1,419 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.HelpLine; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.Parent; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.CommandBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * @author Rob Oxspring - */ -public class ParentTest - extends ParentTestCase { - public static final Argument COMPLEX_ARGUMENT = - new ArgumentBuilder().withName("username").withMinimum(1).withMaximum(1).create(); - public static final Option COMPLEX_CHILD_SSL = - new DefaultOptionBuilder().withLongName("ssl").withShortName("s").create(); - public static final Option COMPLEX_CHILD_BASIC = - new DefaultOptionBuilder().withLongName("basic").withShortName("b").create(); - public static final Option COMPLEX_CHILD_DIGEST = - new DefaultOptionBuilder().withLongName("digest").withShortName("d").create(); - public static final Group COMPLEX_CHILDREN = - new GroupBuilder().withName("login-opts").withOption(COMPLEX_CHILD_BASIC) - .withOption(COMPLEX_CHILD_DIGEST).withOption(COMPLEX_CHILD_SSL).create(); - - public static Parent buildLibParent() { - final Argument argument = ArgumentTest.buildPathArgument(); - - return new DefaultOption("-", "--", false, "--lib", "Specifies library search path", null, - null, false, argument, null, 'l'); - } - - public static Parent buildKParent() { - final Group children = GroupTest.buildApacheCommandGroup(); - - return new DefaultOption("-", "--", false, "-k", "desc", null, null, false, null, children, - 'k'); - } - - public static Parent buildComplexParent() { - return new CommandBuilder().withName("login").withName("lo").withName("l") - .withArgument(COMPLEX_ARGUMENT).withChildren(COMPLEX_CHILDREN) - .create(); - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() - */ - public void testProcessParent() - throws OptionException { - final Parent option = buildKParent(); - final List args = list("-k", "start"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processParent(commandLine, iterator); - - assertEquals("start", iterator.next()); - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("-k")); - assertTrue(commandLine.getValues(option).isEmpty()); - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() - */ - public void testCanProcess() { - final Parent option = buildKParent(); - assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "-k")); - } - - public void testCanProcess_BadMatch() { - final Parent option = buildKParent(); - assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "-K")); - } - - public void testCanProcess_ContractedArgument() { - final Parent option = buildLibParent(); - assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "--lib=/usr/lib")); - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() - */ - public void testPrefixes() { - final Parent option = buildKParent(); - assertContentsEqual(list("-", "--"), option.getPrefixes()); - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.OptionTestCase#testProcess() - */ - public void testProcess() - throws OptionException { - final Parent option = CommandTest.buildStartCommand(); - final List args = list("start"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.process(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("start")); - assertFalse(commandLine.hasOption("stop")); - assertTrue(commandLine.getValues(option).isEmpty()); - } - - public void testProcess_NoMatch() - throws OptionException { - final Parent option = CommandTest.buildStartCommand(); - final List args = list("whatever"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - try { - option.process(commandLine, iterator); - fail("unexpected token not thrown"); - } catch (OptionException exp) { - OptionException e = - new OptionException(option, ResourceConstants.UNEXPECTED_TOKEN, "whatever"); - assertEquals("wrong exception message", e.getMessage(), exp.getMessage()); - } - } - - public void testProcess_Children() - throws OptionException { - final Parent option = buildKParent(); - final List args = list("-k", "start"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.process(commandLine, iterator); - - assertNull(option.findOption("whatever")); - assertNotNull(option.findOption("start")); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("-k")); - assertTrue(commandLine.hasOption("start")); - assertFalse(commandLine.hasOption("stop")); - assertTrue(commandLine.getValues(option).isEmpty()); - } - - public void testProcess_Argument() - throws OptionException { - final Parent option = buildLibParent(); - final List args = list("--lib=C:\\WINDOWS;C:\\WINNT;C:\\"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.process(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("--lib")); - assertContentsEqual(list("C:\\WINDOWS", "C:\\WINNT", "C:\\"), commandLine.getValues(option)); - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.OptionTestCase#testTriggers() - */ - public void testTriggers() { - final Parent option = buildKParent(); - assertContentsEqual(list("-k"), option.getTriggers()); - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.OptionTestCase#testValidate() - */ - public void testValidate() - throws OptionException { - final Parent option = CommandTest.buildStartCommand(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - option.validate(commandLine); - - commandLine.addOption(option); - - option.validate(commandLine); - } - - public void testValidate_Children() - throws OptionException { - final Parent option = buildKParent(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - option.validate(commandLine); - commandLine.addOption(option); - - try { - option.validate(commandLine); - fail("Missing a command"); - } catch (OptionException moe) { - assertNotNull(moe.getOption()); - assertNotSame(option, moe.getOption()); - } - } - - public void testValidate_Argument() - throws OptionException { - final Command option = CommandTest.buildLoginCommand(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - option.validate(commandLine); - - commandLine.addOption(option); - - try { - option.validate(commandLine); - fail("Missing a value"); - } catch (OptionException moe) { - assertSame(option, moe.getOption()); - } - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() - */ - public void testAppendUsage() { - final Option option = buildComplexParent(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); - option.appendUsage(buffer, settings, null); - - assertEquals("[login (l,lo) [login-opts (--basic (-b)|--digest (-d)|--ssl (-s))]]", - buffer.toString()); - } - - public void testAppendUsage_NoArguments() { - final Option option = buildComplexParent(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); - settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); - option.appendUsage(buffer, settings, null); - - assertEquals("[login (l,lo) [login-opts (--basic (-b)|--digest (-d)|--ssl (-s))]]", - buffer.toString()); - } - - public void testAppendUsage_NoChildren() { - final Option option = buildComplexParent(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); - option.appendUsage(buffer, settings, null); - - assertEquals("[login (l,lo) ]", buffer.toString()); - } - - public void testAppendUsage_NoArgumentsOrChildren() { - final Option option = buildComplexParent(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); - settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); - option.appendUsage(buffer, settings, null); - - assertEquals("[login (l,lo)]", buffer.toString()); - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() - */ - public void testGetPreferredName() { - final Option option = buildLibParent(); - assertEquals("--lib", option.getPreferredName()); - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() - */ - public void testGetDescription() { - final Option option = buildLibParent(); - assertEquals("Specifies library search path", option.getDescription()); - } - - /* (non-Javadoc) - * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() - */ - public void testHelpLines() { - final Option option = buildComplexParent(); - final List lines = option.helpLines(0, DisplaySetting.ALL, null); - final Iterator i = lines.iterator(); - - final HelpLine line1 = (HelpLine) i.next(); - assertEquals(0, line1.getIndent()); - assertEquals(option, line1.getOption()); - - final HelpLine line2 = (HelpLine) i.next(); - assertEquals(1, line2.getIndent()); - assertEquals(COMPLEX_ARGUMENT, line2.getOption()); - - final HelpLine line3 = (HelpLine) i.next(); - assertEquals(1, line3.getIndent()); - assertEquals(COMPLEX_CHILDREN, line3.getOption()); - - final HelpLine line4 = (HelpLine) i.next(); - assertEquals(2, line4.getIndent()); - assertEquals(COMPLEX_CHILD_BASIC, line4.getOption()); - - final HelpLine line5 = (HelpLine) i.next(); - assertEquals(2, line5.getIndent()); - assertEquals(COMPLEX_CHILD_DIGEST, line5.getOption()); - - final HelpLine line6 = (HelpLine) i.next(); - assertEquals(2, line6.getIndent()); - assertEquals(COMPLEX_CHILD_SSL, line6.getOption()); - - assertFalse(i.hasNext()); - } - - public void testHelpLines_NoArgument() { - final Option option = buildComplexParent(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); - - final List lines = option.helpLines(0, settings, null); - final Iterator i = lines.iterator(); - - final HelpLine line1 = (HelpLine) i.next(); - assertEquals(0, line1.getIndent()); - assertEquals(option, line1.getOption()); - - final HelpLine line3 = (HelpLine) i.next(); - assertEquals(1, line3.getIndent()); - assertEquals(COMPLEX_CHILDREN, line3.getOption()); - - final HelpLine line4 = (HelpLine) i.next(); - assertEquals(2, line4.getIndent()); - assertEquals(COMPLEX_CHILD_BASIC, line4.getOption()); - - final HelpLine line5 = (HelpLine) i.next(); - assertEquals(2, line5.getIndent()); - assertEquals(COMPLEX_CHILD_DIGEST, line5.getOption()); - - final HelpLine line6 = (HelpLine) i.next(); - assertEquals(2, line6.getIndent()); - assertEquals(COMPLEX_CHILD_SSL, line6.getOption()); - - assertFalse(i.hasNext()); - } - - public void testHelpLines_NoChildren() { - final Option option = buildComplexParent(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); - - final List lines = option.helpLines(0, settings, null); - final Iterator i = lines.iterator(); - - final HelpLine line1 = (HelpLine) i.next(); - assertEquals(0, line1.getIndent()); - assertEquals(option, line1.getOption()); - - final HelpLine line2 = (HelpLine) i.next(); - assertEquals(1, line2.getIndent()); - assertEquals(COMPLEX_ARGUMENT, line2.getOption()); - - assertFalse(i.hasNext()); - } - - public void testNullPreferredName() { - try { - new CommandBuilder().create(); - } catch (IllegalStateException exp) { - assertEquals(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME), exp.getMessage()); - } - } - - public void testRequired() { - Command cmd = new CommandBuilder().withRequired(true).withName("blah").create(); - assertTrue("cmd is not required", cmd.isRequired()); - assertEquals("id is incorrect", 0, cmd.getId()); - } - - public void testID() { - Command cmd = new CommandBuilder().withId('c').withName("blah").create(); - assertEquals("id is incorrect", 'c', cmd.getId()); - } - - public void testGetId() { - assertEquals('h', DefaultOptionTest.buildHelpOption().getId()); - assertEquals('X', DefaultOptionTest.buildXOption().getId()); - assertEquals(0, CommandTest.buildStartCommand().getId()); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.Parent;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.CommandBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * @author Rob Oxspring */public class ParentTest extends ParentTestCase { public static final Argument COMPLEX_ARGUMENT = new ArgumentBuilder().withName("username").withMinimum(1).withMaximum(1).create(); public static final Option COMPLEX_CHILD_SSL = new DefaultOptionBuilder().withLongName("ssl").withShortName("s").create(); public static final Option COMPLEX_CHILD_BASIC = new DefaultOptionBuilder().withLongName("basic").withShortName("b").create(); public static final Option COMPLEX_CHILD_DIGEST = new DefaultOptionBuilder().withLongName("digest").withShortName("d").create(); public static final Group COMPLEX_CHILDREN = new GroupBuilder().withName("login-opts").withOption(COMPLEX_CHILD_BASIC) .withOption(COMPLEX_CHILD_DIGEST).withOption(COMPLEX_CHILD_SSL).create(); public static Parent buildLibParent() { final Argument argument = ArgumentTest.buildPathArgument(); return new DefaultOption("-", "--", false, "--lib", "Specifies library search path", null, null, false, argument, null, 'l'); } public static Parent buildKParent() { final Group children = GroupTest.buildApacheCommandGroup(); return new DefaultOption("-", "--", false, "-k", "desc", null, null, false, null, children, 'k'); } public static Parent buildComplexParent() { return new CommandBuilder().withName("login").withName("lo").withName("l") .withArgument(COMPLEX_ARGUMENT).withChildren(COMPLEX_CHILDREN) .create(); } /* (non-Javadoc) * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() */ public void testProcessParent() throws OptionException { final Parent option = buildKParent(); final List args = list("-k", "start"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertEquals("start", iterator.next()); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("-k")); assertTrue(commandLine.getValues(option).isEmpty()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Parent option = buildKParent(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "-k")); } public void testCanProcess_BadMatch() { final Parent option = buildKParent(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "-K")); } public void testCanProcess_ContractedArgument() { final Parent option = buildLibParent(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "--lib=/usr/lib")); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Parent option = buildKParent(); assertContentsEqual(list("-", "--"), option.getPrefixes()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { final Parent option = CommandTest.buildStartCommand(); final List args = list("start"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("start")); assertFalse(commandLine.hasOption("stop")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcess_NoMatch() throws OptionException { final Parent option = CommandTest.buildStartCommand(); final List args = list("whatever"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.process(commandLine, iterator); fail("unexpected token not thrown"); } catch (OptionException exp) { OptionException e = new OptionException(option, ResourceConstants.UNEXPECTED_TOKEN, "whatever"); assertEquals("wrong exception message", e.getMessage(), exp.getMessage()); } } public void testProcess_Children() throws OptionException { final Parent option = buildKParent(); final List args = list("-k", "start"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertNull(option.findOption("whatever")); assertNotNull(option.findOption("start")); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("-k")); assertTrue(commandLine.hasOption("start")); assertFalse(commandLine.hasOption("stop")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcess_Argument() throws OptionException { final Parent option = buildLibParent(); final List args = list("--lib=C:\\WINDOWS;C:\\WINNT;C:\\"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("--lib")); assertContentsEqual(list("C:\\WINDOWS", "C:\\WINNT", "C:\\"), commandLine.getValues(option)); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Parent option = buildKParent(); assertContentsEqual(list("-k"), option.getTriggers()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() throws OptionException { final Parent option = CommandTest.buildStartCommand(); final WriteableCommandLine commandLine = commandLine(option, list()); option.validate(commandLine); commandLine.addOption(option); option.validate(commandLine); } public void testValidate_Children() throws OptionException { final Parent option = buildKParent(); final WriteableCommandLine commandLine = commandLine(option, list()); option.validate(commandLine); commandLine.addOption(option); try { option.validate(commandLine); fail("Missing a command"); } catch (OptionException moe) { assertNotNull(moe.getOption()); assertNotSame(option, moe.getOption()); } } public void testValidate_Argument() throws OptionException { final Command option = CommandTest.buildLoginCommand(); final WriteableCommandLine commandLine = commandLine(option, list()); option.validate(commandLine); commandLine.addOption(option); try { option.validate(commandLine); fail("Missing a value"); } catch (OptionException moe) { assertSame(option, moe.getOption()); } } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildComplexParent(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); option.appendUsage(buffer, settings, null); assertEquals("[login (l,lo) [login-opts (--basic (-b)|--digest (-d)|--ssl (-s))]]", buffer.toString()); } public void testAppendUsage_NoArguments() { final Option option = buildComplexParent(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); option.appendUsage(buffer, settings, null); assertEquals("[login (l,lo) [login-opts (--basic (-b)|--digest (-d)|--ssl (-s))]]", buffer.toString()); } public void testAppendUsage_NoChildren() { final Option option = buildComplexParent(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); option.appendUsage(buffer, settings, null); assertEquals("[login (l,lo) ]", buffer.toString()); } public void testAppendUsage_NoArgumentsOrChildren() { final Option option = buildComplexParent(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); option.appendUsage(buffer, settings, null); assertEquals("[login (l,lo)]", buffer.toString()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildLibParent(); assertEquals("--lib", option.getPreferredName()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildLibParent(); assertEquals("Specifies library search path", option.getDescription()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { final Option option = buildComplexParent(); final List lines = option.helpLines(0, DisplaySetting.ALL, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); final HelpLine line2 = (HelpLine) i.next(); assertEquals(1, line2.getIndent()); assertEquals(COMPLEX_ARGUMENT, line2.getOption()); final HelpLine line3 = (HelpLine) i.next(); assertEquals(1, line3.getIndent()); assertEquals(COMPLEX_CHILDREN, line3.getOption()); final HelpLine line4 = (HelpLine) i.next(); assertEquals(2, line4.getIndent()); assertEquals(COMPLEX_CHILD_BASIC, line4.getOption()); final HelpLine line5 = (HelpLine) i.next(); assertEquals(2, line5.getIndent()); assertEquals(COMPLEX_CHILD_DIGEST, line5.getOption()); final HelpLine line6 = (HelpLine) i.next(); assertEquals(2, line6.getIndent()); assertEquals(COMPLEX_CHILD_SSL, line6.getOption()); assertFalse(i.hasNext()); } public void testHelpLines_NoArgument() { final Option option = buildComplexParent(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); final List lines = option.helpLines(0, settings, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); final HelpLine line3 = (HelpLine) i.next(); assertEquals(1, line3.getIndent()); assertEquals(COMPLEX_CHILDREN, line3.getOption()); final HelpLine line4 = (HelpLine) i.next(); assertEquals(2, line4.getIndent()); assertEquals(COMPLEX_CHILD_BASIC, line4.getOption()); final HelpLine line5 = (HelpLine) i.next(); assertEquals(2, line5.getIndent()); assertEquals(COMPLEX_CHILD_DIGEST, line5.getOption()); final HelpLine line6 = (HelpLine) i.next(); assertEquals(2, line6.getIndent()); assertEquals(COMPLEX_CHILD_SSL, line6.getOption()); assertFalse(i.hasNext()); } public void testHelpLines_NoChildren() { final Option option = buildComplexParent(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); final List lines = option.helpLines(0, settings, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); final HelpLine line2 = (HelpLine) i.next(); assertEquals(1, line2.getIndent()); assertEquals(COMPLEX_ARGUMENT, line2.getOption()); assertFalse(i.hasNext()); } public void testNullPreferredName() { try { new CommandBuilder().create(); } catch (IllegalStateException exp) { assertEquals(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME), exp.getMessage()); } } public void testRequired() { Command cmd = new CommandBuilder().withRequired(true).withName("blah").create(); assertTrue("cmd is not required", cmd.isRequired()); assertEquals("id is incorrect", 0, cmd.getId()); } public void testID() { Command cmd = new CommandBuilder().withId('c').withName("blah").create(); assertEquals("id is incorrect", 'c', cmd.getId()); } public void testGetId() { assertEquals('h', DefaultOptionTest.buildHelpOption().getId()); assertEquals('X', DefaultOptionTest.buildXOption().getId()); assertEquals(0, CommandTest.buildStartCommand().getId()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/ParentTestCase.java b/src/test/org/apache/commons/cli2/option/ParentTestCase.java index e6e0db717..d4d19770c 100644 --- a/src/test/org/apache/commons/cli2/option/ParentTestCase.java +++ b/src/test/org/apache/commons/cli2/option/ParentTestCase.java @@ -1,26 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import org.apache.commons.cli2.OptionException; - -/** - * @author Rob Oxspring - */ -public abstract class ParentTestCase extends OptionTestCase { - public abstract void testProcessParent() throws OptionException; -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import org.apache.commons.cli2.OptionException;/** * @author Rob Oxspring */public abstract class ParentTestCase extends OptionTestCase { public abstract void testProcessParent() throws OptionException;} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java b/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java index 196e315a8..4116ddb22 100644 --- a/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java +++ b/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java @@ -1,233 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.HelpLine; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; - -/** - * @author Rob Oxspring - */ -public class PropertyOptionTest extends OptionTestCase { - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() - */ - public void testCanProcess() { - final Option option = new PropertyOption(); - assertTrue(option.canProcess(new WriteableCommandLineImpl(option,null), "-Dmyprop=myval")); - } - - public void testCanProcess_Null() { - final Option option = new PropertyOption(); - assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), (String) null)); - } - - public void testCanProcess_TooShort() { - final Option option = new PropertyOption(); - assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), "-D")); - } - - public void testCanProcess_BadMatch() { - final Option option = new PropertyOption(); - assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null),"-dump")); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() - */ - public void testPrefixes() { - final Option option = new PropertyOption(); - assertContentsEqual(list("-D"), option.getPrefixes()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testProcess() - */ - public void testProcess() throws OptionException { - final Option option = new PropertyOption(); - final List args = list("-Dmyprop=myvalue"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - option.process(commandLine, iterator); - assertEquals("myvalue", commandLine.getProperty("myprop")); - assertFalse(iterator.hasNext()); - assertEquals(1, commandLine.getProperties().size()); - } - - public void testProcess_UnexpectedOptionException() { - final Option option = new PropertyOption(); - final List args = list("--help"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - try { - option.process(commandLine, iterator); - fail("UnexpectedOption"); - } - catch (final OptionException uoe) { - assertEquals(option, uoe.getOption()); - assertEquals( - "Unexpected --help while processing -Dproperty=value", - uoe.getMessage()); - } - } - - public void testProcess_BadPropertyException() throws OptionException { - final Option option = new PropertyOption(); - final List args = list("-Dmyprop"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - option.process(commandLine, iterator); - - assertEquals("true", commandLine.getProperty("myprop")); - } - - public void testProcess_SetToEmpty() throws OptionException { - final Option option = new PropertyOption(); - final List args = list("-Dmyprop="); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - option.process(commandLine, iterator); - assertEquals("", commandLine.getProperty("myprop")); - assertFalse(iterator.hasNext()); - assertEquals(1, commandLine.getProperties().size()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testTriggers() - */ - public void testTriggers() { - final Option option = new PropertyOption(); - - assertContentsEqual(list("-D"), option.getTriggers()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testValidate() - */ - public void testValidate() throws OptionException { - final Option option = new PropertyOption(); - final List args = list("-Dproperty=value"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - - option.process(commandLine, iterator); - - option.validate(commandLine); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() - */ - public void testAppendUsage() { - final Option option = new PropertyOption(); - final StringBuffer buffer = new StringBuffer(); - option.appendUsage(buffer, DisplaySetting.ALL, null); - - assertEquals("-D=", buffer.toString()); - } - - public void testAppendUsage_Hidden() { - final Option option = new PropertyOption(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_PROPERTY_OPTION); - option.appendUsage(buffer, settings, null); - - assertEquals("", buffer.toString()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() - */ - public void testGetPreferredName() { - final Option option = new PropertyOption(); - assertEquals("-D", option.getPreferredName()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() - */ - public void testGetDescription() { - final Option option = new PropertyOption(); - assertEquals( - "Passes properties and values to the application", - option.getDescription()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() - */ - public void testHelpLines() { - final Option option = new PropertyOption(); - final List lines = option.helpLines(0, DisplaySetting.ALL, null); - final Iterator i = lines.iterator(); - - final HelpLine line1 = (HelpLine)i.next(); - assertEquals(0, line1.getIndent()); - assertEquals(option, line1.getOption()); - - assertFalse(i.hasNext()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() - */ - public void testHelpLines_NoDisplay() { - final Option option = new PropertyOption(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_PROPERTY_OPTION); - final List lines = option.helpLines(0, settings, null); - final Iterator i = lines.iterator(); - - assertFalse(i.hasNext()); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;/** * @author Rob Oxspring */public class PropertyOptionTest extends OptionTestCase { /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Option option = new PropertyOption(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option,null), "-Dmyprop=myval")); } public void testCanProcess_Null() { final Option option = new PropertyOption(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), (String) null)); } public void testCanProcess_TooShort() { final Option option = new PropertyOption(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), "-D")); } public void testCanProcess_BadMatch() { final Option option = new PropertyOption(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null),"-dump")); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Option option = new PropertyOption(); assertContentsEqual(list("-D"), option.getPrefixes()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { final Option option = new PropertyOption(); final List args = list("-Dmyprop=myvalue"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertEquals("myvalue", commandLine.getProperty("myprop")); assertFalse(iterator.hasNext()); assertEquals(1, commandLine.getProperties().size()); } public void testProcess_UnexpectedOptionException() { final Option option = new PropertyOption(); final List args = list("--help"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.process(commandLine, iterator); fail("UnexpectedOption"); } catch (final OptionException uoe) { assertEquals(option, uoe.getOption()); assertEquals( "Unexpected --help while processing -Dproperty=value", uoe.getMessage()); } } public void testProcess_BadPropertyException() throws OptionException { final Option option = new PropertyOption(); final List args = list("-Dmyprop"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertEquals("true", commandLine.getProperty("myprop")); } public void testProcess_SetToEmpty() throws OptionException { final Option option = new PropertyOption(); final List args = list("-Dmyprop="); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertEquals("", commandLine.getProperty("myprop")); assertFalse(iterator.hasNext()); assertEquals(1, commandLine.getProperties().size()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Option option = new PropertyOption(); assertContentsEqual(list("-D"), option.getTriggers()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() throws OptionException { final Option option = new PropertyOption(); final List args = list("-Dproperty=value"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); option.validate(commandLine); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = new PropertyOption(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("-D=", buffer.toString()); } public void testAppendUsage_Hidden() { final Option option = new PropertyOption(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PROPERTY_OPTION); option.appendUsage(buffer, settings, null); assertEquals("", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = new PropertyOption(); assertEquals("-D", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = new PropertyOption(); assertEquals( "Passes properties and values to the application", option.getDescription()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { final Option option = new PropertyOption(); final List lines = option.helpLines(0, DisplaySetting.ALL, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine)i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); assertFalse(i.hasNext()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines_NoDisplay() { final Option option = new PropertyOption(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PROPERTY_OPTION); final List lines = option.helpLines(0, settings, null); final Iterator i = lines.iterator(); assertFalse(i.hasNext()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/option/SwitchTest.java b/src/test/org/apache/commons/cli2/option/SwitchTest.java index b3dd9658c..20a75aa8b 100644 --- a/src/test/org/apache/commons/cli2/option/SwitchTest.java +++ b/src/test/org/apache/commons/cli2/option/SwitchTest.java @@ -1,308 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.option; - -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.Parent; -import org.apache.commons.cli2.WriteableCommandLine; -import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * @author Rob Oxspring - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class SwitchTest - extends ParentTestCase { - public static Switch buildDisplaySwitch() { - final Set aliases = new HashSet(); - aliases.add("d"); - aliases.add("disp"); - - return new Switch("+", "-", "display", aliases, "Sets whether to display to screen", true, - null, null, 'd', null); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() - */ - public void testProcessParent() - throws OptionException { - final Switch option = buildDisplaySwitch(); - final List args = list("+d"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.processParent(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("+d")); - assertTrue(commandLine.hasOption("-display")); - assertEquals(Boolean.TRUE, commandLine.getSwitch("-d")); - assertTrue(commandLine.getValues(option).isEmpty()); - } - - public void testProcessParent_Disabled() - throws OptionException { - final Switch option = buildDisplaySwitch(); - final List args = list("-disp"); - final WriteableCommandLine commandLine = commandLine(option, args); - final ListIterator iterator = args.listIterator(); - option.process(commandLine, iterator); - - assertFalse(iterator.hasNext()); - assertTrue(commandLine.hasOption(option)); - assertTrue(commandLine.hasOption("+d")); - assertTrue(commandLine.hasOption("-display")); - assertEquals(Boolean.FALSE, commandLine.getSwitch("-d")); - assertTrue(commandLine.getValues(option).isEmpty()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() - */ - public void testCanProcess() { - final Switch option = buildDisplaySwitch(); - assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "+d")); - } - - public void testCanProcess_BadMatch() { - final Switch option = buildDisplaySwitch(); - assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "-dont")); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() - */ - public void testPrefixes() { - final Switch option = buildDisplaySwitch(); - assertContentsEqual(list("-", "+"), option.getPrefixes()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testProcess() - */ - public void testProcess() { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testTriggers() - */ - public void testTriggers() { - final Switch option = buildDisplaySwitch(); - assertContentsEqual(list("-d", "+d", "-disp", "+disp", "+display", "-display"), - option.getTriggers()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testValidate() - */ - public void testValidate() { - final Parent option = buildDisplaySwitch(); - final WriteableCommandLine commandLine = commandLine(option, list()); - - try { - option.validate(commandLine); - fail("Missing an option"); - } catch (OptionException moe) { - assertSame(option, moe.getOption()); - } - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() - */ - public void testAppendUsage() { - final Option option = buildDisplaySwitch(); - final StringBuffer buffer = new StringBuffer(); - option.appendUsage(buffer, DisplaySetting.ALL, null); - - assertEquals("+display|-display (+d|-d,+disp|-disp)", buffer.toString()); - } - - public void testAppendUsage_NoAlias() { - final Option option = buildDisplaySwitch(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_ALIASES); - option.appendUsage(buffer, settings, null); - - assertEquals("+display|-display", buffer.toString()); - } - - public void testAppendUsage_NoDisabled() { - final Option option = buildDisplaySwitch(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_SWITCH_DISABLED); - option.appendUsage(buffer, settings, null); - - assertEquals("+display (+d,+disp)", buffer.toString()); - } - - public void testAppendUsage_NoEnabled() { - final Option option = buildDisplaySwitch(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_SWITCH_ENABLED); - option.appendUsage(buffer, settings, null); - - assertEquals("-display (-d,-disp)", buffer.toString()); - } - - public void testAppendUsage_NoDisabledOrEnabled() { - final Option option = buildDisplaySwitch(); - final StringBuffer buffer = new StringBuffer(); - final Set settings = new HashSet(DisplaySetting.ALL); - settings.remove(DisplaySetting.DISPLAY_SWITCH_DISABLED); - settings.remove(DisplaySetting.DISPLAY_SWITCH_ENABLED); - option.appendUsage(buffer, settings, null); - - assertEquals("+display (+d,+disp)", buffer.toString()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() - */ - public void testGetPreferredName() { - final Option option = buildDisplaySwitch(); - assertEquals("+display", option.getPreferredName()); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() - */ - public void testGetDescription() { - final Option option = buildDisplaySwitch(); - assertEquals("Sets whether to display to screen", option.getDescription()); - } - - public void testNullPreferredName() { - try { - new Switch("+", "-", null, null, "Sets whether to display to screen", true, null, null, - 'd', null); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), - exp.getMessage()); - } - } - - public void testEmptyPreferredName() { - try { - new Switch("+", "-", "", null, "Sets whether to display to screen", true, null, null, - 'd', null); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), - exp.getMessage()); - } - } - - public void testNullAliases() { - try { - new Switch("+", "-", "display", null, "Sets whether to display to screen", true, null, - null, 'd', null); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), - exp.getMessage()); - } - } - - public void testNullEnablePrefix() { - try { - new Switch(null, "-", "display", null, "Sets whether to display to screen", true, null, - null, 'd', null); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_NO_ENABLED_PREFIX), - exp.getMessage()); - } - } - - public void testNullDisablePrefix() { - try { - new Switch("+", null, "display", null, "Sets whether to display to screen", true, null, - null, 'd', null); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_NO_DISABLED_PREFIX), - exp.getMessage()); - } - } - - public void testEnabledPrefixStartsWithDisabledPrefix() { - try { - new Switch("-", "-", "display", null, "Sets whether to display to screen", true, null, - null, 'd', null); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ENABLED_STARTS_WITH_DISABLED), - exp.getMessage()); - } - } - - public void testDisabledPrefixStartsWithEnabledPrefix() { - try { - new Switch("o", "on", "display", null, "Sets whether to display to screen", true, null, - null, 'd', null); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_DISABLED_STARTWS_WITH_ENABLED), - exp.getMessage()); - } - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() - */ - public void testHelpLines() { - // TODO Auto-generated method stub - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.HashSet;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.Parent;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * @author Rob Oxspring * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */public class SwitchTest extends ParentTestCase { public static Switch buildDisplaySwitch() { final Set aliases = new HashSet(); aliases.add("d"); aliases.add("disp"); return new Switch("+", "-", "display", aliases, "Sets whether to display to screen", true, null, null, 'd', null); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() */ public void testProcessParent() throws OptionException { final Switch option = buildDisplaySwitch(); final List args = list("+d"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("+d")); assertTrue(commandLine.hasOption("-display")); assertEquals(Boolean.TRUE, commandLine.getSwitch("-d")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcessParent_Disabled() throws OptionException { final Switch option = buildDisplaySwitch(); final List args = list("-disp"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("+d")); assertTrue(commandLine.hasOption("-display")); assertEquals(Boolean.FALSE, commandLine.getSwitch("-d")); assertTrue(commandLine.getValues(option).isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Switch option = buildDisplaySwitch(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "+d")); } public void testCanProcess_BadMatch() { final Switch option = buildDisplaySwitch(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "-dont")); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Switch option = buildDisplaySwitch(); assertContentsEqual(list("-", "+"), option.getPrefixes()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Switch option = buildDisplaySwitch(); assertContentsEqual(list("-d", "+d", "-disp", "+disp", "+display", "-display"), option.getTriggers()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() { final Parent option = buildDisplaySwitch(); final WriteableCommandLine commandLine = commandLine(option, list()); try { option.validate(commandLine); fail("Missing an option"); } catch (OptionException moe) { assertSame(option, moe.getOption()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildDisplaySwitch(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("+display|-display (+d|-d,+disp|-disp)", buffer.toString()); } public void testAppendUsage_NoAlias() { final Option option = buildDisplaySwitch(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_ALIASES); option.appendUsage(buffer, settings, null); assertEquals("+display|-display", buffer.toString()); } public void testAppendUsage_NoDisabled() { final Option option = buildDisplaySwitch(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_SWITCH_DISABLED); option.appendUsage(buffer, settings, null); assertEquals("+display (+d,+disp)", buffer.toString()); } public void testAppendUsage_NoEnabled() { final Option option = buildDisplaySwitch(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_SWITCH_ENABLED); option.appendUsage(buffer, settings, null); assertEquals("-display (-d,-disp)", buffer.toString()); } public void testAppendUsage_NoDisabledOrEnabled() { final Option option = buildDisplaySwitch(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_SWITCH_DISABLED); settings.remove(DisplaySetting.DISPLAY_SWITCH_ENABLED); option.appendUsage(buffer, settings, null); assertEquals("+display (+d,+disp)", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildDisplaySwitch(); assertEquals("+display", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildDisplaySwitch(); assertEquals("Sets whether to display to screen", option.getDescription()); } public void testNullPreferredName() { try { new Switch("+", "-", null, null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), exp.getMessage()); } } public void testEmptyPreferredName() { try { new Switch("+", "-", "", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), exp.getMessage()); } } public void testNullAliases() { try { new Switch("+", "-", "display", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), exp.getMessage()); } } public void testNullEnablePrefix() { try { new Switch(null, "-", "display", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_NO_ENABLED_PREFIX), exp.getMessage()); } } public void testNullDisablePrefix() { try { new Switch("+", null, "display", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_NO_DISABLED_PREFIX), exp.getMessage()); } } public void testEnabledPrefixStartsWithDisabledPrefix() { try { new Switch("-", "-", "display", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ENABLED_STARTS_WITH_DISABLED), exp.getMessage()); } } public void testDisabledPrefixStartsWithEnabledPrefix() { try { new Switch("o", "on", "display", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_DISABLED_STARTWS_WITH_ENABLED), exp.getMessage()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { // TODO Auto-generated method stub }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java b/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java index 38223d79b..2fd3cdd08 100644 --- a/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java +++ b/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java @@ -1,84 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.commons.cli2.resource; - -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -import junit.framework.TestCase; - -/** - * A utility class used to provide internationalisation support. - * - * @author John Keyes - */ -public class ResourceHelperTest extends TestCase { - /** system property */ - private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle"; - - private static ResourceHelper helper; - - /** resource bundle */ - private ResourceBundle bundle; - - public void setUp() { - System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.TestBundle"); - helper = ResourceHelper.getResourceHelper(); - } - - public void tearDown() { - System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.CLIMessageBundle_en_US.properties"); - } - - /** - * Create a new ResourceHelper for the specified class. - * - * @param clazz the Class that requires some resources - */ - public ResourceHelperTest() { - super("ResourceHelperTest"); - } - - public void testOverridden() { - assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); - } - - public void testNewMessage1Param() { - assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message")); - } - - public void testNewMessage2Params() { - assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some")); - } - - public void testNewMessage3Params() { - assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might")); - } - - public void testNewMessage4Params() { - assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might", "say")); - } - - public void testDefaultBundle() { - System.setProperty(PROP_LOCALE, "madeupname.properties"); - helper = ResourceHelper.getResourceHelper(); - assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.commons.cli2.resource;import java.util.Locale;import java.util.MissingResourceException;import java.util.ResourceBundle;import junit.framework.TestCase;/** * A utility class used to provide internationalisation support. * * @author John Keyes */public class ResourceHelperTest extends TestCase { /** system property */ private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle"; private static ResourceHelper helper; /** resource bundle */ private ResourceBundle bundle; public void setUp() { System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.TestBundle"); helper = ResourceHelper.getResourceHelper(); } public void tearDown() { System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.CLIMessageBundle_en_US.properties"); } /** * Create a new ResourceHelper for the specified class. * * @param clazz the Class that requires some resources */ public ResourceHelperTest() { super("ResourceHelperTest"); } public void testOverridden() { assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); } public void testNewMessage1Param() { assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message")); } public void testNewMessage2Params() { assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some")); } public void testNewMessage3Params() { assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might")); } public void testNewMessage4Params() { assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might", "say")); } public void testDefaultBundle() { System.setProperty(PROP_LOCALE, "madeupname.properties"); helper = ResourceHelper.getResourceHelper(); assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/util/ComparatorsTest.java b/src/test/org/apache/commons/cli2/util/ComparatorsTest.java index b8e0a25cf..5d53ec2c5 100644 --- a/src/test/org/apache/commons/cli2/util/ComparatorsTest.java +++ b/src/test/org/apache/commons/cli2/util/ComparatorsTest.java @@ -1,221 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.util; - -import java.util.Collections; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.CLITestCase; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.option.CommandTest; -import org.apache.commons.cli2.option.DefaultOptionTest; -import org.apache.commons.cli2.option.GroupTest; -import org.apache.commons.cli2.option.ParentTest; -import org.apache.commons.cli2.option.SwitchTest; - -/** - * @author Rob Oxspring - */ -public class ComparatorsTest extends TestCase { - public void testGroupFirst() { - final Option o1 = GroupTest.buildAntGroup(); - final Option o2 = ParentTest.buildLibParent(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.groupFirst()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o1, o2), - list); - } - - public void testGroupLast() { - final Option o1 = GroupTest.buildAntGroup(); - final Option o2 = ParentTest.buildLibParent(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.groupLast()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o2, o1), - list); - } - - public void testSwitchFirst() { - final Option o1 = SwitchTest.buildDisplaySwitch(); - final Option o2 = ParentTest.buildLibParent(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.switchFirst()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o1, o2), - list); - } - - public void testSwitchLast() { - final Option o1 = SwitchTest.buildDisplaySwitch(); - final Option o2 = ParentTest.buildLibParent(); - //final Option o3 = new SwitchBuilder().withName("hidden").create(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.switchLast()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o2, o1), - list); - } - - public void testCommandFirst() { - final Option o1 = CommandTest.buildCommitCommand(); - final Option o2 = ParentTest.buildLibParent(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.commandFirst()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o1, o2), - list); - } - - public void testCommandLast() { - final Option o1 = CommandTest.buildCommitCommand(); - final Option o2 = ParentTest.buildLibParent(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.commandLast()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o2, o1), - list); - } - - public void testDefaultOptionFirst() { - final Option o1 = DefaultOptionTest.buildHelpOption(); - final Option o2 = CommandTest.buildCommitCommand(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.defaultOptionFirst()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o1, o2), - list); - } - - public void testDefaultOptionLast() { - final Option o1 = DefaultOptionTest.buildHelpOption(); - final Option o2 = CommandTest.buildCommitCommand(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.defaultOptionLast()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o2, o1), - list); - } - - public void testNamedFirst() { - final Option o1 = DefaultOptionTest.buildHelpOption(); - final Option o2 = ParentTest.buildLibParent(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.namedFirst("--help")); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o1, o2), - list); - } - - public void testNamedLast() { - final Option o1 = DefaultOptionTest.buildHelpOption(); - final Option o2 = ParentTest.buildLibParent(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.namedLast("--help")); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o2, o1), - list); - } - - public void testPreferredNameFirst() { - final Option o1 = DefaultOptionTest.buildHelpOption(); - final Option o2 = ParentTest.buildLibParent(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.preferredNameFirst()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o1, o2), - list); - } - - public void testPreferredNameLast() { - final Option o1 = DefaultOptionTest.buildHelpOption(); - final Option o2 = ParentTest.buildLibParent(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.preferredNameLast()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o2, o1), - list); - } - - public void testRequiredFirst() { - final Option o1 = DefaultOptionTest.buildHelpOption(); - final Option o2 = DefaultOptionTest.buildXOption(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.requiredFirst()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o2, o1), - list); - } - - public void testRequiredLast() { - final Option o1 = DefaultOptionTest.buildHelpOption(); - final Option o2 = DefaultOptionTest.buildXOption(); - final List list = CLITestCase.list(o1, o2); - - Collections.sort(list, Comparators.requiredLast()); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o1, o2), - list); - } - - public void testChained() { - final Option o1 = CommandTest.buildCommitCommand(); - final Option o2 = SwitchTest.buildDisplaySwitch(); - final Option o3 = DefaultOptionTest.buildHelpOption(); - final List list = CLITestCase.list(o1, o2, o3); - - Collections.sort( - list, - Comparators.chain( - Comparators.namedFirst("--help"), - Comparators.commandFirst())); - - CLITestCase.assertListContentsEqual( - CLITestCase.list(o3, o1, o2), - list); - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.util;import java.util.Collections;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.CLITestCase;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.option.CommandTest;import org.apache.commons.cli2.option.DefaultOptionTest;import org.apache.commons.cli2.option.GroupTest;import org.apache.commons.cli2.option.ParentTest;import org.apache.commons.cli2.option.SwitchTest;/** * @author Rob Oxspring */public class ComparatorsTest extends TestCase { public void testGroupFirst() { final Option o1 = GroupTest.buildAntGroup(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.groupFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testGroupLast() { final Option o1 = GroupTest.buildAntGroup(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.groupLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testSwitchFirst() { final Option o1 = SwitchTest.buildDisplaySwitch(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.switchFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testSwitchLast() { final Option o1 = SwitchTest.buildDisplaySwitch(); final Option o2 = ParentTest.buildLibParent(); //final Option o3 = new SwitchBuilder().withName("hidden").create(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.switchLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testCommandFirst() { final Option o1 = CommandTest.buildCommitCommand(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.commandFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testCommandLast() { final Option o1 = CommandTest.buildCommitCommand(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.commandLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testDefaultOptionFirst() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = CommandTest.buildCommitCommand(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.defaultOptionFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testDefaultOptionLast() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = CommandTest.buildCommitCommand(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.defaultOptionLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testNamedFirst() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.namedFirst("--help")); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testNamedLast() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.namedLast("--help")); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testPreferredNameFirst() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.preferredNameFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testPreferredNameLast() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.preferredNameLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testRequiredFirst() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = DefaultOptionTest.buildXOption(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.requiredFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testRequiredLast() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = DefaultOptionTest.buildXOption(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.requiredLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testChained() { final Option o1 = CommandTest.buildCommitCommand(); final Option o2 = SwitchTest.buildDisplaySwitch(); final Option o3 = DefaultOptionTest.buildHelpOption(); final List list = CLITestCase.list(o1, o2, o3); Collections.sort( list, Comparators.chain( Comparators.namedFirst("--help"), Comparators.commandFirst())); CLITestCase.assertListContentsEqual( CLITestCase.list(o3, o1, o2), list); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java b/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java index 4b2d8e4dc..62dd7b755 100644 --- a/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java +++ b/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java @@ -1,545 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.commons.cli2.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; -import java.io.StringWriter; - -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.DisplaySetting; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.Option; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.option.ArgumentTest; -import org.apache.commons.cli2.option.DefaultOptionTest; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -public class HelpFormatterTest - extends TestCase { - private ResourceHelper resources = ResourceHelper.getResourceHelper(); - private HelpFormatter helpFormatter; - private Option verbose; - private Group options; - - public void setUp() { - helpFormatter = new HelpFormatter("|*", "*-*", "*|", 80); - helpFormatter.setDivider("+------------------------------------------------------------------------------+"); - helpFormatter.setHeader("Apache Commons CLI"); - helpFormatter.setFooter("Copyright 2003\nApache Software Foundation"); - helpFormatter.setShellCommand("ant"); - - verbose = - new DefaultOptionBuilder().withLongName("verbose") - .withDescription("print the version information and exit") - .create(); - - options = - new GroupBuilder().withName("options").withOption(DefaultOptionTest.buildHelpOption()) - .withOption(ArgumentTest.buildTargetsArgument()) - .withOption(new DefaultOptionBuilder().withLongName("diagnostics") - .withDescription("print information that might be helpful to diagnose or report problems.") - .create()) - .withOption(new DefaultOptionBuilder().withLongName("projecthelp") - .withDescription("print project help information") - .create()).withOption(verbose) - .create(); - - helpFormatter.setGroup(options); - } - - public void testPrint() - throws IOException { - final StringWriter writer = new StringWriter(); - final PrintWriter pw = new PrintWriter(writer); - helpFormatter.setPrintWriter(pw); - helpFormatter.print(); - - // test shell - assertEquals("incorrect shell command", "ant", helpFormatter.getShellCommand()); - - // test group - assertEquals("incorrect group", this.options, helpFormatter.getGroup()); - - // test pagewidth - assertEquals("incorrect page width", 76, helpFormatter.getPageWidth()); - - // test pw - assertEquals("incorrect print writer", pw, helpFormatter.getPrintWriter()); - - // test divider - assertEquals("incorrect divider", - "+------------------------------------------------------------------------------+", - helpFormatter.getDivider()); - - // test header - assertEquals("incorrect header", "Apache Commons CLI", helpFormatter.getHeader()); - - // test footer - assertEquals("incorrect footer", "Copyright 2003\nApache Software Foundation", - helpFormatter.getFooter()); - - // test gutters - assertEquals("incorrect left gutter", "|*", helpFormatter.getGutterLeft()); - assertEquals("incorrect right gutter", "*|", helpFormatter.getGutterRight()); - assertEquals("incorrect center gutter", "*-*", helpFormatter.getGutterCenter()); - - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*Apache Commons CLI *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*Usage: *|", - reader.readLine()); - assertEquals("|*ant [--help --diagnostics --projecthelp --verbose] [ [ *|", - reader.readLine()); - assertEquals("|*...]] *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*options *-* *|", - reader.readLine()); - assertEquals("|* --help (-?,-h) *-*Displays the help *|", - reader.readLine()); - assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", - reader.readLine()); - assertEquals("|* *-*or report problems. *|", - reader.readLine()); - assertEquals("|* --projecthelp *-*print project help information *|", - reader.readLine()); - assertEquals("|* --verbose *-*print the version information and exit *|", - reader.readLine()); - assertEquals("|* target [target ...]*-*The targets ant should build *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*Copyright 2003 *|", - reader.readLine()); - assertEquals("|*Apache Software Foundation *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertNull(reader.readLine()); - } - - public void testComparator() - throws IOException { - final StringWriter writer = new StringWriter(); - final PrintWriter pw = new PrintWriter(writer); - helpFormatter.setPrintWriter(pw); - - final Comparator comparator = new OptionComparator(); - helpFormatter.setComparator(comparator); - helpFormatter.print(); - - // test comparator - assertEquals("invalid comparator", comparator, helpFormatter.getComparator()); - - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*Apache Commons CLI *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*Usage: *|", - reader.readLine()); - assertEquals("|*ant [--verbose --projecthelp --help --diagnostics] [ [ *|", - reader.readLine()); - assertEquals("|*...]] *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*options *-* *|", - reader.readLine()); - assertEquals("|* --verbose *-*print the version information and exit *|", - reader.readLine()); - assertEquals("|* --projecthelp *-*print project help information *|", - reader.readLine()); - assertEquals("|* --help (-?,-h) *-*Displays the help *|", - reader.readLine()); - assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", - reader.readLine()); - assertEquals("|* *-*or report problems. *|", - reader.readLine()); - assertEquals("|* target [target ...]*-*The targets ant should build *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*Copyright 2003 *|", - reader.readLine()); - assertEquals("|*Apache Software Foundation *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertNull(reader.readLine()); - } - - public void testPrintHelp() - throws IOException { - final StringWriter writer = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(writer)); - helpFormatter.printHelp(); - - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*options *-* *|", - reader.readLine()); - assertEquals("|* --help (-?,-h) *-*Displays the help *|", - reader.readLine()); - assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", - reader.readLine()); - assertEquals("|* *-*or report problems. *|", - reader.readLine()); - assertEquals("|* --projecthelp *-*print project help information *|", - reader.readLine()); - assertEquals("|* --verbose *-*print the version information and exit *|", - reader.readLine()); - assertEquals("|* target [target ...]*-*The targets ant should build *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertNull(reader.readLine()); - } - - public void testPrintHelp_WithException() - throws IOException { - final StringWriter writer = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(writer)); - helpFormatter.setException(new OptionException(verbose)); - helpFormatter.printHelp(); - - //System.out.println(writer); - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*--verbose*-*print the version information and exit *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertNull(reader.readLine()); - } - - public void testPrintHelp_TooNarrow() - throws IOException { - final StringWriter writer = new StringWriter(); - helpFormatter = new HelpFormatter("<", "=", ">", 4); - helpFormatter.setGroup(options); - helpFormatter.setPrintWriter(new PrintWriter(writer)); - helpFormatter.printHelp(); - - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("", reader.readLine()); - assertEquals("< --help (-?,-h) =D>", reader.readLine()); - assertEquals("< =i>", reader.readLine()); - - // lots more lines unchecked - } - - public void testPrintException() - throws IOException { - final StringWriter writer = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(writer)); - helpFormatter.setException(new OptionException(verbose, ResourceConstants.MISSING_OPTION)); - helpFormatter.printException(); - - //System.out.println(writer); - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*Missing option --verbose *|", - reader.readLine()); - assertNull(reader.readLine()); - } - - public void testPrintUsage() - throws IOException { - final StringWriter writer = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(writer)); - helpFormatter.printUsage(); - - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*Usage: *|", - reader.readLine()); - assertEquals("|*ant [--help --diagnostics --projecthelp --verbose] [ [ *|", - reader.readLine()); - assertEquals("|*...]] *|", - reader.readLine()); - assertNull(reader.readLine()); - } - - public void testPrintHeader() - throws IOException { - final StringWriter writer = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(writer)); - helpFormatter.printHeader(); - - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertEquals("|*Apache Commons CLI *|", - reader.readLine()); - assertNull(reader.readLine()); - } - - public void testPrintFooter() - throws IOException { - final StringWriter writer = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(writer)); - helpFormatter.printFooter(); - - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("|*Copyright 2003 *|", - reader.readLine()); - assertEquals("|*Apache Software Foundation *|", - reader.readLine()); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertNull(reader.readLine()); - } - - public void testPrintDivider() - throws IOException { - final StringWriter writer = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(writer)); - helpFormatter.printDivider(); - - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("+------------------------------------------------------------------------------+", - reader.readLine()); - assertNull(reader.readLine()); - } - - public void testWrap() { - final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 30).iterator(); - assertEquals("Apache Software Foundation", i.next()); - assertFalse(i.hasNext()); - } - - public void testWrap_WrapNeeded() { - final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 20).iterator(); - assertEquals("Apache Software", i.next()); - assertEquals("Foundation", i.next()); - assertFalse(i.hasNext()); - } - - public void testWrap_BeforeSpace() { - final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 16).iterator(); - assertEquals("Apache Software", i.next()); - assertEquals("Foundation", i.next()); - assertFalse(i.hasNext()); - } - - public void testWrap_AfterSpace() { - final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 17).iterator(); - assertEquals("Apache Software", i.next()); - assertEquals("Foundation", i.next()); - assertFalse(i.hasNext()); - } - - public void testWrap_InWord() { - final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 8).iterator(); - assertEquals("Apache", i.next()); - assertEquals("Software", i.next()); - assertEquals("Foundati", i.next()); - assertEquals("on", i.next()); - assertFalse(i.hasNext()); - } - - public void testWrap_NewLine() { - final Iterator i = HelpFormatter.wrap("\nApache Software Foundation\n", 30).iterator(); - assertEquals("", i.next()); - assertEquals("Apache Software Foundation", i.next()); - assertEquals("", i.next()); - assertFalse(i.hasNext()); - } - - public void testWrap_NewLine2() { - List wrapped = - HelpFormatter.wrap("A really quite long general description of the option with specific alternatives documented:\n" + - " Indented special case\n" + " Alternative scenario", 30); - - final Iterator i = wrapped.iterator(); - - assertEquals("A really quite long general", i.next()); - assertEquals("description of the option", i.next()); - assertEquals("with specific alternatives", i.next()); - assertEquals("documented:", i.next()); - assertEquals(" Indented special case", i.next()); - assertEquals(" Alternative scenario", i.next()); - assertFalse(i.hasNext()); - } - - public void testWrap_Below1Length() { - try { - HelpFormatter.wrap("Apache Software Foundation", -1); - fail("IllegalArgumentException"); - } catch (IllegalArgumentException e) { - assertEquals(resources.getMessage(ResourceConstants.HELPFORMATTER_WIDTH_TOO_NARROW, - new Object[] { new Integer(-1) }), e.getMessage()); - } - } - - public void testPad() - throws IOException { - final StringWriter writer = new StringWriter(); - HelpFormatter.pad("hello", 10, new PrintWriter(writer)); - assertEquals("hello ", writer.toString()); - } - - public void testPad_Null() - throws IOException { - final StringWriter writer = new StringWriter(); - HelpFormatter.pad(null, 10, new PrintWriter(writer)); - assertEquals(" ", writer.toString()); - } - - public void testPad_TooLong() - throws IOException { - final StringWriter writer = new StringWriter(); - HelpFormatter.pad("hello world", 10, new PrintWriter(writer)); - assertEquals("hello world", writer.toString()); - } - - public void testPad_TooShort() - throws IOException { - final StringWriter writer = new StringWriter(); - HelpFormatter.pad("hello world", -5, new PrintWriter(writer)); - assertEquals("hello world", writer.toString()); - } - - public void testGutters() - throws IOException { - helpFormatter = new HelpFormatter(null, null, null, 80); - helpFormatter.setShellCommand("ant"); - - final Set lusage = new HashSet(); - lusage.add(DisplaySetting.DISPLAY_ALIASES); - lusage.add(DisplaySetting.DISPLAY_GROUP_NAME); - helpFormatter.setLineUsageSettings(lusage); - - // test line usage - assertEquals("incorrect line usage", lusage, helpFormatter.getLineUsageSettings()); - - final Set fusage = new HashSet(); - fusage.add(DisplaySetting.DISPLAY_PARENT_CHILDREN); - fusage.add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); - fusage.add(DisplaySetting.DISPLAY_GROUP_OUTER); - fusage.add(DisplaySetting.DISPLAY_GROUP_EXPANDED); - fusage.add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); - fusage.add(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); - fusage.add(DisplaySetting.DISPLAY_SWITCH_ENABLED); - fusage.add(DisplaySetting.DISPLAY_SWITCH_DISABLED); - fusage.add(DisplaySetting.DISPLAY_PROPERTY_OPTION); - fusage.add(DisplaySetting.DISPLAY_PARENT_CHILDREN); - fusage.add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); - fusage.add(DisplaySetting.DISPLAY_OPTIONAL); - helpFormatter.setFullUsageSettings(fusage); - - // test line usage - assertEquals("incorrect full usage", fusage, helpFormatter.getFullUsageSettings()); - - final Set dsettings = new HashSet(); - dsettings.add(DisplaySetting.DISPLAY_GROUP_NAME); - dsettings.add(DisplaySetting.DISPLAY_GROUP_EXPANDED); - dsettings.add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); - - helpFormatter.setDisplaySettings(dsettings); - - verbose = - new DefaultOptionBuilder().withLongName("verbose") - .withDescription("print the version information and exit") - .create(); - - options = - new GroupBuilder().withName("options").withOption(DefaultOptionTest.buildHelpOption()) - .withOption(ArgumentTest.buildTargetsArgument()) - .withOption(new DefaultOptionBuilder().withLongName("diagnostics") - .withDescription("print information that might be helpful to diagnose or report problems.") - .create()) - .withOption(new DefaultOptionBuilder().withLongName("projecthelp") - .withDescription("print project help information") - .create()).withOption(verbose) - .create(); - - helpFormatter.setGroup(options); - - // test default gutters - assertEquals("incorrect left gutter", HelpFormatter.DEFAULT_GUTTER_LEFT, - helpFormatter.getGutterLeft()); - assertEquals("incorrect right gutter", HelpFormatter.DEFAULT_GUTTER_RIGHT, - helpFormatter.getGutterRight()); - assertEquals("incorrect center gutter", HelpFormatter.DEFAULT_GUTTER_CENTER, - helpFormatter.getGutterCenter()); - - final StringWriter writer = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(writer)); - helpFormatter.print(); - - final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); - assertEquals("Usage: ", - reader.readLine()); - assertEquals("ant [--help --diagnostics --projecthelp --verbose] [ [ ...]] ", - reader.readLine()); - assertEquals("options ", - reader.readLine()); - assertEquals(" --help (-?,-h) Displays the help ", - reader.readLine()); - assertEquals(" --diagnostics print information that might be helpful to diagnose or ", - reader.readLine()); - assertEquals(" report problems. ", - reader.readLine()); - assertEquals(" --projecthelp print project help information ", - reader.readLine()); - assertEquals(" --verbose print the version information and exit ", - reader.readLine()); - assertEquals(" target [target ...] The targets ant should build ", - reader.readLine()); - assertNull(reader.readLine()); - } -} - - -class OptionComparator implements Comparator { - public int compare(Object o1, - Object o2) { - Option opt1 = (Option) o1; - Option opt2 = (Option) o2; - - return -opt1.getPreferredName().compareTo(opt2.getPreferredName()); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.commons.cli2.util;import java.io.BufferedReader;import java.io.IOException;import java.io.PrintWriter;import java.io.StringReader;import java.io.StringWriter;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;import junit.framework.TestCase;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.option.ArgumentTest;import org.apache.commons.cli2.option.DefaultOptionTest;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;public class HelpFormatterTest extends TestCase { private ResourceHelper resources = ResourceHelper.getResourceHelper(); private HelpFormatter helpFormatter; private Option verbose; private Group options; public void setUp() { helpFormatter = new HelpFormatter("|*", "*-*", "*|", 80); helpFormatter.setDivider("+------------------------------------------------------------------------------+"); helpFormatter.setHeader("Apache Commons CLI"); helpFormatter.setFooter("Copyright 2003\nApache Software Foundation"); helpFormatter.setShellCommand("ant"); verbose = new DefaultOptionBuilder().withLongName("verbose") .withDescription("print the version information and exit") .create(); options = new GroupBuilder().withName("options").withOption(DefaultOptionTest.buildHelpOption()) .withOption(ArgumentTest.buildTargetsArgument()) .withOption(new DefaultOptionBuilder().withLongName("diagnostics") .withDescription("print information that might be helpful to diagnose or report problems.") .create()) .withOption(new DefaultOptionBuilder().withLongName("projecthelp") .withDescription("print project help information") .create()).withOption(verbose) .create(); helpFormatter.setGroup(options); } public void testPrint() throws IOException { final StringWriter writer = new StringWriter(); final PrintWriter pw = new PrintWriter(writer); helpFormatter.setPrintWriter(pw); helpFormatter.print(); // test shell assertEquals("incorrect shell command", "ant", helpFormatter.getShellCommand()); // test group assertEquals("incorrect group", this.options, helpFormatter.getGroup()); // test pagewidth assertEquals("incorrect page width", 76, helpFormatter.getPageWidth()); // test pw assertEquals("incorrect print writer", pw, helpFormatter.getPrintWriter()); // test divider assertEquals("incorrect divider", "+------------------------------------------------------------------------------+", helpFormatter.getDivider()); // test header assertEquals("incorrect header", "Apache Commons CLI", helpFormatter.getHeader()); // test footer assertEquals("incorrect footer", "Copyright 2003\nApache Software Foundation", helpFormatter.getFooter()); // test gutters assertEquals("incorrect left gutter", "|*", helpFormatter.getGutterLeft()); assertEquals("incorrect right gutter", "*|", helpFormatter.getGutterRight()); assertEquals("incorrect center gutter", "*-*", helpFormatter.getGutterCenter()); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Apache Commons CLI *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Usage: *|", reader.readLine()); assertEquals("|*ant [--help --diagnostics --projecthelp --verbose] [ [ *|", reader.readLine()); assertEquals("|*...]] *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*options *-* *|", reader.readLine()); assertEquals("|* --help (-?,-h) *-*Displays the help *|", reader.readLine()); assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", reader.readLine()); assertEquals("|* *-*or report problems. *|", reader.readLine()); assertEquals("|* --projecthelp *-*print project help information *|", reader.readLine()); assertEquals("|* --verbose *-*print the version information and exit *|", reader.readLine()); assertEquals("|* target [target ...]*-*The targets ant should build *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Copyright 2003 *|", reader.readLine()); assertEquals("|*Apache Software Foundation *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testComparator() throws IOException { final StringWriter writer = new StringWriter(); final PrintWriter pw = new PrintWriter(writer); helpFormatter.setPrintWriter(pw); final Comparator comparator = new OptionComparator(); helpFormatter.setComparator(comparator); helpFormatter.print(); // test comparator assertEquals("invalid comparator", comparator, helpFormatter.getComparator()); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Apache Commons CLI *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Usage: *|", reader.readLine()); assertEquals("|*ant [--verbose --projecthelp --help --diagnostics] [ [ *|", reader.readLine()); assertEquals("|*...]] *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*options *-* *|", reader.readLine()); assertEquals("|* --verbose *-*print the version information and exit *|", reader.readLine()); assertEquals("|* --projecthelp *-*print project help information *|", reader.readLine()); assertEquals("|* --help (-?,-h) *-*Displays the help *|", reader.readLine()); assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", reader.readLine()); assertEquals("|* *-*or report problems. *|", reader.readLine()); assertEquals("|* target [target ...]*-*The targets ant should build *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Copyright 2003 *|", reader.readLine()); assertEquals("|*Apache Software Foundation *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testPrintHelp() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printHelp(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*options *-* *|", reader.readLine()); assertEquals("|* --help (-?,-h) *-*Displays the help *|", reader.readLine()); assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", reader.readLine()); assertEquals("|* *-*or report problems. *|", reader.readLine()); assertEquals("|* --projecthelp *-*print project help information *|", reader.readLine()); assertEquals("|* --verbose *-*print the version information and exit *|", reader.readLine()); assertEquals("|* target [target ...]*-*The targets ant should build *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testPrintHelp_WithException() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.setException(new OptionException(verbose)); helpFormatter.printHelp(); //System.out.println(writer); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*--verbose*-*print the version information and exit *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testPrintHelp_TooNarrow() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter = new HelpFormatter("<", "=", ">", 4); helpFormatter.setGroup(options); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printHelp(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("", reader.readLine()); assertEquals("< --help (-?,-h) =D>", reader.readLine()); assertEquals("< =i>", reader.readLine()); // lots more lines unchecked } public void testPrintException() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.setException(new OptionException(verbose, ResourceConstants.MISSING_OPTION)); helpFormatter.printException(); //System.out.println(writer); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Missing option --verbose *|", reader.readLine()); assertNull(reader.readLine()); } public void testPrintUsage() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printUsage(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Usage: *|", reader.readLine()); assertEquals("|*ant [--help --diagnostics --projecthelp --verbose] [ [ *|", reader.readLine()); assertEquals("|*...]] *|", reader.readLine()); assertNull(reader.readLine()); } public void testPrintHeader() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printHeader(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Apache Commons CLI *|", reader.readLine()); assertNull(reader.readLine()); } public void testPrintFooter() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printFooter(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("|*Copyright 2003 *|", reader.readLine()); assertEquals("|*Apache Software Foundation *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testPrintDivider() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printDivider(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testWrap() { final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 30).iterator(); assertEquals("Apache Software Foundation", i.next()); assertFalse(i.hasNext()); } public void testWrap_WrapNeeded() { final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 20).iterator(); assertEquals("Apache Software", i.next()); assertEquals("Foundation", i.next()); assertFalse(i.hasNext()); } public void testWrap_BeforeSpace() { final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 16).iterator(); assertEquals("Apache Software", i.next()); assertEquals("Foundation", i.next()); assertFalse(i.hasNext()); } public void testWrap_AfterSpace() { final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 17).iterator(); assertEquals("Apache Software", i.next()); assertEquals("Foundation", i.next()); assertFalse(i.hasNext()); } public void testWrap_InWord() { final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 8).iterator(); assertEquals("Apache", i.next()); assertEquals("Software", i.next()); assertEquals("Foundati", i.next()); assertEquals("on", i.next()); assertFalse(i.hasNext()); } public void testWrap_NewLine() { final Iterator i = HelpFormatter.wrap("\nApache Software Foundation\n", 30).iterator(); assertEquals("", i.next()); assertEquals("Apache Software Foundation", i.next()); assertEquals("", i.next()); assertFalse(i.hasNext()); } public void testWrap_NewLine2() { List wrapped = HelpFormatter.wrap("A really quite long general description of the option with specific alternatives documented:\n" + " Indented special case\n" + " Alternative scenario", 30); final Iterator i = wrapped.iterator(); assertEquals("A really quite long general", i.next()); assertEquals("description of the option", i.next()); assertEquals("with specific alternatives", i.next()); assertEquals("documented:", i.next()); assertEquals(" Indented special case", i.next()); assertEquals(" Alternative scenario", i.next()); assertFalse(i.hasNext()); } public void testWrap_Below1Length() { try { HelpFormatter.wrap("Apache Software Foundation", -1); fail("IllegalArgumentException"); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.HELPFORMATTER_WIDTH_TOO_NARROW, new Object[] { new Integer(-1) }), e.getMessage()); } } public void testPad() throws IOException { final StringWriter writer = new StringWriter(); HelpFormatter.pad("hello", 10, new PrintWriter(writer)); assertEquals("hello ", writer.toString()); } public void testPad_Null() throws IOException { final StringWriter writer = new StringWriter(); HelpFormatter.pad(null, 10, new PrintWriter(writer)); assertEquals(" ", writer.toString()); } public void testPad_TooLong() throws IOException { final StringWriter writer = new StringWriter(); HelpFormatter.pad("hello world", 10, new PrintWriter(writer)); assertEquals("hello world", writer.toString()); } public void testPad_TooShort() throws IOException { final StringWriter writer = new StringWriter(); HelpFormatter.pad("hello world", -5, new PrintWriter(writer)); assertEquals("hello world", writer.toString()); } public void testGutters() throws IOException { helpFormatter = new HelpFormatter(null, null, null, 80); helpFormatter.setShellCommand("ant"); final Set lusage = new HashSet(); lusage.add(DisplaySetting.DISPLAY_ALIASES); lusage.add(DisplaySetting.DISPLAY_GROUP_NAME); helpFormatter.setLineUsageSettings(lusage); // test line usage assertEquals("incorrect line usage", lusage, helpFormatter.getLineUsageSettings()); final Set fusage = new HashSet(); fusage.add(DisplaySetting.DISPLAY_PARENT_CHILDREN); fusage.add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); fusage.add(DisplaySetting.DISPLAY_GROUP_OUTER); fusage.add(DisplaySetting.DISPLAY_GROUP_EXPANDED); fusage.add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); fusage.add(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); fusage.add(DisplaySetting.DISPLAY_SWITCH_ENABLED); fusage.add(DisplaySetting.DISPLAY_SWITCH_DISABLED); fusage.add(DisplaySetting.DISPLAY_PROPERTY_OPTION); fusage.add(DisplaySetting.DISPLAY_PARENT_CHILDREN); fusage.add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); fusage.add(DisplaySetting.DISPLAY_OPTIONAL); helpFormatter.setFullUsageSettings(fusage); // test line usage assertEquals("incorrect full usage", fusage, helpFormatter.getFullUsageSettings()); final Set dsettings = new HashSet(); dsettings.add(DisplaySetting.DISPLAY_GROUP_NAME); dsettings.add(DisplaySetting.DISPLAY_GROUP_EXPANDED); dsettings.add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); helpFormatter.setDisplaySettings(dsettings); verbose = new DefaultOptionBuilder().withLongName("verbose") .withDescription("print the version information and exit") .create(); options = new GroupBuilder().withName("options").withOption(DefaultOptionTest.buildHelpOption()) .withOption(ArgumentTest.buildTargetsArgument()) .withOption(new DefaultOptionBuilder().withLongName("diagnostics") .withDescription("print information that might be helpful to diagnose or report problems.") .create()) .withOption(new DefaultOptionBuilder().withLongName("projecthelp") .withDescription("print project help information") .create()).withOption(verbose) .create(); helpFormatter.setGroup(options); // test default gutters assertEquals("incorrect left gutter", HelpFormatter.DEFAULT_GUTTER_LEFT, helpFormatter.getGutterLeft()); assertEquals("incorrect right gutter", HelpFormatter.DEFAULT_GUTTER_RIGHT, helpFormatter.getGutterRight()); assertEquals("incorrect center gutter", HelpFormatter.DEFAULT_GUTTER_CENTER, helpFormatter.getGutterCenter()); final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.print(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("Usage: ", reader.readLine()); assertEquals("ant [--help --diagnostics --projecthelp --verbose] [ [ ...]] ", reader.readLine()); assertEquals("options ", reader.readLine()); assertEquals(" --help (-?,-h) Displays the help ", reader.readLine()); assertEquals(" --diagnostics print information that might be helpful to diagnose or ", reader.readLine()); assertEquals(" report problems. ", reader.readLine()); assertEquals(" --projecthelp print project help information ", reader.readLine()); assertEquals(" --verbose print the version information and exit ", reader.readLine()); assertEquals(" target [target ...] The targets ant should build ", reader.readLine()); assertNull(reader.readLine()); }}class OptionComparator implements Comparator { public int compare(Object o1, Object o2) { Option opt1 = (Option) o1; Option opt2 = (Option) o2; return -opt1.getPreferredName().compareTo(opt2.getPreferredName()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java b/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java index 1c89b1b12..e67706023 100644 --- a/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java @@ -1,248 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.resource.ResourceHelper; - -public class ClassValidatorTest extends TestCase { - - private final static ResourceHelper resources = - ResourceHelper.getResourceHelper(); - - private ClassValidator validator; - - protected void setUp() { - validator = new ClassValidator(); - } - - public void testValidName() throws InvalidArgumentException { - final Object[] array = new Object[] { "MyApp", "org.apache.ant.Main" }; - final List list = Arrays.asList(array); - - validator.validate(list); - - assertEquals("Name is incorrect", "MyApp", list.get(0)); - assertEquals("Name is incorrect", "org.apache.ant.Main", list.get(1)); - } - - public void testNameBadStart() { - final String className = "1stClass"; - final Object[] array = new Object[] { className }; - final List list = Arrays.asList(array); - - try { - validator.validate(list); - fail("Class name cannot start with a number."); - } catch (InvalidArgumentException ive) { - assertEquals( - resources.getMessage( - "ClassValidator.bad.classname", - className), - ive.getMessage()); - } - } - - public void testNameBadEnd() { - final String className = "My.Class."; - - final Object[] array = new Object[] { className }; - final List list = Arrays.asList(array); - - try { - validator.validate(list); - fail("Trailing period not permitted."); - } catch (InvalidArgumentException ive) { - assertEquals( - resources.getMessage( - "ClassValidator.bad.classname", - className), - ive.getMessage()); - } - } - - public void testNameBadMiddle() { - final String className = "My..Class"; - - final Object[] array = new Object[] { className }; - final List list = Arrays.asList(array); - - try { - validator.validate(list); - fail("Two consecutive periods is not permitted."); - } catch (InvalidArgumentException ive) { - assertEquals( - resources.getMessage( - "ClassValidator.bad.classname", - className), - ive.getMessage()); - } - } - - public void testIllegalNameChar() { - final String className = "My?Class"; - - final Object[] array = new Object[] { className }; - final List list = Arrays.asList(array); - - try { - validator.validate(list); - fail("Illegal character not allowed in Class name."); - } catch (InvalidArgumentException ive) { - assertEquals( - resources.getMessage( - "ClassValidator.bad.classname", - className), - ive.getMessage()); - } - } - - public void testLoadable() { - assertFalse("Validator is loadable", validator.isLoadable()); - validator.setLoadable(true); - assertTrue("Validator is NOT loadable", validator.isLoadable()); - validator.setLoadable(false); - assertFalse("Validator is loadable", validator.isLoadable()); - } - - public void testLoadValid() throws InvalidArgumentException { - final Object[] array = - new Object[] { - "org.apache.commons.cli2.Option", - "java.util.Vector" }; - final List list = Arrays.asList(array); - - validator.setLoadable(true); - validator.validate(list); - - final Iterator i = list.iterator(); - assertEquals( - "org.apache.commons.cli2.Option", - ((Class) i.next()).getName()); - assertEquals("java.util.Vector", ((Class) i.next()).getName()); - assertFalse(i.hasNext()); - } - - public void testLoadInvalid() { - final String className = "org.apache.commons.cli2.NonOption"; - - final Object[] array = new Object[] { className, "java.util.Vectors" }; - final List list = Arrays.asList(array); - - validator.setLoadable(true); - - try { - validator.validate(list); - fail("Class Not Found"); - } catch (InvalidArgumentException ive) { - assertEquals( - resources.getMessage( - "ClassValidator.class.notfound", - className), - ive.getMessage()); - } - } - - public void testInstantiate() { - assertFalse("Validator creates instances", validator.isInstance()); - validator.setInstance(true); - assertTrue( - "Validator does NOT create instances", - validator.isInstance()); - validator.setInstance(false); - assertFalse("Validator creates instances", validator.isInstance()); - } - - public void testCreateClassInstance() throws InvalidArgumentException { - final Object[] array = new Object[] { "java.util.Vector" }; - final List list = Arrays.asList(array); - - validator.setInstance(true); - - validator.validate(list); - assertTrue( - "Vector instance NOT found", - list.get(0) instanceof java.util.Vector); - } - - public void testCreateInterfaceInstance() { - final String className = "java.util.Map"; - final Object[] array = new Object[] { className }; - final List list = Arrays.asList(array); - - validator.setInstance(true); - - try { - validator.validate(list); - fail("It's not possible to create a '" + className + "'"); - } - catch (final InvalidArgumentException ive) { - assertEquals( - resources.getMessage( - "ClassValidator.class.create", - className), - ive.getMessage()); - } - } - - public void testCreateProtectedInstance() { - final String className = "org.apache.commons.cli2.validation.protect.ProtectedClass"; - final Object[] array = new Object[] { className }; - final List list = Arrays.asList(array); - - validator.setInstance(true); - - try { - validator.validate(list); - fail("It's not possible to create a '" + className + "'"); - } - catch (final InvalidArgumentException ive) { - assertEquals( - resources.getMessage( - "ClassValidator.class.access", - className, - "Class org.apache.commons.cli2.validation.ClassValidator " + - "can not access a member of class " + - "org.apache.commons.cli2.validation.protect.ProtectedClass " + - "with modifiers \"protected\""), - ive.getMessage()); - } - } - - public void testClassloader() { - assertEquals( - "Wrong classloader found", - validator.getClass().getClassLoader(), - validator.getClassLoader()); - - URLClassLoader classloader = new URLClassLoader(new URL[] { - }); - validator.setClassLoader(classloader); - - assertEquals( - "Wrong classloader found", - classloader, - validator.getClassLoader()); - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.net.URL;import java.net.URLClassLoader;import java.util.Arrays;import java.util.Iterator;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.resource.ResourceHelper;public class ClassValidatorTest extends TestCase { private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); private ClassValidator validator; protected void setUp() { validator = new ClassValidator(); } public void testValidName() throws InvalidArgumentException { final Object[] array = new Object[] { "MyApp", "org.apache.ant.Main" }; final List list = Arrays.asList(array); validator.validate(list); assertEquals("Name is incorrect", "MyApp", list.get(0)); assertEquals("Name is incorrect", "org.apache.ant.Main", list.get(1)); } public void testNameBadStart() { final String className = "1stClass"; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); try { validator.validate(list); fail("Class name cannot start with a number."); } catch (InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.bad.classname", className), ive.getMessage()); } } public void testNameBadEnd() { final String className = "My.Class."; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); try { validator.validate(list); fail("Trailing period not permitted."); } catch (InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.bad.classname", className), ive.getMessage()); } } public void testNameBadMiddle() { final String className = "My..Class"; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); try { validator.validate(list); fail("Two consecutive periods is not permitted."); } catch (InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.bad.classname", className), ive.getMessage()); } } public void testIllegalNameChar() { final String className = "My?Class"; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); try { validator.validate(list); fail("Illegal character not allowed in Class name."); } catch (InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.bad.classname", className), ive.getMessage()); } } public void testLoadable() { assertFalse("Validator is loadable", validator.isLoadable()); validator.setLoadable(true); assertTrue("Validator is NOT loadable", validator.isLoadable()); validator.setLoadable(false); assertFalse("Validator is loadable", validator.isLoadable()); } public void testLoadValid() throws InvalidArgumentException { final Object[] array = new Object[] { "org.apache.commons.cli2.Option", "java.util.Vector" }; final List list = Arrays.asList(array); validator.setLoadable(true); validator.validate(list); final Iterator i = list.iterator(); assertEquals( "org.apache.commons.cli2.Option", ((Class) i.next()).getName()); assertEquals("java.util.Vector", ((Class) i.next()).getName()); assertFalse(i.hasNext()); } public void testLoadInvalid() { final String className = "org.apache.commons.cli2.NonOption"; final Object[] array = new Object[] { className, "java.util.Vectors" }; final List list = Arrays.asList(array); validator.setLoadable(true); try { validator.validate(list); fail("Class Not Found"); } catch (InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.class.notfound", className), ive.getMessage()); } } public void testInstantiate() { assertFalse("Validator creates instances", validator.isInstance()); validator.setInstance(true); assertTrue( "Validator does NOT create instances", validator.isInstance()); validator.setInstance(false); assertFalse("Validator creates instances", validator.isInstance()); } public void testCreateClassInstance() throws InvalidArgumentException { final Object[] array = new Object[] { "java.util.Vector" }; final List list = Arrays.asList(array); validator.setInstance(true); validator.validate(list); assertTrue( "Vector instance NOT found", list.get(0) instanceof java.util.Vector); } public void testCreateInterfaceInstance() { final String className = "java.util.Map"; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); validator.setInstance(true); try { validator.validate(list); fail("It's not possible to create a '" + className + "'"); } catch (final InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.class.create", className), ive.getMessage()); } } public void testCreateProtectedInstance() { final String className = "org.apache.commons.cli2.validation.protect.ProtectedClass"; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); validator.setInstance(true); try { validator.validate(list); fail("It's not possible to create a '" + className + "'"); } catch (final InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.class.access", className, "Class org.apache.commons.cli2.validation.ClassValidator " + "can not access a member of class " + "org.apache.commons.cli2.validation.protect.ProtectedClass " + "with modifiers \"protected\""), ive.getMessage()); } } public void testClassloader() { assertEquals( "Wrong classloader found", validator.getClass().getClassLoader(), validator.getClassLoader()); URLClassLoader classloader = new URLClassLoader(new URL[] { }); validator.setClassLoader(classloader); assertEquals( "Wrong classloader found", classloader, validator.getClassLoader()); }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java b/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java index ba5112c50..68284dfd8 100644 --- a/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java @@ -1,220 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.text.DateFormat; -import java.text.DateFormatSymbols; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * JUnit test case for DateValidator. - * - * @author Rob Oxspring - * @author John Keyes - */ -public class DateValidatorTest - extends TestCase { - private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); - public static final DateFormat D_M_YY = new SimpleDateFormat("d/M/yy"); - public static final DateFormat YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd"); - private List formats = Arrays.asList(new Object[] { D_M_YY, YYYY_MM_DD }); - - public void testSingleFormatValidate() - throws InvalidArgumentException { - final Object[] array = new Object[] { "23/12/03" }; - final List list = Arrays.asList(array); - final Validator validator = new DateValidator(D_M_YY); - - validator.validate(list); - - final Iterator i = list.iterator(); - assertEquals("2003-12-23", YYYY_MM_DD.format((Date) i.next())); - assertFalse(i.hasNext()); - } - - public void testDefaultDateFormatValidate() - throws InvalidArgumentException { - DateFormatSymbols symbols = new DateFormatSymbols(); - final Object[] array = new Object[] { "23-" + symbols.getShortMonths()[11] + "-2003" }; - final List list = Arrays.asList(array); - final Validator validator = new DateValidator( new SimpleDateFormat("dd-MMM-yyyy") ); - - validator.validate(list); - - final Iterator i = list.iterator(); - // CLI-40: For some reason, the YYYY_MM_DD object gets quite - // confused here and returns 2003-12-22. If we make a new one - // there is no problem. - assertEquals("2003-12-23", new SimpleDateFormat("yyyy-MM-dd").format((Date) i.next())); - assertFalse(i.hasNext()); - } - - public void testDefaultTimeFormatValidate() - throws InvalidArgumentException { - final Object[] array = new Object[] { "18:00:00" }; - final List list = Arrays.asList(array); - final Validator validator = new DateValidator( new SimpleDateFormat("HH:mm:ss") ); - - validator.validate(list); - - final Iterator i = list.iterator(); - final DateFormat df = new SimpleDateFormat("HH:mm:ss"); - assertEquals("18:00:00", df.format((Date) i.next())); - assertFalse(i.hasNext()); - } - - public void testDefaultDateTimeFormatValidate() - throws InvalidArgumentException { - DateFormatSymbols symbols = new DateFormatSymbols(); - final Object[] array = new Object[] { "23-" + symbols.getShortMonths()[0] + "-2003 18:00:00" }; - final List list = Arrays.asList(array); - final Validator validator = new DateValidator( new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss") ); - - validator.validate(list); - - final Iterator i = list.iterator(); - final DateFormat df = new SimpleDateFormat("yyyy/M/dd HH:mm:ss"); - assertEquals("2003/1/23 18:00:00", df.format((Date) i.next())); - assertFalse(i.hasNext()); - } - - public void testDefaultValidator() - throws InvalidArgumentException { - final Object[] array = new Object[] { "23/01/03 18:00" }; - final List list = Arrays.asList(array); - final Validator validator = new DateValidator(new SimpleDateFormat("dd/MM/yy HH:mm")); - - validator.validate(list); - - final Iterator i = list.iterator(); - final DateFormat df = new SimpleDateFormat("yyyy/M/dd HH:mm:ss"); - assertEquals("2003/1/23 18:00:00", df.format((Date) i.next())); - assertFalse(i.hasNext()); - } - - public void testValidate() - throws InvalidArgumentException { - final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; - final List list = Arrays.asList(array); - final Validator validator = new DateValidator(formats); - - validator.validate(list); - - final Iterator i = list.iterator(); - assertEquals("2003-12-23", YYYY_MM_DD.format((Date) i.next())); - assertEquals("2002-10-12", YYYY_MM_DD.format((Date) i.next())); - assertFalse(i.hasNext()); - } - - public void testMinimumBounds() - throws InvalidArgumentException { - final DateValidator validator = new DateValidator(formats); - final Calendar cal = Calendar.getInstance(); - - { - final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; - final List list = Arrays.asList(array); - cal.set(2002, 1, 12); - - final Date min = cal.getTime(); - validator.setMinimum(min); - assertTrue("maximum bound is set", validator.getMaximum() == null); - assertEquals("minimum bound is incorrect", min, validator.getMinimum()); - validator.validate(list); - } - - { - final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; - final List list = Arrays.asList(array); - cal.set(2003, 1, 12); - - final Date min = cal.getTime(); - validator.setMinimum(min); - - try { - validator.validate(list); - fail("minimum out of bounds exception not caught"); - } catch (final InvalidArgumentException exp) { - assertEquals(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, - new Object[] { "2002-10-12" }), exp.getMessage()); - } - } - } - - public void testFormats() - throws InvalidArgumentException { - final DateValidator validator = new DateValidator(formats); - assertEquals("date format is incorrect", ((SimpleDateFormat) formats.get(0)).toPattern(), - ((SimpleDateFormat) validator.getFormats()[0]).toPattern()); - assertEquals("date format is incorrect", ((SimpleDateFormat) formats.get(1)).toPattern(), - ((SimpleDateFormat) validator.getFormats()[1]).toPattern()); - } - - public void testMaximumBounds() - throws InvalidArgumentException { - final DateValidator validator = new DateValidator(formats); - final Calendar cal = Calendar.getInstance(); - - { - final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; - final List list = Arrays.asList(array); - cal.set(2004, 1, 12); - - final Date max = cal.getTime(); - validator.setMaximum(max); - assertTrue("minimum bound is set", validator.getMinimum() == null); - assertEquals("maximum bound is incorrect", max, validator.getMaximum()); - validator.validate(list); - } - - { - final Object[] array = new Object[] { "23/12/03", "2004-10-12" }; - final List list = Arrays.asList(array); - cal.set(2004, 1, 12); - - final Date max = cal.getTime(); - validator.setMaximum(max); - - try { - validator.validate(list); - fail("maximum out of bounds exception not caught"); - } catch (final InvalidArgumentException exp) { - assertEquals(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, - new Object[] { "2004-10-12" }), exp.getMessage()); - } - } - } - - public static Test suite() { - Test result = new TestSuite(DateValidatorTest.class); // default behavior - result = new TimeZoneTestSuite("EST", result); // ensure it runs in EST timezone - - return result; - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.text.DateFormat;import java.text.DateFormatSymbols;import java.text.SimpleDateFormat;import java.util.Arrays;import java.util.Calendar;import java.util.Date;import java.util.Iterator;import java.util.List;import junit.framework.Test;import junit.framework.TestCase;import junit.framework.TestSuite;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * JUnit test case for DateValidator. * * @author Rob Oxspring * @author John Keyes */public class DateValidatorTest extends TestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); public static final DateFormat D_M_YY = new SimpleDateFormat("d/M/yy"); public static final DateFormat YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd"); private List formats = Arrays.asList(new Object[] { D_M_YY, YYYY_MM_DD }); public void testSingleFormatValidate() throws InvalidArgumentException { final Object[] array = new Object[] { "23/12/03" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator(D_M_YY); validator.validate(list); final Iterator i = list.iterator(); assertEquals("2003-12-23", YYYY_MM_DD.format((Date) i.next())); assertFalse(i.hasNext()); } public void testDefaultDateFormatValidate() throws InvalidArgumentException { DateFormatSymbols symbols = new DateFormatSymbols(); final Object[] array = new Object[] { "23-" + symbols.getShortMonths()[11] + "-2003" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator( new SimpleDateFormat("dd-MMM-yyyy") ); validator.validate(list); final Iterator i = list.iterator(); // CLI-40: For some reason, the YYYY_MM_DD object gets quite // confused here and returns 2003-12-22. If we make a new one // there is no problem. assertEquals("2003-12-23", new SimpleDateFormat("yyyy-MM-dd").format((Date) i.next())); assertFalse(i.hasNext()); } public void testDefaultTimeFormatValidate() throws InvalidArgumentException { final Object[] array = new Object[] { "18:00:00" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator( new SimpleDateFormat("HH:mm:ss") ); validator.validate(list); final Iterator i = list.iterator(); final DateFormat df = new SimpleDateFormat("HH:mm:ss"); assertEquals("18:00:00", df.format((Date) i.next())); assertFalse(i.hasNext()); } public void testDefaultDateTimeFormatValidate() throws InvalidArgumentException { DateFormatSymbols symbols = new DateFormatSymbols(); final Object[] array = new Object[] { "23-" + symbols.getShortMonths()[0] + "-2003 18:00:00" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator( new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss") ); validator.validate(list); final Iterator i = list.iterator(); final DateFormat df = new SimpleDateFormat("yyyy/M/dd HH:mm:ss"); assertEquals("2003/1/23 18:00:00", df.format((Date) i.next())); assertFalse(i.hasNext()); } public void testDefaultValidator() throws InvalidArgumentException { final Object[] array = new Object[] { "23/01/03 18:00" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator(new SimpleDateFormat("dd/MM/yy HH:mm")); validator.validate(list); final Iterator i = list.iterator(); final DateFormat df = new SimpleDateFormat("yyyy/M/dd HH:mm:ss"); assertEquals("2003/1/23 18:00:00", df.format((Date) i.next())); assertFalse(i.hasNext()); } public void testValidate() throws InvalidArgumentException { final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator(formats); validator.validate(list); final Iterator i = list.iterator(); assertEquals("2003-12-23", YYYY_MM_DD.format((Date) i.next())); assertEquals("2002-10-12", YYYY_MM_DD.format((Date) i.next())); assertFalse(i.hasNext()); } public void testMinimumBounds() throws InvalidArgumentException { final DateValidator validator = new DateValidator(formats); final Calendar cal = Calendar.getInstance(); { final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; final List list = Arrays.asList(array); cal.set(2002, 1, 12); final Date min = cal.getTime(); validator.setMinimum(min); assertTrue("maximum bound is set", validator.getMaximum() == null); assertEquals("minimum bound is incorrect", min, validator.getMinimum()); validator.validate(list); } { final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; final List list = Arrays.asList(array); cal.set(2003, 1, 12); final Date min = cal.getTime(); validator.setMinimum(min); try { validator.validate(list); fail("minimum out of bounds exception not caught"); } catch (final InvalidArgumentException exp) { assertEquals(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, new Object[] { "2002-10-12" }), exp.getMessage()); } } } public void testFormats() throws InvalidArgumentException { final DateValidator validator = new DateValidator(formats); assertEquals("date format is incorrect", ((SimpleDateFormat) formats.get(0)).toPattern(), ((SimpleDateFormat) validator.getFormats()[0]).toPattern()); assertEquals("date format is incorrect", ((SimpleDateFormat) formats.get(1)).toPattern(), ((SimpleDateFormat) validator.getFormats()[1]).toPattern()); } public void testMaximumBounds() throws InvalidArgumentException { final DateValidator validator = new DateValidator(formats); final Calendar cal = Calendar.getInstance(); { final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; final List list = Arrays.asList(array); cal.set(2004, 1, 12); final Date max = cal.getTime(); validator.setMaximum(max); assertTrue("minimum bound is set", validator.getMinimum() == null); assertEquals("maximum bound is incorrect", max, validator.getMaximum()); validator.validate(list); } { final Object[] array = new Object[] { "23/12/03", "2004-10-12" }; final List list = Arrays.asList(array); cal.set(2004, 1, 12); final Date max = cal.getTime(); validator.setMaximum(max); try { validator.validate(list); fail("maximum out of bounds exception not caught"); } catch (final InvalidArgumentException exp) { assertEquals(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, new Object[] { "2004-10-12" }), exp.getMessage()); } } } public static Test suite() { Test result = new TestSuite(DateValidatorTest.class); // default behavior result = new TimeZoneTestSuite("EST", result); // ensure it runs in EST timezone return result; }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/validation/EnumValidatorTest.java b/src/test/org/apache/commons/cli2/validation/EnumValidatorTest.java index 53673f11a..4da542db7 100644 --- a/src/test/org/apache/commons/cli2/validation/EnumValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/EnumValidatorTest.java @@ -1,66 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -public class EnumValidatorTest - extends TestCase { - private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); - private final Set enumSet = new TreeSet(Arrays.asList(new Object[] { "red", "green", "blue" })); - - public void testValidate() - throws InvalidArgumentException { - final Object[] array = new Object[] { "red", "green" }; - - { - final List list = Arrays.asList(array); - final EnumValidator validator = new EnumValidator(enumSet); - assertEquals("valid values are incorrect", enumSet, validator.getValidValues()); - validator.validate(list); - - final Iterator i = list.iterator(); - assertEquals("red", i.next()); - assertEquals("green", i.next()); - assertFalse(i.hasNext()); - } - } - - public void testNonMember() { - final Object[] array = new Object[] { "red", "pink" }; - final List list = Arrays.asList(array); - final EnumValidator validator = new EnumValidator(enumSet); - - try { - validator.validate(list); - fail("InvalidArgumentException"); - } catch (InvalidArgumentException e) { - assertEquals(resources.getMessage(ResourceConstants.ENUM_ILLEGAL_VALUE, - new Object[] { "pink", validator.getValuesAsString() }), - e.getMessage()); - } - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.util.Arrays;import java.util.Iterator;import java.util.List;import java.util.Set;import java.util.TreeSet;import junit.framework.TestCase;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;public class EnumValidatorTest extends TestCase { private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); private final Set enumSet = new TreeSet(Arrays.asList(new Object[] { "red", "green", "blue" })); public void testValidate() throws InvalidArgumentException { final Object[] array = new Object[] { "red", "green" }; { final List list = Arrays.asList(array); final EnumValidator validator = new EnumValidator(enumSet); assertEquals("valid values are incorrect", enumSet, validator.getValidValues()); validator.validate(list); final Iterator i = list.iterator(); assertEquals("red", i.next()); assertEquals("green", i.next()); assertFalse(i.hasNext()); } } public void testNonMember() { final Object[] array = new Object[] { "red", "pink" }; final List list = Arrays.asList(array); final EnumValidator validator = new EnumValidator(enumSet); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.ENUM_ILLEGAL_VALUE, new Object[] { "pink", validator.getValuesAsString() }), e.getMessage()); } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java b/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java index 16744ca65..912086eaa 100644 --- a/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java @@ -1,196 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -/** - * JUnit test case for the FileValidator. - * - * @author Rob Oxspring - * @author John Keyes - */ -public class FileValidatorTest extends TestCase { - - public void testValidate() throws InvalidArgumentException { - final Object[] array = new Object[] { "src", "project.xml", - "veryunlikelyfilename" }; - final List list = Arrays.asList(array); - final FileValidator validator = new FileValidator(); - - validator.validate(list); - - final Iterator i = list.iterator(); - assertEquals(new File("src"), i.next()); - assertEquals(new File("project.xml"), i.next()); - assertEquals(new File("veryunlikelyfilename"), i.next()); - assertFalse(i.hasNext()); - } - - public void testValidate_Directory() { - final Object[] array = new Object[] { "src", "project.xml" }; - final List list = Arrays.asList(array); - final FileValidator validator = FileValidator - .getExistingDirectoryInstance(); - - assertTrue("is a directory validator", validator.isDirectory()); - assertFalse("is not a file validator", validator.isFile()); - assertTrue("is an existing file validator", validator.isExisting()); - assertFalse("is not a hidden file validator", validator.isHidden()); - - try { - validator.validate(list); - fail("InvalidArgumentException"); - } catch (InvalidArgumentException e) { - assertEquals("project.xml", e.getMessage()); - } - } - - public void testValidate_ReadableFile() { - // make file readonly - File file = new File("src/test/data/readable.txt"); - file.setReadOnly(); - - final Object[] array = new Object[] { "src/test/data/readable.txt", - "src/test/data/notreadable.txt" }; - final List list = Arrays.asList(array); - final FileValidator validator = FileValidator.getExistingFileInstance(); - validator.setReadable(true); - - assertFalse("is not a directory validator", validator.isDirectory()); - assertTrue("is a file validator", validator.isFile()); - assertTrue("is an existing file validator", validator.isExisting()); - assertFalse("is not a hidden file validator", validator.isHidden()); - assertTrue("is a readable file validator", validator.isReadable()); - assertFalse("is not a writable file validator", validator.isWritable()); - - try { - validator.validate(list); - fail("InvalidArgumentException"); - } catch (InvalidArgumentException e) { - assertEquals("src/test/data/notreadable.txt", e.getMessage()); - } - } - - public void testValidate_WritableFile() { - // make file readonly - File file = new File("src/test/data/readable.txt"); - file.setReadOnly(); - - final Object[] array = new Object[] { "src/test/data/writable.txt", - "src/test/data/readable.txt" }; - final List list = Arrays.asList(array); - final FileValidator validator = FileValidator.getExistingFileInstance(); - validator.setWritable(true); - - assertFalse("is not a directory validator", validator.isDirectory()); - assertTrue("is a file validator", validator.isFile()); - assertTrue("is an existing file validator", validator.isExisting()); - assertFalse("is not a hidden file validator", validator.isHidden()); - assertFalse("is not a readable file validator", validator.isReadable()); - assertTrue("is a writable file validator", validator.isWritable()); - - try { - validator.validate(list); - fail("InvalidArgumentException"); - } catch (InvalidArgumentException e) { - assertEquals("src/test/data/readable.txt", e.getMessage()); - } - } - - public void testValidate_HiddenFile() throws InvalidArgumentException { - // make file hidden on Windows - attribute("H"); - - final Object[] array = new Object[] { "src/test/data/.hidden.txt", "src" }; - final List list = Arrays.asList(array); - final FileValidator validator = FileValidator.getExistingFileInstance(); - validator.setHidden(true); - - assertFalse("is not a directory validator", validator.isDirectory()); - assertTrue("is a file validator", validator.isFile()); - assertTrue("is an existing file validator", validator.isExisting()); - assertTrue("is a hidden file validator", validator.isHidden()); - - try { - validator.validate(list); - fail("InvalidArgumentException"); - } catch (InvalidArgumentException e) { - assertEquals("src", e.getMessage()); - } - } - - private void attribute(String attr) { - final String os = System.getProperty("os.name").toLowerCase(); - - // if the test is run on windows, run the attrib program - // to set the hidden attribute - if (os.indexOf("windows") != -1) { - // windows - try { - Process proc = Runtime.getRuntime().exec( - "attrib.exe +" + attr + " src/test/data/.hidden.txt", - null, new File(".")); - proc.waitFor(); - } catch (InterruptedException e) { - System.out.println(e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - System.out.println(e.getMessage()); - e.printStackTrace(); - } - } - } - - public void testValidate_Existing() { - final Object[] array = new Object[] { "project.xml", - "veryunlikelyfilename" }; - final List list = Arrays.asList(array); - final FileValidator validator = FileValidator.getExistingInstance(); - - assertFalse("is not a directory validator", validator.isDirectory()); - assertFalse("is not a file validator", validator.isFile()); - assertTrue("is an existing file validator", validator.isExisting()); - assertFalse("is not a hidden file validator", validator.isHidden()); - - try { - validator.validate(list); - fail("InvalidArgumentException"); - } catch (InvalidArgumentException e) { - assertEquals("veryunlikelyfilename", e.getMessage()); - } - } - - public void testValidate_File() { - final Object[] array = new Object[] { "project.xml", "src" }; - final List list = Arrays.asList(array); - final Validator validator = FileValidator.getExistingFileInstance(); - - try { - validator.validate(list); - fail("InvalidArgumentException"); - } catch (InvalidArgumentException e) { - assertEquals("src", e.getMessage()); - } - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.io.File;import java.io.IOException;import java.util.Arrays;import java.util.Iterator;import java.util.List;import junit.framework.TestCase;/** * JUnit test case for the FileValidator. * * @author Rob Oxspring * @author John Keyes */public class FileValidatorTest extends TestCase { public void testValidate() throws InvalidArgumentException { final Object[] array = new Object[] { "src", "project.xml", "veryunlikelyfilename" }; final List list = Arrays.asList(array); final FileValidator validator = new FileValidator(); validator.validate(list); final Iterator i = list.iterator(); assertEquals(new File("src"), i.next()); assertEquals(new File("project.xml"), i.next()); assertEquals(new File("veryunlikelyfilename"), i.next()); assertFalse(i.hasNext()); } public void testValidate_Directory() { final Object[] array = new Object[] { "src", "project.xml" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator .getExistingDirectoryInstance(); assertTrue("is a directory validator", validator.isDirectory()); assertFalse("is not a file validator", validator.isFile()); assertTrue("is an existing file validator", validator.isExisting()); assertFalse("is not a hidden file validator", validator.isHidden()); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("project.xml", e.getMessage()); } } public void testValidate_ReadableFile() { // make file readonly File file = new File("src/test/data/readable.txt"); file.setReadOnly(); final Object[] array = new Object[] { "src/test/data/readable.txt", "src/test/data/notreadable.txt" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator.getExistingFileInstance(); validator.setReadable(true); assertFalse("is not a directory validator", validator.isDirectory()); assertTrue("is a file validator", validator.isFile()); assertTrue("is an existing file validator", validator.isExisting()); assertFalse("is not a hidden file validator", validator.isHidden()); assertTrue("is a readable file validator", validator.isReadable()); assertFalse("is not a writable file validator", validator.isWritable()); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("src/test/data/notreadable.txt", e.getMessage()); } } public void testValidate_WritableFile() { // make file readonly File file = new File("src/test/data/readable.txt"); file.setReadOnly(); final Object[] array = new Object[] { "src/test/data/writable.txt", "src/test/data/readable.txt" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator.getExistingFileInstance(); validator.setWritable(true); assertFalse("is not a directory validator", validator.isDirectory()); assertTrue("is a file validator", validator.isFile()); assertTrue("is an existing file validator", validator.isExisting()); assertFalse("is not a hidden file validator", validator.isHidden()); assertFalse("is not a readable file validator", validator.isReadable()); assertTrue("is a writable file validator", validator.isWritable()); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("src/test/data/readable.txt", e.getMessage()); } } public void testValidate_HiddenFile() throws InvalidArgumentException { // make file hidden on Windows attribute("H"); final Object[] array = new Object[] { "src/test/data/.hidden.txt", "src" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator.getExistingFileInstance(); validator.setHidden(true); assertFalse("is not a directory validator", validator.isDirectory()); assertTrue("is a file validator", validator.isFile()); assertTrue("is an existing file validator", validator.isExisting()); assertTrue("is a hidden file validator", validator.isHidden()); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("src", e.getMessage()); } } private void attribute(String attr) { final String os = System.getProperty("os.name").toLowerCase(); // if the test is run on windows, run the attrib program // to set the hidden attribute if (os.indexOf("windows") != -1) { // windows try { Process proc = Runtime.getRuntime().exec( "attrib.exe +" + attr + " src/test/data/.hidden.txt", null, new File(".")); proc.waitFor(); } catch (InterruptedException e) { System.out.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } public void testValidate_Existing() { final Object[] array = new Object[] { "project.xml", "veryunlikelyfilename" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator.getExistingInstance(); assertFalse("is not a directory validator", validator.isDirectory()); assertFalse("is not a file validator", validator.isFile()); assertTrue("is an existing file validator", validator.isExisting()); assertFalse("is not a hidden file validator", validator.isHidden()); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("veryunlikelyfilename", e.getMessage()); } } public void testValidate_File() { final Object[] array = new Object[] { "project.xml", "src" }; final List list = Arrays.asList(array); final Validator validator = FileValidator.getExistingFileInstance(); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("src", e.getMessage()); } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/validation/NumberValidatorTest.java b/src/test/org/apache/commons/cli2/validation/NumberValidatorTest.java index b63957d7c..d1595364f 100644 --- a/src/test/org/apache/commons/cli2/validation/NumberValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/NumberValidatorTest.java @@ -1,168 +1 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.text.NumberFormat; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -/** - * JUnit test case for NumberValidator. - * - * @author Rob Oxspring - * @author John Keyes - */ -public class NumberValidatorTest - extends TestCase { - private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); - - public void testValidate_Number() - throws InvalidArgumentException { - final NumberFormat format = NumberFormat.getNumberInstance(); - - final Object[] array = - new Object[] { format.format(1d), format.format(1.07d), format.format(-.45d) }; - - { - final List list = Arrays.asList(array); - final Validator validator = NumberValidator.getNumberInstance(); - - validator.validate(list); - - final Iterator i = list.iterator(); - assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); - assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); - assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); - assertFalse(i.hasNext()); - } - } - - public void testValidate_Currency() - throws InvalidArgumentException { - NumberFormat format = NumberFormat.getCurrencyInstance(); - final Object[] array = - new Object[] { format.format(1d), format.format(1.07), format.format(-0.45) }; - final List list = Arrays.asList(array); - - final NumberValidator validator = NumberValidator.getCurrencyInstance(); - assertEquals("incorrect currency format", format, validator.getFormat()); - - validator.validate(list); - - final Iterator i = list.iterator(); - assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); - assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); - assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); - assertFalse(i.hasNext()); - } - - public void testValidate_Percent() - throws InvalidArgumentException { - final NumberFormat format = NumberFormat.getPercentInstance(); - - final Object[] array = - new Object[] { - format.format(.01), format.format(1.07), format.format(-.45), - format.format(0.001) - }; - final List list = Arrays.asList(array); - final Validator validator = NumberValidator.getPercentInstance(); - - validator.validate(list); - - final Iterator i = list.iterator(); - assertEquals(0.01d, ((Number) i.next()).doubleValue(), 0.0001); - assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); - assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); - assertEquals(0.00001d, ((Number) i.next()).doubleValue(), 0.0001); - assertFalse(i.hasNext()); - } - - public void testValidate_Integer() - throws InvalidArgumentException { - final Object[] array = new Object[] { "1", "107", "-45" }; - final List list = Arrays.asList(array); - final Validator validator = NumberValidator.getIntegerInstance(); - - validator.validate(list); - - final Iterator i = list.iterator(); - assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); - assertEquals(107d, ((Number) i.next()).doubleValue(), 0.0001); - assertEquals(-45d, ((Number) i.next()).doubleValue(), 0.0001); - assertFalse(i.hasNext()); - } - - public void testValidate_ExcessChars() { - final Object[] array = new Object[] { "10DowningStreet" }; - final List list = Arrays.asList(array); - final Validator validator = NumberValidator.getIntegerInstance(); - - try { - validator.validate(list); - fail("InvalidArgumentException"); - } catch (InvalidArgumentException e) { - assertEquals("10DowningStreet", e.getMessage()); - } - } - - public void testValidate_Maximum() { - final Object[] array = new Object[] { "1", "107" }; - final List list = Arrays.asList(array); - final NumberValidator validator = NumberValidator.getIntegerInstance(); - Integer max = new Integer(100); - - validator.setMaximum(max); - - assertTrue("no minimum set", validator.getMinimum() == null); - assertEquals("incorrect maximum value", max, validator.getMaximum()); - - try { - validator.validate(list); - fail("107 too big"); - } catch (InvalidArgumentException ive) { - assertEquals(resources.getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, - "107"), ive.getMessage()); - } - } - - public void testValidate_Minimum() { - final Object[] array = new Object[] { "107", "1" }; - final List list = Arrays.asList(array); - final NumberValidator validator = NumberValidator.getIntegerInstance(); - Integer min = new Integer(100); - validator.setMinimum(min); - - assertTrue("no maximum set", validator.getMaximum() == null); - assertEquals("incorrect minimum value", min, validator.getMinimum()); - - try { - validator.validate(list); - fail("1 too small"); - } catch (InvalidArgumentException ive) { - assertEquals(resources.getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, - "1"), ive.getMessage()); - } - } -} +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.text.NumberFormat;import java.util.Arrays;import java.util.Iterator;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * JUnit test case for NumberValidator. * * @author Rob Oxspring * @author John Keyes */public class NumberValidatorTest extends TestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); public void testValidate_Number() throws InvalidArgumentException { final NumberFormat format = NumberFormat.getNumberInstance(); final Object[] array = new Object[] { format.format(1d), format.format(1.07d), format.format(-.45d) }; { final List list = Arrays.asList(array); final Validator validator = NumberValidator.getNumberInstance(); validator.validate(list); final Iterator i = list.iterator(); assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); assertFalse(i.hasNext()); } } public void testValidate_Currency() throws InvalidArgumentException { NumberFormat format = NumberFormat.getCurrencyInstance(); final Object[] array = new Object[] { format.format(1d), format.format(1.07), format.format(-0.45) }; final List list = Arrays.asList(array); final NumberValidator validator = NumberValidator.getCurrencyInstance(); assertEquals("incorrect currency format", format, validator.getFormat()); validator.validate(list); final Iterator i = list.iterator(); assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); assertFalse(i.hasNext()); } public void testValidate_Percent() throws InvalidArgumentException { final NumberFormat format = NumberFormat.getPercentInstance(); final Object[] array = new Object[] { format.format(.01), format.format(1.07), format.format(-.45), format.format(0.001) }; final List list = Arrays.asList(array); final Validator validator = NumberValidator.getPercentInstance(); validator.validate(list); final Iterator i = list.iterator(); assertEquals(0.01d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(0.00001d, ((Number) i.next()).doubleValue(), 0.0001); assertFalse(i.hasNext()); } public void testValidate_Integer() throws InvalidArgumentException { final Object[] array = new Object[] { "1", "107", "-45" }; final List list = Arrays.asList(array); final Validator validator = NumberValidator.getIntegerInstance(); validator.validate(list); final Iterator i = list.iterator(); assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(107d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(-45d, ((Number) i.next()).doubleValue(), 0.0001); assertFalse(i.hasNext()); } public void testValidate_ExcessChars() { final Object[] array = new Object[] { "10DowningStreet" }; final List list = Arrays.asList(array); final Validator validator = NumberValidator.getIntegerInstance(); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("10DowningStreet", e.getMessage()); } } public void testValidate_Maximum() { final Object[] array = new Object[] { "1", "107" }; final List list = Arrays.asList(array); final NumberValidator validator = NumberValidator.getIntegerInstance(); Integer max = new Integer(100); validator.setMaximum(max); assertTrue("no minimum set", validator.getMinimum() == null); assertEquals("incorrect maximum value", max, validator.getMaximum()); try { validator.validate(list); fail("107 too big"); } catch (InvalidArgumentException ive) { assertEquals(resources.getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, "107"), ive.getMessage()); } } public void testValidate_Minimum() { final Object[] array = new Object[] { "107", "1" }; final List list = Arrays.asList(array); final NumberValidator validator = NumberValidator.getIntegerInstance(); Integer min = new Integer(100); validator.setMinimum(min); assertTrue("no maximum set", validator.getMaximum() == null); assertEquals("incorrect minimum value", min, validator.getMinimum()); try { validator.validate(list); fail("1 too small"); } catch (InvalidArgumentException ive) { assertEquals(resources.getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, "1"), ive.getMessage()); } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/validation/TimeZoneTestSuite.java b/src/test/org/apache/commons/cli2/validation/TimeZoneTestSuite.java index 4935f4d77..8484db2d7 100644 --- a/src/test/org/apache/commons/cli2/validation/TimeZoneTestSuite.java +++ b/src/test/org/apache/commons/cli2/validation/TimeZoneTestSuite.java @@ -1,46 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.util.TimeZone; - -import junit.extensions.TestDecorator; - -import junit.framework.Test; -import junit.framework.TestResult; - -public class TimeZoneTestSuite - extends TestDecorator { - private final TimeZone timeZone; - private final TimeZone originalTimeZone; - - public TimeZoneTestSuite(String timeZone, - Test test) { - super(test); - this.timeZone = TimeZone.getTimeZone(timeZone); - this.originalTimeZone = TimeZone.getDefault(); - } - - public void run(TestResult testResult) { - try { - TimeZone.setDefault(timeZone); - super.run(testResult); - } finally { - TimeZone.setDefault(originalTimeZone); // cleanup - } - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.util.TimeZone;import junit.extensions.TestDecorator;import junit.framework.Test;import junit.framework.TestResult;public class TimeZoneTestSuite extends TestDecorator { private final TimeZone timeZone; private final TimeZone originalTimeZone; public TimeZoneTestSuite(String timeZone, Test test) { super(test); this.timeZone = TimeZone.getTimeZone(timeZone); this.originalTimeZone = TimeZone.getDefault(); } public void run(TestResult testResult) { try { TimeZone.setDefault(timeZone); super.run(testResult); } finally { TimeZone.setDefault(originalTimeZone); // cleanup } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/validation/UrlValidatorTest.java b/src/test/org/apache/commons/cli2/validation/UrlValidatorTest.java index 16fa753b6..69cf875f0 100644 --- a/src/test/org/apache/commons/cli2/validation/UrlValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/UrlValidatorTest.java @@ -1,93 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation; - -import java.net.MalformedURLException; -import java.net.URL; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; - -public class UrlValidatorTest - extends TestCase { - private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); - - public void testValidate() - throws InvalidArgumentException, MalformedURLException { - final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; - final List list = Arrays.asList(array); - final Validator validator = new UrlValidator(); - - validator.validate(list); - - final Iterator i = list.iterator(); - assertEquals(new URL("http://www.apache.org/"), i.next()); - assertEquals(new URL("file:///etc"), i.next()); - assertFalse(i.hasNext()); - } - - public void testMalformedURL() - throws InvalidArgumentException, MalformedURLException { - final Object[] array = new Object[] { "www.apache.org" }; - final List list = Arrays.asList(array); - final Validator validator = new UrlValidator(); - - try { - validator.validate(list); - } catch (InvalidArgumentException e) { - assertEquals(resources.getMessage(ResourceConstants.URLVALIDATOR_MALFORMED_URL, - new Object[] { "www.apache.org" }), e.getMessage()); - } - } - - public void testBadProtocol() { - { - final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; - final List list = Arrays.asList(array); - final UrlValidator validator = new UrlValidator(); - validator.setProtocol("http"); - - assertEquals("incorrect protocol", "http", validator.getProtocol()); - - try { - validator.validate(list); - fail("Expected InvalidArgumentException"); - } catch (InvalidArgumentException e) { - assertEquals("file:///etc", e.getMessage()); - } - } - - { - final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; - final List list = Arrays.asList(array); - final UrlValidator validator = new UrlValidator("http"); - - try { - validator.validate(list); - fail("Expected InvalidArgumentException"); - } catch (InvalidArgumentException e) { - assertEquals("file:///etc", e.getMessage()); - } - } - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.net.MalformedURLException;import java.net.URL;import java.util.Arrays;import java.util.Iterator;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;public class UrlValidatorTest extends TestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); public void testValidate() throws InvalidArgumentException, MalformedURLException { final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; final List list = Arrays.asList(array); final Validator validator = new UrlValidator(); validator.validate(list); final Iterator i = list.iterator(); assertEquals(new URL("http://www.apache.org/"), i.next()); assertEquals(new URL("file:///etc"), i.next()); assertFalse(i.hasNext()); } public void testMalformedURL() throws InvalidArgumentException, MalformedURLException { final Object[] array = new Object[] { "www.apache.org" }; final List list = Arrays.asList(array); final Validator validator = new UrlValidator(); try { validator.validate(list); } catch (InvalidArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.URLVALIDATOR_MALFORMED_URL, new Object[] { "www.apache.org" }), e.getMessage()); } } public void testBadProtocol() { { final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; final List list = Arrays.asList(array); final UrlValidator validator = new UrlValidator(); validator.setProtocol("http"); assertEquals("incorrect protocol", "http", validator.getProtocol()); try { validator.validate(list); fail("Expected InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("file:///etc", e.getMessage()); } } { final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; final List list = Arrays.asList(array); final UrlValidator validator = new UrlValidator("http"); try { validator.validate(list); fail("Expected InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("file:///etc", e.getMessage()); } } }} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/validation/protect/ProtectedClass.java b/src/test/org/apache/commons/cli2/validation/protect/ProtectedClass.java index 572670230..e59ffa458 100644 --- a/src/test/org/apache/commons/cli2/validation/protect/ProtectedClass.java +++ b/src/test/org/apache/commons/cli2/validation/protect/ProtectedClass.java @@ -1,23 +1 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.validation.protect; - -class ProtectedClass { - protected ProtectedClass() { - // used to test something??? - } -} +/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation.protect;class ProtectedClass { protected ProtectedClass() { // used to test something??? }} \ No newline at end of file From 089ba3ce488e810308a4c16097676bc42cffb43f Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 22 Mar 2008 02:54:11 +0000 Subject: [PATCH 0070/1663] Using commons-lang checkstyle as the beginning for a commons-cli checkstyle git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639942 13f79535-47bb-0310-9956-ffa450edef68 --- checkstyle.xml | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 checkstyle.xml diff --git a/checkstyle.xml b/checkstyle.xml new file mode 100644 index 000000000..f7c444b62 --- /dev/null +++ b/checkstyle.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + From ca1e681ac7ce142befe950df5506e81c1935252d Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 22 Mar 2008 03:08:23 +0000 Subject: [PATCH 0071/1663] Removing all new lines in every source file - priceless. Arse. Reverting by exporting the old version on top and committing git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639943 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli2/Argument.java | 108 ++- .../org/apache/commons/cli2/CommandLine.java | 216 +++++- .../apache/commons/cli2/DisplaySetting.java | 156 ++++- src/java/org/apache/commons/cli2/Group.java | 66 +- .../org/apache/commons/cli2/HelpLine.java | 54 +- src/java/org/apache/commons/cli2/Option.java | 198 +++++- .../apache/commons/cli2/OptionException.java | 108 ++- src/java/org/apache/commons/cli2/Parent.java | 42 +- .../commons/cli2/WriteableCommandLine.java | 77 ++- .../commons/cli2/builder/ArgumentBuilder.java | 287 +++++++- .../commons/cli2/builder/CommandBuilder.java | 188 ++++- .../cli2/builder/DefaultOptionBuilder.java | 216 +++++- .../commons/cli2/builder/GroupBuilder.java | 119 +++- .../commons/cli2/builder/PatternBuilder.java | 203 +++++- .../commons/cli2/builder/SwitchBuilder.java | 195 +++++- .../cli2/commandline/CommandLineImpl.java | 121 +++- .../commandline/DefaultingCommandLine.java | 173 ++++- .../commons/cli2/commandline/Parser.java | 177 ++++- .../commandline/PreferencesCommandLine.java | 171 ++++- .../commandline/PropertiesCommandLine.java | 156 ++++- .../commandline/WriteableCommandLineImpl.java | 227 +++++- .../commons/cli2/option/ArgumentImpl.java | 375 +++++++++- .../apache/commons/cli2/option/Command.java | 176 ++++- .../commons/cli2/option/DefaultOption.java | 222 +++++- .../apache/commons/cli2/option/GroupImpl.java | 518 +++++++++++++- .../commons/cli2/option/HelpLineImpl.java | 111 ++- .../commons/cli2/option/OptionImpl.java | 160 ++++- .../commons/cli2/option/ParentImpl.java | 258 ++++++- .../commons/cli2/option/PropertyOption.java | 168 ++++- .../cli2/option/SourceDestArgument.java | 139 +++- .../apache/commons/cli2/option/Switch.java | 249 ++++++- .../cli2/resource/ResourceConstants.java | 71 +- .../commons/cli2/resource/ResourceHelper.java | 161 ++++- .../apache/commons/cli2/util/Comparators.java | 457 ++++++++++++- .../commons/cli2/util/HelpFormatter.java | 639 ++++++++++++++++- .../cli2/validation/ClassValidator.java | 202 +++++- .../cli2/validation/DateValidator.java | 309 ++++++++- .../cli2/validation/EnumValidator.java | 121 +++- .../cli2/validation/FileValidator.java | 266 ++++++- .../validation/InvalidArgumentException.java | 35 +- .../cli2/validation/NumberValidator.java | 201 +++++- .../commons/cli2/validation/UrlValidator.java | 116 +++- .../commons/cli2/validation/Validator.java | 44 +- .../org/apache/commons/cli2/CLITestCase.java | 86 ++- .../commons/cli2/CommandLineDefaultsTest.java | 252 ++++++- .../commons/cli2/CommandLineTestCase.java | 513 +++++++++++++- .../commons/cli2/DocumentationTest.java | 446 +++++++++++- .../apache/commons/cli2/PrecedenceTest.java | 414 ++++++++++- .../cli2/WriteableCommandLineTestCase.java | 93 ++- .../commons/cli2/application/AntTest.java | 199 +++++- .../commons/cli2/application/CpTest.java | 472 ++++++++++++- .../commons/cli2/application/CvsTest.java | 313 ++++++++- .../commons/cli2/application/LsTest.java | 225 +++++- .../apache/commons/cli2/bug/Bug13886Test.java | 90 ++- .../apache/commons/cli2/bug/Bug13935Test.java | 61 +- .../apache/commons/cli2/bug/Bug15046Test.java | 83 ++- .../apache/commons/cli2/bug/Bug15648Test.java | 61 +- .../apache/commons/cli2/bug/Bug27575Test.java | 42 +- .../apache/commons/cli2/bug/Bug28005Test.java | 80 ++- .../apache/commons/cli2/bug/Bug32533Test.java | 49 +- .../commons/cli2/bug/BugCLI122Test.java | 46 +- .../apache/commons/cli2/bug/BugCLI12Test.java | 58 +- .../apache/commons/cli2/bug/BugCLI18Test.java | 61 +- .../apache/commons/cli2/bug/BugCLI80Test.java | 68 +- .../bug/BugLoopingOptionLookAlikeTest.java | 80 ++- .../cli2/builder/ArgumentBuilderTest.java | 255 ++++++- .../builder/DefaultOptionBuilderTest.java | 201 +++++- .../DefaultingCommandLineTest.java | 152 +++- .../commons/cli2/commandline/ParserTest.java | 141 +++- .../PreferencesCommandLineTest.java | 107 ++- .../PropertiesCommandLineTest.java | 102 ++- .../WriteableCommandLineImplTest.java | 37 +- .../commons/cli2/jdepend/JDependTest.java | 110 ++- .../commons/cli2/option/ArgumentTest.java | 647 +++++++++++++++++- .../commons/cli2/option/ArgumentTestCase.java | 29 +- .../commons/cli2/option/CommandTest.java | 250 ++++++- .../cli2/option/DefaultOptionTest.java | 228 +++++- .../apache/commons/cli2/option/GroupTest.java | 441 +++++++++++- .../commons/cli2/option/GroupTestCase.java | 32 +- .../commons/cli2/option/NestedGroupTest.java | 193 +++++- .../commons/cli2/option/OptionTestCase.java | 56 +- .../commons/cli2/option/ParentTest.java | 420 +++++++++++- .../commons/cli2/option/ParentTestCase.java | 27 +- .../cli2/option/PropertyOptionTest.java | 234 ++++++- .../commons/cli2/option/SwitchTest.java | 309 ++++++++- .../cli2/resource/ResourceHelperTest.java | 85 ++- .../commons/cli2/util/ComparatorsTest.java | 222 +++++- .../commons/cli2/util/HelpFormatterTest.java | 546 ++++++++++++++- .../cli2/validation/ClassValidatorTest.java | 249 ++++++- .../cli2/validation/DateValidatorTest.java | 221 +++++- .../cli2/validation/EnumValidatorTest.java | 67 +- .../cli2/validation/FileValidatorTest.java | 197 +++++- .../cli2/validation/NumberValidatorTest.java | 169 ++++- .../cli2/validation/TimeZoneTestSuite.java | 47 +- .../cli2/validation/UrlValidatorTest.java | 94 ++- .../validation/protect/ProtectedClass.java | 24 +- 96 files changed, 17844 insertions(+), 96 deletions(-) diff --git a/src/java/org/apache/commons/cli2/Argument.java b/src/java/org/apache/commons/cli2/Argument.java index 6c239e5f9..49187da1e 100644 --- a/src/java/org/apache/commons/cli2/Argument.java +++ b/src/java/org/apache/commons/cli2/Argument.java @@ -1 +1,107 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.ListIterator;/** * An Option that can process values passed on the command line in the form * "--file README". */public interface Argument extends Option { /** * Returns the initial separator character or * '\0' if no character has been set. * * @return char the initial separator character */ char getInitialSeparator(); /** * Processes the "README" style element of the argument. * * Values identified should be added to the CommandLine object in * association with this Argument. * * @see WriteableCommandLine#addValue(Option,Object) * * @param commandLine The CommandLine object to store results in. * @param args The arguments to process. * @param option The option to register value against. * @throws OptionException if any problems occur. */ void processValues( final WriteableCommandLine commandLine, final ListIterator args, final Option option) throws OptionException; /** * Adds defaults to a CommandLine. * * @param commandLine * The CommandLine object to store defaults in. * @param option * The Option to store the defaults against. */ void defaultValues(final WriteableCommandLine commandLine, final Option option); /** * Performs any necessary validation on the values added to the * CommandLine. * * Validation will typically involve using the * CommandLine.getValues(option) method to retrieve the values * and then either checking each value. Optionally the String * value can be replaced by another Object such as a Number * instance or a File instance. * * @see CommandLine#getValues(Option) * * @param commandLine The CommandLine object to query. * @param option The option to lookup values with. * @throws OptionException if any problems occur. */ void validate(final WriteableCommandLine commandLine, final Option option) throws OptionException; /** * Indicates whether argument values must be present for the CommandLine to * be valid. * * @see #getMinimum() * @see #getMaximum() * @return true iff the CommandLine will be invalid without at least one * value */ boolean isRequired(); /** * Retrieves the minimum number of values required for a valid Argument * * @return the minimum number of values */ int getMinimum(); /** * Retrieves the maximum number of values acceptable for a valid Argument * * @return the maximum number of values */ int getMaximum();} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.ListIterator; + +/** + * An Option that can process values passed on the command line in the form + * "--file README". + */ +public interface Argument extends Option { + + /** + * Returns the initial separator character or + * '\0' if no character has been set. + * + * @return char the initial separator character + */ + char getInitialSeparator(); + + /** + * Processes the "README" style element of the argument. + * + * Values identified should be added to the CommandLine object in + * association with this Argument. + * + * @see WriteableCommandLine#addValue(Option,Object) + * + * @param commandLine The CommandLine object to store results in. + * @param args The arguments to process. + * @param option The option to register value against. + * @throws OptionException if any problems occur. + */ + void processValues( + final WriteableCommandLine commandLine, + final ListIterator args, + final Option option) + throws OptionException; + + /** + * Adds defaults to a CommandLine. + * + * @param commandLine + * The CommandLine object to store defaults in. + * @param option + * The Option to store the defaults against. + */ + void defaultValues(final WriteableCommandLine commandLine, final Option option); + + /** + * Performs any necessary validation on the values added to the + * CommandLine. + * + * Validation will typically involve using the + * CommandLine.getValues(option) method to retrieve the values + * and then either checking each value. Optionally the String + * value can be replaced by another Object such as a Number + * instance or a File instance. + * + * @see CommandLine#getValues(Option) + * + * @param commandLine The CommandLine object to query. + * @param option The option to lookup values with. + * @throws OptionException if any problems occur. + */ + void validate(final WriteableCommandLine commandLine, final Option option) + throws OptionException; + + /** + * Indicates whether argument values must be present for the CommandLine to + * be valid. + * + * @see #getMinimum() + * @see #getMaximum() + * @return true iff the CommandLine will be invalid without at least one + * value + */ + boolean isRequired(); + + /** + * Retrieves the minimum number of values required for a valid Argument + * + * @return the minimum number of values + */ + int getMinimum(); + + /** + * Retrieves the maximum number of values acceptable for a valid Argument + * + * @return the maximum number of values + */ + int getMaximum(); +} diff --git a/src/java/org/apache/commons/cli2/CommandLine.java b/src/java/org/apache/commons/cli2/CommandLine.java index 848fbce98..3c2eeba55 100644 --- a/src/java/org/apache/commons/cli2/CommandLine.java +++ b/src/java/org/apache/commons/cli2/CommandLine.java @@ -1 +1,215 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.List;import java.util.Set;/** * Instances of CommandLine represent a command line that has been processed * according to the definition supplied to the parser. */public interface CommandLine { /** * Detects the presence of an option with the specified trigger in this * CommandLine. * * @param trigger the trigger to search for * @return true iff an option with this trigger is present */ boolean hasOption(final String trigger); /** * Detects the presence of an option in this CommandLine. * * @param option the Option to search for * @return true iff the option is present */ boolean hasOption(final Option option); /** * Finds the Option with the specified trigger * * @param trigger the name of the option to retrieve * @return the Option matching the trigger or null if none exists */ Option getOption(final String trigger); /** * Retrieves the Argument values associated with the specified Option * * @param trigger a trigger used to lookup the Option * @return a list of values or an empty List if none are found */ List getValues(final String trigger); /** * Retrieves the Argument values associated with the specified Option * * @param trigger a trigger used to lookup the Option * @param defaultValues the result to return if no values are found * @return a list of values or defaultValues if none are found */ List getValues(final String trigger, final List defaultValues); /** * Retrieves the Argument values associated with the specified Option * * @param option the Option associated with the values * @return a list of values or an empty List if none are found */ List getValues(final Option option); /** * Retrieves the Argument values associated with the specified Option * * @param option the Option associated with the values * @param defaultValues the result to return if no values are found * @return a list of values or defaultValues if none are found */ List getValues(final Option option, final List defaultValues); /** * Retrieves the single Argument value associated with the specified Option * * @param trigger a trigger used to lookup the Option * @return the matching value or null if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final String trigger) throws IllegalStateException; /** * Retrieves the single Argument value associated with the specified Option * * @param trigger a trigger used to lookup the Option * @param defaultValue the result to use if no values are found * @return the matching value or defaultValue if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final String trigger, final Object defaultValue) throws IllegalStateException; /** * Retrieves the single Argument value associated with the specified Option * * @param option the Option associated with the value * @return the matching value or null if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final Option option) throws IllegalStateException; /** * Retrieves the single Argument value associated with the specified Option * * @param option the Option associated with the value * @param defaultValue the result to use if no values are found * @return the matching value or defaultValue if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final Option option, final Object defaultValue) throws IllegalStateException; /** * Retrieves the Boolean value associated with the specified Switch * * @param trigger a trigger used to lookup the Option * @return the Boolean associated with trigger or null if none exists */ Boolean getSwitch(final String trigger); /** * Retrieves the Boolean value associated with the specified Switch * * @param trigger a trigger used to lookup the Option * @param defaultValue the Boolean to use if none match * @return the Boolean associated with trigger or defaultValue if none exists */ Boolean getSwitch(final String trigger, final Boolean defaultValue); /** * Retrieves the Boolean value associated with the specified Switch * * @param option the Option associated with the value * @return the Boolean associated with option or null if none exists */ Boolean getSwitch(final Option option); /** * Retrieves the Boolean value associated with the specified Switch * * @param option the Option associated with the value * @param defaultValue the Boolean to use if none match * @return the Boolean associated with option or defaultValue if none exists */ Boolean getSwitch(final Option option, final Boolean defaultValue); /** * Retrieves the value associated with the specified property * * @param property the property name to lookup * @return the value of the property or null */ String getProperty(final String property); /** * Retrieves the value associated with the specified property * * @param property the property name to lookup * @param defaultValue the value to use if no other is found * @return the value of the property or defaultValue */ String getProperty(final String property, final String defaultValue); /** * Retrieves the set of all property names associated with this CommandLine * * @return a none null set of property names */ Set getProperties(); /** * Retrieves the number of times the specified Option appeared in this * CommandLine * * @param trigger a trigger used to lookup the Option * @return the number of occurrences of the option */ int getOptionCount(final String trigger); /** * Retrieves the number of times the specified Option appeared in this * CommandLine * * @param option the Option associated to check * @return the number of occurrences of the option */ int getOptionCount(final Option option); /** * Retrieves a list of all Options found in this CommandLine * * @return a none null list of Options */ List getOptions(); /** * Retrieves a list of all Option triggers found in this CommandLine * * @return a none null list of Option triggers */ Set getOptionTriggers();} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.List; +import java.util.Set; + +/** + * Instances of CommandLine represent a command line that has been processed + * according to the definition supplied to the parser. + */ +public interface CommandLine { + + /** + * Detects the presence of an option with the specified trigger in this + * CommandLine. + * + * @param trigger the trigger to search for + * @return true iff an option with this trigger is present + */ + boolean hasOption(final String trigger); + + /** + * Detects the presence of an option in this CommandLine. + * + * @param option the Option to search for + * @return true iff the option is present + */ + boolean hasOption(final Option option); + + /** + * Finds the Option with the specified trigger + * + * @param trigger the name of the option to retrieve + * @return the Option matching the trigger or null if none exists + */ + Option getOption(final String trigger); + + /** + * Retrieves the Argument values associated with the specified Option + * + * @param trigger a trigger used to lookup the Option + * @return a list of values or an empty List if none are found + */ + List getValues(final String trigger); + + /** + * Retrieves the Argument values associated with the specified Option + * + * @param trigger a trigger used to lookup the Option + * @param defaultValues the result to return if no values are found + * @return a list of values or defaultValues if none are found + */ + List getValues(final String trigger, final List defaultValues); + + /** + * Retrieves the Argument values associated with the specified Option + * + * @param option the Option associated with the values + * @return a list of values or an empty List if none are found + */ + List getValues(final Option option); + + /** + * Retrieves the Argument values associated with the specified Option + * + * @param option the Option associated with the values + * @param defaultValues the result to return if no values are found + * @return a list of values or defaultValues if none are found + */ + List getValues(final Option option, final List defaultValues); + + /** + * Retrieves the single Argument value associated with the specified Option + * + * @param trigger a trigger used to lookup the Option + * @return the matching value or null if none exists + * @throws IllegalStateException if more than one values are found + */ + Object getValue(final String trigger) throws IllegalStateException; + + /** + * Retrieves the single Argument value associated with the specified Option + * + * @param trigger a trigger used to lookup the Option + * @param defaultValue the result to use if no values are found + * @return the matching value or defaultValue if none exists + * @throws IllegalStateException if more than one values are found + */ + Object getValue(final String trigger, final Object defaultValue) throws IllegalStateException; + + /** + * Retrieves the single Argument value associated with the specified Option + * + * @param option the Option associated with the value + * @return the matching value or null if none exists + * @throws IllegalStateException if more than one values are found + */ + Object getValue(final Option option) throws IllegalStateException; + + /** + * Retrieves the single Argument value associated with the specified Option + * + * @param option the Option associated with the value + * @param defaultValue the result to use if no values are found + * @return the matching value or defaultValue if none exists + * @throws IllegalStateException if more than one values are found + */ + Object getValue(final Option option, final Object defaultValue) throws IllegalStateException; + + /** + * Retrieves the Boolean value associated with the specified Switch + * + * @param trigger a trigger used to lookup the Option + * @return the Boolean associated with trigger or null if none exists + */ + Boolean getSwitch(final String trigger); + + /** + * Retrieves the Boolean value associated with the specified Switch + * + * @param trigger a trigger used to lookup the Option + * @param defaultValue the Boolean to use if none match + * @return the Boolean associated with trigger or defaultValue if none exists + */ + Boolean getSwitch(final String trigger, final Boolean defaultValue); + + /** + * Retrieves the Boolean value associated with the specified Switch + * + * @param option the Option associated with the value + * @return the Boolean associated with option or null if none exists + */ + Boolean getSwitch(final Option option); + + /** + * Retrieves the Boolean value associated with the specified Switch + * + * @param option the Option associated with the value + * @param defaultValue the Boolean to use if none match + * @return the Boolean associated with option or defaultValue if none exists + */ + Boolean getSwitch(final Option option, final Boolean defaultValue); + + + /** + * Retrieves the value associated with the specified property + * + * @param property the property name to lookup + * @return the value of the property or null + */ + String getProperty(final String property); + + /** + * Retrieves the value associated with the specified property + * + * @param property the property name to lookup + * @param defaultValue the value to use if no other is found + * @return the value of the property or defaultValue + */ + String getProperty(final String property, final String defaultValue); + + /** + * Retrieves the set of all property names associated with this CommandLine + * + * @return a none null set of property names + */ + Set getProperties(); + + /** + * Retrieves the number of times the specified Option appeared in this + * CommandLine + * + * @param trigger a trigger used to lookup the Option + * @return the number of occurrences of the option + */ + int getOptionCount(final String trigger); + + /** + * Retrieves the number of times the specified Option appeared in this + * CommandLine + * + * @param option the Option associated to check + * @return the number of occurrences of the option + */ + int getOptionCount(final Option option); + + /** + * Retrieves a list of all Options found in this CommandLine + * + * @return a none null list of Options + */ + List getOptions(); + + /** + * Retrieves a list of all Option triggers found in this CommandLine + * + * @return a none null list of Option triggers + */ + Set getOptionTriggers(); +} diff --git a/src/java/org/apache/commons/cli2/DisplaySetting.java b/src/java/org/apache/commons/cli2/DisplaySetting.java index 91b64532b..fc522067d 100644 --- a/src/java/org/apache/commons/cli2/DisplaySetting.java +++ b/src/java/org/apache/commons/cli2/DisplaySetting.java @@ -1 +1,155 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Collections;import java.util.HashSet;import java.util.Set;/** * An enum of possible display settings. These settings are used to control the * presence of various features in the String representations of options, * CommandLines and usage strings. Usually a Set of DisplaySetting instances * will be passed to a method that will lookup the presence of the values. */public class DisplaySetting { private static final Set all = new HashSet(); /** * A Set guarenteed to contain all possible DisplaySetting values */ public static final Set ALL = Collections.unmodifiableSet(all); /** * A Set guarenteed to contain no DisplaySetting values */ public static final Set NONE = Collections.EMPTY_SET; /** * Indicates that aliases should be included */ public static final DisplaySetting DISPLAY_ALIASES = new DisplaySetting("DISPLAY_ALIASES"); /** * Indicates that optionality should be included */ public static final DisplaySetting DISPLAY_OPTIONAL = new DisplaySetting("DISPLAY_OPTIONAL"); /** * Indicates that property options should be included */ public static final DisplaySetting DISPLAY_PROPERTY_OPTION = new DisplaySetting("DISPLAY_PROPERTY_OPTION"); /** * Indicates that switches should be included enabled */ public static final DisplaySetting DISPLAY_SWITCH_ENABLED = new DisplaySetting("DISPLAY_SWITCH_ENABLED"); /** * Indicates that switches should be included disabled */ public static final DisplaySetting DISPLAY_SWITCH_DISABLED = new DisplaySetting("DISPLAY_SWITCH_DISABLED"); /** * Indicates that group names should be included */ public static final DisplaySetting DISPLAY_GROUP_NAME = new DisplaySetting("DISPLAY_GROUP_NAME"); /** * Indicates that groups should be included expanded */ public static final DisplaySetting DISPLAY_GROUP_EXPANDED = new DisplaySetting("DISPLAY_GROUP_EXPANDED"); /** * Indicates that group arguments should be included */ public static final DisplaySetting DISPLAY_GROUP_ARGUMENT = new DisplaySetting("DISPLAY_GROUP_ARGUMENT"); /** * Indicates that group outer brackets should be included */ public static final DisplaySetting DISPLAY_GROUP_OUTER = new DisplaySetting("DISPLAY_GROUP_OUTER"); /** * Indicates that arguments should be included numbered */ public static final DisplaySetting DISPLAY_ARGUMENT_NUMBERED = new DisplaySetting("DISPLAY_ARGUMENT_NUMBERED"); /** * Indicates that arguments should be included bracketed */ public static final DisplaySetting DISPLAY_ARGUMENT_BRACKETED = new DisplaySetting("DISPLAY_ARGUMENT_BRACKETED"); /** * Indicates that arguments of Parents should be included */ public static final DisplaySetting DISPLAY_PARENT_ARGUMENT = new DisplaySetting("DISPLAY_PARENT_ARGUMENT"); /** * Indicates that children of Parents should be included */ public static final DisplaySetting DISPLAY_PARENT_CHILDREN = new DisplaySetting("DISPLAY_PARENT_CHILDREN"); /** * The name of the setting */ private final String name; /** * The hashCode of the setting */ private final int hashCode; /** * Creates a new DisplaySetting with the specified name * @param name the name of the setting */ private DisplaySetting(final String name) { this.name = name; this.hashCode = name.hashCode(); all.add(this); } public int hashCode() { return hashCode; } public boolean equals(final Object that) { if (that instanceof DisplaySetting) { return name.compareTo(that.toString()) == 0; } return false; } public String toString() { return name; }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** + * An enum of possible display settings. These settings are used to control the + * presence of various features in the String representations of options, + * CommandLines and usage strings. Usually a Set of DisplaySetting instances + * will be passed to a method that will lookup the presence of the values. + */ +public class DisplaySetting { + + private static final Set all = new HashSet(); + + /** + * A Set guarenteed to contain all possible DisplaySetting values + */ + public static final Set ALL = Collections.unmodifiableSet(all); + + /** + * A Set guarenteed to contain no DisplaySetting values + */ + public static final Set NONE = Collections.EMPTY_SET; + + /** + * Indicates that aliases should be included + */ + public static final DisplaySetting DISPLAY_ALIASES = + new DisplaySetting("DISPLAY_ALIASES"); + + /** + * Indicates that optionality should be included + */ + public static final DisplaySetting DISPLAY_OPTIONAL = + new DisplaySetting("DISPLAY_OPTIONAL"); + + /** + * Indicates that property options should be included + */ + public static final DisplaySetting DISPLAY_PROPERTY_OPTION = + new DisplaySetting("DISPLAY_PROPERTY_OPTION"); + + /** + * Indicates that switches should be included enabled + */ + public static final DisplaySetting DISPLAY_SWITCH_ENABLED = + new DisplaySetting("DISPLAY_SWITCH_ENABLED"); + + /** + * Indicates that switches should be included disabled + */ + public static final DisplaySetting DISPLAY_SWITCH_DISABLED = + new DisplaySetting("DISPLAY_SWITCH_DISABLED"); + + /** + * Indicates that group names should be included + */ + public static final DisplaySetting DISPLAY_GROUP_NAME = + new DisplaySetting("DISPLAY_GROUP_NAME"); + + /** + * Indicates that groups should be included expanded + */ + public static final DisplaySetting DISPLAY_GROUP_EXPANDED = + new DisplaySetting("DISPLAY_GROUP_EXPANDED"); + + /** + * Indicates that group arguments should be included + */ + public static final DisplaySetting DISPLAY_GROUP_ARGUMENT = + new DisplaySetting("DISPLAY_GROUP_ARGUMENT"); + + /** + * Indicates that group outer brackets should be included + */ + public static final DisplaySetting DISPLAY_GROUP_OUTER = + new DisplaySetting("DISPLAY_GROUP_OUTER"); + + /** + * Indicates that arguments should be included numbered + */ + public static final DisplaySetting DISPLAY_ARGUMENT_NUMBERED = + new DisplaySetting("DISPLAY_ARGUMENT_NUMBERED"); + + /** + * Indicates that arguments should be included bracketed + */ + public static final DisplaySetting DISPLAY_ARGUMENT_BRACKETED = + new DisplaySetting("DISPLAY_ARGUMENT_BRACKETED"); + + /** + * Indicates that arguments of Parents should be included + */ + public static final DisplaySetting DISPLAY_PARENT_ARGUMENT = + new DisplaySetting("DISPLAY_PARENT_ARGUMENT"); + + /** + * Indicates that children of Parents should be included + */ + public static final DisplaySetting DISPLAY_PARENT_CHILDREN = + new DisplaySetting("DISPLAY_PARENT_CHILDREN"); + + /** + * The name of the setting + */ + private final String name; + + /** + * The hashCode of the setting + */ + private final int hashCode; + + /** + * Creates a new DisplaySetting with the specified name + * @param name the name of the setting + */ + private DisplaySetting(final String name) { + this.name = name; + this.hashCode = name.hashCode(); + all.add(this); + } + + public int hashCode() { + return hashCode; + } + + public boolean equals(final Object that) { + if (that instanceof DisplaySetting) { + return name.compareTo(that.toString()) == 0; + } + return false; + } + + public String toString() { + return name; + } +} diff --git a/src/java/org/apache/commons/cli2/Group.java b/src/java/org/apache/commons/cli2/Group.java index d884a5269..3a3d4c752 100644 --- a/src/java/org/apache/commons/cli2/Group.java +++ b/src/java/org/apache/commons/cli2/Group.java @@ -1 +1,65 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Comparator;import java.util.Set;/** * An Option representing a choice or group of Options in the form "-a|-b|-c". */public interface Group extends Option { /** * Appends usage information to the specified StringBuffer * * @param buffer the buffer to append to * @param helpSettings a set of display settings @see DisplaySetting * @param comp a comparator used to sort the Options * @param separator the String used to separate member Options */ void appendUsage( final StringBuffer buffer, final Set helpSettings, final Comparator comp, final String separator); /** * Indicates whether group members must be present for the CommandLine to be * valid. * * @see #getMinimum() * @see #getMaximum() * @return true iff the CommandLine will be invalid without at least one * member option */ boolean isRequired(); /** * Retrieves the minimum number of members required for a valid Group * * @return the minimum number of members */ int getMinimum(); /** * Retrieves the maximum number of members acceptable for a valid Group * * @return the maximum number of members */ int getMaximum();} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.Comparator; +import java.util.Set; + +/** + * An Option representing a choice or group of Options in the form "-a|-b|-c". + */ +public interface Group extends Option { + + /** + * Appends usage information to the specified StringBuffer + * + * @param buffer the buffer to append to + * @param helpSettings a set of display settings @see DisplaySetting + * @param comp a comparator used to sort the Options + * @param separator the String used to separate member Options + */ + void appendUsage( + final StringBuffer buffer, + final Set helpSettings, + final Comparator comp, + final String separator); + + /** + * Indicates whether group members must be present for the CommandLine to be + * valid. + * + * @see #getMinimum() + * @see #getMaximum() + * @return true iff the CommandLine will be invalid without at least one + * member option + */ + boolean isRequired(); + + /** + * Retrieves the minimum number of members required for a valid Group + * + * @return the minimum number of members + */ + int getMinimum(); + + /** + * Retrieves the maximum number of members acceptable for a valid Group + * + * @return the maximum number of members + */ + int getMaximum(); +} diff --git a/src/java/org/apache/commons/cli2/HelpLine.java b/src/java/org/apache/commons/cli2/HelpLine.java index def8d2fb7..2043a4841 100644 --- a/src/java/org/apache/commons/cli2/HelpLine.java +++ b/src/java/org/apache/commons/cli2/HelpLine.java @@ -1 +1,53 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Comparator;import java.util.Set;/** * Represents a line of help for a particular Option. */public interface HelpLine { /** * @return The description of the option */ String getDescription(); /** * @return The level of indentation for this line */ int getIndent(); /** * @return The Option that the help line relates to */ Option getOption(); /** * Builds a usage string for the option using the specified settings and * comparator. * * @param helpSettings * the settings to apply * @param comparator * a comparator to sort options when applicable * @return the usage string */ String usage(final Set helpSettings, final Comparator comparator);} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.Comparator; +import java.util.Set; + +/** + * Represents a line of help for a particular Option. + */ +public interface HelpLine { + + /** + * @return The description of the option + */ + String getDescription(); + + /** + * @return The level of indentation for this line + */ + int getIndent(); + + /** + * @return The Option that the help line relates to + */ + Option getOption(); + + /** + * Builds a usage string for the option using the specified settings and + * comparator. + * + * @param helpSettings + * the settings to apply + * @param comparator + * a comparator to sort options when applicable + * @return the usage string + */ + String usage(final Set helpSettings, final Comparator comparator); +} \ No newline at end of file diff --git a/src/java/org/apache/commons/cli2/Option.java b/src/java/org/apache/commons/cli2/Option.java index b33e8cd7e..d0aaaa6c6 100644 --- a/src/java/org/apache/commons/cli2/Option.java +++ b/src/java/org/apache/commons/cli2/Option.java @@ -1 +1,197 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Comparator;import java.util.List;import java.util.ListIterator;import java.util.Set;/** * The super type of all options representing a particular element of the * command line interface. */public interface Option { /** * Processes String arguments into a CommandLine. * * The iterator will initially point at the first argument to be processed * and at the end of the method should point to the first argument not * processed. This method MUST process at least one argument from the * ListIterator. * * @param commandLine * The CommandLine object to store results in * @param args * The arguments to process * @throws OptionException * if any problems occur */ void process( final WriteableCommandLine commandLine, final ListIterator args) throws OptionException; /** * Adds defaults to a CommandLine. * * Any defaults for this option are applied as well as the defaults for * any contained options * * @param commandLine * The CommandLine object to store defaults in */ void defaults(final WriteableCommandLine commandLine); /** * Indicates whether this Option will be able to process the particular * argument. * * @param argument * The argument to be tested * @return true if the argument can be processed by this Option */ boolean canProcess(final WriteableCommandLine commandLine, final String argument); /** * Indicates whether this Option will be able to process the particular * argument. The ListIterator must be restored to the initial state before * returning the boolean. * * @see #canProcess(WriteableCommandLine,String) * @param arguments * the ListIterator over String arguments * @return true if the argument can be processed by this Option */ boolean canProcess(final WriteableCommandLine commandLine, final ListIterator arguments); /** * Identifies the argument prefixes that should trigger this option. This * is used to decide which of many Options should be tried when processing * a given argument string. * * The returned Set must not be null. * * @return The set of triggers for this Option */ Set getTriggers(); /** * Identifies the argument prefixes that should be considered options. This * is used to identify whether a given string looks like an option or an * argument value. Typically an option would return the set [--,-] while * switches might offer [-,+]. * * The returned Set must not be null. * * @return The set of prefixes for this Option */ Set getPrefixes(); /** * Checks that the supplied CommandLine is valid with respect to this * option. * * @param commandLine * The CommandLine to check. * @throws OptionException * if the CommandLine is not valid. */ void validate(final WriteableCommandLine commandLine) throws OptionException; /** * Builds up a list of HelpLineImpl instances to be presented by HelpFormatter. * * @see HelpLine * @see org.apache.commons.cli2.util.HelpFormatter * @param depth * the initial indent depth * @param helpSettings * the HelpSettings that should be applied * @param comp * a comparator used to sort options when applicable. * @return a List of HelpLineImpl objects */ List helpLines( final int depth, final Set helpSettings, final Comparator comp); /** * Appends usage information to the specified StringBuffer * * @param buffer the buffer to append to * @param helpSettings a set of display settings @see DisplaySetting * @param comp a comparator used to sort the Options */ void appendUsage( final StringBuffer buffer, final Set helpSettings, final Comparator comp); /** * The preferred name of an option is used for generating help and usage * information. * * @return The preferred name of the option */ String getPreferredName(); /** * Returns a description of the option. This string is used to build help * messages as in the HelpFormatter. * * @see org.apache.commons.cli2.util.HelpFormatter * @return a description of the option. */ String getDescription(); /** * Returns the id of the option. This can be used in a loop and switch * construct: * * * for(Option o : cmd.getOptions()){ * switch(o.getId()){ * case POTENTIAL_OPTION: * ... * } * } * * * The returned value is not guarenteed to be unique. * * @return the id of the option. */ int getId(); /** * Recursively searches for an option with the supplied trigger. * * @param trigger the trigger to search for. * @return the matching option or null. */ Option findOption(final String trigger); /** * Indicates whether this option is required to be present. * @return true iff the CommandLine will be invalid without this Option */ boolean isRequired();} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.Comparator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +/** + * The super type of all options representing a particular element of the + * command line interface. + */ +public interface Option { + + /** + * Processes String arguments into a CommandLine. + * + * The iterator will initially point at the first argument to be processed + * and at the end of the method should point to the first argument not + * processed. This method MUST process at least one argument from the + * ListIterator. + * + * @param commandLine + * The CommandLine object to store results in + * @param args + * The arguments to process + * @throws OptionException + * if any problems occur + */ + void process( + final WriteableCommandLine commandLine, + final ListIterator args) + throws OptionException; + + /** + * Adds defaults to a CommandLine. + * + * Any defaults for this option are applied as well as the defaults for + * any contained options + * + * @param commandLine + * The CommandLine object to store defaults in + */ + void defaults(final WriteableCommandLine commandLine); + + /** + * Indicates whether this Option will be able to process the particular + * argument. + * + * @param argument + * The argument to be tested + * @return true if the argument can be processed by this Option + */ + boolean canProcess(final WriteableCommandLine commandLine, final String argument); + + /** + * Indicates whether this Option will be able to process the particular + * argument. The ListIterator must be restored to the initial state before + * returning the boolean. + * + * @see #canProcess(WriteableCommandLine,String) + * @param arguments + * the ListIterator over String arguments + * @return true if the argument can be processed by this Option + */ + boolean canProcess(final WriteableCommandLine commandLine, final ListIterator arguments); + + /** + * Identifies the argument prefixes that should trigger this option. This + * is used to decide which of many Options should be tried when processing + * a given argument string. + * + * The returned Set must not be null. + * + * @return The set of triggers for this Option + */ + Set getTriggers(); + + /** + * Identifies the argument prefixes that should be considered options. This + * is used to identify whether a given string looks like an option or an + * argument value. Typically an option would return the set [--,-] while + * switches might offer [-,+]. + * + * The returned Set must not be null. + * + * @return The set of prefixes for this Option + */ + Set getPrefixes(); + + /** + * Checks that the supplied CommandLine is valid with respect to this + * option. + * + * @param commandLine + * The CommandLine to check. + * @throws OptionException + * if the CommandLine is not valid. + */ + void validate(final WriteableCommandLine commandLine) + throws OptionException; + + /** + * Builds up a list of HelpLineImpl instances to be presented by HelpFormatter. + * + * @see HelpLine + * @see org.apache.commons.cli2.util.HelpFormatter + * @param depth + * the initial indent depth + * @param helpSettings + * the HelpSettings that should be applied + * @param comp + * a comparator used to sort options when applicable. + * @return a List of HelpLineImpl objects + */ + List helpLines( + final int depth, + final Set helpSettings, + final Comparator comp); + + /** + * Appends usage information to the specified StringBuffer + * + * @param buffer the buffer to append to + * @param helpSettings a set of display settings @see DisplaySetting + * @param comp a comparator used to sort the Options + */ + void appendUsage( + final StringBuffer buffer, + final Set helpSettings, + final Comparator comp); + + /** + * The preferred name of an option is used for generating help and usage + * information. + * + * @return The preferred name of the option + */ + String getPreferredName(); + + /** + * Returns a description of the option. This string is used to build help + * messages as in the HelpFormatter. + * + * @see org.apache.commons.cli2.util.HelpFormatter + * @return a description of the option. + */ + String getDescription(); + + /** + * Returns the id of the option. This can be used in a loop and switch + * construct: + * + * + * for(Option o : cmd.getOptions()){ + * switch(o.getId()){ + * case POTENTIAL_OPTION: + * ... + * } + * } + * + * + * The returned value is not guarenteed to be unique. + * + * @return the id of the option. + */ + int getId(); + + /** + * Recursively searches for an option with the supplied trigger. + * + * @param trigger the trigger to search for. + * @return the matching option or null. + */ + Option findOption(final String trigger); + + /** + * Indicates whether this option is required to be present. + * @return true iff the CommandLine will be invalid without this Option + */ + boolean isRequired(); +} diff --git a/src/java/org/apache/commons/cli2/OptionException.java b/src/java/org/apache/commons/cli2/OptionException.java index f431def95..15b408ba9 100644 --- a/src/java/org/apache/commons/cli2/OptionException.java +++ b/src/java/org/apache/commons/cli2/OptionException.java @@ -1 +1,107 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Collections;import java.util.Set;import org.apache.commons.cli2.resource.ResourceHelper;/** * A problem found while dealing with command line options. */public class OptionException extends Exception { /** * The settings used when displaying the related Option. * * @see DisplaySetting */ public static final Set HELP_SETTINGS = Collections.unmodifiableSet(Collections.singleton(DisplaySetting.DISPLAY_PROPERTY_OPTION)); /** resource helper instance */ private static final ResourceHelper helper = ResourceHelper.getResourceHelper(); /** The Option the exception relates to */ private final Option option; /** The message explaining the Exception */ private final String message; /** * Creates a new OptionException. * * @param option * The Option the exception relates to */ public OptionException(final Option option) { this(option, null, null); } /** * Creates a new OptionException. * @param option the Option the exception relates to * @param messageKey the id of the message to display */ public OptionException(final Option option, final String messageKey) { this(option, messageKey, null); } /** * Creates a new OptionException. * @param option the Option the exception relates to * @param messageKey the id of the message to display * @param value a value to display with the message */ public OptionException(final Option option, final String messageKey, final String value) { this.option = option; if (messageKey != null) { final StringBuffer buffer = new StringBuffer(); if (value != null) { buffer.append(helper.getMessage(messageKey, value)); } else { buffer.append(helper.getMessage(messageKey)); } buffer.append(" "); option.appendUsage(buffer, HELP_SETTINGS, null); message = buffer.toString(); } else { message = ""; } } /** * Gets the Option the exception relates to * * @return The related Option */ public Option getOption() { return option; } public String getMessage() { return message; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.Collections; +import java.util.Set; + +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * A problem found while dealing with command line options. + */ +public class OptionException + extends Exception { + /** + * The settings used when displaying the related Option. + * + * @see DisplaySetting + */ + public static final Set HELP_SETTINGS = + Collections.unmodifiableSet(Collections.singleton(DisplaySetting.DISPLAY_PROPERTY_OPTION)); + + /** resource helper instance */ + private static final ResourceHelper helper = ResourceHelper.getResourceHelper(); + + /** The Option the exception relates to */ + private final Option option; + + /** The message explaining the Exception */ + private final String message; + + /** + * Creates a new OptionException. + * + * @param option + * The Option the exception relates to + */ + public OptionException(final Option option) { + this(option, null, null); + } + + /** + * Creates a new OptionException. + * @param option the Option the exception relates to + * @param messageKey the id of the message to display + */ + public OptionException(final Option option, + final String messageKey) { + this(option, messageKey, null); + } + + /** + * Creates a new OptionException. + * @param option the Option the exception relates to + * @param messageKey the id of the message to display + * @param value a value to display with the message + */ + public OptionException(final Option option, + final String messageKey, + final String value) { + this.option = option; + + if (messageKey != null) { + final StringBuffer buffer = new StringBuffer(); + + if (value != null) { + buffer.append(helper.getMessage(messageKey, value)); + } else { + buffer.append(helper.getMessage(messageKey)); + } + + buffer.append(" "); + + option.appendUsage(buffer, HELP_SETTINGS, null); + message = buffer.toString(); + } else { + message = ""; + } + } + + /** + * Gets the Option the exception relates to + * + * @return The related Option + */ + public Option getOption() { + return option; + } + + public String getMessage() { + return message; + } +} diff --git a/src/java/org/apache/commons/cli2/Parent.java b/src/java/org/apache/commons/cli2/Parent.java index b8af44c59..eafad2dc2 100644 --- a/src/java/org/apache/commons/cli2/Parent.java +++ b/src/java/org/apache/commons/cli2/Parent.java @@ -1 +1,41 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.ListIterator;/** * An Option that can have an argument and/or group of child Options in the form * "-f <arg> [-a|-b|-c]". */public interface Parent extends Option { /** * Processes the parent part of the Option. The combination of parent, * argument and children is handled by the process method. * @see Option#process(WriteableCommandLine, ListIterator) * * @param commandLine the CommandLine to write results to * @param args a ListIterator over argument strings positioned at the next * argument to process * @throws OptionException if an error occurs while processing */ void processParent( final WriteableCommandLine commandLine, final ListIterator args) throws OptionException;} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.ListIterator; + +/** + * An Option that can have an argument and/or group of child Options in the form + * "-f <arg> [-a|-b|-c]". + */ +public interface Parent extends Option { + + /** + * Processes the parent part of the Option. The combination of parent, + * argument and children is handled by the process method. + * @see Option#process(WriteableCommandLine, ListIterator) + * + * @param commandLine the CommandLine to write results to + * @param args a ListIterator over argument strings positioned at the next + * argument to process + * @throws OptionException if an error occurs while processing + */ + void processParent( + final WriteableCommandLine commandLine, + final ListIterator args) + throws OptionException; +} diff --git a/src/java/org/apache/commons/cli2/WriteableCommandLine.java b/src/java/org/apache/commons/cli2/WriteableCommandLine.java index 1189e10e9..dae2a39b5 100644 --- a/src/java/org/apache/commons/cli2/WriteableCommandLine.java +++ b/src/java/org/apache/commons/cli2/WriteableCommandLine.java @@ -1 +1,76 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.List;/** * A CommandLine that detected values and options can be written to. */public interface WriteableCommandLine extends CommandLine { /** * Adds an Option to the CommandLine * @param option the Option to add */ void addOption(final Option option); /** * Adds a value to an Option in the CommandLine. * @param option the Option to add to * @param value the value to add */ void addValue(final Option option, final Object value); /** * Sets the default values for an Option in the CommandLine * @param option the Option to add to * @param defaultValues the defaults for the option */ void setDefaultValues(final Option option, final List defaultValues); /** * Adds a switch value to an Option in the CommandLine. * @param option the Option to add to * @param value the switch value to add * @throws IllegalStateException if the switch has already been added */ void addSwitch(final Option option, final boolean value) throws IllegalStateException; /** * Sets the default state for a Switch in the CommandLine. * @param option the Option to add to * @param defaultSwitch the defaults state for ths switch */ void setDefaultSwitch(final Option option, final Boolean defaultSwitch); /** * Adds a property value to a name in the CommandLine. * Replaces any existing value for the property. * * @param property the name of the property * @param value the value of the property */ void addProperty(final String property, final String value); /** * Detects whether the argument looks like an Option trigger * @param argument the argument to test * @return true if the argument looks like an Option trigger */ boolean looksLikeOption(final String argument);} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.List; + +/** + * A CommandLine that detected values and options can be written to. + */ +public interface WriteableCommandLine extends CommandLine { + + /** + * Adds an Option to the CommandLine + * @param option the Option to add + */ + void addOption(final Option option); + + /** + * Adds a value to an Option in the CommandLine. + * @param option the Option to add to + * @param value the value to add + */ + void addValue(final Option option, final Object value); + + /** + * Sets the default values for an Option in the CommandLine + * @param option the Option to add to + * @param defaultValues the defaults for the option + */ + void setDefaultValues(final Option option, final List defaultValues); + + /** + * Adds a switch value to an Option in the CommandLine. + * @param option the Option to add to + * @param value the switch value to add + * @throws IllegalStateException if the switch has already been added + */ + void addSwitch(final Option option, final boolean value) throws IllegalStateException; + + /** + * Sets the default state for a Switch in the CommandLine. + * @param option the Option to add to + * @param defaultSwitch the defaults state for ths switch + */ + void setDefaultSwitch(final Option option, final Boolean defaultSwitch); + + /** + * Adds a property value to a name in the CommandLine. + * Replaces any existing value for the property. + * + * @param property the name of the property + * @param value the value of the property + */ + void addProperty(final String property, final String value); + + /** + * Detects whether the argument looks like an Option trigger + * @param argument the argument to test + * @return true if the argument looks like an Option trigger + */ + boolean looksLikeOption(final String argument); +} diff --git a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java b/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java index 491106472..6c115d170 100644 --- a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java @@ -1 +1,286 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.ArrayList;import java.util.List;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.option.ArgumentImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;import org.apache.commons.cli2.validation.Validator;/** * Builds Argument instances. */public class ArgumentBuilder { /** i18n */ private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); /** name of the argument. Used for display and lookups in CommandLine */ private String name; /** description of the argument. Used in the automated online help */ private String description; /** minimum number of values required */ private int minimum; /** maximum number of values permitted */ private int maximum; /** character used to separate the values from the option */ private char initialSeparator; /** character used to separate the values from each other */ private char subsequentSeparator; /** object that should be used to ensure the values are valid */ private Validator validator; /** used to identify the consume remaining option, typically "--" */ private String consumeRemaining; /** default values for argument */ private List defaultValues; /** id of the argument */ private int id; /** * Creates a new ArgumentBuilder instance */ public ArgumentBuilder() { reset(); } /** * Creates a new Argument instance using the options specified in this * ArgumentBuilder. * * @return A new Argument instance using the options specified in this * ArgumentBuilder. */ public final Argument create() { final Argument argument = new ArgumentImpl( name, description, minimum, maximum, initialSeparator, subsequentSeparator, validator, consumeRemaining, defaultValues, id); reset(); return argument; } /** * Resets the ArgumentBuilder to the defaults for a new Argument. The * method is called automatically at the end of a create() call. */ public final ArgumentBuilder reset() { name = "arg"; description = null; minimum = 0; maximum = Integer.MAX_VALUE; initialSeparator = ArgumentImpl.DEFAULT_INITIAL_SEPARATOR; subsequentSeparator = ArgumentImpl.DEFAULT_SUBSEQUENT_SEPARATOR; validator = null; consumeRemaining = "--"; defaultValues = null; id = 0; return this; } /** * Sets the name of the argument. The name is used when displaying usage * information and to allow lookups in the CommandLine object. * * @see org.apache.commons.cli2.CommandLine#getValue(String) * * @param newName the name of the argument * @return this ArgumentBuilder */ public final ArgumentBuilder withName(final String newName) { if (newName == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME)); } if ("".equals(newName)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME)); } this.name = newName; return this; } /** * Sets the description of the argument. * * The description is used when displaying online help. * * @param newDescription a description of the argument * @return this ArgumentBuilder */ public final ArgumentBuilder withDescription(final String newDescription) { this.description = newDescription; return this; } /** * Sets the minimum number of values needed for the argument to be valid. * * @param newMinimum the number of values needed * @return this ArgumentBuilder */ public final ArgumentBuilder withMinimum(final int newMinimum) { if (newMinimum < 0) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM)); } this.minimum = newMinimum; return this; } /** * Sets the maximum number of values allowed for the argument to be valid. * * @param newMaximum the number of values allowed * @return this ArgumentBuilder */ public final ArgumentBuilder withMaximum(final int newMaximum) { if (newMaximum < 0) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM)); } this.maximum = newMaximum; return this; } /** * Sets the character used to separate the values from the option. When an * argument is of the form -libs:dir1,dir2,dir3 the initialSeparator would * be ':'. * * @param newInitialSeparator the character used to separate the values * from the option * @return this ArgumentBuilder */ public final ArgumentBuilder withInitialSeparator( final char newInitialSeparator) { this.initialSeparator = newInitialSeparator; return this; } /** * Sets the character used to separate the values from each other. When an * argument is of the form -libs:dir1,dir2,dir3 the subsequentSeparator * would be ','. * * @param newSubsequentSeparator the character used to separate the values * from each other * @return this ArgumentBuilder */ public final ArgumentBuilder withSubsequentSeparator( final char newSubsequentSeparator) { this.subsequentSeparator = newSubsequentSeparator; return this; } /** * Sets the validator instance used to perform validation on the Argument * values. * * @param newValidator a Validator instance * @return this ArgumentBuilder */ public final ArgumentBuilder withValidator(final Validator newValidator) { if (newValidator == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR)); } this.validator = newValidator; return this; } /** * Sets the "consume remaining" option, defaults to "--". Use this if you * want to allow values that might be confused with option strings. * * @param newConsumeRemaining the string to use for the consume * remaining option * @return this ArgumentBuilder */ public final ArgumentBuilder withConsumeRemaining(final String newConsumeRemaining) { if (newConsumeRemaining == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING)); } if ( "".equals(newConsumeRemaining)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING)); } this.consumeRemaining = newConsumeRemaining; return this; } /** * Sets the default value. * * @param defaultValue the default value for the Argument * @return this ArgumentBuilder */ public final ArgumentBuilder withDefault(final Object defaultValue) { if (defaultValue == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT)); } if (this.defaultValues == null) { this.defaultValues = new ArrayList(1); } this.defaultValues.add(defaultValue); return this; } /** * Sets the default values. * * @param newDefaultValues the default values for the Argument * @return this ArgumentBuilder */ public final ArgumentBuilder withDefaults(final List newDefaultValues) { if (newDefaultValues == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS)); } this.defaultValues = newDefaultValues; return this; } /** * Sets the id * * @param newId the id of the Argument * @return this ArgumentBuilder */ public final ArgumentBuilder withId(final int newId) { this.id = newId; return this; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.builder; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.option.ArgumentImpl; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; +import org.apache.commons.cli2.validation.Validator; + +/** + * Builds Argument instances. + */ +public class ArgumentBuilder { + + /** i18n */ + private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); + + /** name of the argument. Used for display and lookups in CommandLine */ + private String name; + + /** description of the argument. Used in the automated online help */ + private String description; + + /** minimum number of values required */ + private int minimum; + + /** maximum number of values permitted */ + private int maximum; + + /** character used to separate the values from the option */ + private char initialSeparator; + + /** character used to separate the values from each other */ + private char subsequentSeparator; + + /** object that should be used to ensure the values are valid */ + private Validator validator; + + /** used to identify the consume remaining option, typically "--" */ + private String consumeRemaining; + + /** default values for argument */ + private List defaultValues; + + /** id of the argument */ + private int id; + + /** + * Creates a new ArgumentBuilder instance + */ + public ArgumentBuilder() { + reset(); + } + + /** + * Creates a new Argument instance using the options specified in this + * ArgumentBuilder. + * + * @return A new Argument instance using the options specified in this + * ArgumentBuilder. + */ + public final Argument create() { + final Argument argument = + new ArgumentImpl( + name, + description, + minimum, + maximum, + initialSeparator, + subsequentSeparator, + validator, + consumeRemaining, + defaultValues, + id); + + reset(); + + return argument; + } + + /** + * Resets the ArgumentBuilder to the defaults for a new Argument. The + * method is called automatically at the end of a create() call. + */ + public final ArgumentBuilder reset() { + name = "arg"; + description = null; + minimum = 0; + maximum = Integer.MAX_VALUE; + initialSeparator = ArgumentImpl.DEFAULT_INITIAL_SEPARATOR; + subsequentSeparator = ArgumentImpl.DEFAULT_SUBSEQUENT_SEPARATOR; + validator = null; + consumeRemaining = "--"; + defaultValues = null; + id = 0; + return this; + } + + /** + * Sets the name of the argument. The name is used when displaying usage + * information and to allow lookups in the CommandLine object. + * + * @see org.apache.commons.cli2.CommandLine#getValue(String) + * + * @param newName the name of the argument + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withName(final String newName) { + if (newName == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME)); + } + if ("".equals(newName)) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME)); + } + this.name = newName; + return this; + } + + /** + * Sets the description of the argument. + * + * The description is used when displaying online help. + * + * @param newDescription a description of the argument + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withDescription(final String newDescription) { + this.description = newDescription; + return this; + } + + /** + * Sets the minimum number of values needed for the argument to be valid. + * + * @param newMinimum the number of values needed + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withMinimum(final int newMinimum) { + if (newMinimum < 0) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM)); + } + this.minimum = newMinimum; + return this; + } + + /** + * Sets the maximum number of values allowed for the argument to be valid. + * + * @param newMaximum the number of values allowed + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withMaximum(final int newMaximum) { + if (newMaximum < 0) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM)); + } + this.maximum = newMaximum; + return this; + } + + /** + * Sets the character used to separate the values from the option. When an + * argument is of the form -libs:dir1,dir2,dir3 the initialSeparator would + * be ':'. + * + * @param newInitialSeparator the character used to separate the values + * from the option + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withInitialSeparator( + final char newInitialSeparator) { + + this.initialSeparator = newInitialSeparator; + return this; + } + + /** + * Sets the character used to separate the values from each other. When an + * argument is of the form -libs:dir1,dir2,dir3 the subsequentSeparator + * would be ','. + * + * @param newSubsequentSeparator the character used to separate the values + * from each other + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withSubsequentSeparator( + final char newSubsequentSeparator) { + + this.subsequentSeparator = newSubsequentSeparator; + return this; + } + + /** + * Sets the validator instance used to perform validation on the Argument + * values. + * + * @param newValidator a Validator instance + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withValidator(final Validator newValidator) { + if (newValidator == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR)); + } + this.validator = newValidator; + return this; + } + + /** + * Sets the "consume remaining" option, defaults to "--". Use this if you + * want to allow values that might be confused with option strings. + * + * @param newConsumeRemaining the string to use for the consume + * remaining option + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withConsumeRemaining(final String newConsumeRemaining) { + if (newConsumeRemaining == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING)); + } + if ( "".equals(newConsumeRemaining)) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING)); + } + this.consumeRemaining = newConsumeRemaining; + return this; + } + + /** + * Sets the default value. + * + * @param defaultValue the default value for the Argument + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withDefault(final Object defaultValue) { + if (defaultValue == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT)); + } + + if (this.defaultValues == null) { + this.defaultValues = new ArrayList(1); + } + this.defaultValues.add(defaultValue); + return this; + } + + /** + * Sets the default values. + * + * @param newDefaultValues the default values for the Argument + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withDefaults(final List newDefaultValues) { + if (newDefaultValues == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS)); + } + this.defaultValues = newDefaultValues; + return this; + } + + /** + * Sets the id + * + * @param newId the id of the Argument + * @return this ArgumentBuilder + */ + public final ArgumentBuilder withId(final int newId) { + this.id = newId; + return this; + } +} diff --git a/src/java/org/apache/commons/cli2/builder/CommandBuilder.java b/src/java/org/apache/commons/cli2/builder/CommandBuilder.java index 190f45590..56c7eb21d 100644 --- a/src/java/org/apache/commons/cli2/builder/CommandBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/CommandBuilder.java @@ -1 +1,187 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.HashSet;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.option.Command;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Builds Command instances */public class CommandBuilder { /** the preferred name of the command */ private String preferredName; /** the description of the command */ private String description; /** the aliases of the command */ private Set aliases; /** whether the command is required or not */ private boolean required; /** the argument of the command */ private Argument argument; /** the children of the command */ private Group children; /** the id of the command */ private int id; /** * Creates a new CommandBuilder instance. */ public CommandBuilder() { reset(); } /** * Creates a new Command instance using the properties of the * CommandBuilder. * * @return the new Command instance */ public Command create() { // check we have a valid name if (preferredName == null) { throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME)); } // build the command final Command option = new Command(preferredName, description, aliases, required, argument, children, id); // reset the builder reset(); return option; } /** * Resets the CommandBuilder to the defaults for a new Command. * * This method is called automatically at the end of the * {@link #create() create} method. */ public CommandBuilder reset() { preferredName = null; description = null; aliases = new HashSet(); required = false; argument = null; children = null; id = 0; return this; } /** * Specifies the name for the next Command * that is created. The first name is used as the preferred * display name for the Command and then * later names are used as aliases. * * @param name the name for the next Command * that is created. * @return this CommandBuilder. */ public CommandBuilder withName(final String name) { if (preferredName == null) { preferredName = name; } else { aliases.add(name); } return this; } /** * Specifies the description for the next Command * that is created. This description is used to produce * help documentation for the Command. * * @param newDescription the description for the next * Command that is created. * @return this CommandBuilder. */ public CommandBuilder withDescription(final String newDescription) { this.description = newDescription; return this; } /** * Specifies whether the next Command created is * required or not. * @param newRequired whether the next Command created is * required or not. * @return this CommandBuilder. */ public CommandBuilder withRequired(final boolean newRequired) { this.required = newRequired; return this; } /** * Specifies the children for the next Command * that is created. * * @param newChildren the child options for the next Command * that is created. * @return this CommandBuilder. */ public CommandBuilder withChildren(final Group newChildren) { this.children = newChildren; return this; } /** * Specifies the argument for the next Command * that is created. * * @param newArgument the argument for the next Command * that is created. * @return this CommandBuilder. */ public CommandBuilder withArgument(final Argument newArgument) { this.argument = newArgument; return this; } /** * Specifies the id for the next Command that is created. * * @param newId the id for the next Command that is created. * @return this CommandBuilder. */ public final CommandBuilder withId(final int newId) { this.id = newId; return this; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.builder; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.option.Command; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * Builds Command instances + */ +public class CommandBuilder { + /** the preferred name of the command */ + private String preferredName; + + /** the description of the command */ + private String description; + + /** the aliases of the command */ + private Set aliases; + + /** whether the command is required or not */ + private boolean required; + + /** the argument of the command */ + private Argument argument; + + /** the children of the command */ + private Group children; + + /** the id of the command */ + private int id; + + /** + * Creates a new CommandBuilder instance. + */ + public CommandBuilder() { + reset(); + } + + /** + * Creates a new Command instance using the properties of the + * CommandBuilder. + * + * @return the new Command instance + */ + public Command create() { + // check we have a valid name + if (preferredName == null) { + throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME)); + } + + // build the command + final Command option = + new Command(preferredName, description, aliases, required, argument, children, id); + + // reset the builder + reset(); + + return option; + } + + /** + * Resets the CommandBuilder to the defaults for a new Command. + * + * This method is called automatically at the end of the + * {@link #create() create} method. + */ + public CommandBuilder reset() { + preferredName = null; + description = null; + aliases = new HashSet(); + required = false; + argument = null; + children = null; + id = 0; + + return this; + } + + /** + * Specifies the name for the next Command + * that is created. The first name is used as the preferred + * display name for the Command and then + * later names are used as aliases. + * + * @param name the name for the next Command + * that is created. + * @return this CommandBuilder. + */ + public CommandBuilder withName(final String name) { + if (preferredName == null) { + preferredName = name; + } else { + aliases.add(name); + } + + return this; + } + + /** + * Specifies the description for the next Command + * that is created. This description is used to produce + * help documentation for the Command. + * + * @param newDescription the description for the next + * Command that is created. + * @return this CommandBuilder. + */ + public CommandBuilder withDescription(final String newDescription) { + this.description = newDescription; + + return this; + } + + /** + * Specifies whether the next Command created is + * required or not. + * @param newRequired whether the next Command created is + * required or not. + * @return this CommandBuilder. + */ + public CommandBuilder withRequired(final boolean newRequired) { + this.required = newRequired; + + return this; + } + + /** + * Specifies the children for the next Command + * that is created. + * + * @param newChildren the child options for the next Command + * that is created. + * @return this CommandBuilder. + */ + public CommandBuilder withChildren(final Group newChildren) { + this.children = newChildren; + + return this; + } + + /** + * Specifies the argument for the next Command + * that is created. + * + * @param newArgument the argument for the next Command + * that is created. + * @return this CommandBuilder. + */ + public CommandBuilder withArgument(final Argument newArgument) { + this.argument = newArgument; + + return this; + } + + /** + * Specifies the id for the next Command that is created. + * + * @param newId the id for the next Command that is created. + * @return this CommandBuilder. + */ + public final CommandBuilder withId(final int newId) { + this.id = newId; + + return this; + } +} diff --git a/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java b/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java index 4cc53bad1..cecfcf54c 100644 --- a/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java @@ -1 +1,215 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.HashSet;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.option.DefaultOption;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Builds DefaultOption instances. */public class DefaultOptionBuilder { private final String shortPrefix; private final String longPrefix; private final boolean burstEnabled; private String preferredName; private Set aliases; private Set burstAliases; private boolean required; private String description; private Argument argument; private Group children; private int id; /** * Creates a new DefaultOptionBuilder using defaults * @see DefaultOption#DEFAULT_SHORT_PREFIX * @see DefaultOption#DEFAULT_LONG_PREFIX * @see DefaultOption#DEFAULT_BURST_ENABLED */ public DefaultOptionBuilder() { this(DefaultOption.DEFAULT_SHORT_PREFIX, DefaultOption.DEFAULT_LONG_PREFIX, DefaultOption.DEFAULT_BURST_ENABLED); } /** * Creates a new DefaultOptionBuilder * @param shortPrefix the prefix to use for short options * @param longPrefix the prefix to use for long options * @param burstEnabled whether to allow gnu style bursting * @throws IllegalArgumentException if either prefix is less than on * character long */ public DefaultOptionBuilder(final String shortPrefix, final String longPrefix, final boolean burstEnabled) throws IllegalArgumentException { if ((shortPrefix == null) || (shortPrefix.length() == 0)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX)); } if ((longPrefix == null) || (longPrefix.length() == 0)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX)); } this.shortPrefix = shortPrefix; this.longPrefix = longPrefix; this.burstEnabled = burstEnabled; reset(); } /** * Creates a DefaultOption instance * @return the new instance * @throws IllegalStateException if no names have been supplied */ public DefaultOption create() throws IllegalStateException { if (preferredName == null) { throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME)); } final DefaultOption option = new DefaultOption(shortPrefix, longPrefix, burstEnabled, preferredName, description, aliases, burstAliases, required, argument, children, id); reset(); return option; } /** * Resets the builder */ public DefaultOptionBuilder reset() { preferredName = null; description = null; aliases = new HashSet(); burstAliases = new HashSet(); required = false; argument = null; children = null; id = 0; return this; } /** * Use this short option name. The first name is used as the preferred * display name for the Command and then later names are used as aliases. * * @param shortName the name to use * @return this builder */ public DefaultOptionBuilder withShortName(final String shortName) { final String name = shortPrefix + shortName; if (preferredName == null) { preferredName = name; } else { aliases.add(name); } if (burstEnabled && (name.length() == (shortPrefix.length() + 1))) { burstAliases.add(name); } return this; } /** * Use this long option name. The first name is used as the preferred * display name for the Command and then later names are used as aliases. * * @param longName the name to use * @return this builder */ public DefaultOptionBuilder withLongName(final String longName) { final String name = longPrefix + longName; if (preferredName == null) { preferredName = name; } else { aliases.add(name); } return this; } /** * Use this option description * @param newDescription the description to use * @return this builder */ public DefaultOptionBuilder withDescription(final String newDescription) { this.description = newDescription; return this; } /** * Use this optionality * @param newRequired true iff the Option is required * @return this builder */ public DefaultOptionBuilder withRequired(final boolean newRequired) { this.required = newRequired; return this; } /** * Use this child Group * @param newChildren the child Group to use * @return this builder */ public DefaultOptionBuilder withChildren(final Group newChildren) { this.children = newChildren; return this; } /** * Use this Argument * @param newArgument the argument to use * @return this builder */ public DefaultOptionBuilder withArgument(final Argument newArgument) { this.argument = newArgument; return this; } /** * Sets the id * * @param newId * the id of the DefaultOption * @return this DefaultOptionBuilder */ public final DefaultOptionBuilder withId(final int newId) { this.id = newId; return this; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.builder; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.option.DefaultOption; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * Builds DefaultOption instances. + */ +public class DefaultOptionBuilder { + private final String shortPrefix; + private final String longPrefix; + private final boolean burstEnabled; + private String preferredName; + private Set aliases; + private Set burstAliases; + private boolean required; + private String description; + private Argument argument; + private Group children; + private int id; + + /** + * Creates a new DefaultOptionBuilder using defaults + * @see DefaultOption#DEFAULT_SHORT_PREFIX + * @see DefaultOption#DEFAULT_LONG_PREFIX + * @see DefaultOption#DEFAULT_BURST_ENABLED + */ + public DefaultOptionBuilder() { + this(DefaultOption.DEFAULT_SHORT_PREFIX, DefaultOption.DEFAULT_LONG_PREFIX, + DefaultOption.DEFAULT_BURST_ENABLED); + } + + /** + * Creates a new DefaultOptionBuilder + * @param shortPrefix the prefix to use for short options + * @param longPrefix the prefix to use for long options + * @param burstEnabled whether to allow gnu style bursting + * @throws IllegalArgumentException if either prefix is less than on + * character long + */ + public DefaultOptionBuilder(final String shortPrefix, + final String longPrefix, + final boolean burstEnabled) + throws IllegalArgumentException { + if ((shortPrefix == null) || (shortPrefix.length() == 0)) { + throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX)); + } + + if ((longPrefix == null) || (longPrefix.length() == 0)) { + throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX)); + } + + this.shortPrefix = shortPrefix; + this.longPrefix = longPrefix; + this.burstEnabled = burstEnabled; + reset(); + } + + /** + * Creates a DefaultOption instance + * @return the new instance + * @throws IllegalStateException if no names have been supplied + */ + public DefaultOption create() + throws IllegalStateException { + if (preferredName == null) { + throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME)); + } + + final DefaultOption option = + new DefaultOption(shortPrefix, longPrefix, burstEnabled, preferredName, description, + aliases, burstAliases, required, argument, children, id); + + reset(); + + return option; + } + + /** + * Resets the builder + */ + public DefaultOptionBuilder reset() { + preferredName = null; + description = null; + aliases = new HashSet(); + burstAliases = new HashSet(); + required = false; + argument = null; + children = null; + id = 0; + + return this; + } + + /** + * Use this short option name. The first name is used as the preferred + * display name for the Command and then later names are used as aliases. + * + * @param shortName the name to use + * @return this builder + */ + public DefaultOptionBuilder withShortName(final String shortName) { + final String name = shortPrefix + shortName; + + if (preferredName == null) { + preferredName = name; + } else { + aliases.add(name); + } + + if (burstEnabled && (name.length() == (shortPrefix.length() + 1))) { + burstAliases.add(name); + } + + return this; + } + + /** + * Use this long option name. The first name is used as the preferred + * display name for the Command and then later names are used as aliases. + * + * @param longName the name to use + * @return this builder + */ + public DefaultOptionBuilder withLongName(final String longName) { + final String name = longPrefix + longName; + + if (preferredName == null) { + preferredName = name; + } else { + aliases.add(name); + } + + return this; + } + + /** + * Use this option description + * @param newDescription the description to use + * @return this builder + */ + public DefaultOptionBuilder withDescription(final String newDescription) { + this.description = newDescription; + + return this; + } + + /** + * Use this optionality + * @param newRequired true iff the Option is required + * @return this builder + */ + public DefaultOptionBuilder withRequired(final boolean newRequired) { + this.required = newRequired; + + return this; + } + + /** + * Use this child Group + * @param newChildren the child Group to use + * @return this builder + */ + public DefaultOptionBuilder withChildren(final Group newChildren) { + this.children = newChildren; + + return this; + } + + /** + * Use this Argument + * @param newArgument the argument to use + * @return this builder + */ + public DefaultOptionBuilder withArgument(final Argument newArgument) { + this.argument = newArgument; + + return this; + } + + /** + * Sets the id + * + * @param newId + * the id of the DefaultOption + * @return this DefaultOptionBuilder + */ + public final DefaultOptionBuilder withId(final int newId) { + this.id = newId; + + return this; + } +} diff --git a/src/java/org/apache/commons/cli2/builder/GroupBuilder.java b/src/java/org/apache/commons/cli2/builder/GroupBuilder.java index 887aa2928..9d098464b 100644 --- a/src/java/org/apache/commons/cli2/builder/GroupBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/GroupBuilder.java @@ -1 +1,118 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.ArrayList;import java.util.List;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.option.GroupImpl;/** * Builds Group instances */public class GroupBuilder { private String name; private String description; private List options; private int minimum; private int maximum; /** * Creates a new GroupBuilder */ public GroupBuilder() { reset(); } /** * Creates a new Group instance * @return the new Group instance */ public Group create() { final GroupImpl group = new GroupImpl(options, name, description, minimum, maximum); reset(); return group; } /** * Resets the builder */ public GroupBuilder reset() { name = null; description = null; options = new ArrayList(); minimum = 0; maximum = Integer.MAX_VALUE; return this; } /** * Use this option description * @param newDescription the description to use * @return this builder */ public GroupBuilder withDescription(final String newDescription) { this.description = newDescription; return this; } /** * Use this option name * @param newName the name to use * @return this builder */ public GroupBuilder withName(final String newName) { this.name = newName; return this; } /** * A valid group requires at least this many options present * @param newMinimum the minimum Options required * @return this builder */ public GroupBuilder withMinimum(final int newMinimum) { this.minimum = newMinimum; return this; } /** * A valid group requires at most this many options present * @param newMaximum the maximum Options allowed * @return this builder */ public GroupBuilder withMaximum(final int newMaximum) { this.maximum = newMaximum; return this; } /** * Add this option to the group * @param option the Option to add * @return this builder */ public GroupBuilder withOption(final Option option) { this.options.add(option); return this; }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.builder; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.option.GroupImpl; + +/** + * Builds Group instances + */ +public class GroupBuilder { + + private String name; + private String description; + private List options; + private int minimum; + private int maximum; + + /** + * Creates a new GroupBuilder + */ + public GroupBuilder() { + reset(); + } + + /** + * Creates a new Group instance + * @return the new Group instance + */ + public Group create() { + final GroupImpl group = + new GroupImpl(options, name, description, minimum, maximum); + + reset(); + + return group; + } + + /** + * Resets the builder + */ + public GroupBuilder reset() { + name = null; + description = null; + options = new ArrayList(); + minimum = 0; + maximum = Integer.MAX_VALUE; + return this; + } + + /** + * Use this option description + * @param newDescription the description to use + * @return this builder + */ + public GroupBuilder withDescription(final String newDescription) { + this.description = newDescription; + return this; + } + + /** + * Use this option name + * @param newName the name to use + * @return this builder + */ + public GroupBuilder withName(final String newName) { + this.name = newName; + return this; + } + + /** + * A valid group requires at least this many options present + * @param newMinimum the minimum Options required + * @return this builder + */ + public GroupBuilder withMinimum(final int newMinimum) { + this.minimum = newMinimum; + return this; + } + + /** + * A valid group requires at most this many options present + * @param newMaximum the maximum Options allowed + * @return this builder + */ + public GroupBuilder withMaximum(final int newMaximum) { + this.maximum = newMaximum; + return this; + } + + /** + * Add this option to the group + * @param option the Option to add + * @return this builder + */ + public GroupBuilder withOption(final Option option) { + this.options.add(option); + return this; + } +} diff --git a/src/java/org/apache/commons/cli2/builder/PatternBuilder.java b/src/java/org/apache/commons/cli2/builder/PatternBuilder.java index 43ed77b4d..2b4c1b54d 100644 --- a/src/java/org/apache/commons/cli2/builder/PatternBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/PatternBuilder.java @@ -1 +1,202 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.Iterator;import java.util.LinkedHashSet;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.validation.ClassValidator;import org.apache.commons.cli2.validation.DateValidator;import org.apache.commons.cli2.validation.FileValidator;import org.apache.commons.cli2.validation.NumberValidator;import org.apache.commons.cli2.validation.UrlValidator;import org.apache.commons.cli2.validation.Validator;/** * Builds Options using a String pattern *///TODO Document and link to the acceptable patternspublic class PatternBuilder { private final GroupBuilder gbuilder; private final DefaultOptionBuilder obuilder; private final ArgumentBuilder abuilder; /** * Creates a new PatternBuilder */ public PatternBuilder() { this( new GroupBuilder(), new DefaultOptionBuilder(), new ArgumentBuilder()); } /** * Creates a new PatternBuilder * @param gbuilder the GroupBuilder to use * @param obuilder the DefaultOptionBuilder to use * @param abuilder the ArgumentBuilder to use */ public PatternBuilder( final GroupBuilder gbuilder, final DefaultOptionBuilder obuilder, final ArgumentBuilder abuilder) { this.gbuilder = gbuilder; this.obuilder = obuilder; this.abuilder = abuilder; } private final Set options = new LinkedHashSet(); /** * Creates a new Option instance. * @return a new Option instance */ public Option create() { final Option option; if (options.size() == 1) { option = (Option)options.iterator().next(); } else { gbuilder.reset(); for (final Iterator i = options.iterator(); i.hasNext();) { gbuilder.withOption((Option)i.next()); } option = gbuilder.create(); } reset(); return option; } /** * Resets this builder */ public PatternBuilder reset() { options.clear(); return this; } private void createOption( final char type, final boolean required, final char opt) { final Argument argument; if (type != ' ') { abuilder.reset(); abuilder.withValidator(validator(type)); if (required) { abuilder.withMinimum(1); } if (type != '*') { abuilder.withMaximum(1); } argument = abuilder.create(); } else { argument = null; } obuilder.reset(); obuilder.withArgument(argument); obuilder.withShortName(String.valueOf(opt)); obuilder.withRequired(required); options.add(obuilder.create()); } /** * Builds an Option using a pattern string. * @param pattern the pattern to build from */ public void withPattern(final String pattern) { int sz = pattern.length(); char opt = ' '; char ch = ' '; char type = ' '; boolean required = false; for (int i = 0; i < sz; i++) { ch = pattern.charAt(i); switch (ch) { case '!' : required = true; break; case '@' : case ':' : case '%' : case '+' : case '#' : case '<' : case '>' : case '*' : case '/' : type = ch; break; default : if (opt != ' ') { createOption(type, required, opt); required = false; type = ' '; } opt = ch; } } if (opt != ' ') { createOption(type, required, opt); } } private static Validator validator(final char c) { switch (c) { case '@' : final ClassValidator classv = new ClassValidator(); classv.setInstance(true); return classv; case '+' : final ClassValidator instancev = new ClassValidator(); return instancev; //case ':':// no validator needed for a string case '%' : return NumberValidator.getNumberInstance(); case '#' : return DateValidator.getDateInstance(); case '<' : final FileValidator existingv = new FileValidator(); existingv.setExisting(true); existingv.setFile(true); return existingv; case '>' : case '*' : return new FileValidator(); case '/' : return new UrlValidator(); default : return null; } }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.builder; + +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.validation.ClassValidator; +import org.apache.commons.cli2.validation.DateValidator; +import org.apache.commons.cli2.validation.FileValidator; +import org.apache.commons.cli2.validation.NumberValidator; +import org.apache.commons.cli2.validation.UrlValidator; +import org.apache.commons.cli2.validation.Validator; + +/** + * Builds Options using a String pattern + */ +//TODO Document and link to the acceptable patterns +public class PatternBuilder { + + private final GroupBuilder gbuilder; + private final DefaultOptionBuilder obuilder; + private final ArgumentBuilder abuilder; + + /** + * Creates a new PatternBuilder + */ + public PatternBuilder() { + this( + new GroupBuilder(), + new DefaultOptionBuilder(), + new ArgumentBuilder()); + } + + /** + * Creates a new PatternBuilder + * @param gbuilder the GroupBuilder to use + * @param obuilder the DefaultOptionBuilder to use + * @param abuilder the ArgumentBuilder to use + */ + public PatternBuilder( + final GroupBuilder gbuilder, + final DefaultOptionBuilder obuilder, + final ArgumentBuilder abuilder) { + this.gbuilder = gbuilder; + this.obuilder = obuilder; + this.abuilder = abuilder; + } + + private final Set options = new LinkedHashSet(); + + /** + * Creates a new Option instance. + * @return a new Option instance + */ + public Option create() { + final Option option; + + if (options.size() == 1) { + option = (Option)options.iterator().next(); + } + else { + gbuilder.reset(); + for (final Iterator i = options.iterator(); i.hasNext();) { + gbuilder.withOption((Option)i.next()); + } + option = gbuilder.create(); + } + + reset(); + + return option; + } + + /** + * Resets this builder + */ + public PatternBuilder reset() { + options.clear(); + return this; + } + + private void createOption( + final char type, + final boolean required, + final char opt) { + final Argument argument; + if (type != ' ') { + abuilder.reset(); + abuilder.withValidator(validator(type)); + if (required) { + abuilder.withMinimum(1); + } + if (type != '*') { + abuilder.withMaximum(1); + } + argument = abuilder.create(); + } + else { + argument = null; + } + + obuilder.reset(); + obuilder.withArgument(argument); + obuilder.withShortName(String.valueOf(opt)); + obuilder.withRequired(required); + + options.add(obuilder.create()); + } + + /** + * Builds an Option using a pattern string. + * @param pattern the pattern to build from + */ + public void withPattern(final String pattern) { + int sz = pattern.length(); + + char opt = ' '; + char ch = ' '; + char type = ' '; + boolean required = false; + + for (int i = 0; i < sz; i++) { + ch = pattern.charAt(i); + + switch (ch) { + case '!' : + required = true; + break; + case '@' : + case ':' : + case '%' : + case '+' : + case '#' : + case '<' : + case '>' : + case '*' : + case '/' : + type = ch; + break; + default : + if (opt != ' ') { + createOption(type, required, opt); + required = false; + type = ' '; + } + + opt = ch; + } + } + + if (opt != ' ') { + createOption(type, required, opt); + } + } + + private static Validator validator(final char c) { + switch (c) { + case '@' : + final ClassValidator classv = new ClassValidator(); + classv.setInstance(true); + return classv; + case '+' : + final ClassValidator instancev = new ClassValidator(); + return instancev; + //case ':':// no validator needed for a string + case '%' : + return NumberValidator.getNumberInstance(); + case '#' : + return DateValidator.getDateInstance(); + case '<' : + final FileValidator existingv = new FileValidator(); + existingv.setExisting(true); + existingv.setFile(true); + return existingv; + case '>' : + case '*' : + return new FileValidator(); + case '/' : + return new UrlValidator(); + default : + return null; + } + } +} diff --git a/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java b/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java index da422aecf..fa88df359 100644 --- a/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java @@ -1 +1,194 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import java.util.HashSet;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.option.Switch;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Builds Switch instance. */public class SwitchBuilder { private final String enabledPrefix; private final String disabledPrefix; private String description; private String preferredName; private Set aliases; private boolean required; private Argument argument; private Group children; private int id; private Boolean switchDefault; /** * Creates a new SwitchBuilder using defaults. * @see Switch#DEFAULT_ENABLED_PREFIX * @see Switch#DEFAULT_DISABLED_PREFIX */ public SwitchBuilder() { this(Switch.DEFAULT_ENABLED_PREFIX, Switch.DEFAULT_DISABLED_PREFIX); } /** * Creates a new SwitchBuilder * @param enabledPrefix the prefix to use for enabling the option * @param disabledPrefix the prefix to use for disabling the option * @throws IllegalArgumentException if either prefix is less than 1 * character long or the prefixes match */ public SwitchBuilder(final String enabledPrefix, final String disabledPrefix) throws IllegalArgumentException { if ((enabledPrefix == null) || (enabledPrefix.length() < 1)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ILLEGAL_ENABLED_PREFIX)); } if ((disabledPrefix == null) || (disabledPrefix.length() < 1)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ILLEGAL_DISABLED_PREFIX)); } if (enabledPrefix.equals(disabledPrefix)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_IDENTICAL_PREFIXES)); } this.enabledPrefix = enabledPrefix; this.disabledPrefix = disabledPrefix; reset(); } /** * Creates a new Switch instance * @return a new Switch instance */ public Switch create() { final Switch option = new Switch(enabledPrefix, disabledPrefix, preferredName, aliases, description, required, argument, children, id, switchDefault); reset(); return option; } /** * Resets the builder */ public SwitchBuilder reset() { description = null; preferredName = null; required = false; aliases = new HashSet(); argument = null; children = null; id = 0; switchDefault = null; return this; } /** * Use this option description * @param newDescription the description to use * @return this builder */ public SwitchBuilder withDescription(final String newDescription) { this.description = newDescription; return this; } /** * Use this option name. The first name is used as the preferred * display name for the Command and then later names are used as aliases. * * @param name the name to use * @return this builder */ public SwitchBuilder withName(final String name) { if (preferredName == null) { preferredName = name; } else { aliases.add(name); } return this; } /** * Use this optionality * @param newRequired true iff the Option is required * @return this builder */ public SwitchBuilder withRequired(final boolean newRequired) { this.required = newRequired; return this; } /** * Use this Argument * @param newArgument the argument to use * @return this builder */ public SwitchBuilder withArgument(final Argument newArgument) { this.argument = newArgument; return this; } /** * Use this child Group * @param newChildren the child Group to use * @return this builder */ public SwitchBuilder withChildren(final Group newChildren) { this.children = newChildren; return this; } /** * Sets the id * * @param newId * the id of the Switch * @return this SwitchBuilder */ public final SwitchBuilder withId(final int newId) { this.id = newId; return this; } /** * Sets the default state for this switch * * @param newSwitchDefault the default state * @return this SwitchBuilder */ public final SwitchBuilder withSwitchDefault(final Boolean newSwitchDefault) { this.switchDefault = newSwitchDefault; return this; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.builder; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.option.Switch; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * Builds Switch instance. + */ +public class SwitchBuilder { + private final String enabledPrefix; + private final String disabledPrefix; + private String description; + private String preferredName; + private Set aliases; + private boolean required; + private Argument argument; + private Group children; + private int id; + private Boolean switchDefault; + + /** + * Creates a new SwitchBuilder using defaults. + * @see Switch#DEFAULT_ENABLED_PREFIX + * @see Switch#DEFAULT_DISABLED_PREFIX + */ + public SwitchBuilder() { + this(Switch.DEFAULT_ENABLED_PREFIX, Switch.DEFAULT_DISABLED_PREFIX); + } + + /** + * Creates a new SwitchBuilder + * @param enabledPrefix the prefix to use for enabling the option + * @param disabledPrefix the prefix to use for disabling the option + * @throws IllegalArgumentException if either prefix is less than 1 + * character long or the prefixes match + */ + public SwitchBuilder(final String enabledPrefix, + final String disabledPrefix) + throws IllegalArgumentException { + if ((enabledPrefix == null) || (enabledPrefix.length() < 1)) { + throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ILLEGAL_ENABLED_PREFIX)); + } + + if ((disabledPrefix == null) || (disabledPrefix.length() < 1)) { + throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ILLEGAL_DISABLED_PREFIX)); + } + + if (enabledPrefix.equals(disabledPrefix)) { + throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_IDENTICAL_PREFIXES)); + } + + this.enabledPrefix = enabledPrefix; + this.disabledPrefix = disabledPrefix; + reset(); + } + + /** + * Creates a new Switch instance + * @return a new Switch instance + */ + public Switch create() { + final Switch option = + new Switch(enabledPrefix, disabledPrefix, preferredName, aliases, description, + required, argument, children, id, switchDefault); + + reset(); + + return option; + } + + /** + * Resets the builder + */ + public SwitchBuilder reset() { + description = null; + preferredName = null; + required = false; + aliases = new HashSet(); + argument = null; + children = null; + id = 0; + switchDefault = null; + + return this; + } + + /** + * Use this option description + * @param newDescription the description to use + * @return this builder + */ + public SwitchBuilder withDescription(final String newDescription) { + this.description = newDescription; + + return this; + } + + /** + * Use this option name. The first name is used as the preferred + * display name for the Command and then later names are used as aliases. + * + * @param name the name to use + * @return this builder + */ + public SwitchBuilder withName(final String name) { + if (preferredName == null) { + preferredName = name; + } else { + aliases.add(name); + } + + return this; + } + + /** + * Use this optionality + * @param newRequired true iff the Option is required + * @return this builder + */ + public SwitchBuilder withRequired(final boolean newRequired) { + this.required = newRequired; + + return this; + } + + /** + * Use this Argument + * @param newArgument the argument to use + * @return this builder + */ + public SwitchBuilder withArgument(final Argument newArgument) { + this.argument = newArgument; + + return this; + } + + /** + * Use this child Group + * @param newChildren the child Group to use + * @return this builder + */ + public SwitchBuilder withChildren(final Group newChildren) { + this.children = newChildren; + + return this; + } + + /** + * Sets the id + * + * @param newId + * the id of the Switch + * @return this SwitchBuilder + */ + public final SwitchBuilder withId(final int newId) { + this.id = newId; + + return this; + } + + /** + * Sets the default state for this switch + * + * @param newSwitchDefault the default state + * @return this SwitchBuilder + */ + public final SwitchBuilder withSwitchDefault(final Boolean newSwitchDefault) { + this.switchDefault = newSwitchDefault; + + return this; + } +} diff --git a/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java index aff253d20..37f8b37b6 100644 --- a/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java @@ -1 +1,120 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.Collections;import java.util.Iterator;import java.util.List;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Instances of CommandLine represent a command line that has been processed * according to the definition supplied to the parser. */public abstract class CommandLineImpl implements CommandLine { public final boolean hasOption(final String trigger) { return hasOption(getOption(trigger)); } public final List getValues(final String trigger) { return getValues(getOption(trigger), Collections.EMPTY_LIST); } public final List getValues(final String trigger, final List defaultValues) { return getValues(getOption(trigger), defaultValues); } public final List getValues(final Option option) { return getValues(option, Collections.EMPTY_LIST); } public final Object getValue(final String trigger) { return getValue(getOption(trigger), null); } public final Object getValue(final String trigger, final Object defaultValue) { return getValue(getOption(trigger), defaultValue); } public final Object getValue(final Option option) { return getValue(option, null); } public final Object getValue(final Option option, final Object defaultValue) { final List values; if (defaultValue == null) { values = getValues(option); } else { values = getValues(option, Collections.singletonList(defaultValue)); } if (values.size() > 1) { throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES)); } if (values.isEmpty()) { return defaultValue; } return values.get(0); } public final Boolean getSwitch(final String trigger) { return getSwitch(getOption(trigger), null); } public final Boolean getSwitch(final String trigger, final Boolean defaultValue) { return getSwitch(getOption(trigger), defaultValue); } public final Boolean getSwitch(final Option option) { return getSwitch(option, null); } public final String getProperty(final String property) { return getProperty(property, null); } public final int getOptionCount(final String trigger) { return getOptionCount(getOption(trigger)); } public final int getOptionCount(final Option option) { if (option == null) { return 0; } int count = 0; for (Iterator i = getOptions().iterator(); i.hasNext();) { if (option.equals(i.next())) { ++count; } } return count; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * Instances of CommandLine represent a command line that has been processed + * according to the definition supplied to the parser. + */ +public abstract class CommandLineImpl implements CommandLine { + public final boolean hasOption(final String trigger) { + return hasOption(getOption(trigger)); + } + + public final List getValues(final String trigger) { + return getValues(getOption(trigger), Collections.EMPTY_LIST); + } + + public final List getValues(final String trigger, + final List defaultValues) { + return getValues(getOption(trigger), defaultValues); + } + + public final List getValues(final Option option) { + return getValues(option, Collections.EMPTY_LIST); + } + + public final Object getValue(final String trigger) { + return getValue(getOption(trigger), null); + } + + public final Object getValue(final String trigger, + final Object defaultValue) { + return getValue(getOption(trigger), defaultValue); + } + + public final Object getValue(final Option option) { + return getValue(option, null); + } + + public final Object getValue(final Option option, + final Object defaultValue) { + final List values; + + if (defaultValue == null) { + values = getValues(option); + } else { + values = getValues(option, Collections.singletonList(defaultValue)); + } + + if (values.size() > 1) { + throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES)); + } + + if (values.isEmpty()) { + return defaultValue; + } + + return values.get(0); + } + + public final Boolean getSwitch(final String trigger) { + return getSwitch(getOption(trigger), null); + } + + public final Boolean getSwitch(final String trigger, + final Boolean defaultValue) { + return getSwitch(getOption(trigger), defaultValue); + } + + public final Boolean getSwitch(final Option option) { + return getSwitch(option, null); + } + + public final String getProperty(final String property) { + return getProperty(property, null); + } + + public final int getOptionCount(final String trigger) { + return getOptionCount(getOption(trigger)); + } + + public final int getOptionCount(final Option option) { + if (option == null) { + return 0; + } + + int count = 0; + + for (Iterator i = getOptions().iterator(); i.hasNext();) { + if (option.equals(i.next())) { + ++count; + } + } + + return count; + } +} diff --git a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java b/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java index 1b887af8f..cb85e1fa7 100644 --- a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java @@ -1 +1,172 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Option;/** * Manages a queue of default CommandLines. This CommandLine implementation is * backed by a queue of CommandLine instances which are queried in turn until a * suitable result is found. * * CommandLine instances can either be added to the back of the queue or can be * pushed in at a specific position. * * @see #appendCommandLine(CommandLine) * @see #insertCommandLine(int, CommandLine) */public class DefaultingCommandLine extends CommandLineImpl { /** * The list of default CommandLine instances */ private final List commandLines = new ArrayList(); /** * Adds a CommandLine instance to the back of the queue. The supplied * CommandLine will be used as defaults when all other CommandLines produce * no result * * @param commandLine * the default values to use if all CommandLines */ public void appendCommandLine(final CommandLine commandLine) { commandLines.add(commandLine); } /** * Adds a CommandLine instance to a specified position in the queue. * * @param index ths position at which to insert * @param commandLine the CommandLine to insert */ public void insertCommandLine( final int index, final CommandLine commandLine) { commandLines.add(index, commandLine); } /** * Builds an iterator over the build in CommandLines. * * @return an unmodifiable iterator */ public Iterator commandLines(){ return Collections.unmodifiableList(commandLines).iterator(); } public Option getOption(String trigger) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); final Option actual = commandLine.getOption(trigger); if (actual != null) { return actual; } } return null; } public List getOptions() { final List options = new ArrayList(); final List temp = new ArrayList(); for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); temp.clear(); temp.addAll(commandLine.getOptions()); temp.removeAll(options); options.addAll(temp); } return Collections.unmodifiableList(options); } public Set getOptionTriggers() { final Set all = new HashSet(); for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); all.addAll(commandLine.getOptionTriggers()); } return Collections.unmodifiableSet(all); } public boolean hasOption(Option option) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); if (commandLine.hasOption(option)) { return true; } } return false; } public List getValues(Option option, List defaultValues) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); final List actual = commandLine.getValues(option); if (actual != null && !actual.isEmpty()) { return actual; } } if(defaultValues==null){ return Collections.EMPTY_LIST; } else{ return defaultValues; } } public Boolean getSwitch(Option option, Boolean defaultValue) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); final Boolean actual = commandLine.getSwitch(option); if (actual != null) { return actual; } } return defaultValue; } public String getProperty(String property, String defaultValue) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); final String actual = commandLine.getProperty(property); if (actual != null) { return actual; } } return defaultValue; } public Set getProperties() { final Set all = new HashSet(); for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); all.addAll(commandLine.getProperties()); } return Collections.unmodifiableSet(all); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Option; + +/** + * Manages a queue of default CommandLines. This CommandLine implementation is + * backed by a queue of CommandLine instances which are queried in turn until a + * suitable result is found. + * + * CommandLine instances can either be added to the back of the queue or can be + * pushed in at a specific position. + * + * @see #appendCommandLine(CommandLine) + * @see #insertCommandLine(int, CommandLine) + */ +public class DefaultingCommandLine extends CommandLineImpl { + + /** + * The list of default CommandLine instances + */ + private final List commandLines = new ArrayList(); + + /** + * Adds a CommandLine instance to the back of the queue. The supplied + * CommandLine will be used as defaults when all other CommandLines produce + * no result + * + * @param commandLine + * the default values to use if all CommandLines + */ + public void appendCommandLine(final CommandLine commandLine) { + commandLines.add(commandLine); + } + + /** + * Adds a CommandLine instance to a specified position in the queue. + * + * @param index ths position at which to insert + * @param commandLine the CommandLine to insert + */ + public void insertCommandLine( + final int index, + final CommandLine commandLine) { + commandLines.add(index, commandLine); + } + + /** + * Builds an iterator over the build in CommandLines. + * + * @return an unmodifiable iterator + */ + public Iterator commandLines(){ + return Collections.unmodifiableList(commandLines).iterator(); + } + + public Option getOption(String trigger) { + for (final Iterator i = commandLines.iterator(); i.hasNext();) { + final CommandLine commandLine = (CommandLine)i.next(); + final Option actual = commandLine.getOption(trigger); + if (actual != null) { + return actual; + } + } + return null; + } + + public List getOptions() { + final List options = new ArrayList(); + + final List temp = new ArrayList(); + for (final Iterator i = commandLines.iterator(); i.hasNext();) { + final CommandLine commandLine = (CommandLine)i.next(); + temp.clear(); + temp.addAll(commandLine.getOptions()); + temp.removeAll(options); + options.addAll(temp); + } + + return Collections.unmodifiableList(options); + } + + public Set getOptionTriggers() { + final Set all = new HashSet(); + for (final Iterator i = commandLines.iterator(); i.hasNext();) { + final CommandLine commandLine = (CommandLine)i.next(); + all.addAll(commandLine.getOptionTriggers()); + } + + return Collections.unmodifiableSet(all); + } + + public boolean hasOption(Option option) { + for (final Iterator i = commandLines.iterator(); i.hasNext();) { + final CommandLine commandLine = (CommandLine)i.next(); + if (commandLine.hasOption(option)) { + return true; + } + } + return false; + } + + public List getValues(Option option, List defaultValues) { + for (final Iterator i = commandLines.iterator(); i.hasNext();) { + final CommandLine commandLine = (CommandLine)i.next(); + final List actual = commandLine.getValues(option); + if (actual != null && !actual.isEmpty()) { + return actual; + } + } + if(defaultValues==null){ + return Collections.EMPTY_LIST; + } + else{ + return defaultValues; + } + } + + public Boolean getSwitch(Option option, Boolean defaultValue) { + for (final Iterator i = commandLines.iterator(); i.hasNext();) { + final CommandLine commandLine = (CommandLine)i.next(); + final Boolean actual = commandLine.getSwitch(option); + if (actual != null) { + return actual; + } + } + return defaultValue; + } + + public String getProperty(String property, String defaultValue) { + for (final Iterator i = commandLines.iterator(); i.hasNext();) { + final CommandLine commandLine = (CommandLine)i.next(); + final String actual = commandLine.getProperty(property); + if (actual != null) { + return actual; + } + } + return defaultValue; + } + + public Set getProperties() { + final Set all = new HashSet(); + for (final Iterator i = commandLines.iterator(); i.hasNext();) { + final CommandLine commandLine = (CommandLine)i.next(); + all.addAll(commandLine.getProperties()); + } + return Collections.unmodifiableSet(all); + } +} diff --git a/src/java/org/apache/commons/cli2/commandline/Parser.java b/src/java/org/apache/commons/cli2/commandline/Parser.java index 34229e368..4dd3f9670 100644 --- a/src/java/org/apache/commons/cli2/commandline/Parser.java +++ b/src/java/org/apache/commons/cli2/commandline/Parser.java @@ -1 +1,176 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.LinkedList;import java.util.List;import java.util.ListIterator;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.util.HelpFormatter;/** * A class that implements the Parser interface can parse a * String array according to the {@link Group}specified and return a * {@link CommandLine}. * * @author John Keyes (john at integralsource.com) */public class Parser { private HelpFormatter helpFormatter = new HelpFormatter(); private Option helpOption = null; private String helpTrigger = null; private Group group = null; /** * Parse the arguments according to the specified options and properties. * * @param arguments * the command line arguments * * @return the list of atomic option and value tokens * @throws OptionException * if there are any problems encountered while parsing the * command line tokens. */ public CommandLine parse(final String[] arguments) throws OptionException { // build a mutable list for the arguments final List argumentList = new LinkedList(); // copy the arguments into the new list for (int i = 0; i < arguments.length; i++) { final String argument = arguments[i]; // ensure non intern'd strings are used // so that == comparisons work as expected argumentList.add(new String(argument)); } // wet up a command line for this group final WriteableCommandLine commandLine = new WriteableCommandLineImpl(group, argumentList); // pick up any defaults from the model group.defaults(commandLine); // process the options as far as possible final ListIterator iterator = argumentList.listIterator(); Object previous = null; while (group.canProcess(commandLine, iterator)) { // peek at the next item and backtrack final Object next = iterator.next(); iterator.previous(); // if we have just tried to process this instance if (next == previous) { // abort break; } // remember previous previous = next; group.process(commandLine, iterator); } // if there are more arguments we have a problem if (iterator.hasNext()) { final String arg = (String) iterator.next(); throw new OptionException(group, ResourceConstants.UNEXPECTED_TOKEN, arg); } // no need to validate if the help option is present if (!commandLine.hasOption(helpOption) && !commandLine.hasOption(helpTrigger)) { group.validate(commandLine); } return commandLine; } /** * Parse the arguments according to the specified options and properties and * displays the usage screen if the CommandLine is not valid or the help * option was specified. * * @param arguments the command line arguments * @return a valid CommandLine or null if the parse was unsuccessful * @throws IOException if an error occurs while formatting help */ public CommandLine parseAndHelp(final String[] arguments) { helpFormatter.setGroup(group); try { // attempt to parse the command line final CommandLine commandLine = parse(arguments); if (!commandLine.hasOption(helpOption) && !commandLine.hasOption(helpTrigger)) { return commandLine; } } catch (final OptionException oe) { // display help regarding the exception helpFormatter.setException(oe); } // print help helpFormatter.print(); return null; } /** * Sets the Group of options to parse against * @param group the group of options to parse against */ public void setGroup(final Group group) { this.group = group; } /** * Sets the HelpFormatter to use with the simplified parsing. * @see #parseAndHelp(String[]) * @param helpFormatter the HelpFormatter to use with the simplified parsing */ public void setHelpFormatter(final HelpFormatter helpFormatter) { this.helpFormatter = helpFormatter; } /** * Sets the help option to use with the simplified parsing. For example * --help, -h and -? are often used. * @see #parseAndHelp(String[]) * @param helpOption the help Option */ public void setHelpOption(final Option helpOption) { this.helpOption = helpOption; } /** * Sets the help option to use with the simplified parsing. For example * --help, -h and -? are often used. * @see #parseAndHelp(String[]) * @param helpTrigger the trigger of the help Option */ public void setHelpTrigger(final String helpTrigger) { this.helpTrigger = helpTrigger; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.util.HelpFormatter; + +/** + * A class that implements the Parser interface can parse a + * String array according to the {@link Group}specified and return a + * {@link CommandLine}. + * + * @author John Keyes (john at integralsource.com) + */ +public class Parser { + private HelpFormatter helpFormatter = new HelpFormatter(); + private Option helpOption = null; + private String helpTrigger = null; + private Group group = null; + + /** + * Parse the arguments according to the specified options and properties. + * + * @param arguments + * the command line arguments + * + * @return the list of atomic option and value tokens + * @throws OptionException + * if there are any problems encountered while parsing the + * command line tokens. + */ + public CommandLine parse(final String[] arguments) + throws OptionException { + // build a mutable list for the arguments + final List argumentList = new LinkedList(); + + // copy the arguments into the new list + for (int i = 0; i < arguments.length; i++) { + final String argument = arguments[i]; + + // ensure non intern'd strings are used + // so that == comparisons work as expected + argumentList.add(new String(argument)); + } + + // wet up a command line for this group + final WriteableCommandLine commandLine = new WriteableCommandLineImpl(group, argumentList); + + // pick up any defaults from the model + group.defaults(commandLine); + + // process the options as far as possible + final ListIterator iterator = argumentList.listIterator(); + Object previous = null; + + while (group.canProcess(commandLine, iterator)) { + // peek at the next item and backtrack + final Object next = iterator.next(); + iterator.previous(); + + // if we have just tried to process this instance + if (next == previous) { + // abort + break; + } + + // remember previous + previous = next; + + group.process(commandLine, iterator); + } + + // if there are more arguments we have a problem + if (iterator.hasNext()) { + final String arg = (String) iterator.next(); + throw new OptionException(group, ResourceConstants.UNEXPECTED_TOKEN, arg); + } + + // no need to validate if the help option is present + if (!commandLine.hasOption(helpOption) && !commandLine.hasOption(helpTrigger)) { + group.validate(commandLine); + } + + return commandLine; + } + + /** + * Parse the arguments according to the specified options and properties and + * displays the usage screen if the CommandLine is not valid or the help + * option was specified. + * + * @param arguments the command line arguments + * @return a valid CommandLine or null if the parse was unsuccessful + * @throws IOException if an error occurs while formatting help + */ + public CommandLine parseAndHelp(final String[] arguments) { + helpFormatter.setGroup(group); + + try { + // attempt to parse the command line + final CommandLine commandLine = parse(arguments); + + if (!commandLine.hasOption(helpOption) && !commandLine.hasOption(helpTrigger)) { + return commandLine; + } + } catch (final OptionException oe) { + // display help regarding the exception + helpFormatter.setException(oe); + } + + // print help + helpFormatter.print(); + + return null; + } + + /** + * Sets the Group of options to parse against + * @param group the group of options to parse against + */ + public void setGroup(final Group group) { + this.group = group; + } + + /** + * Sets the HelpFormatter to use with the simplified parsing. + * @see #parseAndHelp(String[]) + * @param helpFormatter the HelpFormatter to use with the simplified parsing + */ + public void setHelpFormatter(final HelpFormatter helpFormatter) { + this.helpFormatter = helpFormatter; + } + + /** + * Sets the help option to use with the simplified parsing. For example + * --help, -h and -? are often used. + * @see #parseAndHelp(String[]) + * @param helpOption the help Option + */ + public void setHelpOption(final Option helpOption) { + this.helpOption = helpOption; + } + + /** + * Sets the help option to use with the simplified parsing. For example + * --help, -h and -? are often used. + * @see #parseAndHelp(String[]) + * @param helpTrigger the trigger of the help Option + */ + public void setHelpTrigger(final String helpTrigger) { + this.helpTrigger = helpTrigger; + } +} diff --git a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java b/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java index 2cc868cd6..5b74f5a09 100644 --- a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java @@ -1 +1,170 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;import java.util.StringTokenizer;import java.util.prefs.BackingStoreException;import java.util.prefs.Preferences;import org.apache.commons.cli2.Option;/** * A CommandLine implementation using the Preferences API, useful when * constructing a complex DefaultingCommandLine * * This implementation uses the children of a single preference node to populate * the CommandLine. Options are keyed from their preferred name and presence in * the Preferences object is taken as presence in the CommandLine. Argument * values are taken from the Preference value and are optionally separated using * the separator char defined, at construction time. Switch values can be * specified using a simple value of true or false; * obviously this means that Switches with Arguments are not supported by this * implementation. * * @see java.util.prefs.Preferences * @see org.apache.commons.cli2.commandline.DefaultingCommandLine * @see org.apache.commons.cli2.Option#getPreferredName() */public class PreferencesCommandLine extends CommandLineImpl { private static final char NUL = '\0'; private final Preferences preferences; private final Option root; private final char separator; /** * Creates a new PreferencesCommandLine using the specified root Option and * Preferences node. Argument values will be separated using the char 0. * * @param root the CommandLine's root Option * @param preferences the Preferences node to get values from */ public PreferencesCommandLine(final Option root, final Preferences preferences){ this(root,preferences,NUL); } /** * Creates a new PreferencesCommandLine using the specified root Option, * Preferences node and value separator. * * @param root the CommandLine's root Option * @param preferences the Preferences node to get values from * @param separator the character to split argument values */ public PreferencesCommandLine(final Option root, final Preferences preferences, final char separator){ this.root = root; this.preferences = preferences; this.separator = separator; } public boolean hasOption(Option option) { if(option==null){ return false; } else{ try { return Arrays.asList(preferences.keys()).contains(option.getPreferredName()); } catch (BackingStoreException e) { return false; } } } public Option getOption(String trigger) { return root.findOption(trigger); } public List getValues(final Option option, final List defaultValues) { final String value = preferences.get(option.getPreferredName(),null); if(value==null){ return defaultValues; } else if(separator>NUL){ final List values = new ArrayList(); final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); while(tokens.hasMoreTokens()){ values.add(tokens.nextToken()); } return values; } else{ return Collections.singletonList(value); } } public Boolean getSwitch(final Option option, final Boolean defaultValue) { final String value = preferences.get(option.getPreferredName(),null); if("true".equals(value)){ return Boolean.TRUE; } else if("false".equals(value)){ return Boolean.FALSE; } else{ return defaultValue; } } public String getProperty(final String property, final String defaultValue) { return preferences.get(property, defaultValue); } public Set getProperties() { try { return new HashSet(Arrays.asList(preferences.keys())); } catch (BackingStoreException e) { return Collections.EMPTY_SET; } } public List getOptions() { try { final List options = new ArrayList(); final Iterator keys = Arrays.asList(preferences.keys()).iterator(); while (keys.hasNext()) { final String trigger = (String) keys.next(); final Option option = root.findOption(trigger); if (option != null) { options.add(option); } } return Collections.unmodifiableList(options); } catch (BackingStoreException e) { return Collections.EMPTY_LIST; } } public Set getOptionTriggers() { final Set triggers = new HashSet(); final Iterator options = getOptions().iterator(); while(options.hasNext()){ final Option option = (Option)options.next(); triggers.addAll(option.getTriggers()); } return Collections.unmodifiableSet(triggers); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.prefs.BackingStoreException; +import java.util.prefs.Preferences; + +import org.apache.commons.cli2.Option; + +/** + * A CommandLine implementation using the Preferences API, useful when + * constructing a complex DefaultingCommandLine + * + * This implementation uses the children of a single preference node to populate + * the CommandLine. Options are keyed from their preferred name and presence in + * the Preferences object is taken as presence in the CommandLine. Argument + * values are taken from the Preference value and are optionally separated using + * the separator char defined, at construction time. Switch values can be + * specified using a simple value of true or false; + * obviously this means that Switches with Arguments are not supported by this + * implementation. + * + * @see java.util.prefs.Preferences + * @see org.apache.commons.cli2.commandline.DefaultingCommandLine + * @see org.apache.commons.cli2.Option#getPreferredName() + */ +public class PreferencesCommandLine extends CommandLineImpl { + + private static final char NUL = '\0'; + private final Preferences preferences; + private final Option root; + private final char separator; + + /** + * Creates a new PreferencesCommandLine using the specified root Option and + * Preferences node. Argument values will be separated using the char 0. + * + * @param root the CommandLine's root Option + * @param preferences the Preferences node to get values from + */ + public PreferencesCommandLine(final Option root, final Preferences preferences){ + this(root,preferences,NUL); + } + + /** + * Creates a new PreferencesCommandLine using the specified root Option, + * Preferences node and value separator. + * + * @param root the CommandLine's root Option + * @param preferences the Preferences node to get values from + * @param separator the character to split argument values + */ + public PreferencesCommandLine(final Option root, final Preferences preferences, final char separator){ + this.root = root; + this.preferences = preferences; + this.separator = separator; + } + + public boolean hasOption(Option option) { + if(option==null){ + return false; + } + else{ + try { + return Arrays.asList(preferences.keys()).contains(option.getPreferredName()); + } catch (BackingStoreException e) { + return false; + } + } + } + + public Option getOption(String trigger) { + return root.findOption(trigger); + } + + public List getValues(final Option option, final List defaultValues) { + final String value = preferences.get(option.getPreferredName(),null); + + if(value==null){ + return defaultValues; + } + else if(separator>NUL){ + final List values = new ArrayList(); + final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); + + while(tokens.hasMoreTokens()){ + values.add(tokens.nextToken()); + } + + return values; + } + else{ + return Collections.singletonList(value); + } + } + + public Boolean getSwitch(final Option option, final Boolean defaultValue) { + final String value = preferences.get(option.getPreferredName(),null); + if("true".equals(value)){ + return Boolean.TRUE; + } + else if("false".equals(value)){ + return Boolean.FALSE; + } + else{ + return defaultValue; + } + } + + public String getProperty(final String property, final String defaultValue) { + return preferences.get(property, defaultValue); + } + + public Set getProperties() { + try { + return new HashSet(Arrays.asList(preferences.keys())); + } catch (BackingStoreException e) { + return Collections.EMPTY_SET; + } + } + + public List getOptions() { + try { + final List options = new ArrayList(); + final Iterator keys = Arrays.asList(preferences.keys()).iterator(); + while (keys.hasNext()) { + final String trigger = (String) keys.next(); + final Option option = root.findOption(trigger); + if (option != null) { + options.add(option); + } + } + return Collections.unmodifiableList(options); + } catch (BackingStoreException e) { + return Collections.EMPTY_LIST; + } + } + + public Set getOptionTriggers() { + final Set triggers = new HashSet(); + final Iterator options = getOptions().iterator(); + while(options.hasNext()){ + final Option option = (Option)options.next(); + triggers.addAll(option.getTriggers()); + } + return Collections.unmodifiableSet(triggers); + } +} diff --git a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java b/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java index 1c99983f0..6e04b6728 100644 --- a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java @@ -1 +1,155 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Properties;import java.util.Set;import java.util.StringTokenizer;import org.apache.commons.cli2.Option;/** * A CommandLine implementation using a java Properties instance, useful for * constructing a complex DefaultingCommandLine * * Options are keyed from their property name and presence in the Properties * instance is taken as presence in the CommandLine. Argument values are taken * from the property value and are optionally separated using the separator * char, defined at construction time. Switch values can be specified using a * simple value of true or false; obviously this means * that Switches with Arguments are not supported by this implementation. * * @see java.util.Properties * @see org.apache.commons.cli2.commandline.DefaultingCommandLine * @see org.apache.commons.cli2.Option#getPreferredName() */public class PropertiesCommandLine extends CommandLineImpl { private static final char NUL = '\0'; private final Properties properties; private final Option root; private final char separator; /** * Creates a new PropertiesCommandLine using the specified root Option, * Properties instance. The character 0 is used as the value separator. * * @param root the CommandLine's root Option * @param properties the Properties instance to get values from */ public PropertiesCommandLine(final Option root, final Properties properties){ this(root,properties,NUL); } /** * Creates a new PropertiesCommandLine using the specified root Option, * Properties instance and value separator. * * @param root the CommandLine's root Option * @param properties the Properties instance to get values from * @param separator the character to split argument values */ public PropertiesCommandLine(final Option root, final Properties properties, final char separator){ this.root = root; this.properties = properties; this.separator = separator; } public boolean hasOption(Option option) { if(option==null){ return false; } else{ return properties.containsKey(option.getPreferredName()); } } public Option getOption(String trigger) { return root.findOption(trigger); } public List getValues(final Option option, final List defaultValues) { final String value = properties.getProperty(option.getPreferredName()); if(value==null){ return defaultValues; } else if(separator>NUL){ final List values = new ArrayList(); final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); while(tokens.hasMoreTokens()){ values.add(tokens.nextToken()); } return values; } else{ return Collections.singletonList(value); } } public Boolean getSwitch(final Option option, final Boolean defaultValue) { final String value = properties.getProperty(option.getPreferredName()); if("true".equals(value)){ return Boolean.TRUE; } else if("false".equals(value)){ return Boolean.FALSE; } else{ return defaultValue; } } public String getProperty(final String property, final String defaultValue) { return properties.getProperty(property,defaultValue); } public Set getProperties() { return properties.keySet(); } public List getOptions() { final List options = new ArrayList(); final Iterator keys = properties.keySet().iterator(); while(keys.hasNext()){ final String trigger = (String)keys.next(); final Option option = root.findOption(trigger); if(option!=null){ options.add(option); } } return Collections.unmodifiableList(options); } public Set getOptionTriggers() { final Set triggers = new HashSet(); final Iterator options = getOptions().iterator(); while(options.hasNext()){ final Option option = (Option)options.next(); triggers.addAll(option.getTriggers()); } return Collections.unmodifiableSet(triggers); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.StringTokenizer; + +import org.apache.commons.cli2.Option; + +/** + * A CommandLine implementation using a java Properties instance, useful for + * constructing a complex DefaultingCommandLine + * + * Options are keyed from their property name and presence in the Properties + * instance is taken as presence in the CommandLine. Argument values are taken + * from the property value and are optionally separated using the separator + * char, defined at construction time. Switch values can be specified using a + * simple value of true or false; obviously this means + * that Switches with Arguments are not supported by this implementation. + * + * @see java.util.Properties + * @see org.apache.commons.cli2.commandline.DefaultingCommandLine + * @see org.apache.commons.cli2.Option#getPreferredName() + */ +public class PropertiesCommandLine extends CommandLineImpl { + + private static final char NUL = '\0'; + private final Properties properties; + private final Option root; + private final char separator; + + /** + * Creates a new PropertiesCommandLine using the specified root Option, + * Properties instance. The character 0 is used as the value separator. + * + * @param root the CommandLine's root Option + * @param properties the Properties instance to get values from + */ + public PropertiesCommandLine(final Option root, final Properties properties){ + this(root,properties,NUL); + } + + /** + * Creates a new PropertiesCommandLine using the specified root Option, + * Properties instance and value separator. + * + * @param root the CommandLine's root Option + * @param properties the Properties instance to get values from + * @param separator the character to split argument values + */ + public PropertiesCommandLine(final Option root, final Properties properties, final char separator){ + this.root = root; + this.properties = properties; + this.separator = separator; + } + + + public boolean hasOption(Option option) { + if(option==null){ + return false; + } + else{ + return properties.containsKey(option.getPreferredName()); + } + } + + public Option getOption(String trigger) { + return root.findOption(trigger); + } + + public List getValues(final Option option, final List defaultValues) { + final String value = properties.getProperty(option.getPreferredName()); + + if(value==null){ + return defaultValues; + } + else if(separator>NUL){ + final List values = new ArrayList(); + final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); + + while(tokens.hasMoreTokens()){ + values.add(tokens.nextToken()); + } + + return values; + } + else{ + return Collections.singletonList(value); + } + } + + public Boolean getSwitch(final Option option, final Boolean defaultValue) { + final String value = properties.getProperty(option.getPreferredName()); + if("true".equals(value)){ + return Boolean.TRUE; + } + else if("false".equals(value)){ + return Boolean.FALSE; + } + else{ + return defaultValue; + } + } + + public String getProperty(final String property, final String defaultValue) { + return properties.getProperty(property,defaultValue); + } + + public Set getProperties() { + return properties.keySet(); + } + + public List getOptions() { + final List options = new ArrayList(); + final Iterator keys = properties.keySet().iterator(); + while(keys.hasNext()){ + final String trigger = (String)keys.next(); + final Option option = root.findOption(trigger); + if(option!=null){ + options.add(option); + } + } + return Collections.unmodifiableList(options); + } + + public Set getOptionTriggers() { + final Set triggers = new HashSet(); + final Iterator options = getOptions().iterator(); + while(options.hasNext()){ + final Option option = (Option)options.next(); + triggers.addAll(option.getTriggers()); + } + return Collections.unmodifiableSet(triggers); + } +} diff --git a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java index 85e3bfc5a..bb1610e16 100644 --- a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java @@ -1 +1,226 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * A WriteableCommandLine implementation allowing Options to write their * processed information to a CommandLine. */public class WriteableCommandLineImpl extends CommandLineImpl implements WriteableCommandLine { private final Properties properties = new Properties(); private final List options = new ArrayList(); private final Map nameToOption = new HashMap(); private final Map values = new HashMap(); private final Map switches = new HashMap(); private final Map defaultValues = new HashMap(); private final Map defaultSwitches = new HashMap(); private final List normalised; private final Set prefixes; /** * Creates a new WriteableCommandLineImpl rooted on the specified Option, to * hold the parsed arguments. * * @param rootOption the CommandLine's root Option * @param arguments the arguments this CommandLine represents */ public WriteableCommandLineImpl(final Option rootOption, final List arguments) { this.prefixes = rootOption.getPrefixes(); this.normalised = arguments; } public void addOption(Option option) { options.add(option); nameToOption.put(option.getPreferredName(), option); for (Iterator i = option.getTriggers().iterator(); i.hasNext();) { nameToOption.put(i.next(), option); } } public void addValue(final Option option, final Object value) { if (option instanceof Argument) { addOption(option); } List valueList = (List) values.get(option); if (valueList == null) { valueList = new ArrayList(); values.put(option, valueList); } valueList.add(value); } public void addSwitch(final Option option, final boolean value) { addOption(option); if (switches.containsKey(option)) { throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ALREADY_SET)); } else { switches.put(option, value ? Boolean.TRUE : Boolean.FALSE); } } public boolean hasOption(final Option option) { final boolean present = options.contains(option); return present; } public Option getOption(final String trigger) { return (Option) nameToOption.get(trigger); } public List getValues(final Option option, final List defaultValues) { // First grab the command line values List valueList = (List) values.get(option); // Secondly try the defaults supplied to the method if ((valueList == null) || valueList.isEmpty()) { valueList = defaultValues; } // Thirdly try the option's default values if ((valueList == null) || valueList.isEmpty()) { valueList = (List) this.defaultValues.get(option); } // Finally use an empty list if (valueList == null) { valueList = Collections.EMPTY_LIST; } return valueList; } public Boolean getSwitch(final Option option, final Boolean defaultValue) { // First grab the command line values Boolean bool = (Boolean) switches.get(option); // Secondly try the defaults supplied to the method if (bool == null) { bool = defaultValue; } // Thirdly try the option's default values if (bool == null) { bool = (Boolean) this.defaultSwitches.get(option); } return bool; } public void addProperty(final String property, final String value) { properties.setProperty(property, value); } public String getProperty(final String property, final String defaultValue) { return properties.getProperty(property, defaultValue); } public Set getProperties() { return Collections.unmodifiableSet(properties.keySet()); } public boolean looksLikeOption(final String trigger) { for (final Iterator i = prefixes.iterator(); i.hasNext();) { final String prefix = (String) i.next(); if (trigger.startsWith(prefix)) { return true; } } return false; } public String toString() { final StringBuffer buffer = new StringBuffer(); // need to add group header for (final Iterator i = normalised.iterator(); i.hasNext();) { final String arg = (String) i.next(); if (arg.indexOf(' ') >= 0) { buffer.append("\"").append(arg).append("\""); } else { buffer.append(arg); } if (i.hasNext()) { buffer.append(' '); } } return buffer.toString(); } public List getOptions() { return Collections.unmodifiableList(options); } public Set getOptionTriggers() { return Collections.unmodifiableSet(nameToOption.keySet()); } public void setDefaultValues(final Option option, final List defaults) { if (defaults == null) { defaultValues.remove(option); } else { defaultValues.put(option, defaults); } } public void setDefaultSwitch(final Option option, final Boolean defaultSwitch) { if (defaultSwitch == null) { defaultSwitches.remove(option); } else { defaultSwitches.put(option, defaultSwitch); } } public List getNormalised() { return Collections.unmodifiableList(normalised); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * A WriteableCommandLine implementation allowing Options to write their + * processed information to a CommandLine. + */ +public class WriteableCommandLineImpl + extends CommandLineImpl implements WriteableCommandLine { + private final Properties properties = new Properties(); + private final List options = new ArrayList(); + private final Map nameToOption = new HashMap(); + private final Map values = new HashMap(); + private final Map switches = new HashMap(); + private final Map defaultValues = new HashMap(); + private final Map defaultSwitches = new HashMap(); + private final List normalised; + private final Set prefixes; + + /** + * Creates a new WriteableCommandLineImpl rooted on the specified Option, to + * hold the parsed arguments. + * + * @param rootOption the CommandLine's root Option + * @param arguments the arguments this CommandLine represents + */ + public WriteableCommandLineImpl(final Option rootOption, + final List arguments) { + this.prefixes = rootOption.getPrefixes(); + this.normalised = arguments; + } + + public void addOption(Option option) { + options.add(option); + nameToOption.put(option.getPreferredName(), option); + + for (Iterator i = option.getTriggers().iterator(); i.hasNext();) { + nameToOption.put(i.next(), option); + } + } + + public void addValue(final Option option, + final Object value) { + if (option instanceof Argument) { + addOption(option); + } + + List valueList = (List) values.get(option); + + if (valueList == null) { + valueList = new ArrayList(); + values.put(option, valueList); + } + + valueList.add(value); + } + + public void addSwitch(final Option option, + final boolean value) { + addOption(option); + + if (switches.containsKey(option)) { + throw new IllegalStateException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ALREADY_SET)); + } else { + switches.put(option, value ? Boolean.TRUE : Boolean.FALSE); + } + } + + public boolean hasOption(final Option option) { + final boolean present = options.contains(option); + + return present; + } + + public Option getOption(final String trigger) { + return (Option) nameToOption.get(trigger); + } + + public List getValues(final Option option, + final List defaultValues) { + // First grab the command line values + List valueList = (List) values.get(option); + + // Secondly try the defaults supplied to the method + if ((valueList == null) || valueList.isEmpty()) { + valueList = defaultValues; + } + + // Thirdly try the option's default values + if ((valueList == null) || valueList.isEmpty()) { + valueList = (List) this.defaultValues.get(option); + } + + // Finally use an empty list + if (valueList == null) { + valueList = Collections.EMPTY_LIST; + } + + return valueList; + } + + public Boolean getSwitch(final Option option, + final Boolean defaultValue) { + // First grab the command line values + Boolean bool = (Boolean) switches.get(option); + + // Secondly try the defaults supplied to the method + if (bool == null) { + bool = defaultValue; + } + + // Thirdly try the option's default values + if (bool == null) { + bool = (Boolean) this.defaultSwitches.get(option); + } + + return bool; + } + + public void addProperty(final String property, + final String value) { + properties.setProperty(property, value); + } + + public String getProperty(final String property, + final String defaultValue) { + return properties.getProperty(property, defaultValue); + } + + public Set getProperties() { + return Collections.unmodifiableSet(properties.keySet()); + } + + public boolean looksLikeOption(final String trigger) { + for (final Iterator i = prefixes.iterator(); i.hasNext();) { + final String prefix = (String) i.next(); + + if (trigger.startsWith(prefix)) { + return true; + } + } + + return false; + } + + public String toString() { + final StringBuffer buffer = new StringBuffer(); + + // need to add group header + for (final Iterator i = normalised.iterator(); i.hasNext();) { + final String arg = (String) i.next(); + + if (arg.indexOf(' ') >= 0) { + buffer.append("\"").append(arg).append("\""); + } else { + buffer.append(arg); + } + + if (i.hasNext()) { + buffer.append(' '); + } + } + + return buffer.toString(); + } + + public List getOptions() { + return Collections.unmodifiableList(options); + } + + public Set getOptionTriggers() { + return Collections.unmodifiableSet(nameToOption.keySet()); + } + + public void setDefaultValues(final Option option, + final List defaults) { + if (defaults == null) { + defaultValues.remove(option); + } else { + defaultValues.put(option, defaults); + } + } + + public void setDefaultSwitch(final Option option, + final Boolean defaultSwitch) { + if (defaultSwitch == null) { + defaultSwitches.remove(option); + } else { + defaultSwitches.put(option, defaultSwitch); + } + } + + public List getNormalised() { + return Collections.unmodifiableList(normalised); + } +} diff --git a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java index e9d5f1f93..066a8ce82 100644 --- a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java @@ -1 +1,374 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.ListIterator;import java.util.Set;import java.util.StringTokenizer;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;import org.apache.commons.cli2.validation.InvalidArgumentException;import org.apache.commons.cli2.validation.Validator;/** * An implementation of an Argument. */public class ArgumentImpl extends OptionImpl implements Argument { private static final char NUL = '\0'; /** * The default value for the initial separator char. */ public static final char DEFAULT_INITIAL_SEPARATOR = NUL; /** * The default value for the subsequent separator char. */ public static final char DEFAULT_SUBSEQUENT_SEPARATOR = NUL; /** * The default token to indicate that remaining arguments should be consumed * as values. */ public static final String DEFAULT_CONSUME_REMAINING = "--"; private final String name; private final String description; private final int minimum; private final int maximum; private final char initialSeparator; private final char subsequentSeparator; private final boolean subsequentSplit; private final Validator validator; private final String consumeRemaining; private final List defaultValues; private final ResourceHelper resources = ResourceHelper.getResourceHelper(); /** * Creates a new Argument instance. * * @param name * The name of the argument * @param description * A description of the argument * @param minimum * The minimum number of values needed to be valid * @param maximum * The maximum number of values allowed to be valid * @param initialSeparator * The char separating option from value * @param subsequentSeparator * The char separating values from each other * @param validator * The object responsible for validating the values * @param consumeRemaining * The String used for the "consuming option" group * @param valueDefaults * The values to be used if none are specified. * @param id * The id of the option, 0 implies automatic assignment. * * @see OptionImpl#OptionImpl(int,boolean) */ public ArgumentImpl(final String name, final String description, final int minimum, final int maximum, final char initialSeparator, final char subsequentSeparator, final Validator validator, final String consumeRemaining, final List valueDefaults, final int id) { super(id, false); this.name = (name == null) ? "arg" : name; this.description = description; this.minimum = minimum; this.maximum = maximum; this.initialSeparator = initialSeparator; this.subsequentSeparator = subsequentSeparator; this.subsequentSplit = subsequentSeparator != NUL; this.validator = validator; this.consumeRemaining = consumeRemaining; this.defaultValues = valueDefaults; if (minimum > maximum) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_MIN_EXCEEDS_MAX)); } if ((valueDefaults != null) && (valueDefaults.size() > 0)) { if (valueDefaults.size() < minimum) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_TOO_FEW_DEFAULTS)); } if (valueDefaults.size() > maximum) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_DEFAULTS)); } } } public String getPreferredName() { return name; } public void processValues(final WriteableCommandLine commandLine, final ListIterator arguments, final Option option) throws OptionException { int argumentCount = commandLine.getValues(option, Collections.EMPTY_LIST).size(); while (arguments.hasNext() && (argumentCount < maximum)) { final String allValuesQuoted = (String) arguments.next(); final String allValues = stripBoundaryQuotes(allValuesQuoted); // should we ignore things that look like options? if (allValuesQuoted.equals(consumeRemaining)) { while (arguments.hasNext() && (argumentCount < maximum)) { ++argumentCount; commandLine.addValue(option, arguments.next()); } } // does it look like an option? else if (commandLine.looksLikeOption(allValuesQuoted)) { arguments.previous(); break; } // should we split the string up? else if (subsequentSplit) { final StringTokenizer values = new StringTokenizer(allValues, String.valueOf(subsequentSeparator)); arguments.remove(); while (values.hasMoreTokens() && (argumentCount < maximum)) { ++argumentCount; final String token = values.nextToken(); commandLine.addValue(option, token); arguments.add(token); } if (values.hasMoreTokens()) { throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, values.nextToken()); } } // it must be a value as it is else { ++argumentCount; commandLine.addValue(option, allValues); } } } public boolean canProcess(final WriteableCommandLine commandLine, final String arg) { return true; } public Set getPrefixes() { return Collections.EMPTY_SET; } public void process(WriteableCommandLine commandLine, ListIterator args) throws OptionException { processValues(commandLine, args, this); } public char getInitialSeparator() { return this.initialSeparator; } public char getSubsequentSeparator() { return this.subsequentSeparator; } public Set getTriggers() { return Collections.EMPTY_SET; } public String getConsumeRemaining() { return this.consumeRemaining; } public List getDefaultValues() { return this.defaultValues; } public Validator getValidator() { return this.validator; } public void validate(final WriteableCommandLine commandLine) throws OptionException { validate(commandLine, this); } public void validate(final WriteableCommandLine commandLine, final Option option) throws OptionException { final List values = commandLine.getValues(option); if (values.size() < minimum) { throw new OptionException(option, ResourceConstants.ARGUMENT_MISSING_VALUES); } if (values.size() > maximum) { throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, (String) values.get(maximum)); } if (validator != null) { try { validator.validate(values); } catch (InvalidArgumentException ive) { throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, ive.getMessage()); } } } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { // do we display the outer optionality final boolean optional = helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); // allow numbering if multiple args final boolean numbered = (maximum > 1) && helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); final boolean bracketed = helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); // if infinite args are allowed then crop the list final int max = (maximum == Integer.MAX_VALUE) ? 2 : maximum; int i = 0; // for each argument while (i < max) { // if we're past the first add a space if (i > 0) { buffer.append(' '); } // if the next arg is optional if ((i >= minimum) && (optional || (i > 0))) { buffer.append('['); } if (bracketed) { buffer.append('<'); } // add name buffer.append(name); ++i; // if numbering if (numbered) { buffer.append(i); } if (bracketed) { buffer.append('>'); } } // if infinite args are allowed if (maximum == Integer.MAX_VALUE) { // append elipsis buffer.append(" ..."); } // for each argument while (i > 0) { --i; // if the next arg is optional if ((i >= minimum) && (optional || (i > 0))) { buffer.append(']'); } } } public String getDescription() { return description; } public List helpLines(final int depth, final Set helpSettings, final Comparator comp) { final HelpLine helpLine = new HelpLineImpl(this, depth); return Collections.singletonList(helpLine); } public int getMaximum() { return maximum; } public int getMinimum() { return minimum; } /** * If there are any leading or trailing quotes remove them from the * specified token. * * @param token * the token to strip leading and trailing quotes * * @return String the possibly modified token */ public String stripBoundaryQuotes(String token) { if (!token.startsWith("\"") || !token.endsWith("\"")) { return token; } token = token.substring(1, token.length() - 1); return token; } public boolean isRequired() { return getMinimum() > 0; } public void defaults(final WriteableCommandLine commandLine) { super.defaults(commandLine); defaultValues(commandLine, this); } public void defaultValues(final WriteableCommandLine commandLine, final Option option) { commandLine.setDefaultValues(option, defaultValues); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; +import java.util.StringTokenizer; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.HelpLine; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; +import org.apache.commons.cli2.validation.InvalidArgumentException; +import org.apache.commons.cli2.validation.Validator; + +/** + * An implementation of an Argument. + */ +public class ArgumentImpl + extends OptionImpl implements Argument { + private static final char NUL = '\0'; + + /** + * The default value for the initial separator char. + */ + public static final char DEFAULT_INITIAL_SEPARATOR = NUL; + + /** + * The default value for the subsequent separator char. + */ + public static final char DEFAULT_SUBSEQUENT_SEPARATOR = NUL; + + /** + * The default token to indicate that remaining arguments should be consumed + * as values. + */ + public static final String DEFAULT_CONSUME_REMAINING = "--"; + private final String name; + private final String description; + private final int minimum; + private final int maximum; + private final char initialSeparator; + private final char subsequentSeparator; + private final boolean subsequentSplit; + private final Validator validator; + private final String consumeRemaining; + private final List defaultValues; + private final ResourceHelper resources = ResourceHelper.getResourceHelper(); + + /** + * Creates a new Argument instance. + * + * @param name + * The name of the argument + * @param description + * A description of the argument + * @param minimum + * The minimum number of values needed to be valid + * @param maximum + * The maximum number of values allowed to be valid + * @param initialSeparator + * The char separating option from value + * @param subsequentSeparator + * The char separating values from each other + * @param validator + * The object responsible for validating the values + * @param consumeRemaining + * The String used for the "consuming option" group + * @param valueDefaults + * The values to be used if none are specified. + * @param id + * The id of the option, 0 implies automatic assignment. + * + * @see OptionImpl#OptionImpl(int,boolean) + */ + public ArgumentImpl(final String name, + final String description, + final int minimum, + final int maximum, + final char initialSeparator, + final char subsequentSeparator, + final Validator validator, + final String consumeRemaining, + final List valueDefaults, + final int id) { + super(id, false); + + this.name = (name == null) ? "arg" : name; + this.description = description; + this.minimum = minimum; + this.maximum = maximum; + this.initialSeparator = initialSeparator; + this.subsequentSeparator = subsequentSeparator; + this.subsequentSplit = subsequentSeparator != NUL; + this.validator = validator; + this.consumeRemaining = consumeRemaining; + this.defaultValues = valueDefaults; + + if (minimum > maximum) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_MIN_EXCEEDS_MAX)); + } + + if ((valueDefaults != null) && (valueDefaults.size() > 0)) { + if (valueDefaults.size() < minimum) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_TOO_FEW_DEFAULTS)); + } + + if (valueDefaults.size() > maximum) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_DEFAULTS)); + } + } + } + + public String getPreferredName() { + return name; + } + + public void processValues(final WriteableCommandLine commandLine, + final ListIterator arguments, + final Option option) + throws OptionException { + int argumentCount = commandLine.getValues(option, Collections.EMPTY_LIST).size(); + + while (arguments.hasNext() && (argumentCount < maximum)) { + final String allValuesQuoted = (String) arguments.next(); + final String allValues = stripBoundaryQuotes(allValuesQuoted); + + // should we ignore things that look like options? + if (allValuesQuoted.equals(consumeRemaining)) { + while (arguments.hasNext() && (argumentCount < maximum)) { + ++argumentCount; + commandLine.addValue(option, arguments.next()); + } + } + // does it look like an option? + else if (commandLine.looksLikeOption(allValuesQuoted)) { + arguments.previous(); + + break; + } + // should we split the string up? + else if (subsequentSplit) { + final StringTokenizer values = + new StringTokenizer(allValues, String.valueOf(subsequentSeparator)); + + arguments.remove(); + + while (values.hasMoreTokens() && (argumentCount < maximum)) { + ++argumentCount; + + final String token = values.nextToken(); + commandLine.addValue(option, token); + arguments.add(token); + } + + if (values.hasMoreTokens()) { + throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, + values.nextToken()); + } + } + // it must be a value as it is + else { + ++argumentCount; + commandLine.addValue(option, allValues); + } + } + } + + public boolean canProcess(final WriteableCommandLine commandLine, + final String arg) { + return true; + } + + public Set getPrefixes() { + return Collections.EMPTY_SET; + } + + public void process(WriteableCommandLine commandLine, + ListIterator args) + throws OptionException { + processValues(commandLine, args, this); + } + + public char getInitialSeparator() { + return this.initialSeparator; + } + + public char getSubsequentSeparator() { + return this.subsequentSeparator; + } + + public Set getTriggers() { + return Collections.EMPTY_SET; + } + + public String getConsumeRemaining() { + return this.consumeRemaining; + } + + public List getDefaultValues() { + return this.defaultValues; + } + + public Validator getValidator() { + return this.validator; + } + + public void validate(final WriteableCommandLine commandLine) + throws OptionException { + validate(commandLine, this); + } + + public void validate(final WriteableCommandLine commandLine, + final Option option) + throws OptionException { + final List values = commandLine.getValues(option); + + if (values.size() < minimum) { + throw new OptionException(option, ResourceConstants.ARGUMENT_MISSING_VALUES); + } + + if (values.size() > maximum) { + throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, + (String) values.get(maximum)); + } + + if (validator != null) { + try { + validator.validate(values); + } catch (InvalidArgumentException ive) { + throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, + ive.getMessage()); + } + } + } + + public void appendUsage(final StringBuffer buffer, + final Set helpSettings, + final Comparator comp) { + // do we display the outer optionality + final boolean optional = helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); + + // allow numbering if multiple args + final boolean numbered = + (maximum > 1) && helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); + + final boolean bracketed = helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); + + // if infinite args are allowed then crop the list + final int max = (maximum == Integer.MAX_VALUE) ? 2 : maximum; + + int i = 0; + + // for each argument + while (i < max) { + // if we're past the first add a space + if (i > 0) { + buffer.append(' '); + } + + // if the next arg is optional + if ((i >= minimum) && (optional || (i > 0))) { + buffer.append('['); + } + + if (bracketed) { + buffer.append('<'); + } + + // add name + buffer.append(name); + ++i; + + // if numbering + if (numbered) { + buffer.append(i); + } + + if (bracketed) { + buffer.append('>'); + } + } + + // if infinite args are allowed + if (maximum == Integer.MAX_VALUE) { + // append elipsis + buffer.append(" ..."); + } + + // for each argument + while (i > 0) { + --i; + + // if the next arg is optional + if ((i >= minimum) && (optional || (i > 0))) { + buffer.append(']'); + } + } + } + + public String getDescription() { + return description; + } + + public List helpLines(final int depth, + final Set helpSettings, + final Comparator comp) { + final HelpLine helpLine = new HelpLineImpl(this, depth); + + return Collections.singletonList(helpLine); + } + + public int getMaximum() { + return maximum; + } + + public int getMinimum() { + return minimum; + } + + /** + * If there are any leading or trailing quotes remove them from the + * specified token. + * + * @param token + * the token to strip leading and trailing quotes + * + * @return String the possibly modified token + */ + public String stripBoundaryQuotes(String token) { + if (!token.startsWith("\"") || !token.endsWith("\"")) { + return token; + } + + token = token.substring(1, token.length() - 1); + + return token; + } + + public boolean isRequired() { + return getMinimum() > 0; + } + + public void defaults(final WriteableCommandLine commandLine) { + super.defaults(commandLine); + defaultValues(commandLine, this); + } + + public void defaultValues(final WriteableCommandLine commandLine, + final Option option) { + commandLine.setDefaultValues(option, defaultValues); + } +} diff --git a/src/java/org/apache/commons/cli2/option/Command.java b/src/java/org/apache/commons/cli2/option/Command.java index a76b82c6c..99f8c721a 100644 --- a/src/java/org/apache/commons/cli2/option/Command.java +++ b/src/java/org/apache/commons/cli2/option/Command.java @@ -1 +1,175 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Represents a cvs "update" style command line option. * * Like all Parents, Commands can have child options and can be part of * Arguments */public class Command extends ParentImpl { /** The display name for the command */ private final String preferredName; /** The aliases for this command */ private final Set aliases; /** All the names for this command */ private final Set triggers; /** * Creates a new Command instance. * * @param preferredName * The name normally used to refer to the Command * @param description * A description of the Command * @param aliases * Alternative names for the Command * @param required * Whether the Command is required * @param argument * An Argument that the command takes * @param children * The Group of child options for this Command * @param id * A unique id for the Command * * @see ParentImpl#ParentImpl(Argument, Group, String, int, boolean) */ public Command(final String preferredName, final String description, final Set aliases, final boolean required, final Argument argument, final Group children, final int id) { super(argument, children, description, id, required); // check the preferred name is valid if ((preferredName == null) || (preferredName.length() < 1)) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT)); } this.preferredName = preferredName; // gracefully and defensively handle aliases this.aliases = (aliases == null) ? Collections.EMPTY_SET : Collections.unmodifiableSet(new HashSet(aliases)); // populate the triggers Set final Set newTriggers = new HashSet(); newTriggers.add(preferredName); newTriggers.addAll(this.aliases); this.triggers = Collections.unmodifiableSet(newTriggers); } public void processParent(final WriteableCommandLine commandLine, final ListIterator arguments) throws OptionException { // grab the argument to process final String arg = (String) arguments.next(); // if we can process it if (canProcess(commandLine, arg)) { // then note the option commandLine.addOption(this); // normalise the argument list arguments.set(preferredName); } else { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); } } public Set getTriggers() { return triggers; } public void validate(WriteableCommandLine commandLine) throws OptionException { if (isRequired() && !commandLine.hasOption(this)) { throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, getPreferredName()); } super.validate(commandLine); } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { // do we display optionality final boolean optional = !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); if (optional) { buffer.append('['); } buffer.append(preferredName); if (displayAliases && !aliases.isEmpty()) { buffer.append(" ("); final List list = new ArrayList(aliases); Collections.sort(list); for (final Iterator i = list.iterator(); i.hasNext();) { final String alias = (String) i.next(); buffer.append(alias); if (i.hasNext()) { buffer.append(','); } } buffer.append(')'); } super.appendUsage(buffer, helpSettings, comp); if (optional) { buffer.append(']'); } } public String getPreferredName() { return preferredName; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * Represents a cvs "update" style command line option. + * + * Like all Parents, Commands can have child options and can be part of + * Arguments + */ +public class Command + extends ParentImpl { + /** The display name for the command */ + private final String preferredName; + + /** The aliases for this command */ + private final Set aliases; + + /** All the names for this command */ + private final Set triggers; + + /** + * Creates a new Command instance. + * + * @param preferredName + * The name normally used to refer to the Command + * @param description + * A description of the Command + * @param aliases + * Alternative names for the Command + * @param required + * Whether the Command is required + * @param argument + * An Argument that the command takes + * @param children + * The Group of child options for this Command + * @param id + * A unique id for the Command + * + * @see ParentImpl#ParentImpl(Argument, Group, String, int, boolean) + */ + public Command(final String preferredName, + final String description, + final Set aliases, + final boolean required, + final Argument argument, + final Group children, + final int id) { + super(argument, children, description, id, required); + + // check the preferred name is valid + if ((preferredName == null) || (preferredName.length() < 1)) { + throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT)); + } + + this.preferredName = preferredName; + + // gracefully and defensively handle aliases + this.aliases = + (aliases == null) ? Collections.EMPTY_SET + : Collections.unmodifiableSet(new HashSet(aliases)); + + // populate the triggers Set + final Set newTriggers = new HashSet(); + newTriggers.add(preferredName); + newTriggers.addAll(this.aliases); + this.triggers = Collections.unmodifiableSet(newTriggers); + } + + public void processParent(final WriteableCommandLine commandLine, + final ListIterator arguments) + throws OptionException { + // grab the argument to process + final String arg = (String) arguments.next(); + + // if we can process it + if (canProcess(commandLine, arg)) { + // then note the option + commandLine.addOption(this); + + // normalise the argument list + arguments.set(preferredName); + } else { + throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); + } + } + + public Set getTriggers() { + return triggers; + } + + public void validate(WriteableCommandLine commandLine) + throws OptionException { + if (isRequired() && !commandLine.hasOption(this)) { + throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, + getPreferredName()); + } + + super.validate(commandLine); + } + + public void appendUsage(final StringBuffer buffer, + final Set helpSettings, + final Comparator comp) { + // do we display optionality + final boolean optional = + !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); + final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); + + if (optional) { + buffer.append('['); + } + + buffer.append(preferredName); + + if (displayAliases && !aliases.isEmpty()) { + buffer.append(" ("); + + final List list = new ArrayList(aliases); + Collections.sort(list); + + for (final Iterator i = list.iterator(); i.hasNext();) { + final String alias = (String) i.next(); + buffer.append(alias); + + if (i.hasNext()) { + buffer.append(','); + } + } + + buffer.append(')'); + } + + super.appendUsage(buffer, helpSettings, comp); + + if (optional) { + buffer.append(']'); + } + } + + public String getPreferredName() { + return preferredName; + } +} diff --git a/src/java/org/apache/commons/cli2/option/DefaultOption.java b/src/java/org/apache/commons/cli2/option/DefaultOption.java index 5e18ea79c..d5246e1b7 100644 --- a/src/java/org/apache/commons/cli2/option/DefaultOption.java +++ b/src/java/org/apache/commons/cli2/option/DefaultOption.java @@ -1 +1,221 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;/** * A Parent implementation representing normal options. */public class DefaultOption extends ParentImpl { /** * The default token used to prefix a short option */ public static final String DEFAULT_SHORT_PREFIX = "-"; /** * The default token used to prefix a long option */ public static final String DEFAULT_LONG_PREFIX = "--"; /** * The default value for the burstEnabled constructor parameter */ public static final boolean DEFAULT_BURST_ENABLED = true; private final String preferredName; private final Set aliases; private final Set burstAliases; private final Set triggers; private final Set prefixes; private final String shortPrefix; private final boolean burstEnabled; private final int burstLength; /** * Creates a new DefaultOption * * @param shortPrefix the prefix used for short options * @param longPrefix the prefix used for long options * @param burstEnabled should option bursting be enabled * @param preferredName the preferred name for this Option, this should begin with either shortPrefix or longPrefix * @param description a description of this Option * @param aliases the alternative names for this Option * @param burstAliases the aliases that can be burst * @param required whether the Option is strictly required * @param argument the Argument belonging to this Parent, or null * @param children the Group children belonging to this Parent, ot null * @param id the unique identifier for this Option * @throws IllegalArgumentException if the preferredName or an alias isn't * prefixed with shortPrefix or longPrefix */ public DefaultOption(final String shortPrefix, final String longPrefix, final boolean burstEnabled, final String preferredName, final String description, final Set aliases, final Set burstAliases, final boolean required, final Argument argument, final Group children, final int id) { super(argument, children, description, id, required); this.shortPrefix = shortPrefix; this.burstEnabled = burstEnabled; this.burstLength = shortPrefix.length() + 1; this.preferredName = preferredName; this.aliases = (aliases == null) ? Collections.EMPTY_SET : Collections.unmodifiableSet(new HashSet(aliases)); this.burstAliases = (burstAliases == null) ? Collections.EMPTY_SET : Collections.unmodifiableSet(new HashSet(burstAliases)); final Set newTriggers = new HashSet(); newTriggers.add(preferredName); newTriggers.addAll(this.aliases); newTriggers.addAll(this.burstAliases); this.triggers = Collections.unmodifiableSet(newTriggers); final Set newPrefixes = new HashSet(super.getPrefixes()); newPrefixes.add(shortPrefix); newPrefixes.add(longPrefix); this.prefixes = Collections.unmodifiableSet(newPrefixes); checkPrefixes(newPrefixes); } public boolean canProcess(final WriteableCommandLine commandLine, final String argument) { return (argument != null) && (super.canProcess(commandLine, argument) || ((argument.length() >= burstLength) && burstAliases.contains(argument.substring(0, burstLength)))); } public void processParent(WriteableCommandLine commandLine, ListIterator arguments) throws OptionException { final String argument = (String) arguments.next(); if (triggers.contains(argument)) { commandLine.addOption(this); arguments.set(preferredName); } else if (burstEnabled && (argument.length() >= burstLength)) { final String burst = argument.substring(0, burstLength); if (burstAliases.contains(burst)) { commandLine.addOption(this); //HMM test bursting all vs bursting one by one. arguments.set(preferredName); if (getArgument() == null) { arguments.add(shortPrefix + argument.substring(burstLength)); } else { arguments.add(argument.substring(burstLength)); } arguments.previous(); } else { throw new OptionException(this, ResourceConstants.CANNOT_BURST, argument); } } else { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, argument); } } public Set getTriggers() { return triggers; } public Set getPrefixes() { return prefixes; } public void validate(WriteableCommandLine commandLine) throws OptionException { if (isRequired() && !commandLine.hasOption(this)) { throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, getPreferredName()); } super.validate(commandLine); } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { // do we display optionality final boolean optional = !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); if (optional) { buffer.append('['); } buffer.append(preferredName); if (displayAliases && !aliases.isEmpty()) { buffer.append(" ("); final List list = new ArrayList(aliases); Collections.sort(list); for (final Iterator i = list.iterator(); i.hasNext();) { final String alias = (String) i.next(); buffer.append(alias); if (i.hasNext()) { buffer.append(','); } } buffer.append(')'); } super.appendUsage(buffer, helpSettings, comp); if (optional) { buffer.append(']'); } } public String getPreferredName() { return preferredName; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.resource.ResourceConstants; + +/** + * A Parent implementation representing normal options. + */ +public class DefaultOption + extends ParentImpl { + /** + * The default token used to prefix a short option + */ + public static final String DEFAULT_SHORT_PREFIX = "-"; + + /** + * The default token used to prefix a long option + */ + public static final String DEFAULT_LONG_PREFIX = "--"; + + /** + * The default value for the burstEnabled constructor parameter + */ + public static final boolean DEFAULT_BURST_ENABLED = true; + private final String preferredName; + private final Set aliases; + private final Set burstAliases; + private final Set triggers; + private final Set prefixes; + private final String shortPrefix; + private final boolean burstEnabled; + private final int burstLength; + + /** + * Creates a new DefaultOption + * + * @param shortPrefix the prefix used for short options + * @param longPrefix the prefix used for long options + * @param burstEnabled should option bursting be enabled + * @param preferredName the preferred name for this Option, this should begin with either shortPrefix or longPrefix + * @param description a description of this Option + * @param aliases the alternative names for this Option + * @param burstAliases the aliases that can be burst + * @param required whether the Option is strictly required + * @param argument the Argument belonging to this Parent, or null + * @param children the Group children belonging to this Parent, ot null + * @param id the unique identifier for this Option + * @throws IllegalArgumentException if the preferredName or an alias isn't + * prefixed with shortPrefix or longPrefix + */ + public DefaultOption(final String shortPrefix, + final String longPrefix, + final boolean burstEnabled, + final String preferredName, + final String description, + final Set aliases, + final Set burstAliases, + final boolean required, + final Argument argument, + final Group children, + final int id) { + super(argument, children, description, id, required); + + this.shortPrefix = shortPrefix; + this.burstEnabled = burstEnabled; + + this.burstLength = shortPrefix.length() + 1; + + this.preferredName = preferredName; + this.aliases = + (aliases == null) ? Collections.EMPTY_SET + : Collections.unmodifiableSet(new HashSet(aliases)); + + this.burstAliases = + (burstAliases == null) ? Collections.EMPTY_SET + : Collections.unmodifiableSet(new HashSet(burstAliases)); + + final Set newTriggers = new HashSet(); + newTriggers.add(preferredName); + newTriggers.addAll(this.aliases); + newTriggers.addAll(this.burstAliases); + this.triggers = Collections.unmodifiableSet(newTriggers); + + final Set newPrefixes = new HashSet(super.getPrefixes()); + newPrefixes.add(shortPrefix); + newPrefixes.add(longPrefix); + this.prefixes = Collections.unmodifiableSet(newPrefixes); + + checkPrefixes(newPrefixes); + } + + public boolean canProcess(final WriteableCommandLine commandLine, + final String argument) { + return (argument != null) && + (super.canProcess(commandLine, argument) || + ((argument.length() >= burstLength) && + burstAliases.contains(argument.substring(0, burstLength)))); + } + + public void processParent(WriteableCommandLine commandLine, + ListIterator arguments) + throws OptionException { + final String argument = (String) arguments.next(); + + if (triggers.contains(argument)) { + commandLine.addOption(this); + arguments.set(preferredName); + } else if (burstEnabled && (argument.length() >= burstLength)) { + final String burst = argument.substring(0, burstLength); + + if (burstAliases.contains(burst)) { + commandLine.addOption(this); + + //HMM test bursting all vs bursting one by one. + arguments.set(preferredName); + + if (getArgument() == null) { + arguments.add(shortPrefix + argument.substring(burstLength)); + } else { + arguments.add(argument.substring(burstLength)); + } + + arguments.previous(); + } else { + throw new OptionException(this, ResourceConstants.CANNOT_BURST, argument); + } + } else { + throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, argument); + } + } + + public Set getTriggers() { + return triggers; + } + + public Set getPrefixes() { + return prefixes; + } + + public void validate(WriteableCommandLine commandLine) + throws OptionException { + if (isRequired() && !commandLine.hasOption(this)) { + throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, + getPreferredName()); + } + + super.validate(commandLine); + } + + public void appendUsage(final StringBuffer buffer, + final Set helpSettings, + final Comparator comp) { + // do we display optionality + final boolean optional = + !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); + final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); + + if (optional) { + buffer.append('['); + } + + buffer.append(preferredName); + + if (displayAliases && !aliases.isEmpty()) { + buffer.append(" ("); + + final List list = new ArrayList(aliases); + Collections.sort(list); + + for (final Iterator i = list.iterator(); i.hasNext();) { + final String alias = (String) i.next(); + buffer.append(alias); + + if (i.hasNext()) { + buffer.append(','); + } + } + + buffer.append(')'); + } + + super.appendUsage(buffer, helpSettings, comp); + + if (optional) { + buffer.append(']'); + } + } + + public String getPreferredName() { + return preferredName; + } +} diff --git a/src/java/org/apache/commons/cli2/option/GroupImpl.java b/src/java/org/apache/commons/cli2/option/GroupImpl.java index b8bbffa5f..e6a84dd51 100644 --- a/src/java/org/apache/commons/cli2/option/GroupImpl.java +++ b/src/java/org/apache/commons/cli2/option/GroupImpl.java @@ -1 +1,517 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Map;import java.util.Set;import java.util.SortedMap;import java.util.TreeMap;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;/** * An implementation of Group */public class GroupImpl extends OptionImpl implements Group { private final String name; private final String description; private final List options; private final int minimum; private final int maximum; private final List anonymous; private final SortedMap optionMap; private final Set prefixes; /** * Creates a new GroupImpl using the specified parameters. * * @param options the Options and Arguments that make up the Group * @param name the name of this Group, or null * @param description a description of this Group * @param minimum the minimum number of Options for a valid CommandLine * @param maximum the maximum number of Options for a valid CommandLine */ public GroupImpl(final List options, final String name, final String description, final int minimum, final int maximum) { super(0, false); this.name = name; this.description = description; this.minimum = minimum; this.maximum = maximum; // store a copy of the options to be used by the // help methods this.options = Collections.unmodifiableList(options); // anonymous Argument temporary storage final List newAnonymous = new ArrayList(); // map (key=trigger & value=Option) temporary storage final SortedMap newOptionMap = new TreeMap(ReverseStringComparator.getInstance()); // prefixes temporary storage final Set newPrefixes = new HashSet(); // process the options for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); if (option instanceof Argument) { i.remove(); newAnonymous.add(option); } else { final Set triggers = option.getTriggers(); for (Iterator j = triggers.iterator(); j.hasNext();) { newOptionMap.put(j.next(), option); } // store the prefixes newPrefixes.addAll(option.getPrefixes()); } } this.anonymous = Collections.unmodifiableList(newAnonymous); this.optionMap = Collections.unmodifiableSortedMap(newOptionMap); this.prefixes = Collections.unmodifiableSet(newPrefixes); } public boolean canProcess(final WriteableCommandLine commandLine, final String arg) { if (arg == null) { return false; } // if arg does not require bursting if (optionMap.containsKey(arg)) { return true; } // filter final Map tailMap = optionMap.tailMap(arg); // check if bursting is required for (final Iterator iter = tailMap.values().iterator(); iter.hasNext();) { final Option option = (Option) iter.next(); if (option.canProcess(commandLine, arg)) { return true; } } if (commandLine.looksLikeOption(arg)) { return false; } // anonymous argument(s) means we can process it if (anonymous.size() > 0) { return true; } return false; } public Set getPrefixes() { return prefixes; } public Set getTriggers() { return optionMap.keySet(); } public void process(final WriteableCommandLine commandLine, final ListIterator arguments) throws OptionException { String previous = null; // [START process each command line token while (arguments.hasNext()) { // grab the next argument final String arg = (String) arguments.next(); // if we have just tried to process this instance if (arg == previous) { // rollback and abort arguments.previous(); break; } // remember last processed instance previous = arg; final Option opt = (Option) optionMap.get(arg); // option found if (opt != null) { arguments.previous(); opt.process(commandLine, arguments); } // [START option NOT found else { // it might be an anonymous argument continue search // [START argument may be anonymous if (commandLine.looksLikeOption(arg)) { // narrow the search final Collection values = optionMap.tailMap(arg).values(); boolean foundMemberOption = false; for (Iterator i = values.iterator(); i.hasNext() && !foundMemberOption;) { final Option option = (Option) i.next(); if (option.canProcess(commandLine, arg)) { foundMemberOption = true; arguments.previous(); option.process(commandLine, arguments); } } // back track and abort this group if necessary if (!foundMemberOption) { arguments.previous(); return; } } // [END argument may be anonymous // [START argument is NOT anonymous else { // move iterator back, current value not used arguments.previous(); // if there are no anonymous arguments then this group can't // process the argument if (anonymous.isEmpty()) { break; } // TODO: why do we iterate over all anonymous arguments? // canProcess will always return true? for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Argument argument = (Argument) i.next(); if (argument.canProcess(commandLine, arguments)) { argument.process(commandLine, arguments); } } } // [END argument is NOT anonymous } // [END option NOT found } // [END process each command line token } public void validate(final WriteableCommandLine commandLine) throws OptionException { // number of options found int present = 0; // reference to first unexpected option Option unexpected = null; for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); // if the child option is required then validate it if (option.isRequired()) { option.validate(commandLine); } if (option instanceof Group) { option.validate(commandLine); } // if the child option is present then validate it if (commandLine.hasOption(option)) { if (++present > maximum) { unexpected = option; break; } option.validate(commandLine); } } // too many options if (unexpected != null) { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, unexpected.getPreferredName()); } // too few option if (present < minimum) { throw new OptionException(this, ResourceConstants.MISSING_OPTION); } // validate each anonymous argument for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Option option = (Option) i.next(); option.validate(commandLine); } } public String getPreferredName() { return name; } public String getDescription() { return description; } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { appendUsage(buffer, helpSettings, comp, "|"); } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp, final String separator) { final Set helpSettingsCopy = new HashSet(helpSettings); final boolean optional = (minimum == 0) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_OPTIONAL); final boolean expanded = (name == null) || helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED); final boolean named = !expanded || ((name != null) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_NAME)); final boolean arguments = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT); final boolean outer = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_OUTER); helpSettingsCopy.remove(DisplaySetting.DISPLAY_GROUP_OUTER); final boolean both = named && expanded; if (optional) { buffer.append('['); } if (named) { buffer.append(name); } if (both) { buffer.append(" ("); } if (expanded) { final Set childSettings; if (!helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) { childSettings = DisplaySetting.NONE; } else { childSettings = new HashSet(helpSettingsCopy); childSettings.remove(DisplaySetting.DISPLAY_OPTIONAL); } // grab a list of the group's options. final List list; if (comp == null) { // default to using the initial order list = options; } else { // sort options if comparator is supplied list = new ArrayList(options); Collections.sort(list, comp); } // for each option. for (final Iterator i = list.iterator(); i.hasNext();) { final Option option = (Option) i.next(); // append usage information option.appendUsage(buffer, childSettings, comp); // add separators as needed if (i.hasNext()) { buffer.append(separator); } } } if (both) { buffer.append(')'); } if (optional && outer) { buffer.append(']'); } if (arguments) { for (final Iterator i = anonymous.iterator(); i.hasNext();) { buffer.append(' '); final Option option = (Option) i.next(); option.appendUsage(buffer, helpSettingsCopy, comp); } } if (optional && !outer) { buffer.append(']'); } } public List helpLines(final int depth, final Set helpSettings, final Comparator comp) { final List helpLines = new ArrayList(); if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_NAME)) { final HelpLine helpLine = new HelpLineImpl(this, depth); helpLines.add(helpLine); } if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) { // grab a list of the group's options. final List list; if (comp == null) { // default to using the initial order list = options; } else { // sort options if comparator is supplied list = new ArrayList(options); Collections.sort(list, comp); } // for each option for (final Iterator i = list.iterator(); i.hasNext();) { final Option option = (Option) i.next(); helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp)); } } if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT)) { for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Option option = (Option) i.next(); helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp)); } } return helpLines; } /** * Gets the member Options of thie Group. * Note this does not include any Arguments * @return only the non Argument Options of the Group */ public List getOptions() { return options; } /** * Gets the anonymous Arguments of this Group. * @return the Argument options of this Group */ public List getAnonymous() { return anonymous; } public Option findOption(final String trigger) { final Iterator i = getOptions().iterator(); while (i.hasNext()) { final Option option = (Option) i.next(); final Option found = option.findOption(trigger); if (found != null) { return found; } } return null; } public int getMinimum() { return minimum; } public int getMaximum() { return maximum; } public boolean isRequired() { return getMinimum() > 0; } public void defaults(final WriteableCommandLine commandLine) { super.defaults(commandLine); for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); option.defaults(commandLine); } for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Option option = (Option) i.next(); option.defaults(commandLine); } }}class ReverseStringComparator implements Comparator { private static final Comparator instance = new ReverseStringComparator(); private ReverseStringComparator() { // just making sure nobody else creates one } /** * Gets a singleton instance of a ReverseStringComparator * @return the singleton instance */ public static final Comparator getInstance() { return instance; } public int compare(final Object o1, final Object o2) { final String s1 = (String) o1; final String s2 = (String) o2; return -s1.compareTo(s2); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.HelpLine; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.resource.ResourceConstants; + +/** + * An implementation of Group + */ +public class GroupImpl + extends OptionImpl implements Group { + private final String name; + private final String description; + private final List options; + private final int minimum; + private final int maximum; + private final List anonymous; + private final SortedMap optionMap; + private final Set prefixes; + + /** + * Creates a new GroupImpl using the specified parameters. + * + * @param options the Options and Arguments that make up the Group + * @param name the name of this Group, or null + * @param description a description of this Group + * @param minimum the minimum number of Options for a valid CommandLine + * @param maximum the maximum number of Options for a valid CommandLine + */ + public GroupImpl(final List options, + final String name, + final String description, + final int minimum, + final int maximum) { + super(0, false); + + this.name = name; + this.description = description; + this.minimum = minimum; + this.maximum = maximum; + + // store a copy of the options to be used by the + // help methods + this.options = Collections.unmodifiableList(options); + + // anonymous Argument temporary storage + final List newAnonymous = new ArrayList(); + + // map (key=trigger & value=Option) temporary storage + final SortedMap newOptionMap = new TreeMap(ReverseStringComparator.getInstance()); + + // prefixes temporary storage + final Set newPrefixes = new HashSet(); + + // process the options + for (final Iterator i = options.iterator(); i.hasNext();) { + final Option option = (Option) i.next(); + + if (option instanceof Argument) { + i.remove(); + newAnonymous.add(option); + } else { + final Set triggers = option.getTriggers(); + + for (Iterator j = triggers.iterator(); j.hasNext();) { + newOptionMap.put(j.next(), option); + } + + // store the prefixes + newPrefixes.addAll(option.getPrefixes()); + } + } + + this.anonymous = Collections.unmodifiableList(newAnonymous); + this.optionMap = Collections.unmodifiableSortedMap(newOptionMap); + this.prefixes = Collections.unmodifiableSet(newPrefixes); + } + + public boolean canProcess(final WriteableCommandLine commandLine, + final String arg) { + if (arg == null) { + return false; + } + + // if arg does not require bursting + if (optionMap.containsKey(arg)) { + return true; + } + + // filter + final Map tailMap = optionMap.tailMap(arg); + + // check if bursting is required + for (final Iterator iter = tailMap.values().iterator(); iter.hasNext();) { + final Option option = (Option) iter.next(); + + if (option.canProcess(commandLine, arg)) { + return true; + } + } + + if (commandLine.looksLikeOption(arg)) { + return false; + } + + // anonymous argument(s) means we can process it + if (anonymous.size() > 0) { + return true; + } + + return false; + } + + public Set getPrefixes() { + return prefixes; + } + + public Set getTriggers() { + return optionMap.keySet(); + } + + public void process(final WriteableCommandLine commandLine, + final ListIterator arguments) + throws OptionException { + String previous = null; + + // [START process each command line token + while (arguments.hasNext()) { + // grab the next argument + final String arg = (String) arguments.next(); + + // if we have just tried to process this instance + if (arg == previous) { + // rollback and abort + arguments.previous(); + + break; + } + + // remember last processed instance + previous = arg; + + final Option opt = (Option) optionMap.get(arg); + + // option found + if (opt != null) { + arguments.previous(); + opt.process(commandLine, arguments); + } + // [START option NOT found + else { + // it might be an anonymous argument continue search + // [START argument may be anonymous + if (commandLine.looksLikeOption(arg)) { + // narrow the search + final Collection values = optionMap.tailMap(arg).values(); + + boolean foundMemberOption = false; + + for (Iterator i = values.iterator(); i.hasNext() && !foundMemberOption;) { + final Option option = (Option) i.next(); + + if (option.canProcess(commandLine, arg)) { + foundMemberOption = true; + arguments.previous(); + option.process(commandLine, arguments); + } + } + + // back track and abort this group if necessary + if (!foundMemberOption) { + arguments.previous(); + + return; + } + } // [END argument may be anonymous + + // [START argument is NOT anonymous + else { + // move iterator back, current value not used + arguments.previous(); + + // if there are no anonymous arguments then this group can't + // process the argument + if (anonymous.isEmpty()) { + break; + } + + // TODO: why do we iterate over all anonymous arguments? + // canProcess will always return true? + for (final Iterator i = anonymous.iterator(); i.hasNext();) { + final Argument argument = (Argument) i.next(); + + if (argument.canProcess(commandLine, arguments)) { + argument.process(commandLine, arguments); + } + } + } // [END argument is NOT anonymous + } // [END option NOT found + } // [END process each command line token + } + + public void validate(final WriteableCommandLine commandLine) + throws OptionException { + // number of options found + int present = 0; + + // reference to first unexpected option + Option unexpected = null; + + for (final Iterator i = options.iterator(); i.hasNext();) { + final Option option = (Option) i.next(); + + // if the child option is required then validate it + if (option.isRequired()) { + option.validate(commandLine); + } + + if (option instanceof Group) { + option.validate(commandLine); + } + + // if the child option is present then validate it + if (commandLine.hasOption(option)) { + if (++present > maximum) { + unexpected = option; + + break; + } + + option.validate(commandLine); + } + } + + // too many options + if (unexpected != null) { + throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, + unexpected.getPreferredName()); + } + + // too few option + if (present < minimum) { + throw new OptionException(this, ResourceConstants.MISSING_OPTION); + } + + // validate each anonymous argument + for (final Iterator i = anonymous.iterator(); i.hasNext();) { + final Option option = (Option) i.next(); + option.validate(commandLine); + } + } + + public String getPreferredName() { + return name; + } + + public String getDescription() { + return description; + } + + public void appendUsage(final StringBuffer buffer, + final Set helpSettings, + final Comparator comp) { + appendUsage(buffer, helpSettings, comp, "|"); + } + + public void appendUsage(final StringBuffer buffer, + final Set helpSettings, + final Comparator comp, + final String separator) { + final Set helpSettingsCopy = new HashSet(helpSettings); + + final boolean optional = + (minimum == 0) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_OPTIONAL); + + final boolean expanded = + (name == null) || helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED); + + final boolean named = + !expanded || + ((name != null) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_NAME)); + + final boolean arguments = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT); + + final boolean outer = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_OUTER); + + helpSettingsCopy.remove(DisplaySetting.DISPLAY_GROUP_OUTER); + + final boolean both = named && expanded; + + if (optional) { + buffer.append('['); + } + + if (named) { + buffer.append(name); + } + + if (both) { + buffer.append(" ("); + } + + if (expanded) { + final Set childSettings; + + if (!helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) { + childSettings = DisplaySetting.NONE; + } else { + childSettings = new HashSet(helpSettingsCopy); + childSettings.remove(DisplaySetting.DISPLAY_OPTIONAL); + } + + // grab a list of the group's options. + final List list; + + if (comp == null) { + // default to using the initial order + list = options; + } else { + // sort options if comparator is supplied + list = new ArrayList(options); + Collections.sort(list, comp); + } + + // for each option. + for (final Iterator i = list.iterator(); i.hasNext();) { + final Option option = (Option) i.next(); + + // append usage information + option.appendUsage(buffer, childSettings, comp); + + // add separators as needed + if (i.hasNext()) { + buffer.append(separator); + } + } + } + + if (both) { + buffer.append(')'); + } + + if (optional && outer) { + buffer.append(']'); + } + + if (arguments) { + for (final Iterator i = anonymous.iterator(); i.hasNext();) { + buffer.append(' '); + + final Option option = (Option) i.next(); + option.appendUsage(buffer, helpSettingsCopy, comp); + } + } + + if (optional && !outer) { + buffer.append(']'); + } + } + + public List helpLines(final int depth, + final Set helpSettings, + final Comparator comp) { + final List helpLines = new ArrayList(); + + if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_NAME)) { + final HelpLine helpLine = new HelpLineImpl(this, depth); + helpLines.add(helpLine); + } + + if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) { + // grab a list of the group's options. + final List list; + + if (comp == null) { + // default to using the initial order + list = options; + } else { + // sort options if comparator is supplied + list = new ArrayList(options); + Collections.sort(list, comp); + } + + // for each option + for (final Iterator i = list.iterator(); i.hasNext();) { + final Option option = (Option) i.next(); + helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp)); + } + } + + if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT)) { + for (final Iterator i = anonymous.iterator(); i.hasNext();) { + final Option option = (Option) i.next(); + helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp)); + } + } + + return helpLines; + } + + /** + * Gets the member Options of thie Group. + * Note this does not include any Arguments + * @return only the non Argument Options of the Group + */ + public List getOptions() { + return options; + } + + /** + * Gets the anonymous Arguments of this Group. + * @return the Argument options of this Group + */ + public List getAnonymous() { + return anonymous; + } + + public Option findOption(final String trigger) { + final Iterator i = getOptions().iterator(); + + while (i.hasNext()) { + final Option option = (Option) i.next(); + final Option found = option.findOption(trigger); + + if (found != null) { + return found; + } + } + + return null; + } + + public int getMinimum() { + return minimum; + } + + public int getMaximum() { + return maximum; + } + + public boolean isRequired() { + return getMinimum() > 0; + } + + public void defaults(final WriteableCommandLine commandLine) { + super.defaults(commandLine); + + for (final Iterator i = options.iterator(); i.hasNext();) { + final Option option = (Option) i.next(); + option.defaults(commandLine); + } + + for (final Iterator i = anonymous.iterator(); i.hasNext();) { + final Option option = (Option) i.next(); + option.defaults(commandLine); + } + } +} + + +class ReverseStringComparator implements Comparator { + private static final Comparator instance = new ReverseStringComparator(); + + private ReverseStringComparator() { + // just making sure nobody else creates one + } + + /** + * Gets a singleton instance of a ReverseStringComparator + * @return the singleton instance + */ + public static final Comparator getInstance() { + return instance; + } + + public int compare(final Object o1, + final Object o2) { + final String s1 = (String) o1; + final String s2 = (String) o2; + + return -s1.compareTo(s2); + } +} diff --git a/src/java/org/apache/commons/cli2/option/HelpLineImpl.java b/src/java/org/apache/commons/cli2/option/HelpLineImpl.java index 144076e5c..da938c89e 100644 --- a/src/java/org/apache/commons/cli2/option/HelpLineImpl.java +++ b/src/java/org/apache/commons/cli2/option/HelpLineImpl.java @@ -1 +1,110 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Comparator;import java.util.Set;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;/** * Represents a line in the help screen. */public class HelpLineImpl implements HelpLine { /** The option that this HelpLineImpl describes */ private final Option option; /** The level of indenting for this item */ private final int indent; /** The help settings used to obtain the previous usage */ private transient Set cachedHelpSettings; /** The comparator used to obtain the previous usage */ private transient Comparator cachedComparator; /** The previously obtained usage */ private transient String cachedUsage; /** * Creates a new HelpLineImpl to represent a particular Option in the online * help. * * @param option * Option that the HelpLineImpl describes * @param indent * Level of indentation for this line */ public HelpLineImpl(final Option option, final int indent) { this.option = option; this.indent = indent; } /** * @return The description of the option */ public String getDescription() { return option.getDescription(); } /** * @return The level of indentation for this line */ public int getIndent() { return indent; } /** * @return The Option that the help line relates to */ public Option getOption() { return option; } /** * Builds a usage string for the option using the specified settings and * comparator. * * * @param helpSettings the settings to apply * @param comparator a comparator to sort options when applicable * @return the usage string */ public String usage(final Set helpSettings, final Comparator comparator) { if (cachedUsage == null || cachedHelpSettings != helpSettings || cachedComparator != comparator) { // cache the arguments to avoid redoing work cachedHelpSettings = helpSettings; cachedComparator = comparator; // build the new buffer final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < indent; ++i) { buffer.append(" "); } option.appendUsage(buffer, helpSettings, comparator); // cache the usage string cachedUsage = buffer.toString(); } return cachedUsage; }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.Comparator; +import java.util.Set; + +import org.apache.commons.cli2.HelpLine; +import org.apache.commons.cli2.Option; + +/** + * Represents a line in the help screen. + */ +public class HelpLineImpl implements HelpLine { + + /** The option that this HelpLineImpl describes */ + private final Option option; + + /** The level of indenting for this item */ + private final int indent; + + /** The help settings used to obtain the previous usage */ + private transient Set cachedHelpSettings; + + /** The comparator used to obtain the previous usage */ + private transient Comparator cachedComparator; + + /** The previously obtained usage */ + private transient String cachedUsage; + + /** + * Creates a new HelpLineImpl to represent a particular Option in the online + * help. + * + * @param option + * Option that the HelpLineImpl describes + * @param indent + * Level of indentation for this line + */ + public HelpLineImpl(final Option option, final int indent) { + this.option = option; + this.indent = indent; + } + + /** + * @return The description of the option + */ + public String getDescription() { + return option.getDescription(); + } + + /** + * @return The level of indentation for this line + */ + public int getIndent() { + return indent; + } + + /** + * @return The Option that the help line relates to + */ + public Option getOption() { + return option; + } + + /** + * Builds a usage string for the option using the specified settings and + * comparator. + * + * + * @param helpSettings the settings to apply + * @param comparator a comparator to sort options when applicable + * @return the usage string + */ + public String usage(final Set helpSettings, final Comparator comparator) { + if (cachedUsage == null + || cachedHelpSettings != helpSettings + || cachedComparator != comparator) { + + // cache the arguments to avoid redoing work + cachedHelpSettings = helpSettings; + cachedComparator = comparator; + + // build the new buffer + final StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < indent; ++i) { + buffer.append(" "); + } + option.appendUsage(buffer, helpSettings, comparator); + + // cache the usage string + cachedUsage = buffer.toString(); + } + return cachedUsage; + } +} diff --git a/src/java/org/apache/commons/cli2/option/OptionImpl.java b/src/java/org/apache/commons/cli2/option/OptionImpl.java index 4a7f895c1..eab47a9bd 100644 --- a/src/java/org/apache/commons/cli2/option/OptionImpl.java +++ b/src/java/org/apache/commons/cli2/option/OptionImpl.java @@ -1 +1,159 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Iterator;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * A base implementation of Option providing limited ground work for further * Option implementations. */public abstract class OptionImpl implements Option { private final int id; private final boolean required; /** * Creates an OptionImpl with the specified id * @param id the unique id of this Option * @param required true iff this Option must be present */ public OptionImpl(final int id, final boolean required) { this.id = id; this.required = required; } public boolean canProcess(final WriteableCommandLine commandLine, final ListIterator arguments) { if (arguments.hasNext()) { final String argument = (String) arguments.next(); arguments.previous(); return canProcess(commandLine, argument); } else { return false; } } public String toString() { final StringBuffer buffer = new StringBuffer(); appendUsage(buffer, DisplaySetting.ALL, null); return buffer.toString(); } public int getId() { return id; } public boolean equals(final Object thatObj) { if (thatObj instanceof OptionImpl) { final OptionImpl that = (OptionImpl) thatObj; return (getId() == that.getId()) && equals(getPreferredName(), that.getPreferredName()) && equals(getDescription(), that.getDescription()) && equals(getPrefixes(), that.getPrefixes()) && equals(getTriggers(), that.getTriggers()); } else { return false; } } private boolean equals(Object left, Object right) { if ((left == null) && (right == null)) { return true; } else if ((left == null) || (right == null)) { return false; } else { return left.equals(right); } } public int hashCode() { int hashCode = getId(); hashCode = (hashCode * 37) + getPreferredName().hashCode(); if (getDescription() != null) { hashCode = (hashCode * 37) + getDescription().hashCode(); } hashCode = (hashCode * 37) + getPrefixes().hashCode(); hashCode = (hashCode * 37) + getTriggers().hashCode(); return hashCode; } public Option findOption(String trigger) { if (getTriggers().contains(trigger)) { return this; } else { return null; } } public boolean isRequired() { return required; } public void defaults(final WriteableCommandLine commandLine) { // nothing to do normally } protected void checkPrefixes(final Set prefixes) { // nothing to do if empty prefix list if (prefixes.isEmpty()) { return; } // check preferred name checkPrefix(prefixes, getPreferredName()); // check triggers this.getTriggers(); for (final Iterator i = getTriggers().iterator(); i.hasNext();) { checkPrefix(prefixes, (String) i.next()); } } private void checkPrefix(final Set prefixes, final String trigger) { for (final Iterator i = prefixes.iterator(); i.hasNext();) { String prefix = (String) i.next(); if (trigger.startsWith(prefix)) { return; } } final ResourceHelper helper = ResourceHelper.getResourceHelper(); final String message = helper.getMessage(ResourceConstants.OPTION_TRIGGER_NEEDS_PREFIX, trigger, prefixes.toString()); throw new IllegalArgumentException(message); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.Iterator; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * A base implementation of Option providing limited ground work for further + * Option implementations. + */ +public abstract class OptionImpl implements Option { + private final int id; + private final boolean required; + + /** + * Creates an OptionImpl with the specified id + * @param id the unique id of this Option + * @param required true iff this Option must be present + */ + public OptionImpl(final int id, + final boolean required) { + this.id = id; + this.required = required; + } + + public boolean canProcess(final WriteableCommandLine commandLine, + final ListIterator arguments) { + if (arguments.hasNext()) { + final String argument = (String) arguments.next(); + arguments.previous(); + + return canProcess(commandLine, argument); + } else { + return false; + } + } + + public String toString() { + final StringBuffer buffer = new StringBuffer(); + appendUsage(buffer, DisplaySetting.ALL, null); + + return buffer.toString(); + } + + public int getId() { + return id; + } + + public boolean equals(final Object thatObj) { + if (thatObj instanceof OptionImpl) { + final OptionImpl that = (OptionImpl) thatObj; + + return (getId() == that.getId()) && + equals(getPreferredName(), that.getPreferredName()) && + equals(getDescription(), that.getDescription()) && + equals(getPrefixes(), that.getPrefixes()) && + equals(getTriggers(), that.getTriggers()); + } else { + return false; + } + } + + private boolean equals(Object left, + Object right) { + if ((left == null) && (right == null)) { + return true; + } else if ((left == null) || (right == null)) { + return false; + } else { + return left.equals(right); + } + } + + public int hashCode() { + int hashCode = getId(); + hashCode = (hashCode * 37) + getPreferredName().hashCode(); + + if (getDescription() != null) { + hashCode = (hashCode * 37) + getDescription().hashCode(); + } + + hashCode = (hashCode * 37) + getPrefixes().hashCode(); + hashCode = (hashCode * 37) + getTriggers().hashCode(); + + return hashCode; + } + + public Option findOption(String trigger) { + if (getTriggers().contains(trigger)) { + return this; + } else { + return null; + } + } + + public boolean isRequired() { + return required; + } + + public void defaults(final WriteableCommandLine commandLine) { + // nothing to do normally + } + + protected void checkPrefixes(final Set prefixes) { + // nothing to do if empty prefix list + if (prefixes.isEmpty()) { + return; + } + + // check preferred name + checkPrefix(prefixes, getPreferredName()); + + // check triggers + this.getTriggers(); + + for (final Iterator i = getTriggers().iterator(); i.hasNext();) { + checkPrefix(prefixes, (String) i.next()); + } + } + + private void checkPrefix(final Set prefixes, + final String trigger) { + for (final Iterator i = prefixes.iterator(); i.hasNext();) { + String prefix = (String) i.next(); + + if (trigger.startsWith(prefix)) { + return; + } + } + + final ResourceHelper helper = ResourceHelper.getResourceHelper(); + final String message = + helper.getMessage(ResourceConstants.OPTION_TRIGGER_NEEDS_PREFIX, trigger, + prefixes.toString()); + throw new IllegalArgumentException(message); + } +} diff --git a/src/java/org/apache/commons/cli2/option/ParentImpl.java b/src/java/org/apache/commons/cli2/option/ParentImpl.java index 9ac08c9da..064c80418 100644 --- a/src/java/org/apache/commons/cli2/option/ParentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ParentImpl.java @@ -1 +1,257 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.Parent;import org.apache.commons.cli2.WriteableCommandLine;/** * A base implementation of Parent providing limited ground work for further * Parent implementations. */public abstract class ParentImpl extends OptionImpl implements Parent { private static final char NUL = '\0'; private final Group children; private final Argument argument; private final String description; protected ParentImpl(final Argument argument, final Group children, final String description, final int id, final boolean required) { super(id, required); this.children = children; this.argument = argument; this.description = description; } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#process(org.apache.commons.cli2.CommandLine, * java.util.ListIterator) */ public void process(final WriteableCommandLine commandLine, final ListIterator arguments) throws OptionException { if (argument != null) { handleInitialSeparator(arguments, argument.getInitialSeparator()); } processParent(commandLine, arguments); if (argument != null) { argument.processValues(commandLine, arguments, this); } if ((children != null) && children.canProcess(commandLine, arguments)) { children.process(commandLine, arguments); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#canProcess(java.lang.String) */ public boolean canProcess(final WriteableCommandLine commandLine, final String arg) { final Set triggers = getTriggers(); if (argument != null) { final char separator = argument.getInitialSeparator(); // if there is a valid separator character if (separator != NUL) { final int initialIndex = arg.indexOf(separator); // if there is a separator present if (initialIndex > 0) { return triggers.contains(arg.substring(0, initialIndex)); } } } return triggers.contains(arg); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#prefixes() */ public Set getPrefixes() { return (children == null) ? Collections.EMPTY_SET : children.getPrefixes(); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#validate(org.apache.commons.cli2.CommandLine) */ public void validate(WriteableCommandLine commandLine) throws OptionException { if (commandLine.hasOption(this)) { if (argument != null) { argument.validate(commandLine, this); } if (children != null) { children.validate(commandLine); } } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#appendUsage(java.lang.StringBuffer, * java.util.Set, java.util.Comparator) */ public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { final boolean displayArgument = (this.argument != null) && helpSettings.contains(DisplaySetting.DISPLAY_PARENT_ARGUMENT); final boolean displayChildren = (this.children != null) && helpSettings.contains(DisplaySetting.DISPLAY_PARENT_CHILDREN); if (displayArgument) { buffer.append(' '); argument.appendUsage(buffer, helpSettings, comp); } if (displayChildren) { buffer.append(' '); children.appendUsage(buffer, helpSettings, comp); } } /** * @return a description of this parent option */ public String getDescription() { return description; } /* * (non-Javadoc) * * @see org.apache.commons.cli2.Option#helpLines(int, java.util.Set, * java.util.Comparator) */ public List helpLines(final int depth, final Set helpSettings, final Comparator comp) { final List helpLines = new ArrayList(); helpLines.add(new HelpLineImpl(this, depth)); if (helpSettings.contains(DisplaySetting.DISPLAY_PARENT_ARGUMENT) && (argument != null)) { helpLines.addAll(argument.helpLines(depth + 1, helpSettings, comp)); } if (helpSettings.contains(DisplaySetting.DISPLAY_PARENT_CHILDREN) && (children != null)) { helpLines.addAll(children.helpLines(depth + 1, helpSettings, comp)); } return helpLines; } /** * @return Returns the argument. */ public Argument getArgument() { return argument; } /** * @return Returns the children. */ public Group getChildren() { return children; } /** * Split the token using the specified separator character. * @param arguments the current position in the arguments iterator * @param separator the separator char to split on */ private void handleInitialSeparator(final ListIterator arguments, final char separator) { // next token final String newArgument = (String) arguments.next(); // split the token final int initialIndex = newArgument.indexOf(separator); if (initialIndex > 0) { arguments.remove(); arguments.add(newArgument.substring(0, initialIndex)); String value = newArgument.substring(initialIndex + 1); // The value obviously isn't an option, so we need to quote it if looks like an option. // The quotes will be removed later if (value.startsWith("-")) { value = '"' + value + '"'; } arguments.add(value); arguments.previous(); } arguments.previous(); } /* * @see org.apache.commons.cli2.Option#findOption(java.lang.String) */ public Option findOption(final String trigger) { final Option found = super.findOption(trigger); if ((found == null) && (children != null)) { return children.findOption(trigger); } else { return found; } } public void defaults(final WriteableCommandLine commandLine) { super.defaults(commandLine); if (argument != null) { argument.defaultValues(commandLine, this); } if (children != null) { children.defaults(commandLine); } }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.Parent; +import org.apache.commons.cli2.WriteableCommandLine; + +/** + * A base implementation of Parent providing limited ground work for further + * Parent implementations. + */ +public abstract class ParentImpl + extends OptionImpl implements Parent { + private static final char NUL = '\0'; + private final Group children; + private final Argument argument; + private final String description; + + protected ParentImpl(final Argument argument, + final Group children, + final String description, + final int id, + final boolean required) { + super(id, required); + this.children = children; + this.argument = argument; + this.description = description; + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.Option#process(org.apache.commons.cli2.CommandLine, + * java.util.ListIterator) + */ + public void process(final WriteableCommandLine commandLine, + final ListIterator arguments) + throws OptionException { + if (argument != null) { + handleInitialSeparator(arguments, argument.getInitialSeparator()); + } + + processParent(commandLine, arguments); + + if (argument != null) { + argument.processValues(commandLine, arguments, this); + } + + if ((children != null) && children.canProcess(commandLine, arguments)) { + children.process(commandLine, arguments); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.Option#canProcess(java.lang.String) + */ + public boolean canProcess(final WriteableCommandLine commandLine, + final String arg) { + final Set triggers = getTriggers(); + + if (argument != null) { + final char separator = argument.getInitialSeparator(); + + // if there is a valid separator character + if (separator != NUL) { + final int initialIndex = arg.indexOf(separator); + + // if there is a separator present + if (initialIndex > 0) { + return triggers.contains(arg.substring(0, initialIndex)); + } + } + } + + return triggers.contains(arg); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.Option#prefixes() + */ + public Set getPrefixes() { + return (children == null) ? Collections.EMPTY_SET : children.getPrefixes(); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.Option#validate(org.apache.commons.cli2.CommandLine) + */ + public void validate(WriteableCommandLine commandLine) + throws OptionException { + if (commandLine.hasOption(this)) { + if (argument != null) { + argument.validate(commandLine, this); + } + + if (children != null) { + children.validate(commandLine); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.Option#appendUsage(java.lang.StringBuffer, + * java.util.Set, java.util.Comparator) + */ + public void appendUsage(final StringBuffer buffer, + final Set helpSettings, + final Comparator comp) { + final boolean displayArgument = + (this.argument != null) && + helpSettings.contains(DisplaySetting.DISPLAY_PARENT_ARGUMENT); + final boolean displayChildren = + (this.children != null) && + helpSettings.contains(DisplaySetting.DISPLAY_PARENT_CHILDREN); + + if (displayArgument) { + buffer.append(' '); + argument.appendUsage(buffer, helpSettings, comp); + } + + if (displayChildren) { + buffer.append(' '); + children.appendUsage(buffer, helpSettings, comp); + } + } + + /** + * @return a description of this parent option + */ + public String getDescription() { + return description; + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.Option#helpLines(int, java.util.Set, + * java.util.Comparator) + */ + public List helpLines(final int depth, + final Set helpSettings, + final Comparator comp) { + final List helpLines = new ArrayList(); + helpLines.add(new HelpLineImpl(this, depth)); + + if (helpSettings.contains(DisplaySetting.DISPLAY_PARENT_ARGUMENT) && (argument != null)) { + helpLines.addAll(argument.helpLines(depth + 1, helpSettings, comp)); + } + + if (helpSettings.contains(DisplaySetting.DISPLAY_PARENT_CHILDREN) && (children != null)) { + helpLines.addAll(children.helpLines(depth + 1, helpSettings, comp)); + } + + return helpLines; + } + + /** + * @return Returns the argument. + */ + public Argument getArgument() { + return argument; + } + + /** + * @return Returns the children. + */ + public Group getChildren() { + return children; + } + + /** + * Split the token using the specified separator character. + * @param arguments the current position in the arguments iterator + * @param separator the separator char to split on + */ + private void handleInitialSeparator(final ListIterator arguments, + final char separator) { + // next token + final String newArgument = (String) arguments.next(); + + // split the token + final int initialIndex = newArgument.indexOf(separator); + + if (initialIndex > 0) { + arguments.remove(); + arguments.add(newArgument.substring(0, initialIndex)); + String value = newArgument.substring(initialIndex + 1); + // The value obviously isn't an option, so we need to quote it if looks like an option. + // The quotes will be removed later + if (value.startsWith("-")) { + value = '"' + value + '"'; + } + arguments.add(value); + arguments.previous(); + } + + arguments.previous(); + } + + /* + * @see org.apache.commons.cli2.Option#findOption(java.lang.String) + */ + public Option findOption(final String trigger) { + final Option found = super.findOption(trigger); + + if ((found == null) && (children != null)) { + return children.findOption(trigger); + } else { + return found; + } + } + + public void defaults(final WriteableCommandLine commandLine) { + super.defaults(commandLine); + + if (argument != null) { + argument.defaultValues(commandLine, this); + } + + if (children != null) { + children.defaults(commandLine); + } + } +} diff --git a/src/java/org/apache/commons/cli2/option/PropertyOption.java b/src/java/org/apache/commons/cli2/option/PropertyOption.java index 83a5c5aea..6c418eca0 100644 --- a/src/java/org/apache/commons/cli2/option/PropertyOption.java +++ b/src/java/org/apache/commons/cli2/option/PropertyOption.java @@ -1 +1,167 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;/** * Handles the java style "-Dprop=value" opions */public class PropertyOption extends OptionImpl { public static final String DEFAULT_OPTION_STRING = "-D"; public static final String DEFAULT_DESCRIPTION = "Passes properties and values to the application"; /** * A default PropertyOption instance */ public static final PropertyOption INSTANCE = new PropertyOption(); private final String optionString; private final String description; private final Set prefixes; /** * Creates a new PropertyOption using the default settings of a "-D" trigger * and an id of 'D' */ public PropertyOption() { this(DEFAULT_OPTION_STRING, DEFAULT_DESCRIPTION, 'D'); } /** * Creates a new PropertyOption using the specified parameters * @param optionString the trigger for the Option * @param description the description of the Option * @param id the id of the Option */ public PropertyOption(final String optionString, final String description, final int id) { super(id, false); this.optionString = optionString; this.description = description; this.prefixes = Collections.singleton(optionString); } public boolean canProcess(final WriteableCommandLine commandLine, final String argument) { return (argument != null) && argument.startsWith(optionString) && (argument.length() > optionString.length()); } public Set getPrefixes() { return prefixes; } public void process(final WriteableCommandLine commandLine, final ListIterator arguments) throws OptionException { final String arg = (String) arguments.next(); if (!canProcess(commandLine, arg)) { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); } final int propertyStart = optionString.length(); final int equalsIndex = arg.indexOf('=', propertyStart); final String property; final String value; if (equalsIndex < 0) { property = arg.substring(propertyStart); value = "true"; } else { property = arg.substring(propertyStart, equalsIndex); value = arg.substring(equalsIndex + 1); } commandLine.addProperty(property, value); } public Set getTriggers() { return Collections.singleton(optionString); } public void validate(WriteableCommandLine commandLine) { // PropertyOption needs no validation } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { final boolean display = helpSettings.contains(DisplaySetting.DISPLAY_PROPERTY_OPTION); final boolean bracketed = helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); if (display) { buffer.append(optionString); if (bracketed) { buffer.append('<'); } buffer.append("property"); if (bracketed) { buffer.append('>'); } buffer.append("="); if (bracketed) { buffer.append('<'); } buffer.append("value"); if (bracketed) { buffer.append('>'); } } } public String getPreferredName() { return optionString; } public String getDescription() { return description; } public List helpLines(final int depth, final Set helpSettings, final Comparator comp) { if (helpSettings.contains(DisplaySetting.DISPLAY_PROPERTY_OPTION)) { final HelpLine helpLine = new HelpLineImpl(this, depth); return Collections.singletonList(helpLine); } else { return Collections.EMPTY_LIST; } }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.HelpLine; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.resource.ResourceConstants; + +/** + * Handles the java style "-Dprop=value" opions + */ +public class PropertyOption + extends OptionImpl { + public static final String DEFAULT_OPTION_STRING = "-D"; + public static final String DEFAULT_DESCRIPTION = + "Passes properties and values to the application"; + + /** + * A default PropertyOption instance + */ + public static final PropertyOption INSTANCE = new PropertyOption(); + private final String optionString; + private final String description; + private final Set prefixes; + + /** + * Creates a new PropertyOption using the default settings of a "-D" trigger + * and an id of 'D' + */ + public PropertyOption() { + this(DEFAULT_OPTION_STRING, DEFAULT_DESCRIPTION, 'D'); + } + + /** + * Creates a new PropertyOption using the specified parameters + * @param optionString the trigger for the Option + * @param description the description of the Option + * @param id the id of the Option + */ + public PropertyOption(final String optionString, + final String description, + final int id) { + super(id, false); + this.optionString = optionString; + this.description = description; + this.prefixes = Collections.singleton(optionString); + } + + public boolean canProcess(final WriteableCommandLine commandLine, + final String argument) { + return (argument != null) && argument.startsWith(optionString) && + (argument.length() > optionString.length()); + } + + public Set getPrefixes() { + return prefixes; + } + + public void process(final WriteableCommandLine commandLine, + final ListIterator arguments) + throws OptionException { + final String arg = (String) arguments.next(); + + if (!canProcess(commandLine, arg)) { + throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); + } + + final int propertyStart = optionString.length(); + final int equalsIndex = arg.indexOf('=', propertyStart); + final String property; + final String value; + + if (equalsIndex < 0) { + property = arg.substring(propertyStart); + value = "true"; + } else { + property = arg.substring(propertyStart, equalsIndex); + value = arg.substring(equalsIndex + 1); + } + + commandLine.addProperty(property, value); + } + + public Set getTriggers() { + return Collections.singleton(optionString); + } + + public void validate(WriteableCommandLine commandLine) { + // PropertyOption needs no validation + } + + public void appendUsage(final StringBuffer buffer, + final Set helpSettings, + final Comparator comp) { + final boolean display = helpSettings.contains(DisplaySetting.DISPLAY_PROPERTY_OPTION); + + final boolean bracketed = helpSettings.contains(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); + + if (display) { + buffer.append(optionString); + + if (bracketed) { + buffer.append('<'); + } + + buffer.append("property"); + + if (bracketed) { + buffer.append('>'); + } + + buffer.append("="); + + if (bracketed) { + buffer.append('<'); + } + + buffer.append("value"); + + if (bracketed) { + buffer.append('>'); + } + } + } + + public String getPreferredName() { + return optionString; + } + + public String getDescription() { + return description; + } + + public List helpLines(final int depth, + final Set helpSettings, + final Comparator comp) { + if (helpSettings.contains(DisplaySetting.DISPLAY_PROPERTY_OPTION)) { + final HelpLine helpLine = new HelpLineImpl(this, depth); + + return Collections.singletonList(helpLine); + } else { + return Collections.EMPTY_LIST; + } + } +} diff --git a/src/java/org/apache/commons/cli2/option/SourceDestArgument.java b/src/java/org/apache/commons/cli2/option/SourceDestArgument.java index 2a346efd2..52402fef9 100644 --- a/src/java/org/apache/commons/cli2/option/SourceDestArgument.java +++ b/src/java/org/apache/commons/cli2/option/SourceDestArgument.java @@ -1 +1,138 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Comparator;import java.util.Iterator;import java.util.List;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * An Argument implementation that allows a variable size Argument to precede a * fixed size argument. The canonical example of it's use is in the unix * cp command where a number of source can be specified with * exactly one destination specfied at the end. */public class SourceDestArgument extends ArgumentImpl { private final Argument source; private final Argument dest; /** * Creates a SourceDestArgument using defaults where possible. * * @param source the variable size Argument * @param dest the fixed size Argument */ public SourceDestArgument(final Argument source, final Argument dest) { this(source, dest, DEFAULT_INITIAL_SEPARATOR, DEFAULT_SUBSEQUENT_SEPARATOR, DEFAULT_CONSUME_REMAINING, null); } /** * Creates a SourceDestArgument using the specified parameters. * * @param source the variable size Argument * @param dest the fixed size Argument * @param initialSeparator the inistial separator to use * @param subsequentSeparator the subsequent separator to use * @param consumeRemaining the token triggering consume remaining behaviour * @param defaultValues the default values for the SourceDestArgument */ public SourceDestArgument(final Argument source, final Argument dest, final char initialSeparator, final char subsequentSeparator, final String consumeRemaining, final List defaultValues) { super("SourceDestArgument", null, sum(source.getMinimum(), dest.getMinimum()), sum(source.getMaximum(), dest.getMaximum()), initialSeparator, subsequentSeparator, null, consumeRemaining, defaultValues, 0); this.source = source; this.dest = dest; if (dest.getMinimum() != dest.getMaximum()) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SOURCE_DEST_MUST_ENFORCE_VALUES)); } } private static int sum(final int a, final int b) { return Math.max(a, Math.max(b, a + b)); } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { final int length = buffer.length(); source.appendUsage(buffer, helpSettings, comp); if (buffer.length() != length) { buffer.append(' '); } dest.appendUsage(buffer, helpSettings, comp); } public List helpLines(int depth, Set helpSettings, Comparator comp) { final List helpLines = new ArrayList(); helpLines.addAll(source.helpLines(depth, helpSettings, comp)); helpLines.addAll(dest.helpLines(depth, helpSettings, comp)); return helpLines; } public void validate(WriteableCommandLine commandLine, Option option) throws OptionException { final List values = commandLine.getValues(option); final int limit = values.size() - dest.getMinimum(); int count = 0; final Iterator i = values.iterator(); while (count++ < limit) { commandLine.addValue(source, i.next()); } while (i.hasNext()) { commandLine.addValue(dest, i.next()); } source.validate(commandLine, source); dest.validate(commandLine, dest); } public boolean canProcess(final WriteableCommandLine commandLine, final String arg) { return source.canProcess(commandLine, arg) || dest.canProcess(commandLine, arg); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * An Argument implementation that allows a variable size Argument to precede a + * fixed size argument. The canonical example of it's use is in the unix + * cp command where a number of source can be specified with + * exactly one destination specfied at the end. + */ +public class SourceDestArgument + extends ArgumentImpl { + private final Argument source; + private final Argument dest; + + /** + * Creates a SourceDestArgument using defaults where possible. + * + * @param source the variable size Argument + * @param dest the fixed size Argument + */ + public SourceDestArgument(final Argument source, + final Argument dest) { + this(source, dest, DEFAULT_INITIAL_SEPARATOR, DEFAULT_SUBSEQUENT_SEPARATOR, + DEFAULT_CONSUME_REMAINING, null); + } + + /** + * Creates a SourceDestArgument using the specified parameters. + * + * @param source the variable size Argument + * @param dest the fixed size Argument + * @param initialSeparator the inistial separator to use + * @param subsequentSeparator the subsequent separator to use + * @param consumeRemaining the token triggering consume remaining behaviour + * @param defaultValues the default values for the SourceDestArgument + */ + public SourceDestArgument(final Argument source, + final Argument dest, + final char initialSeparator, + final char subsequentSeparator, + final String consumeRemaining, + final List defaultValues) { + super("SourceDestArgument", null, sum(source.getMinimum(), dest.getMinimum()), + sum(source.getMaximum(), dest.getMaximum()), initialSeparator, subsequentSeparator, + null, consumeRemaining, defaultValues, 0); + + this.source = source; + this.dest = dest; + + if (dest.getMinimum() != dest.getMaximum()) { + throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SOURCE_DEST_MUST_ENFORCE_VALUES)); + } + } + + private static int sum(final int a, + final int b) { + return Math.max(a, Math.max(b, a + b)); + } + + public void appendUsage(final StringBuffer buffer, + final Set helpSettings, + final Comparator comp) { + final int length = buffer.length(); + + source.appendUsage(buffer, helpSettings, comp); + + if (buffer.length() != length) { + buffer.append(' '); + } + + dest.appendUsage(buffer, helpSettings, comp); + } + + public List helpLines(int depth, + Set helpSettings, + Comparator comp) { + final List helpLines = new ArrayList(); + helpLines.addAll(source.helpLines(depth, helpSettings, comp)); + helpLines.addAll(dest.helpLines(depth, helpSettings, comp)); + + return helpLines; + } + + public void validate(WriteableCommandLine commandLine, + Option option) + throws OptionException { + final List values = commandLine.getValues(option); + + final int limit = values.size() - dest.getMinimum(); + int count = 0; + + final Iterator i = values.iterator(); + + while (count++ < limit) { + commandLine.addValue(source, i.next()); + } + + while (i.hasNext()) { + commandLine.addValue(dest, i.next()); + } + + source.validate(commandLine, source); + dest.validate(commandLine, dest); + } + + public boolean canProcess(final WriteableCommandLine commandLine, + final String arg) { + return source.canProcess(commandLine, arg) || dest.canProcess(commandLine, arg); + } +} diff --git a/src/java/org/apache/commons/cli2/option/Switch.java b/src/java/org/apache/commons/cli2/option/Switch.java index d4f68e3e2..0781bb645 100644 --- a/src/java/org/apache/commons/cli2/option/Switch.java +++ b/src/java/org/apache/commons/cli2/option/Switch.java @@ -1 +1,248 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * A Parent implementation representing normal switch options. * For example: +d|-d or --enable-x|--disable-x. */public class Switch extends ParentImpl { /** i18n */ public static final ResourceHelper resources = ResourceHelper.getResourceHelper(); /** * The default prefix for enabled switches */ public static final String DEFAULT_ENABLED_PREFIX = "+"; /** * The default prefix for disabled switches */ public static final String DEFAULT_DISABLED_PREFIX = "-"; private final String enabledPrefix; private final String disabledPrefix; private final Set triggers; private final String preferredName; private final Set aliases; private final Set prefixes; private final Boolean defaultSwitch; /** * Creates a new Switch with the specified parameters * @param enabledPrefix the prefix used for enabled switches * @param disabledPrefix the prefix used for disabled switches * @param preferredName the preferred name of the switch * @param aliases the aliases by which the Switch is known * @param description a description of the Switch * @param required whether the Option is strictly required * @param argument the Argument belonging to this Parent, or null * @param children the Group children belonging to this Parent, ot null * @param id the unique identifier for this Option * @throws IllegalArgumentException if the preferredName or an alias isn't * prefixed with enabledPrefix or disabledPrefix */ public Switch(final String enabledPrefix, final String disabledPrefix, final String preferredName, final Set aliases, final String description, final boolean required, final Argument argument, final Group children, final int id, final Boolean switchDefault) { super(argument, children, description, id, required); if (enabledPrefix == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_NO_ENABLED_PREFIX)); } if (disabledPrefix == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_NO_DISABLED_PREFIX)); } if (enabledPrefix.startsWith(disabledPrefix)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_ENABLED_STARTS_WITH_DISABLED)); } if (disabledPrefix.startsWith(enabledPrefix)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_DISABLED_STARTWS_WITH_ENABLED)); } this.enabledPrefix = enabledPrefix; this.disabledPrefix = disabledPrefix; this.preferredName = preferredName; if ((preferredName == null) || (preferredName.length() < 1)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT)); } final Set newTriggers = new HashSet(); newTriggers.add(enabledPrefix + preferredName); newTriggers.add(disabledPrefix + preferredName); this.triggers = Collections.unmodifiableSet(newTriggers); if (aliases == null) { this.aliases = Collections.EMPTY_SET; } else { this.aliases = Collections.unmodifiableSet(new HashSet(aliases)); for (final Iterator i = aliases.iterator(); i.hasNext();) { final String alias = (String) i.next(); newTriggers.add(enabledPrefix + alias); newTriggers.add(disabledPrefix + alias); } } final Set newPrefixes = new HashSet(super.getPrefixes()); newPrefixes.add(enabledPrefix); newPrefixes.add(disabledPrefix); this.prefixes = Collections.unmodifiableSet(newPrefixes); this.defaultSwitch = switchDefault; checkPrefixes(newPrefixes); } public void processParent(final WriteableCommandLine commandLine, final ListIterator arguments) throws OptionException { final String arg = (String) arguments.next(); if (canProcess(commandLine, arg)) { if (arg.startsWith(enabledPrefix)) { commandLine.addSwitch(this, true); arguments.set(enabledPrefix + preferredName); } if (arg.startsWith(disabledPrefix)) { commandLine.addSwitch(this, false); arguments.set(disabledPrefix + preferredName); } } else { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); } } public Set getTriggers() { return triggers; } public Set getPrefixes() { return prefixes; } public void validate(WriteableCommandLine commandLine) throws OptionException { if (isRequired() && !commandLine.hasOption(this)) { throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, getPreferredName()); } super.validate(commandLine); } public void appendUsage(final StringBuffer buffer, final Set helpSettings, final Comparator comp) { // do we display optionality final boolean optional = !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); final boolean disabled = helpSettings.contains(DisplaySetting.DISPLAY_SWITCH_DISABLED); final boolean enabled = !disabled || helpSettings.contains(DisplaySetting.DISPLAY_SWITCH_ENABLED); final boolean both = disabled && enabled; if (optional) { buffer.append('['); } if (enabled) { buffer.append(enabledPrefix).append(preferredName); } if (both) { buffer.append('|'); } if (disabled) { buffer.append(disabledPrefix).append(preferredName); } if (displayAliases && !aliases.isEmpty()) { buffer.append(" ("); final List list = new ArrayList(aliases); Collections.sort(list); for (final Iterator i = list.iterator(); i.hasNext();) { final String alias = (String) i.next(); if (enabled) { buffer.append(enabledPrefix).append(alias); } if (both) { buffer.append('|'); } if (disabled) { buffer.append(disabledPrefix).append(alias); } if (i.hasNext()) { buffer.append(','); } } buffer.append(')'); } super.appendUsage(buffer, helpSettings, comp); if (optional) { buffer.append(']'); } } public String getPreferredName() { return enabledPrefix + preferredName; } public void defaults(final WriteableCommandLine commandLine) { commandLine.setDefaultSwitch(this, defaultSwitch); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * A Parent implementation representing normal switch options. + * For example: +d|-d or --enable-x|--disable-x. + */ +public class Switch + extends ParentImpl { + /** i18n */ + public static final ResourceHelper resources = ResourceHelper.getResourceHelper(); + + /** + * The default prefix for enabled switches + */ + public static final String DEFAULT_ENABLED_PREFIX = "+"; + + /** + * The default prefix for disabled switches + */ + public static final String DEFAULT_DISABLED_PREFIX = "-"; + private final String enabledPrefix; + private final String disabledPrefix; + private final Set triggers; + private final String preferredName; + private final Set aliases; + private final Set prefixes; + private final Boolean defaultSwitch; + + /** + * Creates a new Switch with the specified parameters + * @param enabledPrefix the prefix used for enabled switches + * @param disabledPrefix the prefix used for disabled switches + * @param preferredName the preferred name of the switch + * @param aliases the aliases by which the Switch is known + * @param description a description of the Switch + * @param required whether the Option is strictly required + * @param argument the Argument belonging to this Parent, or null + * @param children the Group children belonging to this Parent, ot null + * @param id the unique identifier for this Option + * @throws IllegalArgumentException if the preferredName or an alias isn't + * prefixed with enabledPrefix or disabledPrefix + */ + public Switch(final String enabledPrefix, + final String disabledPrefix, + final String preferredName, + final Set aliases, + final String description, + final boolean required, + final Argument argument, + final Group children, + final int id, + final Boolean switchDefault) { + super(argument, children, description, id, required); + + if (enabledPrefix == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_NO_ENABLED_PREFIX)); + } + + if (disabledPrefix == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_NO_DISABLED_PREFIX)); + } + + if (enabledPrefix.startsWith(disabledPrefix)) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_ENABLED_STARTS_WITH_DISABLED)); + } + + if (disabledPrefix.startsWith(enabledPrefix)) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_DISABLED_STARTWS_WITH_ENABLED)); + } + + this.enabledPrefix = enabledPrefix; + this.disabledPrefix = disabledPrefix; + this.preferredName = preferredName; + + if ((preferredName == null) || (preferredName.length() < 1)) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT)); + } + + final Set newTriggers = new HashSet(); + newTriggers.add(enabledPrefix + preferredName); + newTriggers.add(disabledPrefix + preferredName); + this.triggers = Collections.unmodifiableSet(newTriggers); + + if (aliases == null) { + this.aliases = Collections.EMPTY_SET; + } else { + this.aliases = Collections.unmodifiableSet(new HashSet(aliases)); + + for (final Iterator i = aliases.iterator(); i.hasNext();) { + final String alias = (String) i.next(); + newTriggers.add(enabledPrefix + alias); + newTriggers.add(disabledPrefix + alias); + } + } + + final Set newPrefixes = new HashSet(super.getPrefixes()); + newPrefixes.add(enabledPrefix); + newPrefixes.add(disabledPrefix); + this.prefixes = Collections.unmodifiableSet(newPrefixes); + + this.defaultSwitch = switchDefault; + + checkPrefixes(newPrefixes); + } + + public void processParent(final WriteableCommandLine commandLine, + final ListIterator arguments) + throws OptionException { + final String arg = (String) arguments.next(); + + if (canProcess(commandLine, arg)) { + if (arg.startsWith(enabledPrefix)) { + commandLine.addSwitch(this, true); + arguments.set(enabledPrefix + preferredName); + } + + if (arg.startsWith(disabledPrefix)) { + commandLine.addSwitch(this, false); + arguments.set(disabledPrefix + preferredName); + } + } else { + throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg); + } + } + + public Set getTriggers() { + return triggers; + } + + public Set getPrefixes() { + return prefixes; + } + + public void validate(WriteableCommandLine commandLine) + throws OptionException { + if (isRequired() && !commandLine.hasOption(this)) { + throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED, + getPreferredName()); + } + + super.validate(commandLine); + } + + public void appendUsage(final StringBuffer buffer, + final Set helpSettings, + final Comparator comp) { + // do we display optionality + final boolean optional = + !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL); + final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES); + final boolean disabled = helpSettings.contains(DisplaySetting.DISPLAY_SWITCH_DISABLED); + final boolean enabled = + !disabled || helpSettings.contains(DisplaySetting.DISPLAY_SWITCH_ENABLED); + final boolean both = disabled && enabled; + + if (optional) { + buffer.append('['); + } + + if (enabled) { + buffer.append(enabledPrefix).append(preferredName); + } + + if (both) { + buffer.append('|'); + } + + if (disabled) { + buffer.append(disabledPrefix).append(preferredName); + } + + if (displayAliases && !aliases.isEmpty()) { + buffer.append(" ("); + + final List list = new ArrayList(aliases); + Collections.sort(list); + + for (final Iterator i = list.iterator(); i.hasNext();) { + final String alias = (String) i.next(); + + if (enabled) { + buffer.append(enabledPrefix).append(alias); + } + + if (both) { + buffer.append('|'); + } + + if (disabled) { + buffer.append(disabledPrefix).append(alias); + } + + if (i.hasNext()) { + buffer.append(','); + } + } + + buffer.append(')'); + } + + super.appendUsage(buffer, helpSettings, comp); + + if (optional) { + buffer.append(']'); + } + } + + public String getPreferredName() { + return enabledPrefix + preferredName; + } + + public void defaults(final WriteableCommandLine commandLine) { + commandLine.setDefaultSwitch(this, defaultSwitch); + } +} diff --git a/src/java/org/apache/commons/cli2/resource/ResourceConstants.java b/src/java/org/apache/commons/cli2/resource/ResourceConstants.java index 4bcc80077..c0b286f70 100644 --- a/src/java/org/apache/commons/cli2/resource/ResourceConstants.java +++ b/src/java/org/apache/commons/cli2/resource/ResourceConstants.java @@ -1 +1,70 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.commons.cli2.resource;public abstract class ResourceConstants { public static final String CLASSVALIDATOR_BAD_CLASSNAME = "ClassValidator.bad.classname"; public static final String CLASSVALIDATOR_CLASS_NOTFOUND = "ClassValidator.class.notfound"; public static final String CLASSVALIDATOR_CLASS_ACCESS = "ClassValidator.class.access"; public static final String CLASSVALIDATOR_CLASS_CREATE = "ClassValidator.class.create"; public static final String DATEVALIDATOR_DATE_OUTOFRANGE = "DateValidator.date.OutOfRange"; public static final String URLVALIDATOR_MALFORMED_URL = "URLValidator.malformed.URL"; public static final String NUMBERVALIDATOR_NUMBER_OUTOFRANGE = "NumberValidator.number.OutOfRange"; public static final String ARGUMENT_UNEXPECTED_VALUE = "Argument.unexpected.value"; public static final String ARGUMENT_MIN_EXCEEDS_MAX = "Argument.minimum.exceeds.maximum"; public static final String ARGUMENT_TOO_FEW_DEFAULTS = "Argument.too.few.defaults"; public static final String ARGUMENT_TOO_MANY_DEFAULTS = "Argument.too.many.defaults"; public static final String ARGUMENT_MISSING_VALUES = "Argument.missing.values"; public static final String ARGUMENT_TOO_MANY_VALUES = "Argument.too.many.values"; public static final String OPTION_TRIGGER_NEEDS_PREFIX = "Option.trigger.needs.prefix"; public static final String OPTION_MISSING_REQUIRED = "Option.missing.required"; public static final String OPTION_NO_NAME = "Option.no.name"; public static final String OPTION_ILLEGAL_LONG_PREFIX = "Option.illegal.long.prefix"; public static final String OPTION_ILLEGAL_SHORT_PREFIX = "Option.illegal.short.prefix"; public static final String UNEXPECTED_TOKEN = "Unexpected.token"; public static final String MISSING_OPTION = "Missing.option"; public static final String CANNOT_BURST = "Cannot.burst"; public static final String COMMAND_PREFERRED_NAME_TOO_SHORT = "Command.preferredName.too.short"; public static final String SWITCH_ILLEGAL_ENABLED_PREFIX = "Option.illegal.enabled.prefix"; public static final String SWITCH_ILLEGAL_DISABLED_PREFIX = "Option.illegal.disabled.prefix"; public static final String SWITCH_IDENTICAL_PREFIXES = "Option.identical.prefixes"; public static final String SWITCH_ALREADY_SET = "Switch.already.set"; public static final String SWITCH_NO_ENABLED_PREFIX = "Switch.no.enabledPrefix"; public static final String SWITCH_NO_DISABLED_PREFIX = "Switch.no.disabledPrefix"; public static final String SWITCH_ENABLED_STARTS_WITH_DISABLED = "Switch.enabled.startsWith.disabled"; public static final String SWITCH_DISABLED_STARTWS_WITH_ENABLED = "Switch.disabled.startsWith.enabled"; public static final String SWITCH_PREFERRED_NAME_TOO_SHORT = "Switch.preferredName.too.short"; public static final String SOURCE_DEST_MUST_ENFORCE_VALUES = "SourceDest.must.enforce.values"; public static final String HELPFORMATTER_GUTTER_TOO_LONG = "HelpFormatter.gutter.too.long"; public static final String HELPFORMATTER_WIDTH_TOO_NARROW = "HelpFormatter.width.too.narrow"; public static final String ENUM_ILLEGAL_VALUE = "Enum.illegal.value"; public static final String ARGUMENT_BUILDER_NULL_CONSUME_REMAINING = "ArgumentBuilder.null.consume.remaining"; public static final String ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING = "ArgumentBuilder.empty.consume.remaining"; public static final String ARGUMENT_BUILDER_NULL_DEFAULT = "ArgumentBuilder.null.default"; public static final String ARGUMENT_BUILDER_NULL_DEFAULTS = "ArgumentBuilder.null.defaults"; public static final String ARGUMENT_BUILDER_NEGATIVE_MAXIMUM = "ArgumentBuilder.negative.maximum"; public static final String ARGUMENT_BUILDER_NEGATIVE_MINIMUM = "ArgumentBuilder.negative.minimum"; public static final String ARGUMENT_BUILDER_NULL_NAME = "ArgumentBuilder.null.name"; public static final String ARGUMENT_BUILDER_EMPTY_NAME = "ArgumentBuilder.empty.name"; public static final String ARGUMENT_BUILDER_NULL_VALIDATOR = "ArgumentBuilder.null.validator";} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.cli2.resource; + +public abstract class ResourceConstants { + public static final String CLASSVALIDATOR_BAD_CLASSNAME = "ClassValidator.bad.classname"; + public static final String CLASSVALIDATOR_CLASS_NOTFOUND = "ClassValidator.class.notfound"; + public static final String CLASSVALIDATOR_CLASS_ACCESS = "ClassValidator.class.access"; + public static final String CLASSVALIDATOR_CLASS_CREATE = "ClassValidator.class.create"; + public static final String DATEVALIDATOR_DATE_OUTOFRANGE = "DateValidator.date.OutOfRange"; + public static final String URLVALIDATOR_MALFORMED_URL = "URLValidator.malformed.URL"; + public static final String NUMBERVALIDATOR_NUMBER_OUTOFRANGE = + "NumberValidator.number.OutOfRange"; + public static final String ARGUMENT_UNEXPECTED_VALUE = "Argument.unexpected.value"; + public static final String ARGUMENT_MIN_EXCEEDS_MAX = "Argument.minimum.exceeds.maximum"; + public static final String ARGUMENT_TOO_FEW_DEFAULTS = "Argument.too.few.defaults"; + public static final String ARGUMENT_TOO_MANY_DEFAULTS = "Argument.too.many.defaults"; + public static final String ARGUMENT_MISSING_VALUES = "Argument.missing.values"; + public static final String ARGUMENT_TOO_MANY_VALUES = "Argument.too.many.values"; + public static final String OPTION_TRIGGER_NEEDS_PREFIX = "Option.trigger.needs.prefix"; + public static final String OPTION_MISSING_REQUIRED = "Option.missing.required"; + public static final String OPTION_NO_NAME = "Option.no.name"; + public static final String OPTION_ILLEGAL_LONG_PREFIX = "Option.illegal.long.prefix"; + public static final String OPTION_ILLEGAL_SHORT_PREFIX = "Option.illegal.short.prefix"; + public static final String UNEXPECTED_TOKEN = "Unexpected.token"; + public static final String MISSING_OPTION = "Missing.option"; + public static final String CANNOT_BURST = "Cannot.burst"; + public static final String COMMAND_PREFERRED_NAME_TOO_SHORT = "Command.preferredName.too.short"; + public static final String SWITCH_ILLEGAL_ENABLED_PREFIX = "Option.illegal.enabled.prefix"; + public static final String SWITCH_ILLEGAL_DISABLED_PREFIX = "Option.illegal.disabled.prefix"; + public static final String SWITCH_IDENTICAL_PREFIXES = "Option.identical.prefixes"; + public static final String SWITCH_ALREADY_SET = "Switch.already.set"; + public static final String SWITCH_NO_ENABLED_PREFIX = "Switch.no.enabledPrefix"; + public static final String SWITCH_NO_DISABLED_PREFIX = "Switch.no.disabledPrefix"; + public static final String SWITCH_ENABLED_STARTS_WITH_DISABLED = + "Switch.enabled.startsWith.disabled"; + public static final String SWITCH_DISABLED_STARTWS_WITH_ENABLED = + "Switch.disabled.startsWith.enabled"; + public static final String SWITCH_PREFERRED_NAME_TOO_SHORT = "Switch.preferredName.too.short"; + public static final String SOURCE_DEST_MUST_ENFORCE_VALUES = "SourceDest.must.enforce.values"; + public static final String HELPFORMATTER_GUTTER_TOO_LONG = "HelpFormatter.gutter.too.long"; + public static final String HELPFORMATTER_WIDTH_TOO_NARROW = "HelpFormatter.width.too.narrow"; + public static final String ENUM_ILLEGAL_VALUE = "Enum.illegal.value"; + public static final String ARGUMENT_BUILDER_NULL_CONSUME_REMAINING = "ArgumentBuilder.null.consume.remaining"; + public static final String ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING = "ArgumentBuilder.empty.consume.remaining"; + public static final String ARGUMENT_BUILDER_NULL_DEFAULT = "ArgumentBuilder.null.default"; + public static final String ARGUMENT_BUILDER_NULL_DEFAULTS = "ArgumentBuilder.null.defaults"; + public static final String ARGUMENT_BUILDER_NEGATIVE_MAXIMUM = "ArgumentBuilder.negative.maximum"; + public static final String ARGUMENT_BUILDER_NEGATIVE_MINIMUM = "ArgumentBuilder.negative.minimum"; + public static final String ARGUMENT_BUILDER_NULL_NAME = "ArgumentBuilder.null.name"; + public static final String ARGUMENT_BUILDER_EMPTY_NAME = "ArgumentBuilder.empty.name"; + public static final String ARGUMENT_BUILDER_NULL_VALIDATOR = "ArgumentBuilder.null.validator"; + +} diff --git a/src/java/org/apache/commons/cli2/resource/ResourceHelper.java b/src/java/org/apache/commons/cli2/resource/ResourceHelper.java index 6a0128d39..eab71f9e1 100644 --- a/src/java/org/apache/commons/cli2/resource/ResourceHelper.java +++ b/src/java/org/apache/commons/cli2/resource/ResourceHelper.java @@ -1 +1,160 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.resource;import java.text.MessageFormat;import java.util.Locale;import java.util.MissingResourceException;import java.util.ResourceBundle;/** * A utility class used to provide internationalisation support. * * @author John Keyes */public class ResourceHelper { /** system property */ private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle"; /** default package name */ private static final String DEFAULT_BUNDLE = "org.apache.commons.cli2.resource.CLIMessageBundle_en_US"; private static ResourceHelper helper; /** resource bundle */ private ResourceBundle bundle; private String prop; /** * Create a new ResourceHelper for the current locale. */ private ResourceHelper() { String bundleName = System.getProperty(PROP_LOCALE); if (bundleName == null) { bundleName = DEFAULT_BUNDLE; } this.prop = bundleName; int firstUnderscore = bundleName.indexOf('_'); int secondUnderscore = bundleName.indexOf('_', firstUnderscore + 1); Locale locale; if (firstUnderscore != -1) { String language = bundleName.substring(firstUnderscore + 1, secondUnderscore); String country = bundleName.substring(secondUnderscore + 1); locale = new Locale(language, country); } else { locale = Locale.getDefault(); } // initialize the bundle try { bundle = ResourceBundle.getBundle(bundleName, locale); } catch (MissingResourceException exp) { bundle = ResourceBundle.getBundle(DEFAULT_BUNDLE, locale); } } public String getBundleName() { return this.prop; } /** * Gets the ResourceHelper appropriate to the current locale. * @return a ResourceHelper */ public static ResourceHelper getResourceHelper() { String bundleName = System.getProperty(PROP_LOCALE); if (helper == null || !helper.getBundleName().equals(bundleName)) { helper = new ResourceHelper(); } return helper; } /** * Returns the message for the specified key. * * @param key the unique identifier of the message * @return String the formatted String */ public String getMessage(final String key) { return getMessage(key, new Object[] { }); } /** * Returns the message for the specified key and argument. * * @param key the unique identifier of the message * @param value the argument value * @return String the formatted String */ public String getMessage(final String key, final Object value) { return getMessage(key, new Object[] { value }); } /** * Returns the message for the specified key and arguments. * * @param key the unique identifier of the message * @param value1 an argument value * @param value2 an argument value * @return String the formatted String */ public String getMessage(final String key, final Object value1, final Object value2) { return getMessage(key, new Object[] { value1, value2 }); } /** * Returns the message for the specified key and arguments. * * @param key the unique identifier of the message * @param value1 an argument value * @param value2 an argument value * @param value3 an argument value * * @return String the formatted String */ public String getMessage(final String key, final Object value1, final Object value2, final Object value3) { return getMessage(key, new Object[] { value1, value2, value3 }); } /** * Returns the message for the specified key and arguments. * * @param key the unique identifier of the message * @param values argument values * @return String the formatted String */ public String getMessage(final String key, final Object[] values) { final String msgFormatStr = bundle.getString(key); final MessageFormat msgFormat = new MessageFormat(msgFormatStr); return msgFormat.format(values); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.resource; + +import java.text.MessageFormat; + +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +/** + * A utility class used to provide internationalisation support. + * + * @author John Keyes + */ +public class ResourceHelper { + /** system property */ + private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle"; + + /** default package name */ + private static final String DEFAULT_BUNDLE = + "org.apache.commons.cli2.resource.CLIMessageBundle_en_US"; + private static ResourceHelper helper; + + /** resource bundle */ + private ResourceBundle bundle; + + private String prop; + + /** + * Create a new ResourceHelper for the current locale. + */ + private ResourceHelper() { + String bundleName = System.getProperty(PROP_LOCALE); + + if (bundleName == null) { + bundleName = DEFAULT_BUNDLE; + } + + this.prop = bundleName; + + int firstUnderscore = bundleName.indexOf('_'); + int secondUnderscore = bundleName.indexOf('_', firstUnderscore + 1); + + Locale locale; + if (firstUnderscore != -1) { + String language = bundleName.substring(firstUnderscore + 1, secondUnderscore); + String country = bundleName.substring(secondUnderscore + 1); + locale = new Locale(language, country); + } + else { + locale = Locale.getDefault(); + } + // initialize the bundle + try { + bundle = ResourceBundle.getBundle(bundleName, locale); + } catch (MissingResourceException exp) { + bundle = ResourceBundle.getBundle(DEFAULT_BUNDLE, locale); + } + } + + public String getBundleName() { + return this.prop; + } + + /** + * Gets the ResourceHelper appropriate to the current locale. + * @return a ResourceHelper + */ + public static ResourceHelper getResourceHelper() { + String bundleName = System.getProperty(PROP_LOCALE); + if (helper == null || !helper.getBundleName().equals(bundleName)) { + helper = new ResourceHelper(); + } + + return helper; + } + + /** + * Returns the message for the specified key. + * + * @param key the unique identifier of the message + * @return String the formatted String + */ + public String getMessage(final String key) { + return getMessage(key, new Object[] { }); + } + + /** + * Returns the message for the specified key and argument. + * + * @param key the unique identifier of the message + * @param value the argument value + * @return String the formatted String + */ + public String getMessage(final String key, + final Object value) { + return getMessage(key, new Object[] { value }); + } + + /** + * Returns the message for the specified key and arguments. + * + * @param key the unique identifier of the message + * @param value1 an argument value + * @param value2 an argument value + * @return String the formatted String + */ + public String getMessage(final String key, + final Object value1, + final Object value2) { + return getMessage(key, new Object[] { value1, value2 }); + } + + /** + * Returns the message for the specified key and arguments. + * + * @param key the unique identifier of the message + * @param value1 an argument value + * @param value2 an argument value + * @param value3 an argument value + * + * @return String the formatted String + */ + public String getMessage(final String key, + final Object value1, + final Object value2, + final Object value3) { + return getMessage(key, new Object[] { value1, value2, value3 }); + } + + /** + * Returns the message for the specified key and arguments. + * + * @param key the unique identifier of the message + * @param values argument values + * @return String the formatted String + */ + public String getMessage(final String key, + final Object[] values) { + final String msgFormatStr = bundle.getString(key); + final MessageFormat msgFormat = new MessageFormat(msgFormatStr); + + return msgFormat.format(values); + } +} diff --git a/src/java/org/apache/commons/cli2/util/Comparators.java b/src/java/org/apache/commons/cli2/util/Comparators.java index 3cd7c68eb..3cc137e31 100644 --- a/src/java/org/apache/commons/cli2/util/Comparators.java +++ b/src/java/org/apache/commons/cli2/util/Comparators.java @@ -1 +1,456 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.util;import java.util.Comparator;import java.util.List;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.option.Command;import org.apache.commons.cli2.option.DefaultOption;import org.apache.commons.cli2.option.Switch;/** * A collection of Comparators suitable for use with Option instances. */public class Comparators { private Comparators(){ // constructor hiden from potential users } /** * Chains comparators together. * * @see #chain(Comparator[]) * @param c0 * a comparator * @param c1 * a comparator * @return a chained comparator */ public static Comparator chain(final Comparator c0, final Comparator c1) { return chain(new Comparator[] { c0, c1 }); } /** * Chains comparators together. * * @see #chain(Comparator[]) * @param c0 * a comparator * @param c1 * a comparator * @param c2 * a comparator * @return a chained comparator */ public static Comparator chain( final Comparator c0, final Comparator c1, final Comparator c2) { return chain(new Comparator[] { c0, c1, c2 }); } /** * Chains comparators together. * * @see #chain(Comparator[]) * @param c0 * a comparator * @param c1 * a comparator * @param c2 * a comparator * @param c3 * a comparator * @return a chained comparator */ public static Comparator chain( final Comparator c0, final Comparator c1, final Comparator c2, final Comparator c3) { return chain(new Comparator[] { c0, c1, c2, c3 }); } /** * Chains comparators together. * * @see #chain(Comparator[]) * @param c0 * a comparator * @param c1 * a comparator * @param c2 * a comparator * @param c3 * a comparator * @param c4 * a comparator * @return a chained comparator */ public static Comparator chain( final Comparator c0, final Comparator c1, final Comparator c2, final Comparator c3, final Comparator c4) { return chain(new Comparator[] { c0, c1, c2, c3, c4 }); } /** * Chains comparators together. * * @see #chain(Comparator[]) * @param comparators * a List of comparators to chain together * @return a chained comparator */ public static Comparator chain(final List comparators) { return new Chain( (Comparator[])comparators.toArray( new Comparator[comparators.size()])); } /** * Chains an array of comparators together. Each Comparator will be called * in turn until one of them return a non-zero value, this value will be * returned. * * @param comparators * the array of comparators * @return a chained comparator */ public static Comparator chain(final Comparator[] comparators) { return new Chain(comparators); } /** * Chains a series of Comparators together. */ private static class Chain implements Comparator { final Comparator[] chain; /** * Creates a Comparator chain using the specified array of Comparators * @param chain the Comparators in the chain */ public Chain(final Comparator[] chain) { this.chain = new Comparator[chain.length]; System.arraycopy(chain, 0, this.chain, 0, chain.length); } public int compare(final Object left, final Object right) { int result = 0; for (int i = 0; result == 0 && i < chain.length; ++i) { result = chain[i].compare(left, right); } return result; } } /** * Reverses a comparator's logic. * * @param wrapped * the Comparator to reverse the logic of * @return a comparator with reverse logic */ private static Comparator reverse(final Comparator wrapped) { return new Reverse(wrapped); } private static class Reverse implements Comparator { private final Comparator wrapped; /** * Creates a Comparator with reverse logic * @param wrapped the original logic */ public Reverse(final Comparator wrapped) { this.wrapped = wrapped; } public int compare(final Object left, final Object right) { return -wrapped.compare(left, right); } } /** * Forces Group instances to appear at the beginning of lists * * @see Group * @return a new comparator */ public static Comparator groupFirst() { return new GroupFirst(); } /** * Forces Group instances to appear at the end of lists * * @see Group * @return a new comparator */ public static Comparator groupLast() { return reverse(groupFirst()); } private static class GroupFirst implements Comparator { public int compare(final Object left, final Object right) { final boolean l = left instanceof Group; final boolean r = right instanceof Group; if (l ^ r) { if (l) { return -1; } return 1; } return 0; } } /** * Forces Switch instances to appear at the beginning of lists * * @see Switch * @return a new comparator */ public static Comparator switchFirst() { return new SwitchFirst(); } /** * Forces Switch instances to appear at the end of lists * * @see Switch * @return a new comparator */ public static Comparator switchLast() { return reverse(switchFirst()); } private static class SwitchFirst implements Comparator { public int compare(final Object left, final Object right) { final boolean l = left instanceof Switch; final boolean r = right instanceof Switch; if (l ^ r) { if (l) { return -1; } return 1; } return 0; } } /** * Forces Command instances to appear at the beginning of lists * * @see Command * @return a new comparator */ public static Comparator commandFirst() { return new CommandFirst(); } /** * Forces Command instances to appear at the end of lists * * @see Command * @return a new comparator */ public static Comparator commandLast() { return reverse(commandFirst()); } private static class CommandFirst implements Comparator { public int compare(final Object left, final Object right) { final boolean l = left instanceof Command; final boolean r = right instanceof Command; if (l ^ r) { if (l) { return -1; } return 1; } return 0; } } /** * Forces DefaultOption instances to appear at the beginning of lists * * @see DefaultOption * @return a new comparator */ public static Comparator defaultOptionFirst() { return new DefaultOptionFirst(); } /** * Forces DefaultOption instances to appear at the end of lists * * @see DefaultOption * @return a new comparator */ public static Comparator defaultOptionLast() { return reverse(defaultOptionFirst()); } private static class DefaultOptionFirst implements Comparator { public int compare(final Object left, final Object right) { final boolean l = left instanceof DefaultOption; final boolean r = right instanceof DefaultOption; if (l ^ r) { if (l) { return -1; } return 1; } return 0; } } /** * Forces Comparators with a particular trigger to appear at the beginning * of lists * * @param name * the trigger name to select * @see Option#getTriggers() * @return a new comparator */ public static Comparator namedFirst(final String name) { return new Named(name); } /** * Forces Comparators with a particular trigger to appear at the end of * lists * * @param name * the trigger name to select * @see Option#getTriggers() * @return a new comparator */ public static Comparator namedLast(final String name) { return reverse(new Named(name)); } private static class Named implements Comparator { private final String name; /** * Creates a Comparator that sorts a particular name high in order * @param name the trigger name to select */ public Named(final String name) { this.name = name; } public int compare(final Object oleft, final Object oright) { final Option left = (Option)oleft; final Option right = (Option)oright; final boolean l = left.getTriggers().contains(name); final boolean r = right.getTriggers().contains(name); if (l ^ r) { if (l) { return -1; } return 1; } return 0; } } /** * Orders Options by preferredName * * @see Option#getPreferredName() * @return a new comparator */ public static Comparator preferredNameFirst() { return new PreferredName(); } /** * Orders Options by preferredName, reversed * * @see Option#getPreferredName() * @return a new comparator */ public static Comparator preferredNameLast() { return reverse(preferredNameFirst()); } private static class PreferredName implements Comparator { public int compare(final Object oleft, final Object oright) { final Option left = (Option)oleft; final Option right = (Option)oright; return left.getPreferredName().compareTo(right.getPreferredName()); } } /** * Orders Options grouping required Options first * * @see Option#isRequired() * @return a new comparator */ public static Comparator requiredFirst() { return new Required(); } /** * Orders Options grouping required Options last * * @see Option#isRequired() * @return a new comparator */ public static Comparator requiredLast() { return reverse(requiredFirst()); } private static class Required implements Comparator { public int compare(final Object oleft, final Object oright) { final Option left = (Option)oleft; final Option right = (Option)oright; final boolean l = left.isRequired(); final boolean r = right.isRequired(); if (l ^ r) { if (l) { return -1; } return 1; } return 0; } }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.util; + +import java.util.Comparator; +import java.util.List; + +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.option.Command; +import org.apache.commons.cli2.option.DefaultOption; +import org.apache.commons.cli2.option.Switch; + +/** + * A collection of Comparators suitable for use with Option instances. + */ +public class Comparators { + + private Comparators(){ + // constructor hiden from potential users + } + + + /** + * Chains comparators together. + * + * @see #chain(Comparator[]) + * @param c0 + * a comparator + * @param c1 + * a comparator + * @return a chained comparator + */ + public static Comparator chain(final Comparator c0, final Comparator c1) { + return chain(new Comparator[] { c0, c1 }); + } + + /** + * Chains comparators together. + * + * @see #chain(Comparator[]) + * @param c0 + * a comparator + * @param c1 + * a comparator + * @param c2 + * a comparator + * @return a chained comparator + */ + public static Comparator chain( + final Comparator c0, + final Comparator c1, + final Comparator c2) { + return chain(new Comparator[] { c0, c1, c2 }); + } + + /** + * Chains comparators together. + * + * @see #chain(Comparator[]) + * @param c0 + * a comparator + * @param c1 + * a comparator + * @param c2 + * a comparator + * @param c3 + * a comparator + * @return a chained comparator + */ + public static Comparator chain( + final Comparator c0, + final Comparator c1, + final Comparator c2, + final Comparator c3) { + return chain(new Comparator[] { c0, c1, c2, c3 }); + } + + /** + * Chains comparators together. + * + * @see #chain(Comparator[]) + * @param c0 + * a comparator + * @param c1 + * a comparator + * @param c2 + * a comparator + * @param c3 + * a comparator + * @param c4 + * a comparator + * @return a chained comparator + */ + public static Comparator chain( + final Comparator c0, + final Comparator c1, + final Comparator c2, + final Comparator c3, + final Comparator c4) { + return chain(new Comparator[] { c0, c1, c2, c3, c4 }); + } + + /** + * Chains comparators together. + * + * @see #chain(Comparator[]) + * @param comparators + * a List of comparators to chain together + * @return a chained comparator + */ + public static Comparator chain(final List comparators) { + return new Chain( + (Comparator[])comparators.toArray( + new Comparator[comparators.size()])); + } + + /** + * Chains an array of comparators together. Each Comparator will be called + * in turn until one of them return a non-zero value, this value will be + * returned. + * + * @param comparators + * the array of comparators + * @return a chained comparator + */ + public static Comparator chain(final Comparator[] comparators) { + return new Chain(comparators); + } + + /** + * Chains a series of Comparators together. + */ + private static class Chain implements Comparator { + + final Comparator[] chain; + + /** + * Creates a Comparator chain using the specified array of Comparators + * @param chain the Comparators in the chain + */ + public Chain(final Comparator[] chain) { + this.chain = new Comparator[chain.length]; + System.arraycopy(chain, 0, this.chain, 0, chain.length); + } + + public int compare(final Object left, final Object right) { + int result = 0; + for (int i = 0; result == 0 && i < chain.length; ++i) { + result = chain[i].compare(left, right); + } + return result; + } + } + + /** + * Reverses a comparator's logic. + * + * @param wrapped + * the Comparator to reverse the logic of + * @return a comparator with reverse logic + */ + private static Comparator reverse(final Comparator wrapped) { + return new Reverse(wrapped); + } + + private static class Reverse implements Comparator { + private final Comparator wrapped; + + /** + * Creates a Comparator with reverse logic + * @param wrapped the original logic + */ + public Reverse(final Comparator wrapped) { + this.wrapped = wrapped; + } + + public int compare(final Object left, final Object right) { + return -wrapped.compare(left, right); + } + } + + /** + * Forces Group instances to appear at the beginning of lists + * + * @see Group + * @return a new comparator + */ + public static Comparator groupFirst() { + return new GroupFirst(); + } + + /** + * Forces Group instances to appear at the end of lists + * + * @see Group + * @return a new comparator + */ + public static Comparator groupLast() { + return reverse(groupFirst()); + } + + private static class GroupFirst implements Comparator { + public int compare(final Object left, final Object right) { + final boolean l = left instanceof Group; + final boolean r = right instanceof Group; + + if (l ^ r) { + if (l) { + return -1; + } + return 1; + } + return 0; + } + } + + /** + * Forces Switch instances to appear at the beginning of lists + * + * @see Switch + * @return a new comparator + */ + public static Comparator switchFirst() { + return new SwitchFirst(); + } + + /** + * Forces Switch instances to appear at the end of lists + * + * @see Switch + * @return a new comparator + */ + public static Comparator switchLast() { + return reverse(switchFirst()); + } + + private static class SwitchFirst implements Comparator { + public int compare(final Object left, final Object right) { + final boolean l = left instanceof Switch; + final boolean r = right instanceof Switch; + + if (l ^ r) { + if (l) { + return -1; + } + return 1; + } + return 0; + } + } + + /** + * Forces Command instances to appear at the beginning of lists + * + * @see Command + * @return a new comparator + */ + public static Comparator commandFirst() { + return new CommandFirst(); + } + + /** + * Forces Command instances to appear at the end of lists + * + * @see Command + * @return a new comparator + */ + public static Comparator commandLast() { + return reverse(commandFirst()); + } + + private static class CommandFirst implements Comparator { + public int compare(final Object left, final Object right) { + final boolean l = left instanceof Command; + final boolean r = right instanceof Command; + + if (l ^ r) { + if (l) { + return -1; + } + return 1; + } + return 0; + } + } + + /** + * Forces DefaultOption instances to appear at the beginning of lists + * + * @see DefaultOption + * @return a new comparator + */ + public static Comparator defaultOptionFirst() { + return new DefaultOptionFirst(); + } + + /** + * Forces DefaultOption instances to appear at the end of lists + * + * @see DefaultOption + * @return a new comparator + */ + public static Comparator defaultOptionLast() { + return reverse(defaultOptionFirst()); + } + + private static class DefaultOptionFirst implements Comparator { + public int compare(final Object left, final Object right) { + final boolean l = left instanceof DefaultOption; + final boolean r = right instanceof DefaultOption; + + if (l ^ r) { + if (l) { + return -1; + } + return 1; + } + return 0; + } + } + + /** + * Forces Comparators with a particular trigger to appear at the beginning + * of lists + * + * @param name + * the trigger name to select + * @see Option#getTriggers() + * @return a new comparator + */ + public static Comparator namedFirst(final String name) { + return new Named(name); + } + + /** + * Forces Comparators with a particular trigger to appear at the end of + * lists + * + * @param name + * the trigger name to select + * @see Option#getTriggers() + * @return a new comparator + */ + public static Comparator namedLast(final String name) { + return reverse(new Named(name)); + } + + private static class Named implements Comparator { + private final String name; + + /** + * Creates a Comparator that sorts a particular name high in order + * @param name the trigger name to select + */ + public Named(final String name) { + this.name = name; + } + public int compare(final Object oleft, final Object oright) { + final Option left = (Option)oleft; + final Option right = (Option)oright; + + final boolean l = left.getTriggers().contains(name); + final boolean r = right.getTriggers().contains(name); + + if (l ^ r) { + if (l) { + return -1; + } + return 1; + } + return 0; + } + } + + /** + * Orders Options by preferredName + * + * @see Option#getPreferredName() + * @return a new comparator + */ + public static Comparator preferredNameFirst() { + return new PreferredName(); + } + + /** + * Orders Options by preferredName, reversed + * + * @see Option#getPreferredName() + * @return a new comparator + */ + public static Comparator preferredNameLast() { + return reverse(preferredNameFirst()); + } + + private static class PreferredName implements Comparator { + public int compare(final Object oleft, final Object oright) { + final Option left = (Option)oleft; + final Option right = (Option)oright; + + return left.getPreferredName().compareTo(right.getPreferredName()); + } + } + + /** + * Orders Options grouping required Options first + * + * @see Option#isRequired() + * @return a new comparator + */ + public static Comparator requiredFirst() { + return new Required(); + } + + /** + * Orders Options grouping required Options last + * + * @see Option#isRequired() + * @return a new comparator + */ + public static Comparator requiredLast() { + return reverse(requiredFirst()); + } + + private static class Required implements Comparator { + public int compare(final Object oleft, final Object oright) { + final Option left = (Option)oleft; + final Option right = (Option)oright; + + final boolean l = left.isRequired(); + final boolean r = right.isRequired(); + + if (l ^ r) { + if (l) { + return -1; + } + return 1; + } + return 0; + } + } +} diff --git a/src/java/org/apache/commons/cli2/util/HelpFormatter.java b/src/java/org/apache/commons/cli2/util/HelpFormatter.java index 12197653a..8f6684f0a 100644 --- a/src/java/org/apache/commons/cli2/util/HelpFormatter.java +++ b/src/java/org/apache/commons/cli2/util/HelpFormatter.java @@ -1 +1,638 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.util;import java.io.PrintWriter;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Presents on screen help based on the application's Options */public class HelpFormatter { /** * The default screen width */ public static final int DEFAULT_FULL_WIDTH = 80; /** * The default screen furniture left of screen */ public static final String DEFAULT_GUTTER_LEFT = ""; /** * The default screen furniture right of screen */ public static final String DEFAULT_GUTTER_CENTER = " "; /** * The default screen furniture between columns */ public static final String DEFAULT_GUTTER_RIGHT = ""; /** * The default DisplaySettings used to select the elements to display in the * displayed line of full usage information. * * @see DisplaySetting */ public static final Set DEFAULT_FULL_USAGE_SETTINGS; /** * The default DisplaySettings used to select the elements of usage per help * line in the main body of help * * @see DisplaySetting */ public static final Set DEFAULT_LINE_USAGE_SETTINGS; /** * The default DisplaySettings used to select the help lines in the main * body of help */ public static final Set DEFAULT_DISPLAY_USAGE_SETTINGS; static { final Set fullUsage = new HashSet(DisplaySetting.ALL); fullUsage.remove(DisplaySetting.DISPLAY_ALIASES); fullUsage.remove(DisplaySetting.DISPLAY_GROUP_NAME); DEFAULT_FULL_USAGE_SETTINGS = Collections.unmodifiableSet(fullUsage); final Set lineUsage = new HashSet(); lineUsage.add(DisplaySetting.DISPLAY_ALIASES); lineUsage.add(DisplaySetting.DISPLAY_GROUP_NAME); lineUsage.add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); DEFAULT_LINE_USAGE_SETTINGS = Collections.unmodifiableSet(lineUsage); final Set displayUsage = new HashSet(DisplaySetting.ALL); displayUsage.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); DEFAULT_DISPLAY_USAGE_SETTINGS = Collections.unmodifiableSet(displayUsage); } private Set fullUsageSettings = new HashSet(DEFAULT_FULL_USAGE_SETTINGS); private Set lineUsageSettings = new HashSet(DEFAULT_LINE_USAGE_SETTINGS); private Set displaySettings = new HashSet(DEFAULT_DISPLAY_USAGE_SETTINGS); private OptionException exception = null; private Group group; private Comparator comparator = null; private String divider = null; private String header = null; private String footer = null; private String shellCommand = ""; private PrintWriter out = new PrintWriter(System.out); //or should this default to .err? private final String gutterLeft; private final String gutterCenter; private final String gutterRight; private final int pageWidth; /** * Creates a new HelpFormatter using the defaults */ public HelpFormatter() { this(DEFAULT_GUTTER_LEFT, DEFAULT_GUTTER_CENTER, DEFAULT_GUTTER_RIGHT, DEFAULT_FULL_WIDTH); } /** * Creates a new HelpFormatter using the specified parameters * @param gutterLeft the string marking left of screen * @param gutterCenter the string marking center of screen * @param gutterRight the string marking right of screen * @param fullWidth the width of the screen */ public HelpFormatter(final String gutterLeft, final String gutterCenter, final String gutterRight, final int fullWidth) { // default the left gutter to empty string this.gutterLeft = (gutterLeft == null) ? DEFAULT_GUTTER_LEFT : gutterLeft; // default the center gutter to a single space this.gutterCenter = (gutterCenter == null) ? DEFAULT_GUTTER_CENTER : gutterCenter; // default the right gutter to empty string this.gutterRight = (gutterRight == null) ? DEFAULT_GUTTER_RIGHT : gutterRight; // calculate the available page width this.pageWidth = fullWidth - this.gutterLeft.length() - this.gutterRight.length(); // check available page width is valid int availableWidth = fullWidth - pageWidth + this.gutterCenter.length(); if (availableWidth < 2) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.HELPFORMATTER_GUTTER_TOO_LONG)); } } /** * Prints the Option help. */ public void print() { printHeader(); printException(); printUsage(); printHelp(); printFooter(); out.flush(); } /** * Prints any error message. */ public void printException() { if (exception != null) { printDivider(); printWrapped(exception.getMessage()); } } /** * Prints detailed help per option. */ public void printHelp() { printDivider(); final Option option; if ((exception != null) && (exception.getOption() != null)) { option = exception.getOption(); } else { option = group; } // grab the HelpLines to display final List helpLines = option.helpLines(0, displaySettings, comparator); // calculate the maximum width of the usage strings int usageWidth = 0; for (final Iterator i = helpLines.iterator(); i.hasNext();) { final HelpLine helpLine = (HelpLine) i.next(); final String usage = helpLine.usage(lineUsageSettings, comparator); usageWidth = Math.max(usageWidth, usage.length()); } // build a blank string to pad wrapped descriptions final StringBuffer blankBuffer = new StringBuffer(); for (int i = 0; i < usageWidth; i++) { blankBuffer.append(' '); } // determine the width available for descriptions final int descriptionWidth = Math.max(1, pageWidth - gutterCenter.length() - usageWidth); // display each HelpLine for (final Iterator i = helpLines.iterator(); i.hasNext();) { // grab the HelpLine final HelpLine helpLine = (HelpLine) i.next(); // wrap the description final List descList = wrap(helpLine.getDescription(), descriptionWidth); final Iterator descriptionIterator = descList.iterator(); // display usage + first line of description printGutterLeft(); pad(helpLine.usage(lineUsageSettings, comparator), usageWidth, out); out.print(gutterCenter); pad((String) descriptionIterator.next(), descriptionWidth, out); printGutterRight(); out.println(); // display padding + remaining lines of description while (descriptionIterator.hasNext()) { printGutterLeft(); //pad(helpLine.getUsage(),usageWidth,out); out.print(blankBuffer); out.print(gutterCenter); pad((String) descriptionIterator.next(), descriptionWidth, out); printGutterRight(); out.println(); } } printDivider(); } /** * Prints a single line of usage information (wrapping if necessary) */ public void printUsage() { printDivider(); final StringBuffer buffer = new StringBuffer("Usage:\n"); buffer.append(shellCommand).append(' '); group.appendUsage(buffer, fullUsageSettings, comparator, " "); printWrapped(buffer.toString()); } /** * Prints a header string if necessary */ public void printHeader() { if (header != null) { printDivider(); printWrapped(header); } } /** * Prints a footer string if necessary */ public void printFooter() { if (footer != null) { printWrapped(footer); printDivider(); } } /** * Prints a string wrapped if necessary * @param text the string to wrap */ public void printWrapped(final String text) { for (final Iterator i = wrap(text, pageWidth).iterator(); i.hasNext();) { printGutterLeft(); pad((String) i.next(), pageWidth, out); printGutterRight(); out.println(); } out.flush(); } /** * Prints the left gutter string */ public void printGutterLeft() { if (gutterLeft != null) { out.print(gutterLeft); } } /** * Prints the right gutter string */ public void printGutterRight() { if (gutterRight != null) { out.print(gutterRight); } } /** * Prints the divider text */ public void printDivider() { if (divider != null) { out.println(divider); } } protected static void pad(final String text, final int width, final PrintWriter writer) { final int left; // write the text and record how many characters written if (text == null) { left = 0; } else { writer.write(text); left = text.length(); } // pad remainder with spaces for (int i = left; i < width; ++i) { writer.write(' '); } } protected static List wrap(final String text, final int width) { // check for valid width if (width < 1) { throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.HELPFORMATTER_WIDTH_TOO_NARROW, new Object[] { new Integer(width) })); } // handle degenerate case if (text == null) { return Collections.singletonList(""); } final List lines = new ArrayList(); final char[] chars = text.toCharArray(); int left = 0; // for each character in the string while (left < chars.length) { // sync left and right indeces int right = left; // move right until we run out of characters, width or find a newline while ((right < chars.length) && (chars[right] != '\n') && (right < (left + width + 1))) { right++; } // if a newline was found if ((right < chars.length) && (chars[right] == '\n')) { // record the substring final String line = new String(chars, left, right - left); lines.add(line); // move to the end of the substring left = right + 1; if (left == chars.length) { lines.add(""); } // restart the loop continue; } // move to the next ideal wrap point right = (left + width) - 1; // if we have run out of characters if (chars.length <= right) { // record the substring final String line = new String(chars, left, chars.length - left); lines.add(line); // abort the loop break; } // back track the substring end until a space is found while ((right >= left) && (chars[right] != ' ')) { right--; } // if a space was found if (right >= left) { // record the substring to space final String line = new String(chars, left, right - left); lines.add(line); // absorb all the spaces before next substring while ((right < chars.length) && (chars[right] == ' ')) { right++; } left = right; // restart the loop continue; } // move to the wrap position irrespective of spaces right = Math.min(left + width, chars.length); // record the substring final String line = new String(chars, left, right - left); lines.add(line); // absorb any the spaces before next substring while ((right < chars.length) && (chars[right] == ' ')) { right++; } left = right; } return lines; } /** * The Comparator to use when sorting Options * @param comparator Comparator to use when sorting Options */ public void setComparator(Comparator comparator) { this.comparator = comparator; } /** * The DisplaySettings used to select the help lines in the main body of * help * * @param displaySettings the settings to use * @see DisplaySetting */ public void setDisplaySettings(Set displaySettings) { this.displaySettings = displaySettings; } /** * Sets the string to use as a divider between sections of help * @param divider the dividing string */ public void setDivider(String divider) { this.divider = divider; } /** * Sets the exception to document * @param exception the exception that occured */ public void setException(OptionException exception) { this.exception = exception; } /** * Sets the footer text of the help screen * @param footer the footer text */ public void setFooter(String footer) { this.footer = footer; } /** * The DisplaySettings used to select the elements to display in the * displayed line of full usage information. * @see DisplaySetting * @param fullUsageSettings */ public void setFullUsageSettings(Set fullUsageSettings) { this.fullUsageSettings = fullUsageSettings; } /** * Sets the Group of Options to document * @param group the options to document */ public void setGroup(Group group) { this.group = group; } /** * Sets the footer text of the help screen * @param header the footer text */ public void setHeader(String header) { this.header = header; } /** * Sets the DisplaySettings used to select elements in the per helpline * usage strings. * @see DisplaySetting * @param lineUsageSettings the DisplaySettings to use */ public void setLineUsageSettings(Set lineUsageSettings) { this.lineUsageSettings = lineUsageSettings; } /** * Sets the command string used to invoke the application * @param shellCommand the invokation command */ public void setShellCommand(String shellCommand) { this.shellCommand = shellCommand; } /** * @return the Comparator used to sort the Group */ public Comparator getComparator() { return comparator; } /** * @return the DisplaySettings used to select HelpLines */ public Set getDisplaySettings() { return displaySettings; } /** * @return the String used as a horizontal section divider */ public String getDivider() { return divider; } /** * @return the Exception being documented by this HelpFormatter */ public OptionException getException() { return exception; } /** * @return the help screen footer text */ public String getFooter() { return footer; } /** * @return the DisplaySettings used in the full usage string */ public Set getFullUsageSettings() { return fullUsageSettings; } /** * @return the group documented by this HelpFormatter */ public Group getGroup() { return group; } /** * @return the String used as the central gutter */ public String getGutterCenter() { return gutterCenter; } /** * @return the String used as the left gutter */ public String getGutterLeft() { return gutterLeft; } /** * @return the String used as the right gutter */ public String getGutterRight() { return gutterRight; } /** * @return the help screen header text */ public String getHeader() { return header; } /** * @return the DisplaySettings used in the per help line usage strings */ public Set getLineUsageSettings() { return lineUsageSettings; } /** * @return the width of the screen in characters */ public int getPageWidth() { return pageWidth; } /** * @return the command used to execute the application */ public String getShellCommand() { return shellCommand; } /** * @param out the PrintWriter to write to */ public void setPrintWriter(PrintWriter out) { this.out = out; } /** * @return the PrintWriter that will be written to */ public PrintWriter getPrintWriter() { return out; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.util; + +import java.io.PrintWriter; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.HelpLine; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * Presents on screen help based on the application's Options + */ +public class HelpFormatter { + /** + * The default screen width + */ + public static final int DEFAULT_FULL_WIDTH = 80; + + /** + * The default screen furniture left of screen + */ + public static final String DEFAULT_GUTTER_LEFT = ""; + + /** + * The default screen furniture right of screen + */ + public static final String DEFAULT_GUTTER_CENTER = " "; + + /** + * The default screen furniture between columns + */ + public static final String DEFAULT_GUTTER_RIGHT = ""; + + /** + * The default DisplaySettings used to select the elements to display in the + * displayed line of full usage information. + * + * @see DisplaySetting + */ + public static final Set DEFAULT_FULL_USAGE_SETTINGS; + + /** + * The default DisplaySettings used to select the elements of usage per help + * line in the main body of help + * + * @see DisplaySetting + */ + public static final Set DEFAULT_LINE_USAGE_SETTINGS; + + /** + * The default DisplaySettings used to select the help lines in the main + * body of help + */ + public static final Set DEFAULT_DISPLAY_USAGE_SETTINGS; + + static { + final Set fullUsage = new HashSet(DisplaySetting.ALL); + fullUsage.remove(DisplaySetting.DISPLAY_ALIASES); + fullUsage.remove(DisplaySetting.DISPLAY_GROUP_NAME); + DEFAULT_FULL_USAGE_SETTINGS = Collections.unmodifiableSet(fullUsage); + + final Set lineUsage = new HashSet(); + lineUsage.add(DisplaySetting.DISPLAY_ALIASES); + lineUsage.add(DisplaySetting.DISPLAY_GROUP_NAME); + lineUsage.add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); + DEFAULT_LINE_USAGE_SETTINGS = Collections.unmodifiableSet(lineUsage); + + final Set displayUsage = new HashSet(DisplaySetting.ALL); + displayUsage.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); + DEFAULT_DISPLAY_USAGE_SETTINGS = Collections.unmodifiableSet(displayUsage); + } + + private Set fullUsageSettings = new HashSet(DEFAULT_FULL_USAGE_SETTINGS); + private Set lineUsageSettings = new HashSet(DEFAULT_LINE_USAGE_SETTINGS); + private Set displaySettings = new HashSet(DEFAULT_DISPLAY_USAGE_SETTINGS); + private OptionException exception = null; + private Group group; + private Comparator comparator = null; + private String divider = null; + private String header = null; + private String footer = null; + private String shellCommand = ""; + private PrintWriter out = new PrintWriter(System.out); + + //or should this default to .err? + private final String gutterLeft; + private final String gutterCenter; + private final String gutterRight; + private final int pageWidth; + + /** + * Creates a new HelpFormatter using the defaults + */ + public HelpFormatter() { + this(DEFAULT_GUTTER_LEFT, DEFAULT_GUTTER_CENTER, DEFAULT_GUTTER_RIGHT, DEFAULT_FULL_WIDTH); + } + + /** + * Creates a new HelpFormatter using the specified parameters + * @param gutterLeft the string marking left of screen + * @param gutterCenter the string marking center of screen + * @param gutterRight the string marking right of screen + * @param fullWidth the width of the screen + */ + public HelpFormatter(final String gutterLeft, + final String gutterCenter, + final String gutterRight, + final int fullWidth) { + // default the left gutter to empty string + this.gutterLeft = (gutterLeft == null) ? DEFAULT_GUTTER_LEFT : gutterLeft; + + // default the center gutter to a single space + this.gutterCenter = (gutterCenter == null) ? DEFAULT_GUTTER_CENTER : gutterCenter; + + // default the right gutter to empty string + this.gutterRight = (gutterRight == null) ? DEFAULT_GUTTER_RIGHT : gutterRight; + + // calculate the available page width + this.pageWidth = fullWidth - this.gutterLeft.length() - this.gutterRight.length(); + + // check available page width is valid + int availableWidth = fullWidth - pageWidth + this.gutterCenter.length(); + + if (availableWidth < 2) { + throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.HELPFORMATTER_GUTTER_TOO_LONG)); + } + } + + /** + * Prints the Option help. + */ + public void print() { + printHeader(); + printException(); + printUsage(); + printHelp(); + printFooter(); + out.flush(); + } + + /** + * Prints any error message. + */ + public void printException() { + if (exception != null) { + printDivider(); + printWrapped(exception.getMessage()); + } + } + + /** + * Prints detailed help per option. + */ + public void printHelp() { + printDivider(); + + final Option option; + + if ((exception != null) && (exception.getOption() != null)) { + option = exception.getOption(); + } else { + option = group; + } + + // grab the HelpLines to display + final List helpLines = option.helpLines(0, displaySettings, comparator); + + // calculate the maximum width of the usage strings + int usageWidth = 0; + + for (final Iterator i = helpLines.iterator(); i.hasNext();) { + final HelpLine helpLine = (HelpLine) i.next(); + final String usage = helpLine.usage(lineUsageSettings, comparator); + usageWidth = Math.max(usageWidth, usage.length()); + } + + // build a blank string to pad wrapped descriptions + final StringBuffer blankBuffer = new StringBuffer(); + + for (int i = 0; i < usageWidth; i++) { + blankBuffer.append(' '); + } + + // determine the width available for descriptions + final int descriptionWidth = Math.max(1, pageWidth - gutterCenter.length() - usageWidth); + + // display each HelpLine + for (final Iterator i = helpLines.iterator(); i.hasNext();) { + // grab the HelpLine + final HelpLine helpLine = (HelpLine) i.next(); + + // wrap the description + final List descList = wrap(helpLine.getDescription(), descriptionWidth); + final Iterator descriptionIterator = descList.iterator(); + + // display usage + first line of description + printGutterLeft(); + pad(helpLine.usage(lineUsageSettings, comparator), usageWidth, out); + out.print(gutterCenter); + pad((String) descriptionIterator.next(), descriptionWidth, out); + printGutterRight(); + out.println(); + + // display padding + remaining lines of description + while (descriptionIterator.hasNext()) { + printGutterLeft(); + + //pad(helpLine.getUsage(),usageWidth,out); + out.print(blankBuffer); + out.print(gutterCenter); + pad((String) descriptionIterator.next(), descriptionWidth, out); + printGutterRight(); + out.println(); + } + } + + printDivider(); + } + + /** + * Prints a single line of usage information (wrapping if necessary) + */ + public void printUsage() { + printDivider(); + + final StringBuffer buffer = new StringBuffer("Usage:\n"); + buffer.append(shellCommand).append(' '); + group.appendUsage(buffer, fullUsageSettings, comparator, " "); + printWrapped(buffer.toString()); + } + + /** + * Prints a header string if necessary + */ + public void printHeader() { + if (header != null) { + printDivider(); + printWrapped(header); + } + } + + /** + * Prints a footer string if necessary + */ + public void printFooter() { + if (footer != null) { + printWrapped(footer); + printDivider(); + } + } + + /** + * Prints a string wrapped if necessary + * @param text the string to wrap + */ + public void printWrapped(final String text) { + for (final Iterator i = wrap(text, pageWidth).iterator(); i.hasNext();) { + printGutterLeft(); + pad((String) i.next(), pageWidth, out); + printGutterRight(); + out.println(); + } + + out.flush(); + } + + /** + * Prints the left gutter string + */ + public void printGutterLeft() { + if (gutterLeft != null) { + out.print(gutterLeft); + } + } + + /** + * Prints the right gutter string + */ + public void printGutterRight() { + if (gutterRight != null) { + out.print(gutterRight); + } + } + + /** + * Prints the divider text + */ + public void printDivider() { + if (divider != null) { + out.println(divider); + } + } + + protected static void pad(final String text, + final int width, + final PrintWriter writer) { + final int left; + + // write the text and record how many characters written + if (text == null) { + left = 0; + } else { + writer.write(text); + left = text.length(); + } + + // pad remainder with spaces + for (int i = left; i < width; ++i) { + writer.write(' '); + } + } + + protected static List wrap(final String text, + final int width) { + // check for valid width + if (width < 1) { + throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.HELPFORMATTER_WIDTH_TOO_NARROW, + new Object[] { + new Integer(width) + })); + } + + // handle degenerate case + if (text == null) { + return Collections.singletonList(""); + } + + final List lines = new ArrayList(); + final char[] chars = text.toCharArray(); + int left = 0; + + // for each character in the string + while (left < chars.length) { + // sync left and right indeces + int right = left; + + // move right until we run out of characters, width or find a newline + while ((right < chars.length) && (chars[right] != '\n') && + (right < (left + width + 1))) { + right++; + } + + // if a newline was found + if ((right < chars.length) && (chars[right] == '\n')) { + // record the substring + final String line = new String(chars, left, right - left); + lines.add(line); + + // move to the end of the substring + left = right + 1; + + if (left == chars.length) { + lines.add(""); + } + + // restart the loop + continue; + } + + // move to the next ideal wrap point + right = (left + width) - 1; + + // if we have run out of characters + if (chars.length <= right) { + // record the substring + final String line = new String(chars, left, chars.length - left); + lines.add(line); + + // abort the loop + break; + } + + // back track the substring end until a space is found + while ((right >= left) && (chars[right] != ' ')) { + right--; + } + + // if a space was found + if (right >= left) { + // record the substring to space + final String line = new String(chars, left, right - left); + lines.add(line); + + // absorb all the spaces before next substring + while ((right < chars.length) && (chars[right] == ' ')) { + right++; + } + + left = right; + + // restart the loop + continue; + } + + // move to the wrap position irrespective of spaces + right = Math.min(left + width, chars.length); + + // record the substring + final String line = new String(chars, left, right - left); + lines.add(line); + + // absorb any the spaces before next substring + while ((right < chars.length) && (chars[right] == ' ')) { + right++; + } + + left = right; + } + + return lines; + } + + /** + * The Comparator to use when sorting Options + * @param comparator Comparator to use when sorting Options + */ + public void setComparator(Comparator comparator) { + this.comparator = comparator; + } + + /** + * The DisplaySettings used to select the help lines in the main body of + * help + * + * @param displaySettings the settings to use + * @see DisplaySetting + */ + public void setDisplaySettings(Set displaySettings) { + this.displaySettings = displaySettings; + } + + /** + * Sets the string to use as a divider between sections of help + * @param divider the dividing string + */ + public void setDivider(String divider) { + this.divider = divider; + } + + /** + * Sets the exception to document + * @param exception the exception that occured + */ + public void setException(OptionException exception) { + this.exception = exception; + } + + /** + * Sets the footer text of the help screen + * @param footer the footer text + */ + public void setFooter(String footer) { + this.footer = footer; + } + + /** + * The DisplaySettings used to select the elements to display in the + * displayed line of full usage information. + * @see DisplaySetting + * @param fullUsageSettings + */ + public void setFullUsageSettings(Set fullUsageSettings) { + this.fullUsageSettings = fullUsageSettings; + } + + /** + * Sets the Group of Options to document + * @param group the options to document + */ + public void setGroup(Group group) { + this.group = group; + } + + /** + * Sets the footer text of the help screen + * @param header the footer text + */ + public void setHeader(String header) { + this.header = header; + } + + /** + * Sets the DisplaySettings used to select elements in the per helpline + * usage strings. + * @see DisplaySetting + * @param lineUsageSettings the DisplaySettings to use + */ + public void setLineUsageSettings(Set lineUsageSettings) { + this.lineUsageSettings = lineUsageSettings; + } + + /** + * Sets the command string used to invoke the application + * @param shellCommand the invokation command + */ + public void setShellCommand(String shellCommand) { + this.shellCommand = shellCommand; + } + + /** + * @return the Comparator used to sort the Group + */ + public Comparator getComparator() { + return comparator; + } + + /** + * @return the DisplaySettings used to select HelpLines + */ + public Set getDisplaySettings() { + return displaySettings; + } + + /** + * @return the String used as a horizontal section divider + */ + public String getDivider() { + return divider; + } + + /** + * @return the Exception being documented by this HelpFormatter + */ + public OptionException getException() { + return exception; + } + + /** + * @return the help screen footer text + */ + public String getFooter() { + return footer; + } + + /** + * @return the DisplaySettings used in the full usage string + */ + public Set getFullUsageSettings() { + return fullUsageSettings; + } + + /** + * @return the group documented by this HelpFormatter + */ + public Group getGroup() { + return group; + } + + /** + * @return the String used as the central gutter + */ + public String getGutterCenter() { + return gutterCenter; + } + + /** + * @return the String used as the left gutter + */ + public String getGutterLeft() { + return gutterLeft; + } + + /** + * @return the String used as the right gutter + */ + public String getGutterRight() { + return gutterRight; + } + + /** + * @return the help screen header text + */ + public String getHeader() { + return header; + } + + /** + * @return the DisplaySettings used in the per help line usage strings + */ + public Set getLineUsageSettings() { + return lineUsageSettings; + } + + /** + * @return the width of the screen in characters + */ + public int getPageWidth() { + return pageWidth; + } + + /** + * @return the command used to execute the application + */ + public String getShellCommand() { + return shellCommand; + } + + /** + * @param out the PrintWriter to write to + */ + public void setPrintWriter(PrintWriter out) { + this.out = out; + } + + /** + * @return the PrintWriter that will be written to + */ + public PrintWriter getPrintWriter() { + return out; + } +} diff --git a/src/java/org/apache/commons/cli2/validation/ClassValidator.java b/src/java/org/apache/commons/cli2/validation/ClassValidator.java index 930afa50a..a4770f2b6 100644 --- a/src/java/org/apache/commons/cli2/validation/ClassValidator.java +++ b/src/java/org/apache/commons/cli2/validation/ClassValidator.java @@ -1 +1,201 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.util.List;import java.util.ListIterator;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * The ClassValidator validates the string argument * values are class names. * * The following example shows how to validate the 'logger' * argument value is a class name, that can be instantiated. * *
       * ... * ClassValidator validator = new ClassValidator(); * validator.setInstance(true); * * ArgumentBuilder builder = new ArgumentBuilder(); * Argument logger = *     builder.withName("logger"); *            .withValidator(validator); * 
      * * @author John Keyes */public class ClassValidator implements Validator { /** i18n */ private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); /** whether the class argument is loadable */ private boolean loadable; /** whether to create an instance of the class */ private boolean instance; /** the classloader to load classes from */ private ClassLoader loader; /** * Validate each argument value in the specified List against this instances * permitted attributes. * * If a value is valid then it's String value in the list is * replaced with it's Class value or instance. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { for (final ListIterator i = values.listIterator(); i.hasNext();) { final String name = (String) i.next(); if (!isPotentialClassName(name)) { throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_BAD_CLASSNAME, name)); } if (loadable || instance) { final ClassLoader theLoader = getClassLoader(); try { final Class clazz = theLoader.loadClass(name); if (instance) { i.set(clazz.newInstance()); } else { i.set(clazz); } } catch (final ClassNotFoundException exp) { throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_NOTFOUND, name)); } catch (final IllegalAccessException exp) { throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_ACCESS, name, exp.getMessage())); } catch (final InstantiationException exp) { throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_CREATE, name)); } } } } /** * Returns whether the argument value must represent a * class that is loadable. * * @return whether the argument value must represent a * class that is loadable. */ public boolean isLoadable() { return loadable; } /** * Specifies whether the argument value must represent a * class that is loadable. * * @param loadable whether the argument value must * represent a class that is loadable. */ public void setLoadable(boolean loadable) { this.loadable = loadable; } /** * Returns the {@link ClassLoader} used to resolve and load * the classes specified by the argument values. * * @return the {@link ClassLoader} used to resolve and load * the classes specified by the argument values. */ public ClassLoader getClassLoader() { if (loader == null) { loader = getClass().getClassLoader(); } return loader; } /** * Specifies the {@link ClassLoader} used to resolve and load * the classes specified by the argument values. * * @param loader the {@link ClassLoader} used to resolve and load * the classes specified by the argument values. */ public void setClassLoader(ClassLoader loader) { this.loader = loader; } /** * Returns whether the argument value must represent a * class that can be instantiated. * * @return whether the argument value must represent a * class that can be instantiated. */ public boolean isInstance() { return instance; } /** * Specifies whether the argument value must represent a * class that can be instantiated. * * @param instance whether the argument value must * represent a class that can be instantiated. */ public void setInstance(boolean instance) { this.instance = instance; } /** * Returns whether the specified name is allowed as * a Java class name. */ protected boolean isPotentialClassName(final String name) { final char[] chars = name.toCharArray(); boolean expectingStart = true; for (int i = 0; i < chars.length; ++i) { final char c = chars[i]; if (expectingStart) { if (!Character.isJavaIdentifierStart(c)) { return false; } expectingStart = false; } else { if (c == '.') { expectingStart = true; } else if (!Character.isJavaIdentifierPart(c)) { return false; } } } return !expectingStart; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * The ClassValidator validates the string argument + * values are class names. + * + * The following example shows how to validate the 'logger' + * argument value is a class name, that can be instantiated. + * + *
      + * ...
      + * ClassValidator validator = new ClassValidator();
      + * validator.setInstance(true);
      + *
      + * ArgumentBuilder builder = new ArgumentBuilder();
      + * Argument logger =
      + *     builder.withName("logger");
      + *            .withValidator(validator);
      + * 
      + * + * @author John Keyes + */ +public class ClassValidator implements Validator { + /** i18n */ + private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); + + /** whether the class argument is loadable */ + private boolean loadable; + + /** whether to create an instance of the class */ + private boolean instance; + + /** the classloader to load classes from */ + private ClassLoader loader; + + /** + * Validate each argument value in the specified List against this instances + * permitted attributes. + * + * If a value is valid then it's String value in the list is + * replaced with it's Class value or instance. + * + * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) + */ + public void validate(final List values) + throws InvalidArgumentException { + for (final ListIterator i = values.listIterator(); i.hasNext();) { + final String name = (String) i.next(); + + if (!isPotentialClassName(name)) { + throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_BAD_CLASSNAME, + name)); + } + + if (loadable || instance) { + final ClassLoader theLoader = getClassLoader(); + + try { + final Class clazz = theLoader.loadClass(name); + + if (instance) { + i.set(clazz.newInstance()); + } else { + i.set(clazz); + } + } catch (final ClassNotFoundException exp) { + throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_NOTFOUND, + name)); + } catch (final IllegalAccessException exp) { + throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_ACCESS, + name, exp.getMessage())); + } catch (final InstantiationException exp) { + throw new InvalidArgumentException(resources.getMessage(ResourceConstants.CLASSVALIDATOR_CLASS_CREATE, + name)); + } + } + } + } + + /** + * Returns whether the argument value must represent a + * class that is loadable. + * + * @return whether the argument value must represent a + * class that is loadable. + */ + public boolean isLoadable() { + return loadable; + } + + /** + * Specifies whether the argument value must represent a + * class that is loadable. + * + * @param loadable whether the argument value must + * represent a class that is loadable. + */ + public void setLoadable(boolean loadable) { + this.loadable = loadable; + } + + /** + * Returns the {@link ClassLoader} used to resolve and load + * the classes specified by the argument values. + * + * @return the {@link ClassLoader} used to resolve and load + * the classes specified by the argument values. + */ + public ClassLoader getClassLoader() { + if (loader == null) { + loader = getClass().getClassLoader(); + } + + return loader; + } + + /** + * Specifies the {@link ClassLoader} used to resolve and load + * the classes specified by the argument values. + * + * @param loader the {@link ClassLoader} used to resolve and load + * the classes specified by the argument values. + */ + public void setClassLoader(ClassLoader loader) { + this.loader = loader; + } + + /** + * Returns whether the argument value must represent a + * class that can be instantiated. + * + * @return whether the argument value must represent a + * class that can be instantiated. + */ + public boolean isInstance() { + return instance; + } + + /** + * Specifies whether the argument value must represent a + * class that can be instantiated. + * + * @param instance whether the argument value must + * represent a class that can be instantiated. + */ + public void setInstance(boolean instance) { + this.instance = instance; + } + + /** + * Returns whether the specified name is allowed as + * a Java class name. + */ + protected boolean isPotentialClassName(final String name) { + final char[] chars = name.toCharArray(); + + boolean expectingStart = true; + + for (int i = 0; i < chars.length; ++i) { + final char c = chars[i]; + + if (expectingStart) { + if (!Character.isJavaIdentifierStart(c)) { + return false; + } + + expectingStart = false; + } else { + if (c == '.') { + expectingStart = true; + } else if (!Character.isJavaIdentifierPart(c)) { + return false; + } + } + } + + return !expectingStart; + } +} diff --git a/src/java/org/apache/commons/cli2/validation/DateValidator.java b/src/java/org/apache/commons/cli2/validation/DateValidator.java index 490bf476d..85fff682d 100644 --- a/src/java/org/apache/commons/cli2/validation/DateValidator.java +++ b/src/java/org/apache/commons/cli2/validation/DateValidator.java @@ -1 +1,308 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.text.DateFormat;import java.text.ParsePosition;import java.util.Date;import java.util.List;import java.util.ListIterator;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * The DateValidator validates the argument values * are date or time value(s). * * The following example shows how to validate that * an argument value(s) is a Date of the following * type: d/M/yy (see {@link java.text.DateFormat}). * *
       * DateFormat date = new SimpleDateFormat("d/M/yy"); * ... * ArgumentBuilder builder = new ArgumentBuilder(); * Argument dateFormat = *     builder.withName("date"); *            .withValidator(new DateValidator(dateFormat)); * 
      * * The following example shows how to validate that * an argument value(s) is a time of the following * type: HH:mm:ss (see {@link java.text.DateFormat}). * *
       * DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); * ... * ArgumentBuilder builder = new ArgumentBuilder(); * Argument time = *     builder.withName("time"); *            .withValidator(new DateValidator(timeFormat)); * 
      * * @author John Keyes * * @see java.text.DateFormat */public class DateValidator implements Validator { /** i18n */ private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); /** an array of permitted DateFormats */ private DateFormat[] formats; /** minimum Date allowed i.e: a valid date occurs later than this date */ private Date minimum; /** maximum Date allowed i.e: a valid date occurs earlier than this date */ private Date maximum; /** leniant parsing */ private boolean isLenient; /** * Creates a Validator for the default date/time format */ public DateValidator() { this(DateFormat.getInstance()); } /** * Creates a Validator for the specified DateFormat. * * @param format * a DateFormat which dates must conform to */ public DateValidator(final DateFormat format) { setFormat(format); } /** * Creates a Validator for the List of specified DateFormats. * * @param formats * a List of DateFormats which dates must conform to */ public DateValidator(final List formats) { setFormats(formats); } /** * Creates a Validator for dates. * * @return DateValidator a Validator for dates */ public static DateValidator getDateInstance() { return new DateValidator(DateFormat.getDateInstance()); } /** * Creates a Validator for times. * * @return DateValidator a Validator for times */ public static DateValidator getTimeInstance() { return new DateValidator(DateFormat.getTimeInstance()); } /** * Creates a Validator for date/times * * @return DateValidator a Validator for date/times */ public static DateValidator getDateTimeInstance() { return new DateValidator(DateFormat.getDateTimeInstance()); } /** * Validate each String value in the specified List against this instances * permitted DateFormats. * * If a value is valid then it's String value in the list is * replaced with it's Date value. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { // for each value for (final ListIterator i = values.listIterator(); i.hasNext();) { final String value = (String) i.next(); Date date = null; // create a resuable ParsePosition instance final ParsePosition pp = new ParsePosition(0); // for each permitted DateFormat for (int f = 0; (f < this.formats.length) && (date == null); ++f) { // reset the parse position pp.setIndex(0); date = this.formats[f].parse(value, pp); // if the wrong number of characters have been parsed if (pp.getIndex() < value.length()) { date = null; } } // if date has not been set throw an InvalidArgumentException if (date == null) { throw new InvalidArgumentException(value); } // if the date is outside the bounds if (isDateEarlier(date) || isDateLater(date)) { throw new InvalidArgumentException(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, value)); } // replace the value in the list with the actual Date i.set(date); } } /** * Sets whether this validator uses lenient parsing. * * @param lenient whether this validator uses lenient parsing */ public void setLenient(final boolean lenient) { for (int i = 0; i < this.formats.length; i++) { this.formats[i].setLenient(lenient); } this.isLenient = lenient; } /** * Returns whether this validator uses lenient parsing. * * @return whether this validator uses lenient parsing */ public boolean isLenient() { return this.isLenient; } /** * Returns the maximum date permitted. * * @return Date the maximum date permitted. If no maximum date has been * specified then return null. */ public Date getMaximum() { return maximum; } /** * Sets the maximum Date to the specified value. * * @param maximum * the maximum Date permitted */ public void setMaximum(final Date maximum) { this.maximum = maximum; } /** * Returns the minimum date permitted. * * @return Date the minimum date permitted. If no minimum date has been * specified then return null. */ public Date getMinimum() { return minimum; } /** * Sets the minimum Date to the specified value. * * @param minimum * the minimum Date permitted */ public void setMinimum(Date minimum) { this.minimum = minimum; } /** * Returns whether the specified Date is later than the maximum date. * * @param date * the Date to evaluate * * @return boolean whether date is earlier than the maximum * date */ private boolean isDateLater(Date date) { return (maximum != null) && (date.getTime() > maximum.getTime()); } /** * Returns whether the specified Date is earlier than the minimum date. * * @param date * the Date to evaluate * * @return boolean whether date is earlier than the minimum * date */ private boolean isDateEarlier(Date date) { return (minimum != null) && (date.getTime() < minimum.getTime()); } /** * Sets the date format permitted. * * @param format * the format to use */ public void setFormat(final DateFormat format) { setFormats(new DateFormat[] { format }); } /** * Sets the date formats permitted. * * @param formats * the List of DateFormats to use */ public void setFormats(final List formats) { setFormats((DateFormat[]) formats.toArray(new DateFormat[formats.size()])); } /** * Sets the date formats permitted. * * @param formats * the array of DateFormats to use */ public void setFormats(final DateFormat[] formats) { this.formats = formats; setLenient(this.isLenient); } /** * Gets the date formats permitted. * * @return the permitted formats */ public DateFormat[] getFormats() { return this.formats; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.text.DateFormat; +import java.text.ParsePosition; + +import java.util.Date; +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * The DateValidator validates the argument values + * are date or time value(s). + * + * The following example shows how to validate that + * an argument value(s) is a Date of the following + * type: d/M/yy (see {@link java.text.DateFormat}). + * + *
      + * DateFormat date = new SimpleDateFormat("d/M/yy");
      + * ...
      + * ArgumentBuilder builder = new ArgumentBuilder();
      + * Argument dateFormat =
      + *     builder.withName("date");
      + *            .withValidator(new DateValidator(dateFormat));
      + * 
      + * + * The following example shows how to validate that + * an argument value(s) is a time of the following + * type: HH:mm:ss (see {@link java.text.DateFormat}). + * + *
      + * DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
      + * ...
      + * ArgumentBuilder builder = new ArgumentBuilder();
      + * Argument time =
      + *     builder.withName("time");
      + *            .withValidator(new DateValidator(timeFormat));
      + * 
      + * + * @author John Keyes + * + * @see java.text.DateFormat + */ +public class DateValidator implements Validator { + /** i18n */ + private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); + + /** an array of permitted DateFormats */ + private DateFormat[] formats; + + /** minimum Date allowed i.e: a valid date occurs later than this date */ + private Date minimum; + + /** maximum Date allowed i.e: a valid date occurs earlier than this date */ + private Date maximum; + + /** leniant parsing */ + private boolean isLenient; + + /** + * Creates a Validator for the default date/time format + */ + public DateValidator() { + this(DateFormat.getInstance()); + } + + /** + * Creates a Validator for the specified DateFormat. + * + * @param format + * a DateFormat which dates must conform to + */ + public DateValidator(final DateFormat format) { + setFormat(format); + } + + /** + * Creates a Validator for the List of specified DateFormats. + * + * @param formats + * a List of DateFormats which dates must conform to + */ + public DateValidator(final List formats) { + setFormats(formats); + } + + /** + * Creates a Validator for dates. + * + * @return DateValidator a Validator for dates + */ + public static DateValidator getDateInstance() { + return new DateValidator(DateFormat.getDateInstance()); + } + + /** + * Creates a Validator for times. + * + * @return DateValidator a Validator for times + */ + public static DateValidator getTimeInstance() { + return new DateValidator(DateFormat.getTimeInstance()); + } + + /** + * Creates a Validator for date/times + * + * @return DateValidator a Validator for date/times + */ + public static DateValidator getDateTimeInstance() { + return new DateValidator(DateFormat.getDateTimeInstance()); + } + + /** + * Validate each String value in the specified List against this instances + * permitted DateFormats. + * + * If a value is valid then it's String value in the list is + * replaced with it's Date value. + * + * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) + */ + public void validate(final List values) + throws InvalidArgumentException { + // for each value + for (final ListIterator i = values.listIterator(); i.hasNext();) { + final String value = (String) i.next(); + + Date date = null; + + // create a resuable ParsePosition instance + final ParsePosition pp = new ParsePosition(0); + + // for each permitted DateFormat + for (int f = 0; (f < this.formats.length) && (date == null); ++f) { + // reset the parse position + pp.setIndex(0); + date = this.formats[f].parse(value, pp); + + // if the wrong number of characters have been parsed + if (pp.getIndex() < value.length()) { + date = null; + } + } + + // if date has not been set throw an InvalidArgumentException + if (date == null) { + throw new InvalidArgumentException(value); + } + + // if the date is outside the bounds + if (isDateEarlier(date) || isDateLater(date)) { + throw new InvalidArgumentException(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, + value)); + } + + // replace the value in the list with the actual Date + i.set(date); + } + } + + /** + * Sets whether this validator uses lenient parsing. + * + * @param lenient whether this validator uses lenient parsing + */ + public void setLenient(final boolean lenient) { + for (int i = 0; i < this.formats.length; i++) { + this.formats[i].setLenient(lenient); + } + + this.isLenient = lenient; + } + + /** + * Returns whether this validator uses lenient parsing. + * + * @return whether this validator uses lenient parsing + */ + public boolean isLenient() { + return this.isLenient; + } + + /** + * Returns the maximum date permitted. + * + * @return Date the maximum date permitted. If no maximum date has been + * specified then return null. + */ + public Date getMaximum() { + return maximum; + } + + /** + * Sets the maximum Date to the specified value. + * + * @param maximum + * the maximum Date permitted + */ + public void setMaximum(final Date maximum) { + this.maximum = maximum; + } + + /** + * Returns the minimum date permitted. + * + * @return Date the minimum date permitted. If no minimum date has been + * specified then return null. + */ + public Date getMinimum() { + return minimum; + } + + /** + * Sets the minimum Date to the specified value. + * + * @param minimum + * the minimum Date permitted + */ + public void setMinimum(Date minimum) { + this.minimum = minimum; + } + + /** + * Returns whether the specified Date is later than the maximum date. + * + * @param date + * the Date to evaluate + * + * @return boolean whether date is earlier than the maximum + * date + */ + private boolean isDateLater(Date date) { + return (maximum != null) && (date.getTime() > maximum.getTime()); + } + + /** + * Returns whether the specified Date is earlier than the minimum date. + * + * @param date + * the Date to evaluate + * + * @return boolean whether date is earlier than the minimum + * date + */ + private boolean isDateEarlier(Date date) { + return (minimum != null) && (date.getTime() < minimum.getTime()); + } + + /** + * Sets the date format permitted. + * + * @param format + * the format to use + */ + public void setFormat(final DateFormat format) { + setFormats(new DateFormat[] { format }); + } + + /** + * Sets the date formats permitted. + * + * @param formats + * the List of DateFormats to use + */ + public void setFormats(final List formats) { + setFormats((DateFormat[]) formats.toArray(new DateFormat[formats.size()])); + } + + /** + * Sets the date formats permitted. + * + * @param formats + * the array of DateFormats to use + */ + public void setFormats(final DateFormat[] formats) { + this.formats = formats; + setLenient(this.isLenient); + } + + /** + * Gets the date formats permitted. + * + * @return the permitted formats + */ + public DateFormat[] getFormats() { + return this.formats; + } +} diff --git a/src/java/org/apache/commons/cli2/validation/EnumValidator.java b/src/java/org/apache/commons/cli2/validation/EnumValidator.java index e67cb62fa..12e376cbb 100644 --- a/src/java/org/apache/commons/cli2/validation/EnumValidator.java +++ b/src/java/org/apache/commons/cli2/validation/EnumValidator.java @@ -1 +1,120 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.util.Iterator;import java.util.List;import java.util.Set;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * The EnumValidator validates the string argument * values are valid. * * The following example shows how to limit the valid values * for the color argument to 'red', 'green', or 'blue'. * *
       * Set values = new HashSet(); * values.add("red"); * values.add("green"); * values.add("blue"); * ... * ArgumentBuilder builder = new ArgumentBuilder(); * Argument color = *     builder.withName("color"); *            .withValidator(new EnumValidator(values)); * 
      * * @author John Keyes */public class EnumValidator implements Validator { /** List of permitted values */ private Set validValues; /** * Creates a new EnumValidator for the specified values. * * @param values The list of permitted values */ public EnumValidator(final Set values) { setValidValues(values); } /** * Validate the list of values against the list of permitted values. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { for (final Iterator iter = values.iterator(); iter.hasNext();) { final String value = (String) iter.next(); if (!this.validValues.contains(value)) { throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ENUM_ILLEGAL_VALUE, new Object[] { value, getValuesAsString() })); } } } /** * Returns the permitted values in a comma separated String * * @return String formatted list of values */ String getValuesAsString() { final StringBuffer buff = new StringBuffer(); buff.append("["); for (final Iterator iter = this.validValues.iterator(); iter.hasNext();) { buff.append("'").append(iter.next()).append("'"); if (iter.hasNext()) { buff.append(", "); } } buff.append("]"); return buff.toString(); } /** * Returns the Set of valid argument values. * * @return Returns the Set of valid argument values. */ public Set getValidValues() { return validValues; } /** * Specifies the Set of valid argument values. * * @param validValues The Set of valid argument values. */ protected void setValidValues(Set validValues) { this.validValues = validValues; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * The EnumValidator validates the string argument + * values are valid. + * + * The following example shows how to limit the valid values + * for the color argument to 'red', 'green', or 'blue'. + * + *
      + * Set values = new HashSet();
      + * values.add("red");
      + * values.add("green");
      + * values.add("blue");
      + * ...
      + * ArgumentBuilder builder = new ArgumentBuilder();
      + * Argument color =
      + *     builder.withName("color");
      + *            .withValidator(new EnumValidator(values));
      + * 
      + * + * @author John Keyes + */ +public class EnumValidator implements Validator { + /** List of permitted values */ + private Set validValues; + + /** + * Creates a new EnumValidator for the specified values. + * + * @param values The list of permitted values + */ + public EnumValidator(final Set values) { + setValidValues(values); + } + + /** + * Validate the list of values against the list of permitted values. + * + * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) + */ + public void validate(final List values) + throws InvalidArgumentException { + for (final Iterator iter = values.iterator(); iter.hasNext();) { + final String value = (String) iter.next(); + + if (!this.validValues.contains(value)) { + throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ENUM_ILLEGAL_VALUE, + new Object[] { + value, + getValuesAsString() + })); + } + } + } + + /** + * Returns the permitted values in a comma separated String + * + * @return String formatted list of values + */ + String getValuesAsString() { + final StringBuffer buff = new StringBuffer(); + + buff.append("["); + + for (final Iterator iter = this.validValues.iterator(); iter.hasNext();) { + buff.append("'").append(iter.next()).append("'"); + + if (iter.hasNext()) { + buff.append(", "); + } + } + + buff.append("]"); + + return buff.toString(); + } + + /** + * Returns the Set of valid argument values. + * + * @return Returns the Set of valid argument values. + */ + public Set getValidValues() { + return validValues; + } + + /** + * Specifies the Set of valid argument values. + * + * @param validValues The Set of valid argument values. + */ + protected void setValidValues(Set validValues) { + this.validValues = validValues; + } +} diff --git a/src/java/org/apache/commons/cli2/validation/FileValidator.java b/src/java/org/apache/commons/cli2/validation/FileValidator.java index fdf996ad6..aff1bc5f1 100644 --- a/src/java/org/apache/commons/cli2/validation/FileValidator.java +++ b/src/java/org/apache/commons/cli2/validation/FileValidator.java @@ -1 +1,265 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.io.File;import java.util.List;import java.util.ListIterator;/** * The FileValidator validates the string argument * values are files. If the value is a file, the string value in * the {@link java.util.List} of values is replaced with the * {@link java.io.File} instance. * * The following attributes can also be specified using the * appropriate settors: *
        *
      • writable
      • *
      • readable
      • *
      • hidden
      • *
      • existing
      • *
      • is a file
      • *
      • is a directory
      • *
      * * The following example shows how to limit the valid values * for the config attribute to files that are readable, writeable, * and that already existing. * *
       * ... * ArgumentBuilder builder = new ArgumentBuilder(); * FileValidator validator = FileValidator.getExistingFileInstance(); * validator.setReadable(true); * validator.setWritable(true); * * Argument age = *     builder.withName("config"); *            .withValidator(validator); * 
      * * @author Rob Oxspring * @author John Keyes */public class FileValidator implements Validator { /** * Returns a FileValidator for existing files/directories. * * @return a FileValidator for existing files/directories. */ public static FileValidator getExistingInstance() { final FileValidator validator = new FileValidator(); validator.setExisting(true); return validator; } /** * Returns a FileValidator for existing files. * * @return a FileValidator for existing files. */ public static FileValidator getExistingFileInstance() { final FileValidator validator = new FileValidator(); validator.setExisting(true); validator.setFile(true); return validator; } /** * Returns a FileValidator for existing directories. * * @return a FileValidator for existing directories. */ public static FileValidator getExistingDirectoryInstance() { final FileValidator validator = new FileValidator(); validator.setExisting(true); validator.setDirectory(true); return validator; } /** whether the argument value is readable */ private boolean readable = false; /** whether the argument value is writable */ private boolean writable = false; /** whether the argument value exists */ private boolean existing = false; /** whether the argument value is a directory */ private boolean directory = false; /** whether the argument value is a file */ private boolean file = false; /** whether the argument value is a hidden file or directory */ private boolean hidden = false; /** * Validate the list of values against the list of permitted values. * If a value is valid, replace the string in the values * {@link java.util.List} with the {@link java.io.File} instance. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { for (final ListIterator i = values.listIterator(); i.hasNext();) { final String name = (String)i.next(); final File f = new File(name); if ((existing && !f.exists()) || (file && !f.isFile()) || (directory && !f.isDirectory()) || (hidden && !f.isHidden()) || (readable && !f.canRead()) || (writable && !f.canWrite())) { throw new InvalidArgumentException(name); } i.set(f); } } /** * Returns whether the argument values must represent directories. * * @return whether the argument values must represent directories. */ public boolean isDirectory() { return directory; } /** * Specifies whether the argument values must represent directories. * * @param directory specifies whether the argument values must * represent directories. */ public void setDirectory(boolean directory) { this.directory = directory; } /** * Returns whether the argument values must represent existing * files/directories. * * @return whether the argument values must represent existing * files/directories. */ public boolean isExisting() { return existing; } /** * Specifies whether the argument values must represent existing * files/directories. * * @param existing specifies whether the argument values must * represent existing files/directories. */ public void setExisting(boolean existing) { this.existing = existing; } /** * Returns whether the argument values must represent directories. * * @return whether the argument values must represent directories. */ public boolean isFile() { return file; } /** * Specifies whether the argument values must represent files. * * @param file specifies whether the argument values must * represent files. */ public void setFile(boolean file) { this.file = file; } /** * Returns whether the argument values must represent hidden * files/directories. * * @return whether the argument values must represent hidden * files/directories. */ public boolean isHidden() { return hidden; } /** * Specifies whether the argument values must represent hidden * files/directories. * * @param hidden specifies whether the argument values must * represent hidden files/directories. */ public void setHidden(boolean hidden) { this.hidden = hidden; } /** * Returns whether the argument values must represent readable * files/directories. * * @return whether the argument values must represent readable * files/directories. */ public boolean isReadable() { return readable; } /** * Specifies whether the argument values must represent readable * files/directories. * * @param readable specifies whether the argument values must * represent readable files/directories. */ public void setReadable(boolean readable) { this.readable = readable; } /** * Returns whether the argument values must represent writable * files/directories. * * @return whether the argument values must represent writable * files/directories. */ public boolean isWritable() { return writable; } /** * Specifies whether the argument values must represent writable * files/directories. * * @param writable specifies whether the argument values must * represent writable files/directories. */ public void setWritable(boolean writable) { this.writable = writable; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.io.File; +import java.util.List; +import java.util.ListIterator; + +/** + * The FileValidator validates the string argument + * values are files. If the value is a file, the string value in + * the {@link java.util.List} of values is replaced with the + * {@link java.io.File} instance. + * + * The following attributes can also be specified using the + * appropriate settors: + *
        + *
      • writable
      • + *
      • readable
      • + *
      • hidden
      • + *
      • existing
      • + *
      • is a file
      • + *
      • is a directory
      • + *
      + * + * The following example shows how to limit the valid values + * for the config attribute to files that are readable, writeable, + * and that already existing. + * + *
      + * ...
      + * ArgumentBuilder builder = new ArgumentBuilder();
      + * FileValidator validator = FileValidator.getExistingFileInstance();
      + * validator.setReadable(true);
      + * validator.setWritable(true);
      + * 
      + * Argument age = 
      + *     builder.withName("config");
      + *            .withValidator(validator);
      + * 
      + * + * @author Rob Oxspring + * @author John Keyes + */ +public class FileValidator implements Validator { + + /** + * Returns a FileValidator for existing files/directories. + * + * @return a FileValidator for existing files/directories. + */ + public static FileValidator getExistingInstance() { + final FileValidator validator = new FileValidator(); + validator.setExisting(true); + return validator; + } + + /** + * Returns a FileValidator for existing files. + * + * @return a FileValidator for existing files. + */ + public static FileValidator getExistingFileInstance() { + final FileValidator validator = new FileValidator(); + validator.setExisting(true); + validator.setFile(true); + return validator; + } + + /** + * Returns a FileValidator for existing directories. + * + * @return a FileValidator for existing directories. + */ + public static FileValidator getExistingDirectoryInstance() { + final FileValidator validator = new FileValidator(); + validator.setExisting(true); + validator.setDirectory(true); + return validator; + } + + /** whether the argument value is readable */ + private boolean readable = false; + + /** whether the argument value is writable */ + private boolean writable = false; + + /** whether the argument value exists */ + private boolean existing = false; + + /** whether the argument value is a directory */ + private boolean directory = false; + + /** whether the argument value is a file */ + private boolean file = false; + + /** whether the argument value is a hidden file or directory */ + private boolean hidden = false; + + /** + * Validate the list of values against the list of permitted values. + * If a value is valid, replace the string in the values + * {@link java.util.List} with the {@link java.io.File} instance. + * + * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) + */ + public void validate(final List values) throws InvalidArgumentException { + for (final ListIterator i = values.listIterator(); i.hasNext();) { + final String name = (String)i.next(); + final File f = new File(name); + + if ((existing && !f.exists()) + || (file && !f.isFile()) + || (directory && !f.isDirectory()) + || (hidden && !f.isHidden()) + || (readable && !f.canRead()) + || (writable && !f.canWrite())) { + + throw new InvalidArgumentException(name); + } + + i.set(f); + } + } + + /** + * Returns whether the argument values must represent directories. + * + * @return whether the argument values must represent directories. + */ + public boolean isDirectory() { + return directory; + } + + /** + * Specifies whether the argument values must represent directories. + * + * @param directory specifies whether the argument values must + * represent directories. + */ + public void setDirectory(boolean directory) { + this.directory = directory; + } + + /** + * Returns whether the argument values must represent existing + * files/directories. + * + * @return whether the argument values must represent existing + * files/directories. + */ + public boolean isExisting() { + return existing; + } + + /** + * Specifies whether the argument values must represent existing + * files/directories. + * + * @param existing specifies whether the argument values must + * represent existing files/directories. + */ + public void setExisting(boolean existing) { + this.existing = existing; + } + + /** + * Returns whether the argument values must represent directories. + * + * @return whether the argument values must represent directories. + */ + public boolean isFile() { + return file; + } + + /** + * Specifies whether the argument values must represent files. + * + * @param file specifies whether the argument values must + * represent files. + */ + public void setFile(boolean file) { + this.file = file; + } + + /** + * Returns whether the argument values must represent hidden + * files/directories. + * + * @return whether the argument values must represent hidden + * files/directories. + */ + public boolean isHidden() { + return hidden; + } + + /** + * Specifies whether the argument values must represent hidden + * files/directories. + * + * @param hidden specifies whether the argument values must + * represent hidden files/directories. + */ + public void setHidden(boolean hidden) { + this.hidden = hidden; + } + + /** + * Returns whether the argument values must represent readable + * files/directories. + * + * @return whether the argument values must represent readable + * files/directories. + */ + public boolean isReadable() { + return readable; + } + + /** + * Specifies whether the argument values must represent readable + * files/directories. + * + * @param readable specifies whether the argument values must + * represent readable files/directories. + */ + public void setReadable(boolean readable) { + this.readable = readable; + } + + /** + * Returns whether the argument values must represent writable + * files/directories. + * + * @return whether the argument values must represent writable + * files/directories. + */ + public boolean isWritable() { + return writable; + } + + /** + * Specifies whether the argument values must represent writable + * files/directories. + * + * @param writable specifies whether the argument values must + * represent writable files/directories. + */ + public void setWritable(boolean writable) { + this.writable = writable; + } +} diff --git a/src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java b/src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java index 13d882fa0..65c503e47 100644 --- a/src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java +++ b/src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java @@ -1 +1,34 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;/** * An exception indicating validation failure. * * @author Rob Oxspring * @author John Keyes */public class InvalidArgumentException extends Exception { /** * Creates a new exception * @param message the reason for failure */ public InvalidArgumentException(final String message) { super(message); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +/** + * An exception indicating validation failure. + * + * @author Rob Oxspring + * @author John Keyes + */ +public class InvalidArgumentException extends Exception { + + /** + * Creates a new exception + * @param message the reason for failure + */ + public InvalidArgumentException(final String message) { + super(message); + } +} diff --git a/src/java/org/apache/commons/cli2/validation/NumberValidator.java b/src/java/org/apache/commons/cli2/validation/NumberValidator.java index b95b309dc..5761a71cd 100644 --- a/src/java/org/apache/commons/cli2/validation/NumberValidator.java +++ b/src/java/org/apache/commons/cli2/validation/NumberValidator.java @@ -1 +1,200 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.text.NumberFormat;import java.text.ParsePosition;import java.util.List;import java.util.ListIterator;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * The NumberValidator validates the string argument * values are numbers. If the value is a number, the string value in * the {@link java.util.List} of values is replaced with the * {@link java.lang.Number} instance. * * A maximum and minimum value can also be specified using * the {@link #setMaximum setMaximum}, and the * {@link #setMinimum setMinimum} methods. * * The following example shows how to limit the valid values * for the age attribute to integers less than 100. * *
       * ... * ArgumentBuilder builder = new ArgumentBuilder(); * NumberValidator validator = NumberValidator.getIntegerInstance(); * validator.setMaximum(new Integer(100)); * * Argument age = *     builder.withName("age"); *            .withValidator(validator); * 
      * * @author Rob Oxspring * @author John Keyes */public class NumberValidator implements Validator { /** the NumberFormat being used. */ private NumberFormat format; /** the lower bound for argument values. */ private Number minimum = null; /** the upper bound for argument values */ private Number maximum = null; /** * Creates a new NumberValidator based on the specified NumberFormat * @param format the format of numbers to accept */ public NumberValidator(final NumberFormat format) { setFormat(format); } /** * Returns a NumberValidator for a currency format * for the current default locale. * @return a NumberValidator for a currency format * for the current default locale. */ public static NumberValidator getCurrencyInstance() { return new NumberValidator(NumberFormat.getCurrencyInstance()); } /** * Returns a NumberValidator for an integer number format * for the current default locale. * @return a NumberValidator for an integer number format * for the current default locale. */ public static NumberValidator getIntegerInstance() { final NumberFormat format = NumberFormat.getNumberInstance(); format.setParseIntegerOnly(true); return new NumberValidator(format); } /** * Returns a NumberValidator for a percentage format * for the current default locale. * @return a NumberValidator for a percentage format * for the current default locale. */ public static NumberValidator getPercentInstance() { return new NumberValidator(NumberFormat.getPercentInstance()); } /** * Returns a NumberValidator for a general-purpose * number format for the current default locale. * @return a NumberValidator for a general-purpose * number format for the current default locale. */ public static NumberValidator getNumberInstance() { return new NumberValidator(NumberFormat.getNumberInstance()); } /** * Validate the list of values against the list of permitted values. * If a value is valid, replace the string in the values * {@link java.util.List} with the {@link java.lang.Number} instance. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { for (final ListIterator i = values.listIterator(); i.hasNext();) { final String value = (String) i.next(); final ParsePosition pp = new ParsePosition(0); final Number number = format.parse(value, pp); if (pp.getIndex() < value.length()) { throw new InvalidArgumentException(value); } if (((minimum != null) && (number.doubleValue() < minimum.doubleValue())) || ((maximum != null) && (number.doubleValue() > maximum.doubleValue()))) { throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, new Object[] { value })); } i.set(number); } } /** * Return the format being used to validate argument values against. * * @return the format being used to validate argument values against. */ public NumberFormat getFormat() { return format; } /** * Specify the format being used to validate argument values against. * * @param format the format being used to validate argument values against. */ protected void setFormat(NumberFormat format) { this.format = format; } /** * Return the maximum value allowed for an argument value. * * @return the maximum value allowed for an argument value. */ public Number getMaximum() { return maximum; } /** * Specify the maximum value allowed for an argument value. * * @param maximum the maximum value allowed for an argument value. */ public void setMaximum(Number maximum) { this.maximum = maximum; } /** * Return the minimum value allowed for an argument value. * * @return the minimum value allowed for an argument value. */ public Number getMinimum() { return minimum; } /** * Specify the minimum value allowed for an argument value. * * @param minimum the minimum value allowed for an argument value. */ public void setMinimum(Number minimum) { this.minimum = minimum; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.text.NumberFormat; +import java.text.ParsePosition; + +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * The NumberValidator validates the string argument + * values are numbers. If the value is a number, the string value in + * the {@link java.util.List} of values is replaced with the + * {@link java.lang.Number} instance. + * + * A maximum and minimum value can also be specified using + * the {@link #setMaximum setMaximum}, and the + * {@link #setMinimum setMinimum} methods. + * + * The following example shows how to limit the valid values + * for the age attribute to integers less than 100. + * + *
      + * ...
      + * ArgumentBuilder builder = new ArgumentBuilder();
      + * NumberValidator validator = NumberValidator.getIntegerInstance();
      + * validator.setMaximum(new Integer(100));
      + *
      + * Argument age =
      + *     builder.withName("age");
      + *            .withValidator(validator);
      + * 
      + * + * @author Rob Oxspring + * @author John Keyes + */ +public class NumberValidator implements Validator { + /** the NumberFormat being used. */ + private NumberFormat format; + + /** the lower bound for argument values. */ + private Number minimum = null; + + /** the upper bound for argument values */ + private Number maximum = null; + + /** + * Creates a new NumberValidator based on the specified NumberFormat + * @param format the format of numbers to accept + */ + public NumberValidator(final NumberFormat format) { + setFormat(format); + } + + /** + * Returns a NumberValidator for a currency format + * for the current default locale. + * @return a NumberValidator for a currency format + * for the current default locale. + */ + public static NumberValidator getCurrencyInstance() { + return new NumberValidator(NumberFormat.getCurrencyInstance()); + } + + /** + * Returns a NumberValidator for an integer number format + * for the current default locale. + * @return a NumberValidator for an integer number format + * for the current default locale. + */ + public static NumberValidator getIntegerInstance() { + final NumberFormat format = NumberFormat.getNumberInstance(); + format.setParseIntegerOnly(true); + + return new NumberValidator(format); + } + + /** + * Returns a NumberValidator for a percentage format + * for the current default locale. + * @return a NumberValidator for a percentage format + * for the current default locale. + */ + public static NumberValidator getPercentInstance() { + return new NumberValidator(NumberFormat.getPercentInstance()); + } + + /** + * Returns a NumberValidator for a general-purpose + * number format for the current default locale. + * @return a NumberValidator for a general-purpose + * number format for the current default locale. + */ + public static NumberValidator getNumberInstance() { + return new NumberValidator(NumberFormat.getNumberInstance()); + } + + /** + * Validate the list of values against the list of permitted values. + * If a value is valid, replace the string in the values + * {@link java.util.List} with the {@link java.lang.Number} instance. + * + * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) + */ + public void validate(final List values) + throws InvalidArgumentException { + for (final ListIterator i = values.listIterator(); i.hasNext();) { + final String value = (String) i.next(); + + final ParsePosition pp = new ParsePosition(0); + final Number number = format.parse(value, pp); + + if (pp.getIndex() < value.length()) { + throw new InvalidArgumentException(value); + } + + if (((minimum != null) && (number.doubleValue() < minimum.doubleValue())) || + ((maximum != null) && (number.doubleValue() > maximum.doubleValue()))) { + throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, + new Object[] { + value + })); + } + + i.set(number); + } + } + + /** + * Return the format being used to validate argument values against. + * + * @return the format being used to validate argument values against. + */ + public NumberFormat getFormat() { + return format; + } + + /** + * Specify the format being used to validate argument values against. + * + * @param format the format being used to validate argument values against. + */ + protected void setFormat(NumberFormat format) { + this.format = format; + } + + /** + * Return the maximum value allowed for an argument value. + * + * @return the maximum value allowed for an argument value. + */ + public Number getMaximum() { + return maximum; + } + + /** + * Specify the maximum value allowed for an argument value. + * + * @param maximum the maximum value allowed for an argument value. + */ + public void setMaximum(Number maximum) { + this.maximum = maximum; + } + + /** + * Return the minimum value allowed for an argument value. + * + * @return the minimum value allowed for an argument value. + */ + public Number getMinimum() { + return minimum; + } + + /** + * Specify the minimum value allowed for an argument value. + * + * @param minimum the minimum value allowed for an argument value. + */ + public void setMinimum(Number minimum) { + this.minimum = minimum; + } +} diff --git a/src/java/org/apache/commons/cli2/validation/UrlValidator.java b/src/java/org/apache/commons/cli2/validation/UrlValidator.java index 9c1da974c..4ce1d37f2 100644 --- a/src/java/org/apache/commons/cli2/validation/UrlValidator.java +++ b/src/java/org/apache/commons/cli2/validation/UrlValidator.java @@ -1 +1,115 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.net.MalformedURLException;import java.net.URL;import java.util.List;import java.util.ListIterator;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * The UrlValidator validates the string argument * values are URLs. If the value is a URL, the string value in * the {@link java.util.List} of values is replaced with the * {@link java.net.URL} instance. * * URLs can also be validated based on their scheme by using * the {@link #setProtocol setProtocol} method, or by using the specified * {@link #UrlValidator(java.lang.String) constructor}. * * The following example shows how to limit the valid values * for the site argument to 'https' URLs. * *
       * ... * ArgumentBuilder builder = new ArgumentBuilder(); * Argument site = *     builder.withName("site"); *            .withValidator(new URLValidator("https")); * 
      * * @author Rob Oxspring * @author John Keyes */public class UrlValidator implements Validator { /** allowed protocol */ private String protocol = null; /** * Creates a UrlValidator. */ public UrlValidator() { } /** * Creates a UrlValidator for the specified protocol. */ public UrlValidator(final String protocol) { setProtocol(protocol); } /** * Validate the list of values against the list of permitted values. * If a value is valid, replace the string in the values * {@link java.util.List} with the { java.net.URL} instance. * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { for (final ListIterator i = values.listIterator(); i.hasNext();) { final String name = (String) i.next(); try { final URL url = new URL(name); if ((protocol != null) && !protocol.equals(url.getProtocol())) { throw new InvalidArgumentException(name); } i.set(url); } catch (final MalformedURLException mue) { throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.URLVALIDATOR_MALFORMED_URL, new Object[] { name })); } } } /** * Returns the protocol that must be used by a valid URL. * * @return the protocol that must be used by a valid URL. */ public String getProtocol() { return protocol; } /** * Specifies the protocol that a URL must have to be valid. * * @param protocol the protocol that a URL must have to be valid. */ public void setProtocol(String protocol) { this.protocol = protocol; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.net.MalformedURLException; +import java.net.URL; + +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * The UrlValidator validates the string argument + * values are URLs. If the value is a URL, the string value in + * the {@link java.util.List} of values is replaced with the + * {@link java.net.URL} instance. + * + * URLs can also be validated based on their scheme by using + * the {@link #setProtocol setProtocol} method, or by using the specified + * {@link #UrlValidator(java.lang.String) constructor}. + * + * The following example shows how to limit the valid values + * for the site argument to 'https' URLs. + * + *
      + * ...
      + * ArgumentBuilder builder = new ArgumentBuilder();
      + * Argument site =
      + *     builder.withName("site");
      + *            .withValidator(new URLValidator("https"));
      + * 
      + * + * @author Rob Oxspring + * @author John Keyes + */ +public class UrlValidator implements Validator { + /** allowed protocol */ + private String protocol = null; + + /** + * Creates a UrlValidator. + */ + public UrlValidator() { + } + + /** + * Creates a UrlValidator for the specified protocol. + */ + public UrlValidator(final String protocol) { + setProtocol(protocol); + } + + /** + * Validate the list of values against the list of permitted values. + * If a value is valid, replace the string in the values + * {@link java.util.List} with the { java.net.URL} instance. + * + * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) + */ + public void validate(final List values) + throws InvalidArgumentException { + for (final ListIterator i = values.listIterator(); i.hasNext();) { + final String name = (String) i.next(); + + try { + final URL url = new URL(name); + + if ((protocol != null) && !protocol.equals(url.getProtocol())) { + throw new InvalidArgumentException(name); + } + + i.set(url); + } catch (final MalformedURLException mue) { + throw new InvalidArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.URLVALIDATOR_MALFORMED_URL, + new Object[] { + name + })); + } + } + } + + /** + * Returns the protocol that must be used by a valid URL. + * + * @return the protocol that must be used by a valid URL. + */ + public String getProtocol() { + return protocol; + } + + /** + * Specifies the protocol that a URL must have to be valid. + * + * @param protocol the protocol that a URL must have to be valid. + */ + public void setProtocol(String protocol) { + this.protocol = protocol; + } +} diff --git a/src/java/org/apache/commons/cli2/validation/Validator.java b/src/java/org/apache/commons/cli2/validation/Validator.java index b0b7f4b92..2147dfd28 100644 --- a/src/java/org/apache/commons/cli2/validation/Validator.java +++ b/src/java/org/apache/commons/cli2/validation/Validator.java @@ -1 +1,43 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.util.List;/** * The validation interface for validating argument values(s). * * A validator can replace the argument string value with a * specific class instance e.g. the {@link UrlValidator} replaces * the string value with a {@link java.net.URL} instance. * * @author Rob Oxspring * @author John Keyes */public interface Validator { /** * Validate the specified values (List of Strings). * * @param values The values to validate. * * @throws InvalidArgumentException If any of the * specified values are not valid. */ void validate(final List values) throws InvalidArgumentException;} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.util.List; + +/** + * The validation interface for validating argument values(s). + * + * A validator can replace the argument string value with a + * specific class instance e.g. the {@link UrlValidator} replaces + * the string value with a {@link java.net.URL} instance. + * + * @author Rob Oxspring + * @author John Keyes + */ +public interface Validator { + + /** + * Validate the specified values (List of Strings). + * + * @param values The values to validate. + * + * @throws InvalidArgumentException If any of the + * specified values are not valid. + */ + void validate(final List values) throws InvalidArgumentException; + +} diff --git a/src/test/org/apache/commons/cli2/CLITestCase.java b/src/test/org/apache/commons/cli2/CLITestCase.java index 59821ed27..e2baf6913 100644 --- a/src/test/org/apache/commons/cli2/CLITestCase.java +++ b/src/test/org/apache/commons/cli2/CLITestCase.java @@ -1 +1,85 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Arrays;import java.util.Collection;import java.util.Collections;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import junit.framework.TestCase;public abstract class CLITestCase extends TestCase { public static List list() { return Collections.EMPTY_LIST; } public static List list(final Object args[]) { return new LinkedList(Arrays.asList(args)); } public static List list(final Object arg0) { return list(new Object[] { arg0 }); } public static List list(final Object arg0, final Object arg1) { return list(new Object[] { arg0, arg1 }); } public static List list(final Object arg0, final Object arg1, final Object arg2) { return list(new Object[] { arg0, arg1, arg2 }); } public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3) { return list(new Object[] { arg0, arg1, arg2, arg3 }); } public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3, final Object arg4) { return list(new Object[] { arg0, arg1, arg2, arg3, arg4 }); } public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3, final Object arg4, final Object arg5) { return list(new Object[] { arg0, arg1, arg2, arg3, arg4, arg5 }); } public static void assertListContentsEqual(final List expected, final List found) { final Iterator e = expected.iterator(); final Iterator f = found.iterator(); while (e.hasNext() && f.hasNext()) { assertEquals(e.next(), f.next()); } if (e.hasNext()) { fail("Expected more elements"); } if (f.hasNext()) { fail("Found more elements"); } } public static void assertContentsEqual(final Collection expected, final Collection found) { assertTrue(expected.containsAll(found)); assertTrue(found.containsAll(expected)); assertEquals(expected.size(), found.size()); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import junit.framework.TestCase; + +public abstract class CLITestCase extends TestCase { + + public static List list() { + return Collections.EMPTY_LIST; + } + + public static List list(final Object args[]) { + return new LinkedList(Arrays.asList(args)); + } + + public static List list(final Object arg0) { + return list(new Object[] { arg0 }); + } + + public static List list(final Object arg0, final Object arg1) { + return list(new Object[] { arg0, arg1 }); + } + + public static List list(final Object arg0, final Object arg1, final Object arg2) { + return list(new Object[] { arg0, arg1, arg2 }); + } + + public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3) { + return list(new Object[] { arg0, arg1, arg2, arg3 }); + } + + public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3, final Object arg4) { + return list(new Object[] { arg0, arg1, arg2, arg3, arg4 }); + } + + public static List list(final Object arg0, final Object arg1, final Object arg2, final Object arg3, final Object arg4, final Object arg5) { + return list(new Object[] { arg0, arg1, arg2, arg3, arg4, arg5 }); + } + + public static void assertListContentsEqual(final List expected, final List found) { + + final Iterator e = expected.iterator(); + final Iterator f = found.iterator(); + + while (e.hasNext() && f.hasNext()) { + assertEquals(e.next(), f.next()); + } + + if (e.hasNext()) { + fail("Expected more elements"); + } + + if (f.hasNext()) { + fail("Found more elements"); + } + } + + public static void assertContentsEqual(final Collection expected, final Collection found) { + assertTrue(expected.containsAll(found)); + assertTrue(found.containsAll(expected)); + assertEquals(expected.size(), found.size()); + } +} diff --git a/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java b/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java index 97e48fca3..c4f1227cf 100644 --- a/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java +++ b/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java @@ -1 +1,251 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Arrays;import java.util.Collections;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.SwitchBuilder;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;/** * Tests the interaction of command line values and defaults supplied in different ways. * * Tests marked _Parsed involve values parsed from a command line. * * Tests marked _Method involve defaults supplied in the query method. * * Tests marked _Option involce defaults specified in the model. * * @author Rob Oxspring */public class CommandLineDefaultsTest extends TestCase { /* * utils to grab the default from the method */ private Object methodSwitch(WriteableCommandLine cl, Option o, Boolean bool) { return cl.getSwitch(o, bool); } private Object methodSwitchNull(WriteableCommandLine cl, Option o) { return methodSwitch(cl, o, null); } private Object methodSwitchOff(WriteableCommandLine cl, Option o) { return methodSwitch(cl, o, Boolean.FALSE); } private Object methodSwitchOn(WriteableCommandLine cl, Option o) { return methodSwitch(cl, o, Boolean.TRUE); } private Object methodValueMissing(WriteableCommandLine cl, Option o) { return cl.getValue(o); } private Object methodValuePresent(WriteableCommandLine cl, Option o) { return cl.getValue(o, "method"); } /* * utils to grab the default from the option model */ private Option optionSwitch(Boolean bool) { return new SwitchBuilder().withName("switch").withSwitchDefault(bool) .create(); } private Option optionSwitchNull() { return optionSwitch(null); } private Option optionSwitchOff() { return optionSwitch(Boolean.FALSE); } private Option optionSwitchOn() { return optionSwitch(Boolean.TRUE); } private Option optionValueMissing() { return new ArgumentBuilder().create(); } private Option optionValuePresent() { return new ArgumentBuilder().withDefaults( Arrays.asList(new String[] { "option" })).create(); } /* * utils to grab the input from the command line */ private WriteableCommandLine parsedSwitch(Option o, Boolean bool) { final List args; if (bool == null) { args = Collections.EMPTY_LIST; } else { args = Collections .singletonList(String.valueOf(bool).toLowerCase()); } WriteableCommandLine cl = new WriteableCommandLineImpl(o, args); o.defaults(cl); if (bool != null) { cl.addSwitch(o, bool.booleanValue()); } return cl; } private WriteableCommandLine parsedSwitchNull(Option o) { return parsedSwitch(o, null); } private WriteableCommandLine parsedSwitchOn(Option o) { return parsedSwitch(o, Boolean.TRUE); } private WriteableCommandLine parsedValueMissing(Option o) { WriteableCommandLine cl = new WriteableCommandLineImpl(o, Collections.EMPTY_LIST); o.defaults(cl); return cl; } private WriteableCommandLine parsedValuePresent(Option o) { WriteableCommandLine cl = new WriteableCommandLineImpl(o, Arrays .asList(new String[] { "parsed" })); o.defaults(cl); cl.addValue(o, "parsed"); return cl; } /* * tests */ public void testSwitch_Method() { final Option o = optionSwitchNull(); final WriteableCommandLine cl = parsedSwitchNull(o); final Object v = methodSwitchOn(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Method_Option() { final Option o = optionSwitchOff(); final WriteableCommandLine cl = parsedSwitchNull(o); final Object v = methodSwitchOn(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Option() { final Option o = optionSwitchOn(); final WriteableCommandLine cl = parsedSwitchNull(o); final Object v = methodSwitchNull(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Parsed() { final Option o = optionSwitchNull(); final WriteableCommandLine cl = parsedSwitchOn(o); final Object v = methodSwitchNull(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Parsed_Method() { final Option o = optionSwitchOff(); final WriteableCommandLine cl = parsedSwitchOn(o); final Object v = methodSwitchNull(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Parsed_Method_Option() { final Option o = optionSwitchOff(); final WriteableCommandLine cl = parsedSwitchOn(o); final Object v = methodSwitchOff(cl, o); assertEquals(Boolean.TRUE, v); } public void testSwitch_Parsed_Option() { final Option o = optionSwitchOff(); final WriteableCommandLine cl = parsedSwitchOn(o); final Object v = methodSwitchNull(cl, o); assertEquals(Boolean.TRUE, v); } public void testValues() { final Option o = optionValueMissing(); final WriteableCommandLine cl = parsedValueMissing(o); final Object v = methodValueMissing(cl, o); assertNull(v); } public void testValues_Method() { final Option o = optionValueMissing(); final WriteableCommandLine cl = parsedValueMissing(o); final Object v = methodValuePresent(cl, o); assertEquals("method", v); } public void testValues_Method_Option() { final Option o = optionValuePresent(); final WriteableCommandLine cl = parsedValueMissing(o); final Object v = methodValuePresent(cl, o); assertEquals("method", v); } public void testValues_Option() { final Option o = optionValuePresent(); final WriteableCommandLine cl = parsedValueMissing(o); final Object v = methodValueMissing(cl, o); assertEquals("option", v); } public void testValues_Parsed() { final Option o = optionValueMissing(); final WriteableCommandLine cl = parsedValuePresent(o); final Object v = methodValueMissing(cl, o); assertEquals("parsed", v); } public void testValues_Parsed_Method() { final Option o = optionValueMissing(); final WriteableCommandLine cl = parsedValuePresent(o); final Object v = methodValuePresent(cl, o); assertEquals("parsed", v); } public void testValues_Parsed_Method_Option() { final Option o = optionValuePresent(); final WriteableCommandLine cl = parsedValuePresent(o); final Object v = methodValuePresent(cl, o); assertEquals("parsed", v); } public void testValues_Parsed_Option() { final Option o = optionValuePresent(); final WriteableCommandLine cl = parsedValuePresent(o); final Object v = methodValueMissing(cl, o); assertEquals("parsed", v); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.SwitchBuilder; +import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; + +/** + * Tests the interaction of command line values and defaults supplied in different ways. + * + * Tests marked _Parsed involve values parsed from a command line. + * + * Tests marked _Method involve defaults supplied in the query method. + * + * Tests marked _Option involce defaults specified in the model. + * + * @author Rob Oxspring + */ +public class CommandLineDefaultsTest extends TestCase { + + /* + * utils to grab the default from the method + */ + + private Object methodSwitch(WriteableCommandLine cl, Option o, Boolean bool) { + return cl.getSwitch(o, bool); + } + + private Object methodSwitchNull(WriteableCommandLine cl, Option o) { + return methodSwitch(cl, o, null); + } + + private Object methodSwitchOff(WriteableCommandLine cl, Option o) { + return methodSwitch(cl, o, Boolean.FALSE); + } + + private Object methodSwitchOn(WriteableCommandLine cl, Option o) { + return methodSwitch(cl, o, Boolean.TRUE); + } + + private Object methodValueMissing(WriteableCommandLine cl, Option o) { + return cl.getValue(o); + } + + private Object methodValuePresent(WriteableCommandLine cl, Option o) { + return cl.getValue(o, "method"); + } + + /* + * utils to grab the default from the option model + */ + + private Option optionSwitch(Boolean bool) { + return new SwitchBuilder().withName("switch").withSwitchDefault(bool) + .create(); + } + + private Option optionSwitchNull() { + return optionSwitch(null); + } + + private Option optionSwitchOff() { + return optionSwitch(Boolean.FALSE); + } + + private Option optionSwitchOn() { + return optionSwitch(Boolean.TRUE); + } + + private Option optionValueMissing() { + return new ArgumentBuilder().create(); + } + + private Option optionValuePresent() { + return new ArgumentBuilder().withDefaults( + Arrays.asList(new String[] { "option" })).create(); + } + + /* + * utils to grab the input from the command line + */ + + private WriteableCommandLine parsedSwitch(Option o, Boolean bool) { + final List args; + if (bool == null) { + args = Collections.EMPTY_LIST; + } else { + args = Collections + .singletonList(String.valueOf(bool).toLowerCase()); + } + WriteableCommandLine cl = new WriteableCommandLineImpl(o, args); + o.defaults(cl); + if (bool != null) { + cl.addSwitch(o, bool.booleanValue()); + } + return cl; + } + + private WriteableCommandLine parsedSwitchNull(Option o) { + return parsedSwitch(o, null); + } + + private WriteableCommandLine parsedSwitchOn(Option o) { + return parsedSwitch(o, Boolean.TRUE); + } + + private WriteableCommandLine parsedValueMissing(Option o) { + WriteableCommandLine cl = new WriteableCommandLineImpl(o, + Collections.EMPTY_LIST); + o.defaults(cl); + return cl; + } + + private WriteableCommandLine parsedValuePresent(Option o) { + WriteableCommandLine cl = new WriteableCommandLineImpl(o, Arrays + .asList(new String[] { "parsed" })); + o.defaults(cl); + cl.addValue(o, "parsed"); + return cl; + } + + /* + * tests + */ + + public void testSwitch_Method() { + final Option o = optionSwitchNull(); + final WriteableCommandLine cl = parsedSwitchNull(o); + final Object v = methodSwitchOn(cl, o); + assertEquals(Boolean.TRUE, v); + } + + public void testSwitch_Method_Option() { + final Option o = optionSwitchOff(); + final WriteableCommandLine cl = parsedSwitchNull(o); + final Object v = methodSwitchOn(cl, o); + assertEquals(Boolean.TRUE, v); + } + + public void testSwitch_Option() { + final Option o = optionSwitchOn(); + final WriteableCommandLine cl = parsedSwitchNull(o); + final Object v = methodSwitchNull(cl, o); + assertEquals(Boolean.TRUE, v); + } + + public void testSwitch_Parsed() { + final Option o = optionSwitchNull(); + final WriteableCommandLine cl = parsedSwitchOn(o); + final Object v = methodSwitchNull(cl, o); + assertEquals(Boolean.TRUE, v); + } + + public void testSwitch_Parsed_Method() { + final Option o = optionSwitchOff(); + final WriteableCommandLine cl = parsedSwitchOn(o); + final Object v = methodSwitchNull(cl, o); + assertEquals(Boolean.TRUE, v); + } + + public void testSwitch_Parsed_Method_Option() { + final Option o = optionSwitchOff(); + final WriteableCommandLine cl = parsedSwitchOn(o); + final Object v = methodSwitchOff(cl, o); + assertEquals(Boolean.TRUE, v); + } + + public void testSwitch_Parsed_Option() { + final Option o = optionSwitchOff(); + final WriteableCommandLine cl = parsedSwitchOn(o); + final Object v = methodSwitchNull(cl, o); + assertEquals(Boolean.TRUE, v); + } + + public void testValues() { + final Option o = optionValueMissing(); + final WriteableCommandLine cl = parsedValueMissing(o); + final Object v = methodValueMissing(cl, o); + assertNull(v); + } + + public void testValues_Method() { + final Option o = optionValueMissing(); + final WriteableCommandLine cl = parsedValueMissing(o); + final Object v = methodValuePresent(cl, o); + assertEquals("method", v); + } + + public void testValues_Method_Option() { + final Option o = optionValuePresent(); + final WriteableCommandLine cl = parsedValueMissing(o); + final Object v = methodValuePresent(cl, o); + assertEquals("method", v); + } + + public void testValues_Option() { + final Option o = optionValuePresent(); + final WriteableCommandLine cl = parsedValueMissing(o); + final Object v = methodValueMissing(cl, o); + assertEquals("option", v); + } + + public void testValues_Parsed() { + final Option o = optionValueMissing(); + final WriteableCommandLine cl = parsedValuePresent(o); + final Object v = methodValueMissing(cl, o); + assertEquals("parsed", v); + } + + public void testValues_Parsed_Method() { + final Option o = optionValueMissing(); + final WriteableCommandLine cl = parsedValuePresent(o); + final Object v = methodValuePresent(cl, o); + assertEquals("parsed", v); + } + + public void testValues_Parsed_Method_Option() { + final Option o = optionValuePresent(); + final WriteableCommandLine cl = parsedValuePresent(o); + final Object v = methodValuePresent(cl, o); + assertEquals("parsed", v); + } + + public void testValues_Parsed_Option() { + final Option o = optionValuePresent(); + final WriteableCommandLine cl = parsedValuePresent(o); + final Object v = methodValueMissing(cl, o); + assertEquals("parsed", v); + } +} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/CommandLineTestCase.java b/src/test/org/apache/commons/cli2/CommandLineTestCase.java index 92398a00b..07b2009b2 100644 --- a/src/test/org/apache/commons/cli2/CommandLineTestCase.java +++ b/src/test/org/apache/commons/cli2/CommandLineTestCase.java @@ -1 +1,512 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Collections;import java.util.Iterator;import java.util.List;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.option.ArgumentTest;import org.apache.commons.cli2.option.CommandTest;import org.apache.commons.cli2.option.DefaultOptionTest;import org.apache.commons.cli2.option.OptionTestCase;import org.apache.commons.cli2.option.PropertyOption;import org.apache.commons.cli2.option.SwitchTest;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;public abstract class CommandLineTestCase extends CLITestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); public final Option present = new DefaultOptionBuilder().withLongName("present").withLongName("alsopresent").create(); public final Option missing = new DefaultOptionBuilder().withLongName("missing").create(); public final Option multiple = new DefaultOptionBuilder().withLongName("multiple").create(); public final Option bool = new DefaultOptionBuilder().withLongName("bool").create(); public final Option root = new GroupBuilder().withOption(present).withOption(missing).withOption(multiple) .withOption(bool).create(); private CommandLine commandLine; protected abstract CommandLine createCommandLine(); /* * @see TestCase#setUp() */ public void setUp() throws Exception { super.setUp(); commandLine = createCommandLine(); } /* * Class to test for boolean hasOption(String) */ public final void testHasOptionString() { assertTrue(commandLine.hasOption("--present")); assertTrue(commandLine.hasOption("--alsopresent")); assertFalse(commandLine.hasOption("--missing")); } /* * Class to test for boolean hasOption(Option) */ public final void testHasOptionOption() { assertTrue(commandLine.hasOption(present)); assertFalse(commandLine.hasOption(missing)); } public final void testGetOption() { assertSame(present, commandLine.getOption("--present")); assertSame(present, commandLine.getOption("--alsopresent")); //TODO decide whether the following assertion is valid //assertSame(missing,commandLine.getOption("--missing")); } /* * Class to test for List getValues(String) */ public final void testGetValuesString() { assertListContentsEqual(list("present value"), commandLine.getValues("--present")); assertListContentsEqual(list("value 1", "value 2", "value 3"), commandLine.getValues("--multiple")); assertTrue(commandLine.getValues("--missing").isEmpty()); } /* * Class to test for List getValues(String, List) */ public final void testGetValuesStringList() { assertListContentsEqual(list("present value"), commandLine.getValues("--present", null)); assertListContentsEqual(list("present value"), commandLine.getValues("--alsopresent", null)); assertSame(commandLine.getValues("--missing", Collections.EMPTY_LIST), Collections.EMPTY_LIST); final List def = Collections.singletonList("default value"); assertSame(def, commandLine.getValues("--missing", def)); } /* * Class to test for List getValues(Option) */ public final void testGetValuesOption() { assertListContentsEqual(list("present value"), commandLine.getValues(present)); assertTrue(commandLine.getValues(missing).isEmpty()); } /* * Class to test for List getValues(Option, List) */ public final void testGetValuesOptionList() { assertListContentsEqual(list("present value"), commandLine.getValues(present)); assertSame(commandLine.getValues(missing, Collections.EMPTY_LIST), Collections.EMPTY_LIST); final List defs = Collections.singletonList("custom default"); assertSame(defs, commandLine.getValues(missing, defs)); } /* * Class to test for Object getValue(String) */ public final void testGetValueString() { assertEquals("present value", commandLine.getValue("--present")); assertEquals("present value", commandLine.getValue("--alsopresent")); assertNull(commandLine.getValue("--missing")); try { commandLine.getValue("--multiple"); fail("expected IllegalStateException"); } catch (IllegalStateException e) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), e.getMessage()); } } /* * Class to test for Object getValue(String, Object) */ public final void testGetValueStringObject() { assertEquals("present value", commandLine.getValue("--present", "default value")); assertEquals("present value", commandLine.getValue("--alsopresent", "default value")); assertEquals("default value", commandLine.getValue("--missing", "default value")); try { commandLine.getValue("--multiple"); fail("expected IllegalStateException"); } catch (IllegalStateException e) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), e.getMessage()); } } /* * Class to test for Object getValue(Option) */ public final void testGetValueOption() { assertEquals("present value", commandLine.getValue(present)); assertNull(commandLine.getValue(missing)); try { commandLine.getValue(multiple); fail("expected IllegalStateException"); } catch (IllegalStateException e) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), e.getMessage()); } } /* * Class to test for Object getValue(Option, Object) */ public final void testGetValueOptionObject() { assertEquals("present value", commandLine.getValue(present, "default value")); assertEquals("default value", commandLine.getValue(missing, "default value")); try { commandLine.getValue(multiple); fail("expected IllegalStateException"); } catch (IllegalStateException e) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), e.getMessage()); } } /* * Class to test for Boolean getSwitch(String) */ public final void testGetSwitchString() { assertEquals(Boolean.TRUE, commandLine.getSwitch("--bool")); assertNull(commandLine.getSwitch("--missing")); } /* * Class to test for Boolean getSwitch(String, Boolean) */ public final void testGetSwitchStringBoolean() { assertEquals(Boolean.TRUE, commandLine.getSwitch("--bool", Boolean.FALSE)); assertEquals(Boolean.FALSE, commandLine.getSwitch("--missing", Boolean.FALSE)); } /* * Class to test for Boolean getSwitch(Option) */ public final void testGetSwitchOption() { assertEquals(Boolean.TRUE, commandLine.getSwitch(bool)); assertNull(commandLine.getSwitch(missing)); } /* * Class to test for Boolean getSwitch(Option, Boolean) */ public final void testGetSwitchOptionBoolean() { assertEquals(Boolean.TRUE, commandLine.getSwitch(bool, Boolean.FALSE)); assertEquals(Boolean.FALSE, commandLine.getSwitch(missing, Boolean.FALSE)); } /* * Class to test for String getProperty(String) */ public final void testGetPropertyString() { assertEquals("present property", commandLine.getProperty("present")); assertNull(commandLine.getProperty("missing")); } /* * Class to test for String getProperty(String, String) */ public final void testGetPropertyStringString() { assertEquals("present property", commandLine.getProperty("present", "default property")); assertEquals("default property", commandLine.getProperty("missing", "default property")); } public final void testGetProperties() { assertTrue(commandLine.getProperties().containsAll(list("present"))); } /* * Class to test for int getOptionCount(String) */ public final void testGetOptionCountString() { // one option, one switch assertTrue(1 <= commandLine.getOptionCount("--present")); assertTrue(1 <= commandLine.getOptionCount("--bool")); assertEquals(0, commandLine.getOptionCount("--missing")); } /* * Class to test for int getOptionCount(Option) */ public final void testGetOptionCountOption() { // one option, one switch assertTrue(1 <= commandLine.getOptionCount(present)); assertTrue(1 <= commandLine.getOptionCount(bool)); assertEquals(0, commandLine.getOptionCount(missing)); } public final void testGetOptions() { //TODO Implement getOptions(). } public final void testGetOptionTriggers() { //TODO Implement getOptionTriggers(). } // OLD TESTS FOLLOW public final void testProperties() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); assertTrue(writeable.getProperties().isEmpty()); writeable.addProperty("myprop", "myval"); assertEquals(1, writeable.getProperties().size()); assertEquals("myval", writeable.getProperty("myprop")); writeable.addProperty("myprop", "myval2"); assertEquals(1, writeable.getProperties().size()); assertEquals("myval2", writeable.getProperty("myprop")); writeable.addProperty("myprop2", "myval3"); assertEquals(2, writeable.getProperties().size()); assertEquals("myval3", writeable.getProperty("myprop2")); } public final void testOptions() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); final Option start = CommandTest.buildStartCommand(); assertFalse(writeable.hasOption(start)); assertFalse(writeable.hasOption("start")); assertFalse(writeable.hasOption("go")); writeable.addOption(start); assertTrue(writeable.hasOption(start)); assertTrue(writeable.hasOption("start")); assertTrue(writeable.hasOption("go")); } public final void testValues() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); final Option start = CommandTest.buildStartCommand(); assertNull(writeable.getValue(start)); assertTrue(writeable.getValues(start).isEmpty()); writeable.addOption(start); assertTrue(writeable.getValues(start).isEmpty()); writeable.addValue(start, "file1"); assertEquals("file1", writeable.getValue(start)); assertEquals("file1", writeable.getValue("start")); assertEquals("file1", writeable.getValue("go")); assertEquals(1, writeable.getValues(start).size()); assertEquals(1, writeable.getValues("start").size()); assertEquals(1, writeable.getValues("go").size()); assertTrue(writeable.getValues(start).contains("file1")); assertTrue(writeable.getValues("start").contains("file1")); assertTrue(writeable.getValues("go").contains("file1")); writeable.addValue(start, "file2"); try { writeable.getValue(start); fail("Cannot get single value if multiple are present"); } catch (IllegalStateException ise) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), ise.getMessage()); } try { writeable.getValue("start"); fail("Cannot get single value if multiple are present"); } catch (IllegalStateException ise) { assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), ise.getMessage()); } writeable.getValues(start).add("file3"); } public final void testSwitches() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); final Option start = CommandTest.buildStartCommand(); assertNull(writeable.getSwitch(start)); assertNull(writeable.getSwitch("start")); assertNull(writeable.getSwitch("go")); writeable.addSwitch(start, true); try { writeable.addSwitch(start, false); fail("Switch cannot be changed"); } catch (IllegalStateException ise) { assertEquals(resources.getMessage(ResourceConstants.SWITCH_ALREADY_SET), ise.getMessage()); } } public final void testSwitches_True() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); final Option start = CommandTest.buildStartCommand(); writeable.addSwitch(start, true); assertSame(Boolean.TRUE, writeable.getSwitch(start)); } public final void testSwitches_False() { final Option option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); final Option start = CommandTest.buildStartCommand(); writeable.addSwitch(start, false); assertSame(Boolean.FALSE, writeable.getSwitch(start)); } // public final void testLooksLikeOption() { // final Option option = new PropertyOption(); // final List args = OptionTestCase.list(); // final WriteableCommandLine commandLine = // OptionTestCase.commandLine(option, args); // // assertTrue(commandLine.looksLikeOption("-D")); // assertFalse(commandLine.looksLikeOption("--help")); // assertFalse(commandLine.looksLikeOption("+display")); // assertFalse(commandLine.looksLikeOption("myprefix")); // assertFalse(commandLine.looksLikeOption("myprefix2")); // assertFalse(commandLine.looksLikeOption("myprefference")); // assertFalse(commandLine.looksLikeOption("/SCANDISK")); // assertFalse(commandLine.looksLikeOption("update")); // } public final void testGetOptions_Order() throws OptionException { final Option help = DefaultOptionTest.buildHelpOption(); final Option login = CommandTest.buildLoginCommand(); final Option targets = ArgumentTest.buildTargetsArgument(); final Group group = new GroupBuilder().withOption(help).withOption(login).withOption(targets).create(); final Parser parser = new Parser(); parser.setGroup(group); final CommandLine cl = parser.parse(new String[] { "login", "rob", "--help", "target1", "target2" }); final Iterator i = cl.getOptions().iterator(); assertSame(login, i.next()); assertSame(help, i.next()); assertSame(targets, i.next()); assertSame(targets, i.next()); assertFalse(i.hasNext()); } public final void testGetOptionCount() throws OptionException { final Option help = DefaultOptionTest.buildHelpOption(); final Option login = CommandTest.buildLoginCommand(); final Option targets = ArgumentTest.buildTargetsArgument(); final Option display = SwitchTest.buildDisplaySwitch(); final Group group = new GroupBuilder().withOption(help).withOption(login).withOption(targets) .withOption(display).create(); final Parser parser = new Parser(); parser.setGroup(group); final CommandLine cl = parser.parse(new String[] { "--help", "login", "rob", "+display", "--help", "--help", "target1", "target2" }); assertEquals(1, cl.getOptionCount(login)); assertEquals(3, cl.getOptionCount(help)); assertEquals(2, cl.getOptionCount(targets)); assertEquals(1, cl.getOptionCount(display)); } public final void testGetOptionCount_Strings() throws OptionException { final Option help = DefaultOptionTest.buildHelpOption(); final Option login = CommandTest.buildLoginCommand(); final Option targets = ArgumentTest.buildTargetsArgument(); final Option display = SwitchTest.buildDisplaySwitch(); final Group group = new GroupBuilder().withOption(help).withOption(login).withOption(targets) .withOption(display).create(); final Parser parser = new Parser(); parser.setGroup(group); final CommandLine cl = parser.parse(new String[] { "--help", "login", "rob", "+display", "--help", "--help", "target1", "target2" }); assertEquals(1, cl.getOptionCount("login")); assertEquals(3, cl.getOptionCount("-?")); assertEquals(1, cl.getOptionCount("+display")); } public final void testOptionAsArgument() throws OptionException { final Option p = new DefaultOptionBuilder().withShortName("p").create(); final Argument argument = new ArgumentBuilder().create(); final Option withArgument = new DefaultOptionBuilder().withShortName("attr").withArgument(argument).create(); final Group group = new GroupBuilder().withOption(p).withOption(withArgument).create(); final Parser parser = new Parser(); parser.setGroup(group); final CommandLine cl = parser.parse(new String[] { "-p", "-attr", "p" }); assertEquals(1, cl.getOptionCount("-p")); assertTrue(cl.hasOption("-p")); assertTrue(cl.hasOption("-attr")); assertTrue(cl.getValue("-attr").equals("p")); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.option.ArgumentTest; +import org.apache.commons.cli2.option.CommandTest; +import org.apache.commons.cli2.option.DefaultOptionTest; +import org.apache.commons.cli2.option.OptionTestCase; +import org.apache.commons.cli2.option.PropertyOption; +import org.apache.commons.cli2.option.SwitchTest; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +public abstract class CommandLineTestCase + extends CLITestCase { + private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); + public final Option present = + new DefaultOptionBuilder().withLongName("present").withLongName("alsopresent").create(); + public final Option missing = new DefaultOptionBuilder().withLongName("missing").create(); + public final Option multiple = new DefaultOptionBuilder().withLongName("multiple").create(); + public final Option bool = new DefaultOptionBuilder().withLongName("bool").create(); + public final Option root = + new GroupBuilder().withOption(present).withOption(missing).withOption(multiple) + .withOption(bool).create(); + private CommandLine commandLine; + + protected abstract CommandLine createCommandLine(); + + /* + * @see TestCase#setUp() + */ + public void setUp() + throws Exception { + super.setUp(); + commandLine = createCommandLine(); + } + + /* + * Class to test for boolean hasOption(String) + */ + public final void testHasOptionString() { + assertTrue(commandLine.hasOption("--present")); + assertTrue(commandLine.hasOption("--alsopresent")); + assertFalse(commandLine.hasOption("--missing")); + } + + /* + * Class to test for boolean hasOption(Option) + */ + public final void testHasOptionOption() { + assertTrue(commandLine.hasOption(present)); + assertFalse(commandLine.hasOption(missing)); + } + + public final void testGetOption() { + assertSame(present, commandLine.getOption("--present")); + assertSame(present, commandLine.getOption("--alsopresent")); + + //TODO decide whether the following assertion is valid + //assertSame(missing,commandLine.getOption("--missing")); + } + + /* + * Class to test for List getValues(String) + */ + public final void testGetValuesString() { + assertListContentsEqual(list("present value"), commandLine.getValues("--present")); + assertListContentsEqual(list("value 1", "value 2", "value 3"), + commandLine.getValues("--multiple")); + assertTrue(commandLine.getValues("--missing").isEmpty()); + } + + /* + * Class to test for List getValues(String, List) + */ + public final void testGetValuesStringList() { + assertListContentsEqual(list("present value"), commandLine.getValues("--present", null)); + assertListContentsEqual(list("present value"), commandLine.getValues("--alsopresent", null)); + assertSame(commandLine.getValues("--missing", Collections.EMPTY_LIST), + Collections.EMPTY_LIST); + + final List def = Collections.singletonList("default value"); + assertSame(def, commandLine.getValues("--missing", def)); + } + + /* + * Class to test for List getValues(Option) + */ + public final void testGetValuesOption() { + assertListContentsEqual(list("present value"), commandLine.getValues(present)); + assertTrue(commandLine.getValues(missing).isEmpty()); + } + + /* + * Class to test for List getValues(Option, List) + */ + public final void testGetValuesOptionList() { + assertListContentsEqual(list("present value"), commandLine.getValues(present)); + assertSame(commandLine.getValues(missing, Collections.EMPTY_LIST), Collections.EMPTY_LIST); + + final List defs = Collections.singletonList("custom default"); + assertSame(defs, commandLine.getValues(missing, defs)); + } + + /* + * Class to test for Object getValue(String) + */ + public final void testGetValueString() { + assertEquals("present value", commandLine.getValue("--present")); + assertEquals("present value", commandLine.getValue("--alsopresent")); + assertNull(commandLine.getValue("--missing")); + + try { + commandLine.getValue("--multiple"); + fail("expected IllegalStateException"); + } catch (IllegalStateException e) { + assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), + e.getMessage()); + } + } + + /* + * Class to test for Object getValue(String, Object) + */ + public final void testGetValueStringObject() { + assertEquals("present value", commandLine.getValue("--present", "default value")); + assertEquals("present value", commandLine.getValue("--alsopresent", "default value")); + assertEquals("default value", commandLine.getValue("--missing", "default value")); + + try { + commandLine.getValue("--multiple"); + fail("expected IllegalStateException"); + } catch (IllegalStateException e) { + assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), + e.getMessage()); + } + } + + /* + * Class to test for Object getValue(Option) + */ + public final void testGetValueOption() { + assertEquals("present value", commandLine.getValue(present)); + assertNull(commandLine.getValue(missing)); + + try { + commandLine.getValue(multiple); + fail("expected IllegalStateException"); + } catch (IllegalStateException e) { + assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), + e.getMessage()); + } + } + + /* + * Class to test for Object getValue(Option, Object) + */ + public final void testGetValueOptionObject() { + assertEquals("present value", commandLine.getValue(present, "default value")); + assertEquals("default value", commandLine.getValue(missing, "default value")); + + try { + commandLine.getValue(multiple); + fail("expected IllegalStateException"); + } catch (IllegalStateException e) { + assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), + e.getMessage()); + } + } + + /* + * Class to test for Boolean getSwitch(String) + */ + public final void testGetSwitchString() { + assertEquals(Boolean.TRUE, commandLine.getSwitch("--bool")); + assertNull(commandLine.getSwitch("--missing")); + } + + /* + * Class to test for Boolean getSwitch(String, Boolean) + */ + public final void testGetSwitchStringBoolean() { + assertEquals(Boolean.TRUE, commandLine.getSwitch("--bool", Boolean.FALSE)); + assertEquals(Boolean.FALSE, commandLine.getSwitch("--missing", Boolean.FALSE)); + } + + /* + * Class to test for Boolean getSwitch(Option) + */ + public final void testGetSwitchOption() { + assertEquals(Boolean.TRUE, commandLine.getSwitch(bool)); + assertNull(commandLine.getSwitch(missing)); + } + + /* + * Class to test for Boolean getSwitch(Option, Boolean) + */ + public final void testGetSwitchOptionBoolean() { + assertEquals(Boolean.TRUE, commandLine.getSwitch(bool, Boolean.FALSE)); + assertEquals(Boolean.FALSE, commandLine.getSwitch(missing, Boolean.FALSE)); + } + + /* + * Class to test for String getProperty(String) + */ + public final void testGetPropertyString() { + assertEquals("present property", commandLine.getProperty("present")); + assertNull(commandLine.getProperty("missing")); + } + + /* + * Class to test for String getProperty(String, String) + */ + public final void testGetPropertyStringString() { + assertEquals("present property", commandLine.getProperty("present", "default property")); + assertEquals("default property", commandLine.getProperty("missing", "default property")); + } + + public final void testGetProperties() { + assertTrue(commandLine.getProperties().containsAll(list("present"))); + } + + /* + * Class to test for int getOptionCount(String) + */ + public final void testGetOptionCountString() { + // one option, one switch + assertTrue(1 <= commandLine.getOptionCount("--present")); + assertTrue(1 <= commandLine.getOptionCount("--bool")); + assertEquals(0, commandLine.getOptionCount("--missing")); + } + + /* + * Class to test for int getOptionCount(Option) + */ + public final void testGetOptionCountOption() { + // one option, one switch + assertTrue(1 <= commandLine.getOptionCount(present)); + assertTrue(1 <= commandLine.getOptionCount(bool)); + assertEquals(0, commandLine.getOptionCount(missing)); + } + + public final void testGetOptions() { + //TODO Implement getOptions(). + } + + public final void testGetOptionTriggers() { + //TODO Implement getOptionTriggers(). + } + + // OLD TESTS FOLLOW + public final void testProperties() { + final Option option = new PropertyOption(); + final List args = CLITestCase.list(); + final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); + + assertTrue(writeable.getProperties().isEmpty()); + + writeable.addProperty("myprop", "myval"); + assertEquals(1, writeable.getProperties().size()); + assertEquals("myval", writeable.getProperty("myprop")); + + writeable.addProperty("myprop", "myval2"); + assertEquals(1, writeable.getProperties().size()); + assertEquals("myval2", writeable.getProperty("myprop")); + + writeable.addProperty("myprop2", "myval3"); + assertEquals(2, writeable.getProperties().size()); + assertEquals("myval3", writeable.getProperty("myprop2")); + } + + public final void testOptions() { + final Option option = new PropertyOption(); + final List args = CLITestCase.list(); + final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); + + final Option start = CommandTest.buildStartCommand(); + + assertFalse(writeable.hasOption(start)); + assertFalse(writeable.hasOption("start")); + assertFalse(writeable.hasOption("go")); + + writeable.addOption(start); + + assertTrue(writeable.hasOption(start)); + assertTrue(writeable.hasOption("start")); + assertTrue(writeable.hasOption("go")); + } + + public final void testValues() { + final Option option = new PropertyOption(); + final List args = CLITestCase.list(); + final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); + + final Option start = CommandTest.buildStartCommand(); + + assertNull(writeable.getValue(start)); + assertTrue(writeable.getValues(start).isEmpty()); + + writeable.addOption(start); + + assertTrue(writeable.getValues(start).isEmpty()); + + writeable.addValue(start, "file1"); + + assertEquals("file1", writeable.getValue(start)); + assertEquals("file1", writeable.getValue("start")); + assertEquals("file1", writeable.getValue("go")); + assertEquals(1, writeable.getValues(start).size()); + assertEquals(1, writeable.getValues("start").size()); + assertEquals(1, writeable.getValues("go").size()); + assertTrue(writeable.getValues(start).contains("file1")); + assertTrue(writeable.getValues("start").contains("file1")); + assertTrue(writeable.getValues("go").contains("file1")); + + writeable.addValue(start, "file2"); + + try { + writeable.getValue(start); + fail("Cannot get single value if multiple are present"); + } catch (IllegalStateException ise) { + assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), + ise.getMessage()); + } + + try { + writeable.getValue("start"); + fail("Cannot get single value if multiple are present"); + } catch (IllegalStateException ise) { + assertEquals(resources.getMessage(ResourceConstants.ARGUMENT_TOO_MANY_VALUES), + ise.getMessage()); + } + + writeable.getValues(start).add("file3"); + } + + public final void testSwitches() { + final Option option = new PropertyOption(); + final List args = CLITestCase.list(); + final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); + + final Option start = CommandTest.buildStartCommand(); + + assertNull(writeable.getSwitch(start)); + assertNull(writeable.getSwitch("start")); + assertNull(writeable.getSwitch("go")); + + writeable.addSwitch(start, true); + + try { + writeable.addSwitch(start, false); + fail("Switch cannot be changed"); + } catch (IllegalStateException ise) { + assertEquals(resources.getMessage(ResourceConstants.SWITCH_ALREADY_SET), + ise.getMessage()); + } + } + + public final void testSwitches_True() { + final Option option = new PropertyOption(); + final List args = CLITestCase.list(); + final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); + + final Option start = CommandTest.buildStartCommand(); + + writeable.addSwitch(start, true); + assertSame(Boolean.TRUE, writeable.getSwitch(start)); + } + + public final void testSwitches_False() { + final Option option = new PropertyOption(); + final List args = CLITestCase.list(); + final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); + + final Option start = CommandTest.buildStartCommand(); + + writeable.addSwitch(start, false); + assertSame(Boolean.FALSE, writeable.getSwitch(start)); + } + + // public final void testLooksLikeOption() { + // final Option option = new PropertyOption(); + // final List args = OptionTestCase.list(); + // final WriteableCommandLine commandLine = + // OptionTestCase.commandLine(option, args); + // + // assertTrue(commandLine.looksLikeOption("-D")); + // assertFalse(commandLine.looksLikeOption("--help")); + // assertFalse(commandLine.looksLikeOption("+display")); + // assertFalse(commandLine.looksLikeOption("myprefix")); + // assertFalse(commandLine.looksLikeOption("myprefix2")); + // assertFalse(commandLine.looksLikeOption("myprefference")); + // assertFalse(commandLine.looksLikeOption("/SCANDISK")); + // assertFalse(commandLine.looksLikeOption("update")); + // } + public final void testGetOptions_Order() + throws OptionException { + final Option help = DefaultOptionTest.buildHelpOption(); + final Option login = CommandTest.buildLoginCommand(); + final Option targets = ArgumentTest.buildTargetsArgument(); + + final Group group = + new GroupBuilder().withOption(help).withOption(login).withOption(targets).create(); + + final Parser parser = new Parser(); + parser.setGroup(group); + + final CommandLine cl = + parser.parse(new String[] { "login", "rob", "--help", "target1", "target2" }); + + final Iterator i = cl.getOptions().iterator(); + + assertSame(login, i.next()); + assertSame(help, i.next()); + assertSame(targets, i.next()); + assertSame(targets, i.next()); + assertFalse(i.hasNext()); + } + + public final void testGetOptionCount() + throws OptionException { + final Option help = DefaultOptionTest.buildHelpOption(); + final Option login = CommandTest.buildLoginCommand(); + final Option targets = ArgumentTest.buildTargetsArgument(); + final Option display = SwitchTest.buildDisplaySwitch(); + + final Group group = + new GroupBuilder().withOption(help).withOption(login).withOption(targets) + .withOption(display).create(); + + final Parser parser = new Parser(); + parser.setGroup(group); + + final CommandLine cl = + parser.parse(new String[] { + "--help", "login", "rob", "+display", "--help", "--help", "target1", + "target2" + }); + + assertEquals(1, cl.getOptionCount(login)); + assertEquals(3, cl.getOptionCount(help)); + assertEquals(2, cl.getOptionCount(targets)); + assertEquals(1, cl.getOptionCount(display)); + } + + public final void testGetOptionCount_Strings() + throws OptionException { + final Option help = DefaultOptionTest.buildHelpOption(); + final Option login = CommandTest.buildLoginCommand(); + final Option targets = ArgumentTest.buildTargetsArgument(); + final Option display = SwitchTest.buildDisplaySwitch(); + + final Group group = + new GroupBuilder().withOption(help).withOption(login).withOption(targets) + .withOption(display).create(); + + final Parser parser = new Parser(); + parser.setGroup(group); + + final CommandLine cl = + parser.parse(new String[] { + "--help", "login", "rob", "+display", "--help", "--help", "target1", + "target2" + }); + + assertEquals(1, cl.getOptionCount("login")); + assertEquals(3, cl.getOptionCount("-?")); + assertEquals(1, cl.getOptionCount("+display")); + } + + public final void testOptionAsArgument() + throws OptionException { + final Option p = new DefaultOptionBuilder().withShortName("p").create(); + final Argument argument = new ArgumentBuilder().create(); + final Option withArgument = + new DefaultOptionBuilder().withShortName("attr").withArgument(argument).create(); + + final Group group = new GroupBuilder().withOption(p).withOption(withArgument).create(); + + final Parser parser = new Parser(); + parser.setGroup(group); + + final CommandLine cl = parser.parse(new String[] { "-p", "-attr", "p" }); + + assertEquals(1, cl.getOptionCount("-p")); + assertTrue(cl.hasOption("-p")); + assertTrue(cl.hasOption("-attr")); + assertTrue(cl.getValue("-attr").equals("p")); + } +} diff --git a/src/test/org/apache/commons/cli2/DocumentationTest.java b/src/test/org/apache/commons/cli2/DocumentationTest.java index 0ab509e16..4b8fe13a1 100644 --- a/src/test/org/apache/commons/cli2/DocumentationTest.java +++ b/src/test/org/apache/commons/cli2/DocumentationTest.java @@ -1 +1,445 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.io.IOException;import java.io.PrintWriter;import java.io.StringWriter;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;import org.apache.commons.cli2.option.DefaultOption;import org.apache.commons.cli2.option.PropertyOption;import org.apache.commons.cli2.util.HelpFormatter;/** * @author Rob */public class DocumentationTest extends TestCase { public void testBasicUsage() throws IOException, OptionException { HelpFormatter helpFormatter = new HelpFormatter(); //ignore all printed helpFormatter.setPrintWriter(new PrintWriter(new StringWriter())); /* * --version -? -h --help -log file -s|-q|-v|-d Bursting File/Num/Date * validation Switches Commands Auto help Auto exception help * */ DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); Option version = obuilder .withLongName("version") .withDescription("Displays version information and then exits") .create(); Option help = obuilder .withShortName("h") .withShortName("?") .withLongName("help") .withDescription("Displays help on usage and then exits") .create(); ArgumentBuilder abuilder = new ArgumentBuilder(); Argument logFile = abuilder .withDescription("The log file to write to") .withName("file") .withMinimum(1) .withMaximum(1) .create(); Option log = obuilder .withArgument(logFile) .withShortName("log") .withDescription("Log progress information to a file") .create(); GroupBuilder gbuilder = new GroupBuilder(); Group outputQuality = gbuilder .withName("quality") .withDescription("Controls the quality of console output") .withMaximum(1) .withOption( obuilder .withShortName("s") .withDescription("Silent") .create()) .withOption( obuilder .withShortName("q") .withDescription("Quiet") .create()) .withOption( obuilder .withShortName("n") .withDescription("Normal") .create()) .withOption( obuilder .withShortName("v") .withDescription("Verbose") .create()) .withOption( obuilder .withShortName("d") .withDescription("Debug") .create()) .create(); Group options = new GroupBuilder() .withName("options") .withOption(version) .withOption(help) .withOption(log) .withOption(outputQuality) .create(); final String[] args = new String[] { "--bad-option" }; Parser parser = new Parser(); parser.setHelpFormatter(helpFormatter); parser.setGroup(options); parser.setHelpOption(help); CommandLine commandLine = parser.parseAndHelp(args); if (commandLine != null) { if (commandLine.hasOption(version)) { System.out.println("MyApp ver 1.0"); return; } if (commandLine.hasOption("-log")) { String filename = (String)commandLine.getValue("-log"); //... } } try { commandLine = parser.parse(args); fail("Unexpected Option!"); } catch (OptionException uoe) { assertEquals( "Unexpected --bad-option while processing options", uoe.getMessage()); } } public void testManualIntroduction() { DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); ArgumentBuilder aBuilder = new ArgumentBuilder(); GroupBuilder gBuilder = new GroupBuilder(); DefaultOption xmlOption = oBuilder .withLongName("xml") .withDescription("Output using xml format") .create(); Argument pathArgument = aBuilder .withName("path") .withMinimum(1) .withMaximum(1) .create(); Group outputChildren = gBuilder .withOption(xmlOption) .create(); Option outputOption = oBuilder .withLongName("output") .withDescription("Outputs to a file") .withArgument(pathArgument) .withChildren(outputChildren) .create(); /////////////////////////////////////////////////// Group options = outputChildren; HelpFormatter hf = new HelpFormatter(); Parser p = new Parser(); p.setGroup(options); p.setHelpFormatter(hf); p.setHelpTrigger("--help"); CommandLine cl = p.parseAndHelp(new String[]{}); if(cl==null) { System.exit(-1); } ////////////////////////////////////////////////// cl = new WriteableCommandLineImpl(outputChildren,new ArrayList()); // if we have --output option if(cl.hasOption("--output")) { // grab the path String path = (String)cl.getValue("--output"); // grab the format boolean xml = cl.hasOption("--xml"); // configure the application's output configureOutput(path,xml); } } private void configureOutput(String path, boolean xml) { // TODO Auto-generated method stub } public void testExampleAnt() throws IOException, OptionException { // Apache Ant version 1.6.1 compiled on February 12 2004 final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); Option help = obuilder .withShortName("help") .withShortName("h") .withDescription("print this message") .create(); Option projecthelp = obuilder .withShortName("projecthelp") .withShortName("p") .withDescription("print project help information") .create(); Option version = obuilder .withShortName("version") .withDescription("print the version information and exit") .create(); Option diagnostics = obuilder .withShortName("diagnostics") .withDescription("print information that might be helpful to diagnose or report problems.") .create(); Option quiet = obuilder .withShortName("quiet") .withShortName("q") .withDescription("be extra quiet") .create(); Option verbose = obuilder .withShortName("verbose") .withShortName("v") .withDescription("be extra verbose") .create(); Option debug = obuilder .withShortName("debug") .withShortName("d") .withDescription("print debugging information") .create(); Option emacs = obuilder .withShortName("emacs") .withShortName("e") .withDescription("produce logging information without adornments") .create(); Option lib = obuilder .withShortName("lib") .withDescription("specifies a path to search for jars and classes") .withArgument( abuilder .withName("path") .withMinimum(1) .withMaximum(1) .create()) .create(); Option logfile = obuilder .withShortName("logfile") .withShortName("l") .withDescription("use given file for log") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create(); Option logger = obuilder .withShortName("logger") .withDescription("the class which is to perform logging") .withArgument( abuilder .withName("classname") .withMinimum(1) .withMaximum(1) .create()) .create(); Option listener = obuilder .withShortName("listener") .withDescription("add an instance of class as a project listener") .withArgument( abuilder .withName("classname") .withMinimum(1) .withMaximum(1) .create()) .create(); Option noinput = obuilder .withShortName("noinput") .withDescription("do not allow interactive input") .create(); Option buildfile = obuilder .withShortName("buildfile") .withShortName("file") .withShortName("f") .withDescription("use given buildfile") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create(); Option property = new PropertyOption(); Option propertyfile = obuilder .withShortName("propertyfile") .withDescription("load all properties from file with -D properties taking precedence") .withArgument( abuilder .withName("name") .withMinimum(1) .withMaximum(1) .create()) .create(); Option inputhandler = obuilder .withShortName("inputhandler") .withDescription("the class which will handle input requests") .withArgument( abuilder .withName("class") .withMinimum(1) .withMaximum(1) .create()) .create(); Option find = obuilder .withShortName("find") .withShortName("s") .withDescription("search for buildfile towards the root of the filesystem and use it") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create(); Option targets = abuilder.withName("target").create(); Group options = gbuilder .withName("options") .withOption(help) .withOption(projecthelp) .withOption(version) .withOption(diagnostics) .withOption(quiet) .withOption(verbose) .withOption(debug) .withOption(emacs) .withOption(lib) .withOption(logfile) .withOption(logger) .withOption(listener) .withOption(noinput) .withOption(buildfile) .withOption(property) .withOption(propertyfile) .withOption(inputhandler) .withOption(find) .withOption(targets) .create(); ///////////////////////////////////// String[] args = new String[]{}; Parser parser = new Parser(); parser.setGroup(options); CommandLine cl = parser.parse(args); if(cl.hasOption(help)) { //displayHelp(); return; } if(cl.hasOption("-version")) { //displayVersion(); return; } if(cl.hasOption(logfile)) { String file = (String)cl.getValue(logfile); //setLogFile(); } List targetList = cl.getValues(targets); for (Iterator i = targetList.iterator(); i.hasNext();) { String target = (String) i.next(); //doTarget(target); } ///////////////////////////////////// HelpFormatter hf = new HelpFormatter(); hf.setShellCommand("ant"); hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_NAME); hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); hf.getFullUsageSettings().remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PROPERTY_OPTION); hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); hf.getDisplaySettings().remove(DisplaySetting.DISPLAY_GROUP_ARGUMENT); hf.setGroup(options); // redirect printed stuff to a string hf.setPrintWriter(new PrintWriter(new StringWriter())); hf.print(); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; +import org.apache.commons.cli2.option.DefaultOption; +import org.apache.commons.cli2.option.PropertyOption; +import org.apache.commons.cli2.util.HelpFormatter; + +/** + * @author Rob + */ +public class DocumentationTest extends TestCase { + + public void testBasicUsage() throws IOException, OptionException { + HelpFormatter helpFormatter = new HelpFormatter(); + //ignore all printed + helpFormatter.setPrintWriter(new PrintWriter(new StringWriter())); + + /* + * --version -? -h --help -log file -s|-q|-v|-d Bursting File/Num/Date + * validation Switches Commands Auto help Auto exception help + * + */ + DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + Option version = + obuilder + .withLongName("version") + .withDescription("Displays version information and then exits") + .create(); + + Option help = + obuilder + .withShortName("h") + .withShortName("?") + .withLongName("help") + .withDescription("Displays help on usage and then exits") + .create(); + + ArgumentBuilder abuilder = new ArgumentBuilder(); + Argument logFile = + abuilder + .withDescription("The log file to write to") + .withName("file") + .withMinimum(1) + .withMaximum(1) + .create(); + Option log = + obuilder + .withArgument(logFile) + .withShortName("log") + .withDescription("Log progress information to a file") + .create(); + + GroupBuilder gbuilder = new GroupBuilder(); + Group outputQuality = + gbuilder + .withName("quality") + .withDescription("Controls the quality of console output") + .withMaximum(1) + .withOption( + obuilder + .withShortName("s") + .withDescription("Silent") + .create()) + .withOption( + obuilder + .withShortName("q") + .withDescription("Quiet") + .create()) + .withOption( + obuilder + .withShortName("n") + .withDescription("Normal") + .create()) + .withOption( + obuilder + .withShortName("v") + .withDescription("Verbose") + .create()) + .withOption( + obuilder + .withShortName("d") + .withDescription("Debug") + .create()) + .create(); + + Group options = + new GroupBuilder() + .withName("options") + .withOption(version) + .withOption(help) + .withOption(log) + .withOption(outputQuality) + .create(); + + final String[] args = new String[] { "--bad-option" }; + + Parser parser = new Parser(); + parser.setHelpFormatter(helpFormatter); + parser.setGroup(options); + parser.setHelpOption(help); + CommandLine commandLine = parser.parseAndHelp(args); + if (commandLine != null) { + if (commandLine.hasOption(version)) { + System.out.println("MyApp ver 1.0"); + return; + } + if (commandLine.hasOption("-log")) { + String filename = (String)commandLine.getValue("-log"); + //... + } + } + + try { + commandLine = parser.parse(args); + fail("Unexpected Option!"); + } + catch (OptionException uoe) { + assertEquals( + "Unexpected --bad-option while processing options", + uoe.getMessage()); + } + } + + public void testManualIntroduction() { + + DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + ArgumentBuilder aBuilder = new ArgumentBuilder(); + GroupBuilder gBuilder = new GroupBuilder(); + + DefaultOption xmlOption = + oBuilder + .withLongName("xml") + .withDescription("Output using xml format") + .create(); + + Argument pathArgument = + aBuilder + .withName("path") + .withMinimum(1) + .withMaximum(1) + .create(); + + Group outputChildren = + gBuilder + .withOption(xmlOption) + .create(); + + Option outputOption = + oBuilder + .withLongName("output") + .withDescription("Outputs to a file") + .withArgument(pathArgument) + .withChildren(outputChildren) + .create(); + + /////////////////////////////////////////////////// + + Group options = outputChildren; + HelpFormatter hf = new HelpFormatter(); + + Parser p = new Parser(); + p.setGroup(options); + p.setHelpFormatter(hf); + p.setHelpTrigger("--help"); + CommandLine cl = p.parseAndHelp(new String[]{}); + if(cl==null) { + System.exit(-1); + } + + ////////////////////////////////////////////////// + + cl = new WriteableCommandLineImpl(outputChildren,new ArrayList()); + + // if we have --output option + if(cl.hasOption("--output")) { + // grab the path + String path = (String)cl.getValue("--output"); + // grab the format + boolean xml = cl.hasOption("--xml"); + // configure the application's output + configureOutput(path,xml); + } + + + + + } + + private void configureOutput(String path, boolean xml) { + // TODO Auto-generated method stub + + } + + public void testExampleAnt() throws IOException, OptionException { + // Apache Ant version 1.6.1 compiled on February 12 2004 + + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + + Option help = + obuilder + .withShortName("help") + .withShortName("h") + .withDescription("print this message") + .create(); + Option projecthelp = + obuilder + .withShortName("projecthelp") + .withShortName("p") + .withDescription("print project help information") + .create(); + Option version = + obuilder + .withShortName("version") + .withDescription("print the version information and exit") + .create(); + Option diagnostics = + obuilder + .withShortName("diagnostics") + .withDescription("print information that might be helpful to diagnose or report problems.") + .create(); + Option quiet = + obuilder + .withShortName("quiet") + .withShortName("q") + .withDescription("be extra quiet") + .create(); + Option verbose = + obuilder + .withShortName("verbose") + .withShortName("v") + .withDescription("be extra verbose") + .create(); + Option debug = + obuilder + .withShortName("debug") + .withShortName("d") + .withDescription("print debugging information") + .create(); + Option emacs = + obuilder + .withShortName("emacs") + .withShortName("e") + .withDescription("produce logging information without adornments") + .create(); + Option lib = + obuilder + .withShortName("lib") + .withDescription("specifies a path to search for jars and classes") + .withArgument( + abuilder + .withName("path") + .withMinimum(1) + .withMaximum(1) + .create()) + .create(); + Option logfile = + obuilder + .withShortName("logfile") + .withShortName("l") + .withDescription("use given file for log") + .withArgument( + abuilder + .withName("file") + .withMinimum(1) + .withMaximum(1) + .create()) + .create(); + Option logger = + obuilder + .withShortName("logger") + .withDescription("the class which is to perform logging") + .withArgument( + abuilder + .withName("classname") + .withMinimum(1) + .withMaximum(1) + .create()) + .create(); + Option listener = + obuilder + .withShortName("listener") + .withDescription("add an instance of class as a project listener") + .withArgument( + abuilder + .withName("classname") + .withMinimum(1) + .withMaximum(1) + .create()) + .create(); + Option noinput = + obuilder + .withShortName("noinput") + .withDescription("do not allow interactive input") + .create(); + Option buildfile = + obuilder + .withShortName("buildfile") + .withShortName("file") + .withShortName("f") + .withDescription("use given buildfile") + .withArgument( + abuilder + .withName("file") + .withMinimum(1) + .withMaximum(1) + .create()) + .create(); + Option property = new PropertyOption(); + Option propertyfile = + obuilder + .withShortName("propertyfile") + .withDescription("load all properties from file with -D properties taking precedence") + .withArgument( + abuilder + .withName("name") + .withMinimum(1) + .withMaximum(1) + .create()) + .create(); + Option inputhandler = + obuilder + .withShortName("inputhandler") + .withDescription("the class which will handle input requests") + .withArgument( + abuilder + .withName("class") + .withMinimum(1) + .withMaximum(1) + .create()) + .create(); + Option find = + obuilder + .withShortName("find") + .withShortName("s") + .withDescription("search for buildfile towards the root of the filesystem and use it") + .withArgument( + abuilder + .withName("file") + .withMinimum(1) + .withMaximum(1) + .create()) + .create(); + Option targets = abuilder.withName("target").create(); + + Group options = + gbuilder + .withName("options") + .withOption(help) + .withOption(projecthelp) + .withOption(version) + .withOption(diagnostics) + .withOption(quiet) + .withOption(verbose) + .withOption(debug) + .withOption(emacs) + .withOption(lib) + .withOption(logfile) + .withOption(logger) + .withOption(listener) + .withOption(noinput) + .withOption(buildfile) + .withOption(property) + .withOption(propertyfile) + .withOption(inputhandler) + .withOption(find) + .withOption(targets) + .create(); + + ///////////////////////////////////// + String[] args = new String[]{}; + + Parser parser = new Parser(); + parser.setGroup(options); + CommandLine cl = parser.parse(args); + + if(cl.hasOption(help)) { + //displayHelp(); + return; + } + if(cl.hasOption("-version")) { + //displayVersion(); + return; + } + if(cl.hasOption(logfile)) { + String file = (String)cl.getValue(logfile); + //setLogFile(); + } + List targetList = cl.getValues(targets); + for (Iterator i = targetList.iterator(); i.hasNext();) { + String target = (String) i.next(); + //doTarget(target); + } + + ///////////////////////////////////// + + HelpFormatter hf = new HelpFormatter(); + hf.setShellCommand("ant"); + hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_NAME); + hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); + hf.getFullUsageSettings().remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); + + hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PROPERTY_OPTION); + hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); + hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); + + hf.getDisplaySettings().remove(DisplaySetting.DISPLAY_GROUP_ARGUMENT); + + hf.setGroup(options); + // redirect printed stuff to a string + hf.setPrintWriter(new PrintWriter(new StringWriter())); + hf.print(); + + } +} diff --git a/src/test/org/apache/commons/cli2/PrecedenceTest.java b/src/test/org/apache/commons/cli2/PrecedenceTest.java index 8928f9b66..f2114afc8 100644 --- a/src/test/org/apache/commons/cli2/PrecedenceTest.java +++ b/src/test/org/apache/commons/cli2/PrecedenceTest.java @@ -1 +1,413 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import java.util.Arrays;import java.util.List;import java.util.Set;import junit.framework.TestCase;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;/** * @author Rob Oxspring */public class PrecedenceTest extends TestCase { private final String[] args = new String[] { "-file" }; public void testSimple() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final Group options = new GroupBuilder() .withOption(oBuilder.withShortName("file").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-file" }, cl); } public void testArgument() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group options = new GroupBuilder() .withOption( oBuilder .withShortName("f") .withArgument(aBuilder.create()) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void testBurst() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group options = gBuilder .withOption(oBuilder.withShortName("f").create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); } public void testChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group children = gBuilder .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final Group options = gBuilder .withOption( oBuilder .withShortName("f") .withChildren(children) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); } public void XtestSimpleVsArgument() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withArgument(aBuilder.create()) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void XtestSimpleVsBurst() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption(oBuilder.withShortName("f").create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); } public void XtestSimpleVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withChildren(children) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals( new String[] { "-f", "-i", "--ci", "-l", "--cl", "-e", "--ce" }, cl); } public void testArgumentVsBurst() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group options = gBuilder .withOption( oBuilder .withShortName("f") .withArgument(aBuilder.create()) .create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void testArgumentVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group children = gBuilder .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final Group options = gBuilder .withOption( oBuilder .withShortName("f") .withChildren(children) .withArgument(aBuilder.create()) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void testBurstVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption( oBuilder .withShortName("f") .withChildren(children) .create()) .withOption( oBuilder.withShortName("i").withLongName("bi").create()) .withOption( oBuilder.withShortName("l").withLongName("bl").create()) .withOption( oBuilder.withShortName("e").withLongName("be").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals( new String[] { "-f", "-i", "--ci", "-l", "--cl", "-e", "--ce" }, cl); } public void XtestSimpleVsArgumentVsBurst() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withArgument(aBuilder.create()) .create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void XtestSimpleVsArgumentVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withChildren(children) .withArgument(aBuilder.create()) .create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void XtestSimpleVsBurstVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withChildren(children) .create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); } public void testArgumentVsBurstVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption( oBuilder .withShortName("f") .withChildren(children) .withArgument(aBuilder.create()) .create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public void XtestSimpleVsArgumentVsBurstVsChildren() throws OptionException { final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); final GroupBuilder gBuilder = new GroupBuilder(); final ArgumentBuilder aBuilder = new ArgumentBuilder(); final Group children = gBuilder .withOption( oBuilder.withShortName("i").withLongName("ci").create()) .withOption( oBuilder.withShortName("l").withLongName("cl").create()) .withOption( oBuilder.withShortName("e").withLongName("ce").create()) .create(); final Group options = gBuilder .withOption(oBuilder.withShortName("file").create()) .withOption( oBuilder .withShortName("f") .withChildren(children) .withArgument(aBuilder.create()) .create()) .withOption(oBuilder.withShortName("i").create()) .withOption(oBuilder.withShortName("l").create()) .withOption(oBuilder.withShortName("e").create()) .create(); final CommandLine cl = buildCommandLine(options, args); assertEquals(new String[] { "-f" }, cl); } public CommandLine buildCommandLine(final Group group, final String[] arguments) throws OptionException { Parser p = new Parser(); p.setGroup(group); return p.parse(arguments); } public void assertEquals(final String options[], final CommandLine line) { final List expected = Arrays.asList(options); final Set actual = line.getOptionTriggers(); assertTrue(expected.containsAll(actual)); assertTrue(actual.containsAll(expected)); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; + +/** + * @author Rob Oxspring + */ +public class PrecedenceTest extends TestCase { + private final String[] args = new String[] { "-file" }; + + public void testSimple() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + + final Group options = + new GroupBuilder() + .withOption(oBuilder.withShortName("file").create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-file" }, cl); + } + + public void testArgument() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final ArgumentBuilder aBuilder = new ArgumentBuilder(); + + final Group options = + new GroupBuilder() + .withOption( + oBuilder + .withShortName("f") + .withArgument(aBuilder.create()) + .create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f" }, cl); + } + + public void testBurst() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + final Group options = + gBuilder + .withOption(oBuilder.withShortName("f").create()) + .withOption(oBuilder.withShortName("i").create()) + .withOption(oBuilder.withShortName("l").create()) + .withOption(oBuilder.withShortName("e").create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); + } + + public void testChildren() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + + final Group children = + gBuilder + .withOption(oBuilder.withShortName("i").create()) + .withOption(oBuilder.withShortName("l").create()) + .withOption(oBuilder.withShortName("e").create()) + .create(); + final Group options = + gBuilder + .withOption( + oBuilder + .withShortName("f") + .withChildren(children) + .create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); + } + + public void XtestSimpleVsArgument() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + final ArgumentBuilder aBuilder = new ArgumentBuilder(); + + final Group options = + gBuilder + .withOption(oBuilder.withShortName("file").create()) + .withOption( + oBuilder + .withShortName("f") + .withArgument(aBuilder.create()) + .create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f" }, cl); + } + + public void XtestSimpleVsBurst() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + final Group options = + gBuilder + .withOption(oBuilder.withShortName("file").create()) + .withOption(oBuilder.withShortName("f").create()) + .withOption(oBuilder.withShortName("i").create()) + .withOption(oBuilder.withShortName("l").create()) + .withOption(oBuilder.withShortName("e").create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); + } + + public void XtestSimpleVsChildren() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + + final Group children = + gBuilder + .withOption( + oBuilder.withShortName("i").withLongName("ci").create()) + .withOption( + oBuilder.withShortName("l").withLongName("cl").create()) + .withOption( + oBuilder.withShortName("e").withLongName("ce").create()) + .create(); + + final Group options = + gBuilder + .withOption(oBuilder.withShortName("file").create()) + .withOption( + oBuilder + .withShortName("f") + .withChildren(children) + .create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals( + new String[] { "-f", "-i", "--ci", "-l", "--cl", "-e", "--ce" }, + cl); + } + + public void testArgumentVsBurst() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + final ArgumentBuilder aBuilder = new ArgumentBuilder(); + + final Group options = + gBuilder + .withOption( + oBuilder + .withShortName("f") + .withArgument(aBuilder.create()) + .create()) + .withOption(oBuilder.withShortName("i").create()) + .withOption(oBuilder.withShortName("l").create()) + .withOption(oBuilder.withShortName("e").create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f" }, cl); + } + + public void testArgumentVsChildren() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + final ArgumentBuilder aBuilder = new ArgumentBuilder(); + + final Group children = + gBuilder + .withOption(oBuilder.withShortName("i").create()) + .withOption(oBuilder.withShortName("l").create()) + .withOption(oBuilder.withShortName("e").create()) + .create(); + final Group options = + gBuilder + .withOption( + oBuilder + .withShortName("f") + .withChildren(children) + .withArgument(aBuilder.create()) + .create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f" }, cl); + } + + public void testBurstVsChildren() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + + final Group children = + gBuilder + .withOption( + oBuilder.withShortName("i").withLongName("ci").create()) + .withOption( + oBuilder.withShortName("l").withLongName("cl").create()) + .withOption( + oBuilder.withShortName("e").withLongName("ce").create()) + .create(); + + final Group options = + gBuilder + .withOption( + oBuilder + .withShortName("f") + .withChildren(children) + .create()) + .withOption( + oBuilder.withShortName("i").withLongName("bi").create()) + .withOption( + oBuilder.withShortName("l").withLongName("bl").create()) + .withOption( + oBuilder.withShortName("e").withLongName("be").create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals( + new String[] { "-f", "-i", "--ci", "-l", "--cl", "-e", "--ce" }, + cl); + } + + public void XtestSimpleVsArgumentVsBurst() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + final ArgumentBuilder aBuilder = new ArgumentBuilder(); + + final Group options = + gBuilder + .withOption(oBuilder.withShortName("file").create()) + .withOption( + oBuilder + .withShortName("f") + .withArgument(aBuilder.create()) + .create()) + .withOption(oBuilder.withShortName("i").create()) + .withOption(oBuilder.withShortName("l").create()) + .withOption(oBuilder.withShortName("e").create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f" }, cl); + } + + public void XtestSimpleVsArgumentVsChildren() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + final ArgumentBuilder aBuilder = new ArgumentBuilder(); + + final Group children = + gBuilder + .withOption( + oBuilder.withShortName("i").withLongName("ci").create()) + .withOption( + oBuilder.withShortName("l").withLongName("cl").create()) + .withOption( + oBuilder.withShortName("e").withLongName("ce").create()) + .create(); + + final Group options = + gBuilder + .withOption(oBuilder.withShortName("file").create()) + .withOption( + oBuilder + .withShortName("f") + .withChildren(children) + .withArgument(aBuilder.create()) + .create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f" }, cl); + } + + public void XtestSimpleVsBurstVsChildren() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + + final Group children = + gBuilder + .withOption( + oBuilder.withShortName("i").withLongName("ci").create()) + .withOption( + oBuilder.withShortName("l").withLongName("cl").create()) + .withOption( + oBuilder.withShortName("e").withLongName("ce").create()) + .create(); + + final Group options = + gBuilder + .withOption(oBuilder.withShortName("file").create()) + .withOption( + oBuilder + .withShortName("f") + .withChildren(children) + .create()) + .withOption(oBuilder.withShortName("i").create()) + .withOption(oBuilder.withShortName("l").create()) + .withOption(oBuilder.withShortName("e").create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f", "-i", "-l", "-e" }, cl); + } + + public void testArgumentVsBurstVsChildren() throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + final ArgumentBuilder aBuilder = new ArgumentBuilder(); + + final Group children = + gBuilder + .withOption( + oBuilder.withShortName("i").withLongName("ci").create()) + .withOption( + oBuilder.withShortName("l").withLongName("cl").create()) + .withOption( + oBuilder.withShortName("e").withLongName("ce").create()) + .create(); + + final Group options = + gBuilder + .withOption( + oBuilder + .withShortName("f") + .withChildren(children) + .withArgument(aBuilder.create()) + .create()) + .withOption(oBuilder.withShortName("i").create()) + .withOption(oBuilder.withShortName("l").create()) + .withOption(oBuilder.withShortName("e").create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f" }, cl); + } + + public void XtestSimpleVsArgumentVsBurstVsChildren() + throws OptionException { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + final ArgumentBuilder aBuilder = new ArgumentBuilder(); + + final Group children = + gBuilder + .withOption( + oBuilder.withShortName("i").withLongName("ci").create()) + .withOption( + oBuilder.withShortName("l").withLongName("cl").create()) + .withOption( + oBuilder.withShortName("e").withLongName("ce").create()) + .create(); + + final Group options = + gBuilder + .withOption(oBuilder.withShortName("file").create()) + .withOption( + oBuilder + .withShortName("f") + .withChildren(children) + .withArgument(aBuilder.create()) + .create()) + .withOption(oBuilder.withShortName("i").create()) + .withOption(oBuilder.withShortName("l").create()) + .withOption(oBuilder.withShortName("e").create()) + .create(); + + final CommandLine cl = buildCommandLine(options, args); + assertEquals(new String[] { "-f" }, cl); + } + + public CommandLine buildCommandLine(final Group group, final String[] arguments) + throws OptionException { + Parser p = new Parser(); + p.setGroup(group); + return p.parse(arguments); + } + + public void assertEquals(final String options[], final CommandLine line) { + final List expected = Arrays.asList(options); + final Set actual = line.getOptionTriggers(); + + assertTrue(expected.containsAll(actual)); + assertTrue(actual.containsAll(expected)); + } + +} diff --git a/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java b/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java index 5e8f68624..eac59b110 100644 --- a/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java +++ b/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java @@ -1 +1,92 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2;import org.apache.commons.cli2.option.ArgumentTest;/** * @author Rob Oxspring */public abstract class WriteableCommandLineTestCase extends CommandLineTestCase { private WriteableCommandLine writeable; protected abstract WriteableCommandLine createWriteableCommandLine(); /* (non-Javadoc) * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() */ protected final CommandLine createCommandLine() { final WriteableCommandLine cl = createWriteableCommandLine(); cl.addOption(present); cl.addProperty("present","present property"); cl.addSwitch(bool,true); cl.addValue(present,"present value"); cl.addOption(multiple); cl.addValue(multiple,"value 1"); cl.addValue(multiple,"value 2"); cl.addValue(multiple,"value 3"); return cl; } /* * @see CommandLineTest#setUp() */ public void setUp() throws Exception { super.setUp(); writeable = createWriteableCommandLine(); } public final void testAddOption() { assertFalse(writeable.hasOption(present)); writeable.addOption(present); assertTrue(writeable.hasOption(present)); } public final void testAddValue() { assertFalse(writeable.hasOption(present)); assertTrue(writeable.getValues(present).isEmpty()); writeable.addValue(present,"value"); assertContentsEqual(list("value"),writeable.getValues(present)); // most options shouldn't appear due to adding values assertFalse(writeable.hasOption(present)); final Argument arg = ArgumentTest.buildHostArgument(); assertFalse(writeable.hasOption(arg)); assertTrue(writeable.getValues(arg).isEmpty()); writeable.addValue(arg,"value"); assertContentsEqual(list("value"),writeable.getValues(arg)); // Arguments should force the option present assertTrue(writeable.hasOption(arg)); } public final void testAddSwitch() { assertFalse(writeable.hasOption(present)); assertNull(writeable.getSwitch(present)); writeable.addSwitch(present,true); assertEquals(Boolean.TRUE,writeable.getSwitch(present)); assertTrue(writeable.hasOption(present)); } public final void testAddProperty() { assertNull(writeable.getProperty("present")); writeable.addProperty("present","present value"); assertEquals("present value",writeable.getProperty("present")); } public final void testLooksLikeOption() { //TODO Implement looksLikeOption(). }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2; + +import org.apache.commons.cli2.option.ArgumentTest; + +/** + * @author Rob Oxspring + */ +public abstract class WriteableCommandLineTestCase extends CommandLineTestCase { + + private WriteableCommandLine writeable; + + protected abstract WriteableCommandLine createWriteableCommandLine(); + + /* (non-Javadoc) + * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() + */ + protected final CommandLine createCommandLine() { + final WriteableCommandLine cl = createWriteableCommandLine(); + cl.addOption(present); + cl.addProperty("present","present property"); + cl.addSwitch(bool,true); + cl.addValue(present,"present value"); + cl.addOption(multiple); + cl.addValue(multiple,"value 1"); + cl.addValue(multiple,"value 2"); + cl.addValue(multiple,"value 3"); + return cl; + } + + /* + * @see CommandLineTest#setUp() + */ + public void setUp() throws Exception { + super.setUp(); + writeable = createWriteableCommandLine(); + } + public final void testAddOption() { + assertFalse(writeable.hasOption(present)); + writeable.addOption(present); + assertTrue(writeable.hasOption(present)); + } + public final void testAddValue() { + assertFalse(writeable.hasOption(present)); + assertTrue(writeable.getValues(present).isEmpty()); + writeable.addValue(present,"value"); + assertContentsEqual(list("value"),writeable.getValues(present)); + + // most options shouldn't appear due to adding values + assertFalse(writeable.hasOption(present)); + + final Argument arg = ArgumentTest.buildHostArgument(); + + assertFalse(writeable.hasOption(arg)); + assertTrue(writeable.getValues(arg).isEmpty()); + writeable.addValue(arg,"value"); + assertContentsEqual(list("value"),writeable.getValues(arg)); + + // Arguments should force the option present + assertTrue(writeable.hasOption(arg)); + } + public final void testAddSwitch() { + assertFalse(writeable.hasOption(present)); + assertNull(writeable.getSwitch(present)); + writeable.addSwitch(present,true); + assertEquals(Boolean.TRUE,writeable.getSwitch(present)); + assertTrue(writeable.hasOption(present)); + } + public final void testAddProperty() { + assertNull(writeable.getProperty("present")); + writeable.addProperty("present","present value"); + assertEquals("present value",writeable.getProperty("present")); + } + public final void testLooksLikeOption() { + //TODO Implement looksLikeOption(). + } +} diff --git a/src/test/org/apache/commons/cli2/application/AntTest.java b/src/test/org/apache/commons/cli2/application/AntTest.java index d9e655cfc..b9097ccc0 100644 --- a/src/test/org/apache/commons/cli2/application/AntTest.java +++ b/src/test/org/apache/commons/cli2/application/AntTest.java @@ -1 +1,198 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.application;import java.util.ArrayList;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.option.PropertyOption;//TODO Build up AntTest like CpTestpublic class AntTest extends TestCase { public void testAnt() throws OptionException { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Group options = gbuilder .withName("ant") .withOption( obuilder .withShortName("help") .withDescription("print this message") .create()) .withOption( obuilder .withShortName("projecthelp") .withDescription("print project help information") .create()) .withOption( obuilder .withShortName("version") .withDescription("print the version information and exit") .create()) .withOption( obuilder .withShortName("diagnostics") .withDescription("print information that might be helpful to diagnose or report problems.") .create()) .withOption( obuilder .withShortName("quiet") .withShortName("q") .withDescription("be extra quiet") .create()) .withOption( obuilder .withShortName("verbose") .withShortName("v") .withDescription("be extra verbose") .create()) .withOption( obuilder .withShortName("debug") .withDescription("print debugging information") .create()) .withOption( obuilder .withShortName("emacs") .withDescription("produce logging information without adornments") .create()) .withOption( obuilder .withShortName("logfile") .withShortName("l") .withDescription("use given file for log") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption( obuilder .withShortName("logger") .withDescription("the class which is to perform logging") .withArgument( abuilder .withName("classname") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption( obuilder .withShortName("listener") .withDescription("add an instance of class as a project listener") .withArgument( abuilder .withName("classname") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption( obuilder .withShortName("buildfile") .withShortName("file") .withShortName("f") .withDescription("use given buildfile") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption(PropertyOption.INSTANCE) .withOption( obuilder .withShortName("propertyfile") .withDescription("load all properties from file with -D properties taking precedence") .withArgument( abuilder .withName("name") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption( obuilder .withShortName("inputhandler") .withDescription("the class which will handle input requests") .withArgument( abuilder .withName("class") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption( obuilder .withShortName("find") .withDescription("search for buildfile towards the root of the filesystem and use it") .withArgument( abuilder .withName("file") .withMinimum(1) .withMaximum(1) .create()) .create()) .withOption(abuilder.withName("target").create()) .create(); Parser parser = new Parser(); parser.setGroup(options); CommandLine line = parser.parse( new String[] { "-buildfile", "mybuild.xml", "-Dproperty=value", "-Dproperty1=value1", "-projecthelp", "compile", "docs" }); // check properties assertEquals(2, line.getProperties().size()); assertEquals("value", line.getProperty("property")); assertEquals("value1", line.getProperty("property1")); // check single values assertEquals("mybuild.xml", line.getValue("-buildfile")); assertTrue(line.hasOption("-projecthelp")); assertFalse(line.hasOption("-help")); assertTrue(line.hasOption("target")); final List targets = new ArrayList(); targets.add("compile"); targets.add("docs"); assertEquals(targets, line.getValues("target")); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.application; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.option.PropertyOption; + +//TODO Build up AntTest like CpTest +public class AntTest extends TestCase { + public void testAnt() throws OptionException { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + + final Group options = + gbuilder + .withName("ant") + .withOption( + obuilder + .withShortName("help") + .withDescription("print this message") + .create()) + .withOption( + obuilder + .withShortName("projecthelp") + .withDescription("print project help information") + .create()) + .withOption( + obuilder + .withShortName("version") + .withDescription("print the version information and exit") + .create()) + .withOption( + obuilder + .withShortName("diagnostics") + .withDescription("print information that might be helpful to diagnose or report problems.") + .create()) + .withOption( + obuilder + .withShortName("quiet") + .withShortName("q") + .withDescription("be extra quiet") + .create()) + .withOption( + obuilder + .withShortName("verbose") + .withShortName("v") + .withDescription("be extra verbose") + .create()) + .withOption( + obuilder + .withShortName("debug") + .withDescription("print debugging information") + .create()) + .withOption( + obuilder + .withShortName("emacs") + .withDescription("produce logging information without adornments") + .create()) + .withOption( + obuilder + .withShortName("logfile") + .withShortName("l") + .withDescription("use given file for log") + .withArgument( + abuilder + .withName("file") + .withMinimum(1) + .withMaximum(1) + .create()) + .create()) + .withOption( + obuilder + .withShortName("logger") + .withDescription("the class which is to perform logging") + .withArgument( + abuilder + .withName("classname") + .withMinimum(1) + .withMaximum(1) + .create()) + .create()) + .withOption( + obuilder + .withShortName("listener") + .withDescription("add an instance of class as a project listener") + .withArgument( + abuilder + .withName("classname") + .withMinimum(1) + .withMaximum(1) + .create()) + .create()) + .withOption( + obuilder + .withShortName("buildfile") + .withShortName("file") + .withShortName("f") + .withDescription("use given buildfile") + .withArgument( + abuilder + .withName("file") + .withMinimum(1) + .withMaximum(1) + .create()) + .create()) + .withOption(PropertyOption.INSTANCE) + .withOption( + obuilder + .withShortName("propertyfile") + .withDescription("load all properties from file with -D properties taking precedence") + .withArgument( + abuilder + .withName("name") + .withMinimum(1) + .withMaximum(1) + .create()) + .create()) + .withOption( + obuilder + .withShortName("inputhandler") + .withDescription("the class which will handle input requests") + .withArgument( + abuilder + .withName("class") + .withMinimum(1) + .withMaximum(1) + .create()) + .create()) + .withOption( + obuilder + .withShortName("find") + .withDescription("search for buildfile towards the root of the filesystem and use it") + .withArgument( + abuilder + .withName("file") + .withMinimum(1) + .withMaximum(1) + .create()) + .create()) + .withOption(abuilder.withName("target").create()) + .create(); + + Parser parser = new Parser(); + parser.setGroup(options); + CommandLine line = + parser.parse( + new String[] { + "-buildfile", + "mybuild.xml", + "-Dproperty=value", + "-Dproperty1=value1", + "-projecthelp", + "compile", + "docs" }); + + // check properties + assertEquals(2, line.getProperties().size()); + assertEquals("value", line.getProperty("property")); + assertEquals("value1", line.getProperty("property1")); + + // check single values + assertEquals("mybuild.xml", line.getValue("-buildfile")); + assertTrue(line.hasOption("-projecthelp")); + assertFalse(line.hasOption("-help")); + + assertTrue(line.hasOption("target")); + final List targets = new ArrayList(); + targets.add("compile"); + targets.add("docs"); + assertEquals(targets, line.getValues("target")); + } +} diff --git a/src/test/org/apache/commons/cli2/application/CpTest.java b/src/test/org/apache/commons/cli2/application/CpTest.java index 457571c24..bdcc9a5ba 100644 --- a/src/test/org/apache/commons/cli2/application/CpTest.java +++ b/src/test/org/apache/commons/cli2/application/CpTest.java @@ -1 +1,471 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.application;import java.io.BufferedReader;import java.io.IOException;import java.io.PrintWriter;import java.io.StringReader;import java.io.StringWriter;import junit.framework.Test;import junit.framework.TestCase;import junit.framework.TestSuite;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.option.ArgumentImpl;import org.apache.commons.cli2.option.SourceDestArgument;import org.apache.commons.cli2.util.HelpFormatter;/** *

      Test the cp command. Duplicated Option types are not * tested e.g. -a and -d are the same Option type.

      * *

      The following is the man output for 'cp'. See * http://www.rt.com/man/cp.1.html.

      * *
       *  CP(1) FSF CP(1) * *  NAME cp - copy files and directories * *  SYNOPSIS cp [OPTION]... SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY * *  DESCRIPTION Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. * *  -a, --archive same as -dpR * *  -b, --backup make backup before removal * *  -d, --no-dereference preserve links * *  -f, --force remove existing destinations, never prompt * *  -i, --interactive prompt before overwrite * *  -l, --link link files instead of copying * *  -p, --preserve preserve file attributes if possible * *  -P, --parents append source path to DIRECTORY * -r copy recursively, non-directories as files * *  --sparse=WHEN control creation of sparse files * *  -R, --recursive copy directories recursively * *  -s, --symbolic-link make symbolic links instead of copying * *  -S, --suffix=SUFFIX override the usual backup suffix * *  -u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing * *  -v, --verbose explain what is being done * *  -V, --version-control=WORD override the usual version control * *  -x, --one-file-system stay on this file system * *  --help display this help and exit * *  --version output version information and exit * *  By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file when- ever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. * *  The backup suffix is ~, unless set with SIMPLE_BACKUP_SUF- FIX. The version control may be set with VERSION_CONTROL, values are: * t, numbered make numbered backups * *  nil, existing numbered if numbered backups exist, simple other- wise * *  never, simple always make simple backups * *  As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. * 
      * * * @author Rob Oxspring * @author John Keyes */public class CpTest extends TestCase { /** Option Builder */ private static final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); /** Argument Builder */ private static final ArgumentBuilder aBuilder = new ArgumentBuilder(); /** Group Builder */ private static final GroupBuilder gBuilder = new GroupBuilder(); private Group options; public static Test suite() { return new TestSuite(CpTest.class); } private ArgumentImpl source; private ArgumentImpl dest; private Argument targets; private Option archive; private Option backup; private Option noDereference; private Option force; private Option interactive; private Option link; private Option preserve; private Option parents; private Option recursive1; private Option sparse; private Option recursive2; private Option symbolicLink; private Option suffix; private Option update; private Option verbose; private Option versionControl; private Option oneFileSystem; private Option help; private Option version; public void setUp() { source = (ArgumentImpl)aBuilder.withName("SOURCE").withMinimum(1).create(); dest = (ArgumentImpl)aBuilder .withName("DEST") .withMinimum(1) .withMaximum(1) .create(); targets = new SourceDestArgument(source, dest); archive = oBuilder .withShortName("a") .withLongName("archive") .withDescription("same as -dpR") .create(); backup = oBuilder .withShortName("b") .withLongName("backup") .withDescription("make backup before removal") .create(); noDereference = oBuilder .withShortName("d") .withLongName("no-dereference") .withDescription("preserve links") .create(); force = oBuilder .withShortName("f") .withLongName("force") .withDescription("remove existing destinations, never prompt") .create(); interactive = oBuilder .withShortName("i") .withLongName("interactive") .withDescription("prompt before overwrite") .create(); link = oBuilder .withShortName("l") .withLongName("link") .withDescription("link files instead of copying") .create(); preserve = oBuilder .withShortName("p") .withLongName("preserve") .withDescription("preserve file attributes if possible") .create(); parents = oBuilder .withShortName("P") .withLongName("parents") .withDescription("append source path to DIRECTORY") .create(); recursive1 = oBuilder .withShortName("r") .withDescription("copy recursively, non-directories as files") .create(); sparse = oBuilder .withLongName("sparse") .withDescription("control creation of sparse files") .withArgument( aBuilder .withName("WHEN") .withMinimum(1) .withMaximum(1) .withInitialSeparator('=') .create()) .create(); recursive2 = oBuilder .withShortName("R") .withLongName("recursive") .withDescription("copy directories recursively") .create(); symbolicLink = oBuilder .withShortName("s") .withLongName("symbolic-link") .withDescription("make symbolic links instead of copying") .create(); suffix = oBuilder .withShortName("S") .withLongName("suffix") .withDescription("override the usual backup suffix") .withArgument( aBuilder .withName("SUFFIX") .withMinimum(1) .withMaximum(1) .create()) .create(); update = oBuilder .withShortName("u") .withLongName("update") .withDescription("copy only when the SOURCE file is newer than the destination file or when the destination file is missing") .create(); verbose = oBuilder .withShortName("v") .withLongName("verbose") .withDescription("explain what is being done") .create(); versionControl = oBuilder .withShortName("V") .withLongName("version-contol") .withDescription("explain what is being done") .withArgument( aBuilder .withName("WORD") .withInitialSeparator('=') .withMinimum(1) .withMaximum(1) .create()) .create(); oneFileSystem = oBuilder .withShortName("x") .withLongName("one-file-system") .withDescription("stay on this file system") .create(); help = oBuilder .withLongName("help") .withDescription("display this help and exit") .create(); version = oBuilder .withLongName("version") .withDescription("output version information and exit") .create(); options = gBuilder .withOption(archive) .withOption(backup) .withOption(noDereference) .withOption(force) .withOption(interactive) .withOption(link) .withOption(preserve) .withOption(parents) .withOption(recursive1) .withOption(sparse) .withOption(recursive2) .withOption(symbolicLink) .withOption(suffix) .withOption(update) .withOption(verbose) .withOption(versionControl) .withOption(oneFileSystem) .withOption(help) .withOption(version) .withOption(targets) .withName("OPTIONS") .create(); } public void testNoSource() { Parser parser = new Parser(); parser.setGroup(options); try { parser.parse(new String[0]); } catch (OptionException mve) { assertEquals( "Missing value(s) SOURCE [SOURCE ...]", mve.getMessage()); } } public void testOneSource() throws OptionException { final String[] args = new String[] { "source1", "dest1" }; final Parser parser = new Parser(); parser.setGroup(options); final CommandLine commandLine = parser.parse(args); assertTrue(commandLine.getValues(source).contains("source1")); assertEquals(1, commandLine.getValues(source).size()); assertTrue(commandLine.getValues(dest).contains("dest1")); assertEquals(1, commandLine.getValues(dest).size()); } public void testMultiSource() throws OptionException { final String[] args = new String[] { "source1", "source2", "source3", "dest1" }; final Parser parser = new Parser(); parser.setGroup(options); final CommandLine commandLine = parser.parse(args); assertTrue(commandLine.getValues(source).contains("source1")); assertTrue(commandLine.getValues(source).contains("source2")); assertTrue(commandLine.getValues(source).contains("source3")); assertEquals(3, commandLine.getValues(source).size()); assertTrue(commandLine.getValues(dest).contains("dest1")); assertEquals(1, commandLine.getValues(dest).size()); } public void testHelp() throws IOException { final StringWriter out = new StringWriter(); final HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setGroup(options); helpFormatter.setPrintWriter(new PrintWriter(out)); helpFormatter.print(); final BufferedReader in = new BufferedReader(new StringReader(out.toString())); assertEquals( "Usage: ", in.readLine()); assertEquals( " [-a -b -d -f -i -l -p -P -r --sparse -R -s -S -u -v -V ", in.readLine()); assertEquals( "-x --help --version] [ ...] ", in.readLine()); assertEquals( "OPTIONS ", in.readLine()); assertEquals( " -a (--archive) same as -dpR ", in.readLine()); assertEquals( " -b (--backup) make backup before removal ", in.readLine()); assertEquals( " -d (--no-dereference) preserve links ", in.readLine()); assertEquals( " -f (--force) remove existing destinations, never prompt ", in.readLine()); assertEquals( " -i (--interactive) prompt before overwrite ", in.readLine()); assertEquals( " -l (--link) link files instead of copying ", in.readLine()); assertEquals( " -p (--preserve) preserve file attributes if possible ", in.readLine()); assertEquals( " -P (--parents) append source path to DIRECTORY ", in.readLine()); assertEquals( " -r copy recursively, non-directories as files ", in.readLine()); assertEquals( " --sparse WHEN control creation of sparse files ", in.readLine()); assertEquals( " -R (--recursive) copy directories recursively ", in.readLine()); assertEquals( " -s (--symbolic-link) make symbolic links instead of copying ", in.readLine()); assertEquals( " -S (--suffix) SUFFIX override the usual backup suffix ", in.readLine()); assertEquals( " -u (--update) copy only when the SOURCE file is newer than ", in.readLine()); assertEquals( " the destination file or when the destination ", in.readLine()); assertEquals( " file is missing ", in.readLine()); assertEquals( " -v (--verbose) explain what is being done ", in.readLine()); assertEquals( " -V (--version-contol) WORD explain what is being done ", in.readLine()); assertEquals( " -x (--one-file-system) stay on this file system ", in.readLine()); assertEquals( " --help display this help and exit ", in.readLine()); assertEquals( " --version output version information and exit ", in.readLine()); assertEquals( " SOURCE [SOURCE ...] ", in.readLine()); assertEquals( " DEST ", in.readLine()); assertNull(in.readLine()); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.application; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.option.ArgumentImpl; +import org.apache.commons.cli2.option.SourceDestArgument; +import org.apache.commons.cli2.util.HelpFormatter; + +/** + *

      Test the cp command. Duplicated Option types are not + * tested e.g. -a and -d are the same Option type.

      + * + *

      The following is the man output for 'cp'. See + * http://www.rt.com/man/cp.1.html.

      + * + *
      + *  CP(1) FSF CP(1)
      + * 
      + *  NAME cp - copy files and directories
      + * 
      + *  SYNOPSIS cp [OPTION]... SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY
      + * 
      + *  DESCRIPTION Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.
      + * 
      + *  -a, --archive same as -dpR
      + * 
      + *  -b, --backup make backup before removal
      + * 
      + *  -d, --no-dereference preserve links
      + * 
      + *  -f, --force remove existing destinations, never prompt
      + * 
      + *  -i, --interactive prompt before overwrite
      + * 
      + *  -l, --link link files instead of copying
      + * 
      + *  -p, --preserve preserve file attributes if possible
      + * 
      + *  -P, --parents append source path to DIRECTORY
      + * -r copy recursively, non-directories as files
      + * 
      + *  --sparse=WHEN control creation of sparse files
      + * 
      + *  -R, --recursive copy directories recursively
      + * 
      + *  -s, --symbolic-link make symbolic links instead of copying
      + * 
      + *  -S, --suffix=SUFFIX override the usual backup suffix
      + * 
      + *  -u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing
      + * 
      + *  -v, --verbose explain what is being done
      + * 
      + *  -V, --version-control=WORD override the usual version control
      + * 
      + *  -x, --one-file-system stay on this file system
      + * 
      + *  --help display this help and exit
      + * 
      + *  --version output version information and exit
      + * 
      + *  By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file when- ever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files.
      + * 
      + *  The backup suffix is ~, unless set with SIMPLE_BACKUP_SUF- FIX. The version control may be set with VERSION_CONTROL, values are:
      + * t, numbered make numbered backups
      + * 
      + *  nil, existing numbered if numbered backups exist, simple other- wise
      + * 
      + *  never, simple always make simple backups
      + * 
      + *  As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. * 
      + * + * + * @author Rob Oxspring + * @author John Keyes + */ +public class CpTest extends TestCase { + + /** Option Builder */ + private static final DefaultOptionBuilder oBuilder = + new DefaultOptionBuilder(); + + /** Argument Builder */ + private static final ArgumentBuilder aBuilder = new ArgumentBuilder(); + + /** Group Builder */ + private static final GroupBuilder gBuilder = new GroupBuilder(); + + private Group options; + + public static Test suite() { + return new TestSuite(CpTest.class); + } + + private ArgumentImpl source; + private ArgumentImpl dest; + private Argument targets; + + private Option archive; + private Option backup; + private Option noDereference; + private Option force; + private Option interactive; + private Option link; + private Option preserve; + private Option parents; + private Option recursive1; + private Option sparse; + private Option recursive2; + private Option symbolicLink; + private Option suffix; + private Option update; + private Option verbose; + private Option versionControl; + private Option oneFileSystem; + private Option help; + private Option version; + + public void setUp() { + source = + (ArgumentImpl)aBuilder.withName("SOURCE").withMinimum(1).create(); + dest = + (ArgumentImpl)aBuilder + .withName("DEST") + .withMinimum(1) + .withMaximum(1) + .create(); + targets = new SourceDestArgument(source, dest); + + archive = + oBuilder + .withShortName("a") + .withLongName("archive") + .withDescription("same as -dpR") + .create(); + + backup = + oBuilder + .withShortName("b") + .withLongName("backup") + .withDescription("make backup before removal") + .create(); + + noDereference = + oBuilder + .withShortName("d") + .withLongName("no-dereference") + .withDescription("preserve links") + .create(); + + force = + oBuilder + .withShortName("f") + .withLongName("force") + .withDescription("remove existing destinations, never prompt") + .create(); + + interactive = + oBuilder + .withShortName("i") + .withLongName("interactive") + .withDescription("prompt before overwrite") + .create(); + + link = + oBuilder + .withShortName("l") + .withLongName("link") + .withDescription("link files instead of copying") + .create(); + + preserve = + oBuilder + .withShortName("p") + .withLongName("preserve") + .withDescription("preserve file attributes if possible") + .create(); + + parents = + oBuilder + .withShortName("P") + .withLongName("parents") + .withDescription("append source path to DIRECTORY") + .create(); + + recursive1 = + oBuilder + .withShortName("r") + .withDescription("copy recursively, non-directories as files") + .create(); + + sparse = + oBuilder + .withLongName("sparse") + .withDescription("control creation of sparse files") + .withArgument( + aBuilder + .withName("WHEN") + .withMinimum(1) + .withMaximum(1) + .withInitialSeparator('=') + .create()) + .create(); + + recursive2 = + oBuilder + .withShortName("R") + .withLongName("recursive") + .withDescription("copy directories recursively") + .create(); + + symbolicLink = + oBuilder + .withShortName("s") + .withLongName("symbolic-link") + .withDescription("make symbolic links instead of copying") + .create(); + + suffix = + oBuilder + .withShortName("S") + .withLongName("suffix") + .withDescription("override the usual backup suffix") + .withArgument( + aBuilder + .withName("SUFFIX") + .withMinimum(1) + .withMaximum(1) + .create()) + .create(); + + update = + oBuilder + .withShortName("u") + .withLongName("update") + .withDescription("copy only when the SOURCE file is newer than the destination file or when the destination file is missing") + .create(); + + verbose = + oBuilder + .withShortName("v") + .withLongName("verbose") + .withDescription("explain what is being done") + .create(); + + versionControl = + oBuilder + .withShortName("V") + .withLongName("version-contol") + .withDescription("explain what is being done") + .withArgument( + aBuilder + .withName("WORD") + .withInitialSeparator('=') + .withMinimum(1) + .withMaximum(1) + .create()) + .create(); + + oneFileSystem = + oBuilder + .withShortName("x") + .withLongName("one-file-system") + .withDescription("stay on this file system") + .create(); + + help = + oBuilder + .withLongName("help") + .withDescription("display this help and exit") + .create(); + + version = + oBuilder + .withLongName("version") + .withDescription("output version information and exit") + .create(); + + options = + gBuilder + .withOption(archive) + .withOption(backup) + .withOption(noDereference) + .withOption(force) + .withOption(interactive) + .withOption(link) + .withOption(preserve) + .withOption(parents) + .withOption(recursive1) + .withOption(sparse) + .withOption(recursive2) + .withOption(symbolicLink) + .withOption(suffix) + .withOption(update) + .withOption(verbose) + .withOption(versionControl) + .withOption(oneFileSystem) + .withOption(help) + .withOption(version) + .withOption(targets) + .withName("OPTIONS") + .create(); + } + + public void testNoSource() { + Parser parser = new Parser(); + parser.setGroup(options); + try { + parser.parse(new String[0]); + } + catch (OptionException mve) { + assertEquals( + "Missing value(s) SOURCE [SOURCE ...]", + mve.getMessage()); + } + } + + public void testOneSource() throws OptionException { + final String[] args = new String[] { "source1", "dest1" }; + final Parser parser = new Parser(); + parser.setGroup(options); + final CommandLine commandLine = parser.parse(args); + + assertTrue(commandLine.getValues(source).contains("source1")); + assertEquals(1, commandLine.getValues(source).size()); + assertTrue(commandLine.getValues(dest).contains("dest1")); + assertEquals(1, commandLine.getValues(dest).size()); + } + + public void testMultiSource() throws OptionException { + final String[] args = + new String[] { "source1", "source2", "source3", "dest1" }; + final Parser parser = new Parser(); + parser.setGroup(options); + final CommandLine commandLine = parser.parse(args); + + assertTrue(commandLine.getValues(source).contains("source1")); + assertTrue(commandLine.getValues(source).contains("source2")); + assertTrue(commandLine.getValues(source).contains("source3")); + assertEquals(3, commandLine.getValues(source).size()); + + assertTrue(commandLine.getValues(dest).contains("dest1")); + assertEquals(1, commandLine.getValues(dest).size()); + } + + public void testHelp() throws IOException { + final StringWriter out = new StringWriter(); + final HelpFormatter helpFormatter = new HelpFormatter(); + helpFormatter.setGroup(options); + helpFormatter.setPrintWriter(new PrintWriter(out)); + helpFormatter.print(); + + final BufferedReader in = + new BufferedReader(new StringReader(out.toString())); + assertEquals( + "Usage: ", + in.readLine()); + assertEquals( + " [-a -b -d -f -i -l -p -P -r --sparse -R -s -S -u -v -V ", + in.readLine()); + assertEquals( + "-x --help --version] [ ...] ", + in.readLine()); + assertEquals( + "OPTIONS ", + in.readLine()); + assertEquals( + " -a (--archive) same as -dpR ", + in.readLine()); + assertEquals( + " -b (--backup) make backup before removal ", + in.readLine()); + assertEquals( + " -d (--no-dereference) preserve links ", + in.readLine()); + assertEquals( + " -f (--force) remove existing destinations, never prompt ", + in.readLine()); + assertEquals( + " -i (--interactive) prompt before overwrite ", + in.readLine()); + assertEquals( + " -l (--link) link files instead of copying ", + in.readLine()); + assertEquals( + " -p (--preserve) preserve file attributes if possible ", + in.readLine()); + assertEquals( + " -P (--parents) append source path to DIRECTORY ", + in.readLine()); + assertEquals( + " -r copy recursively, non-directories as files ", + in.readLine()); + assertEquals( + " --sparse WHEN control creation of sparse files ", + in.readLine()); + assertEquals( + " -R (--recursive) copy directories recursively ", + in.readLine()); + assertEquals( + " -s (--symbolic-link) make symbolic links instead of copying ", + in.readLine()); + assertEquals( + " -S (--suffix) SUFFIX override the usual backup suffix ", + in.readLine()); + assertEquals( + " -u (--update) copy only when the SOURCE file is newer than ", + in.readLine()); + assertEquals( + " the destination file or when the destination ", + in.readLine()); + assertEquals( + " file is missing ", + in.readLine()); + assertEquals( + " -v (--verbose) explain what is being done ", + in.readLine()); + assertEquals( + " -V (--version-contol) WORD explain what is being done ", + in.readLine()); + assertEquals( + " -x (--one-file-system) stay on this file system ", + in.readLine()); + assertEquals( + " --help display this help and exit ", + in.readLine()); + assertEquals( + " --version output version information and exit ", + in.readLine()); + assertEquals( + " SOURCE [SOURCE ...] ", + in.readLine()); + assertEquals( + " DEST ", + in.readLine()); + assertNull(in.readLine()); + } +} diff --git a/src/test/org/apache/commons/cli2/application/CvsTest.java b/src/test/org/apache/commons/cli2/application/CvsTest.java index adc1e27e9..47186e126 100644 --- a/src/test/org/apache/commons/cli2/application/CvsTest.java +++ b/src/test/org/apache/commons/cli2/application/CvsTest.java @@ -1 +1,312 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.application;import junit.framework.TestCase;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.CommandBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.option.ArgumentTest;//TODO Build up CvsTest like CpTestpublic class CvsTest extends TestCase { public void testCVS() { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final CommandBuilder cbuilder = new CommandBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Group commands = gbuilder .withName("commands") .withOption( cbuilder .withName("add") .withName("ad") .withName("new") .withDescription("Add a new file/directory to the repository") .create()) .withOption( cbuilder .withName("admin") .withName("adm") .withName("rcs") .withDescription("Administration front end for rcs") .create()) .withOption( cbuilder .withName("annotate") .withName("ann") .withDescription("Show last revision where each line was modified") .create()) .withOption( cbuilder .withName("checkout") .withName("co") .withName("get") .withDescription("Checkout sources for editing") .create()) .withOption( cbuilder .withName("commit") .withName("ci") .withName("com") .withDescription("Check files into the repository") .create()) .withOption( cbuilder .withName("diff") .withName("di") .withName("dif") .withDescription("Show differences between revisions") .create()) .withOption( cbuilder .withName("edit") .withDescription("Get ready to edit a watched file") .create()) .withOption( cbuilder .withName("editors") .withDescription("See who is editing a watched file") .create()) .withOption( cbuilder .withName("export") .withName("exp") .withName("ex") .withDescription("Export sources from CVS, similar to checkout") .create()) .withOption( cbuilder .withName("history") .withName("hi") .withName("his") .withDescription("Show repository access history") .create()) .withOption( cbuilder .withName("import") .withName("im") .withName("imp") .withDescription("Import sources into CVS, using vendor branches") .create()) .withOption( cbuilder .withName("init") .withDescription("Create a CVS repository if it doesn't exist") .create()) .withOption( cbuilder .withName("log") .withName("lo") .withName("rlog") .withDescription("Print out history information for files") .create()) .withOption( cbuilder .withName("login") .withName("logon") .withName("lgn") .withDescription("Prompt for password for authenticating server") .create()) .withOption( cbuilder .withName("logout") .withDescription("Removes entry in .cvspass for remote repository") .create()) .withOption( cbuilder .withName("rdiff") .withName("patch") .withName("pa") .withDescription("Create 'patch' format diffs between releases") .create()) .withOption( cbuilder .withName("release") .withName("re") .withName("rel") .withDescription("Indicate that a Module is no longer in use") .create()) .withOption( cbuilder .withName("remove") .withName("rm") .withName("delete") .withDescription("Remove an entry from the repository") .create()) .withOption( cbuilder .withName("rtag") .withName("rt") .withName("rfreeze") .withDescription("Add a symbolic tag to a module") .create()) .withOption( cbuilder .withName("status") .withName("st") .withName("stat") .withDescription("Display status information on checked out files") .create()) .withOption( cbuilder .withName("tag") .withName("ta") .withName("freeze") .withDescription("Add a symbolic tag to checked out version of files") .create()) .withOption( cbuilder .withName("unedit") .withDescription("Undo an edit command") .create()) .withOption( cbuilder .withName("update") .withName("up") .withName("upd") .withDescription("Bring work tree in sync with repository") .create()) .withOption( cbuilder .withName("watch") .withDescription("Set watches") .create()) .withOption( cbuilder .withName("watchers") .withDescription("See who is watching a file") .create()) .withOption( cbuilder .withName("version") .withName("ve") .withName("ver") .withDescription("????") .create()) .withOption(ArgumentTest.buildTargetsArgument()) .create(); final Group cvsOptions = new GroupBuilder() .withName("cvs-options") .withOption( obuilder .withShortName("H") .withDescription("Displays usage information for command.") .create()) .withOption( obuilder .withShortName("Q") .withDescription("Cause CVS to be really quiet.") .create()) .withOption( obuilder .withShortName("q") .withDescription("Cause CVS to be somewhat quiet.") .create()) .withOption( obuilder .withShortName("r") .withDescription("Make checked-out files read-only.") .create()) .withOption( obuilder .withShortName("w") .withDescription("Make checked-out files read-write (default).") .create()) .withOption( obuilder .withShortName("l") .withDescription("Turn history logging off.") .create()) .withOption( obuilder .withShortName("n") .withDescription("Do not execute anything that will change the disk.") .create()) .withOption( obuilder .withShortName("t") .withDescription("Show trace of program execution -- try with -n.") .create()) .withOption( obuilder .withShortName("v") .withDescription("CVS version and copyright.") .create()) .withOption( obuilder .withLongName("crlf") .withDescription("Use the Dos line feed for text files (default).") .create()) .withOption( obuilder .withLongName("lf") .withDescription("Use the Unix line feed for text files.") .create()) .withOption( obuilder .withShortName("T") .withDescription("Use 'tmpdir' for temporary files.") .withArgument(abuilder.withName("tmpdir").create()) .create()) .withOption( obuilder .withShortName("e") .withDescription("Use 'editor' for editing log information.") .withArgument(abuilder.withName("editor").create()) .create()) .withOption( obuilder .withShortName("d") .withDescription("Overrides $CVSROOT as the root of the CVS tree.") .withArgument(abuilder.withName("CVS_root").create()) .create()) .withOption( obuilder .withShortName("f") .withDescription("Do not use the ~/.cvsrc file.") .create()) .withOption( obuilder .withShortName("z") .withDescription("Use compression level '#' for net traffic.") .withArgument(abuilder.withName("#").create()) .create()) .withOption( obuilder .withShortName("a") .withDescription("Authenticate all net traffic.") .create()) .withOption( obuilder .withShortName("s") .withDescription("Set CVS user variable.") .withArgument(abuilder.withName("VAR=VAL").create()) .create()) .withOption(commands) .create(); assertNotNull(cvsOptions); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.application; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.CommandBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.option.ArgumentTest; + +//TODO Build up CvsTest like CpTest +public class CvsTest extends TestCase { + public void testCVS() { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final CommandBuilder cbuilder = new CommandBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + + final Group commands = + gbuilder + .withName("commands") + .withOption( + cbuilder + .withName("add") + .withName("ad") + .withName("new") + .withDescription("Add a new file/directory to the repository") + .create()) + .withOption( + cbuilder + .withName("admin") + .withName("adm") + .withName("rcs") + .withDescription("Administration front end for rcs") + .create()) + .withOption( + cbuilder + .withName("annotate") + .withName("ann") + .withDescription("Show last revision where each line was modified") + .create()) + .withOption( + cbuilder + .withName("checkout") + .withName("co") + .withName("get") + .withDescription("Checkout sources for editing") + .create()) + .withOption( + cbuilder + .withName("commit") + .withName("ci") + .withName("com") + .withDescription("Check files into the repository") + .create()) + .withOption( + cbuilder + .withName("diff") + .withName("di") + .withName("dif") + .withDescription("Show differences between revisions") + .create()) + .withOption( + cbuilder + .withName("edit") + .withDescription("Get ready to edit a watched file") + .create()) + .withOption( + cbuilder + .withName("editors") + .withDescription("See who is editing a watched file") + .create()) + .withOption( + cbuilder + .withName("export") + .withName("exp") + .withName("ex") + .withDescription("Export sources from CVS, similar to checkout") + .create()) + .withOption( + cbuilder + .withName("history") + .withName("hi") + .withName("his") + .withDescription("Show repository access history") + .create()) + .withOption( + cbuilder + .withName("import") + .withName("im") + .withName("imp") + .withDescription("Import sources into CVS, using vendor branches") + .create()) + .withOption( + cbuilder + .withName("init") + .withDescription("Create a CVS repository if it doesn't exist") + .create()) + .withOption( + cbuilder + .withName("log") + .withName("lo") + .withName("rlog") + .withDescription("Print out history information for files") + .create()) + .withOption( + cbuilder + .withName("login") + .withName("logon") + .withName("lgn") + .withDescription("Prompt for password for authenticating server") + .create()) + .withOption( + cbuilder + .withName("logout") + .withDescription("Removes entry in .cvspass for remote repository") + .create()) + .withOption( + cbuilder + .withName("rdiff") + .withName("patch") + .withName("pa") + .withDescription("Create 'patch' format diffs between releases") + .create()) + .withOption( + cbuilder + .withName("release") + .withName("re") + .withName("rel") + .withDescription("Indicate that a Module is no longer in use") + .create()) + .withOption( + cbuilder + .withName("remove") + .withName("rm") + .withName("delete") + .withDescription("Remove an entry from the repository") + .create()) + .withOption( + cbuilder + .withName("rtag") + .withName("rt") + .withName("rfreeze") + .withDescription("Add a symbolic tag to a module") + .create()) + .withOption( + cbuilder + .withName("status") + .withName("st") + .withName("stat") + .withDescription("Display status information on checked out files") + .create()) + .withOption( + cbuilder + .withName("tag") + .withName("ta") + .withName("freeze") + .withDescription("Add a symbolic tag to checked out version of files") + .create()) + .withOption( + cbuilder + .withName("unedit") + .withDescription("Undo an edit command") + .create()) + .withOption( + cbuilder + .withName("update") + .withName("up") + .withName("upd") + .withDescription("Bring work tree in sync with repository") + .create()) + .withOption( + cbuilder + .withName("watch") + .withDescription("Set watches") + .create()) + .withOption( + cbuilder + .withName("watchers") + .withDescription("See who is watching a file") + .create()) + .withOption( + cbuilder + .withName("version") + .withName("ve") + .withName("ver") + .withDescription("????") + .create()) + .withOption(ArgumentTest.buildTargetsArgument()) + .create(); + + final Group cvsOptions = + new GroupBuilder() + .withName("cvs-options") + .withOption( + obuilder + .withShortName("H") + .withDescription("Displays usage information for command.") + .create()) + .withOption( + obuilder + .withShortName("Q") + .withDescription("Cause CVS to be really quiet.") + .create()) + .withOption( + obuilder + .withShortName("q") + .withDescription("Cause CVS to be somewhat quiet.") + .create()) + .withOption( + obuilder + .withShortName("r") + .withDescription("Make checked-out files read-only.") + .create()) + .withOption( + obuilder + .withShortName("w") + .withDescription("Make checked-out files read-write (default).") + .create()) + .withOption( + obuilder + .withShortName("l") + .withDescription("Turn history logging off.") + .create()) + .withOption( + obuilder + .withShortName("n") + .withDescription("Do not execute anything that will change the disk.") + .create()) + .withOption( + obuilder + .withShortName("t") + .withDescription("Show trace of program execution -- try with -n.") + .create()) + .withOption( + obuilder + .withShortName("v") + .withDescription("CVS version and copyright.") + .create()) + .withOption( + obuilder + .withLongName("crlf") + .withDescription("Use the Dos line feed for text files (default).") + .create()) + .withOption( + obuilder + .withLongName("lf") + .withDescription("Use the Unix line feed for text files.") + .create()) + .withOption( + obuilder + .withShortName("T") + .withDescription("Use 'tmpdir' for temporary files.") + .withArgument(abuilder.withName("tmpdir").create()) + .create()) + .withOption( + obuilder + .withShortName("e") + .withDescription("Use 'editor' for editing log information.") + .withArgument(abuilder.withName("editor").create()) + .create()) + .withOption( + obuilder + .withShortName("d") + .withDescription("Overrides $CVSROOT as the root of the CVS tree.") + .withArgument(abuilder.withName("CVS_root").create()) + .create()) + .withOption( + obuilder + .withShortName("f") + .withDescription("Do not use the ~/.cvsrc file.") + .create()) + .withOption( + obuilder + .withShortName("z") + .withDescription("Use compression level '#' for net traffic.") + .withArgument(abuilder.withName("#").create()) + .create()) + .withOption( + obuilder + .withShortName("a") + .withDescription("Authenticate all net traffic.") + .create()) + .withOption( + obuilder + .withShortName("s") + .withDescription("Set CVS user variable.") + .withArgument(abuilder.withName("VAR=VAL").create()) + .create()) + .withOption(commands) + .create(); + + assertNotNull(cvsOptions); + } +} diff --git a/src/test/org/apache/commons/cli2/application/LsTest.java b/src/test/org/apache/commons/cli2/application/LsTest.java index 887d56b95..e68a248f5 100644 --- a/src/test/org/apache/commons/cli2/application/LsTest.java +++ b/src/test/org/apache/commons/cli2/application/LsTest.java @@ -1 +1,224 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.application;import java.util.HashSet;import java.util.Set;import junit.framework.Test;import junit.framework.TestCase;import junit.framework.TestSuite;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.validation.EnumValidator;/** *

      Test the ls command. Duplicated Option types are not * tested e.g. -a and -d are the same Option type.

      * *

      The following is the man output for 'ls'. See * http://www.rt.com/man/ls.1.html.

      * *
       *  LS(1) FSF LS(1) * *  NAME ls - list directory contents * *  SYNOPSIS ls [OPTION]... [FILE]... * *  DESCRIPTION List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuSUX nor --sort. * *  -a, --all do not hide entries starting with . * *  -A, --almost-all do not list implied . and .. * *  -b, --escape print octal escapes for nongraphic characters * *  --block-size=SIZE use SIZE-byte blocks * *  -B, --ignore-backups do not list implied entries ending with ~ -c sort by change time; with -l: show ctime -C list entries by columns * *  --color[=WHEN] control whether color is used to distinguish file types. WHEN may be `never', `always', or `auto' * *  -d, --directory list directory entries instead of contents * *  -D, --dired generate output designed for Emacs' dired mode -f do not sort, enable -aU, disable -lst * *  -F, --classify append indicator (one of /=@|*) to entries * *  --format=WORD across -x, commas -m, horizontal -x, long -l, sin- gle-column -1, verbose -l, vertical -C * *  --full-time list both full date and full time -g (ignored) * *  -G, --no-group inhibit display of group information * *  -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G) * *  -H, --si likewise, but use powers of 1000 not 1024 * *  --indicator-style=WORD append indicator with style WORD to entry names: none (default), classify (-F), file-type (-p) * *  -i, --inode print index number of each file * *  -I, --ignore=PATTERN do not list implied entries matching shell PATTERN * *  -k, --kilobytes like --block-size=1024 -l use a long listing format * *  -L, --dereference list entries pointed to by symbolic links -m fill width with a comma separated list of entries * *  -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names * *  -N, --literal print raw entry names (don't treat e.g. control characters specially) -o use long listing format without group info * *  -p, --file-type append indicator (one of /=@|) to entries * *  -q, --hide-control-chars print ? instead of non graphic characters * *  --show-control-chars show non graphic characters as-is (default) * *  -Q, --quote-name enclose entry names in double quotes * *  --quoting-style=WORD use quoting style WORD for entry names: literal, shell, shell-always, c, escape * *  -r, --reverse reverse order while sorting * *  -R, --recursive list subdirectories recursively * *  -s, --size print size of each file, in blocks -S sort by file size * *  --sort=WORD extension -X, none -U, size -S, time -t, version -v status -c, time -t, atime -u, access -u, use -u * *  --time=WORD show time as WORD instead of modification time: atime, access, use, ctime or status; use specified time as sort key if --sort=time -t sort by modification time * *  -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u sort by last access time; with -l: show atime -U do not sort; list entries in directory order -v sort by version * *  -w, --width=COLS assume screen width instead of current value -x list entries by lines instead of by columns -X sort alphabetically by entry extension -1 list one file per line * *  --help display this help and exit * *  --version output version information and exit * *  By default, color is not used to distinguish types of files. That is equivalent to using --color=none. Using the --color option without the optional WHEN argument is equivalent to using --color=always. With --color=auto, color codes are output only if standard output is con- nected to a terminal (tty). * 
      * * @author Rob Oxspring * @author John Keyes */public class LsTest extends TestCase { /** Option Builder */ private static final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); /** Argument Builder */ private static final ArgumentBuilder aBuilder = new ArgumentBuilder(); /** Group Builder */ private static final GroupBuilder gBuilder = new GroupBuilder(); private static Group options; public static Test suite() { return new TestSuite(LsTest.class); } /** * Required ctor. * * @param name * the name of the TestCase */ public LsTest(final String name) { super(name); } public void setUp() { if (LsTest.options == null) { final Option a = oBuilder .withShortName("a") .withLongName("all") .withDescription("do not hide entries starting with .") .create(); final Option blockSize = oBuilder .withLongName("block-size") .withRequired(false) .withDescription("use SIZE-byte blocks") .withArgument( aBuilder .withMaximum(1) .withMinimum(1) .withInitialSeparator('=') .create()) .create(); final Option c = oBuilder .withShortName("c") .withRequired(false) .withDescription("with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime") .create(); final Set colors = new HashSet(); colors.add("never"); colors.add("always"); colors.add("auto"); final Option color = oBuilder .withLongName("color") .withRequired(false) .withDescription("control whether color is used to distinguish file types. WHEN may be `never', `always', or `auto'") .withArgument( aBuilder .withMaximum(1) .withMinimum(1) .withInitialSeparator('=') .withValidator(new EnumValidator(colors)) .create()) .create(); LsTest.options = gBuilder .withOption(a) .withOption(blockSize) .withOption(c) .withOption(color) .create(); } } public void testLs() throws OptionException { // create the command line parser Parser parser = new Parser(); parser.setGroup(options); CommandLine line = parser.parse(new String[] { "--block-size=10", "--color=never" }); assertTrue(line.hasOption("--block-size")); assertEquals(line.getValue("--block-size"), "10"); assertFalse(line.hasOption("--ignore-backups")); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.application; + +import java.util.HashSet; +import java.util.Set; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.validation.EnumValidator; + +/** + *

      Test the ls command. Duplicated Option types are not + * tested e.g. -a and -d are the same Option type.

      + * + *

      The following is the man output for 'ls'. See + * http://www.rt.com/man/ls.1.html.

      + * + *
      + *  LS(1) FSF LS(1)
      + * 
      + *  NAME ls - list directory contents
      + * 
      + *  SYNOPSIS ls [OPTION]... [FILE]...
      + * 
      + *  DESCRIPTION List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuSUX nor --sort.
      + * 
      + *  -a, --all do not hide entries starting with .
      + * 
      + *  -A, --almost-all do not list implied . and ..
      + * 
      + *  -b, --escape print octal escapes for nongraphic characters
      + * 
      + *  --block-size=SIZE use SIZE-byte blocks
      + * 
      + *  -B, --ignore-backups do not list implied entries ending with ~ -c sort by change time; with -l: show ctime -C list entries by columns
      + * 
      + *  --color[=WHEN] control whether color is used to distinguish file types. WHEN may be `never', `always', or `auto'
      + * 
      + *  -d, --directory list directory entries instead of contents
      + * 
      + *  -D, --dired generate output designed for Emacs' dired mode -f do not sort, enable -aU, disable -lst
      + * 
      + *  -F, --classify append indicator (one of /=@|*) to entries
      + * 
      + *  --format=WORD across -x, commas -m, horizontal -x, long -l, sin- gle-column -1, verbose -l, vertical -C
      + * 
      + *  --full-time list both full date and full time -g (ignored)
      + * 
      + *  -G, --no-group inhibit display of group information
      + * 
      + *  -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)
      + * 
      + *  -H, --si likewise, but use powers of 1000 not 1024
      + * 
      + *  --indicator-style=WORD append indicator with style WORD to entry names: none (default), classify (-F), file-type (-p)
      + * 
      + *  -i, --inode print index number of each file
      + * 
      + *  -I, --ignore=PATTERN do not list implied entries matching shell PATTERN
      + * 
      + *  -k, --kilobytes like --block-size=1024 -l use a long listing format
      + * 
      + *  -L, --dereference list entries pointed to by symbolic links -m fill width with a comma separated list of entries
      + * 
      + *  -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names
      + * 
      + *  -N, --literal print raw entry names (don't treat e.g. control characters specially) -o use long listing format without group info
      + * 
      + *  -p, --file-type append indicator (one of /=@|) to entries
      + * 
      + *  -q, --hide-control-chars print ? instead of non graphic characters
      + * 
      + *  --show-control-chars show non graphic characters as-is (default)
      + * 
      + *  -Q, --quote-name enclose entry names in double quotes
      + * 
      + *  --quoting-style=WORD use quoting style WORD for entry names: literal, shell, shell-always, c, escape
      + * 
      + *  -r, --reverse reverse order while sorting
      + * 
      + *  -R, --recursive list subdirectories recursively
      + * 
      + *  -s, --size print size of each file, in blocks -S sort by file size
      + * 
      + *  --sort=WORD extension -X, none -U, size -S, time -t, version -v status -c, time -t, atime -u, access -u, use -u
      + * 
      + *  --time=WORD show time as WORD instead of modification time: atime, access, use, ctime or status; use specified time as sort key if --sort=time -t sort by modification time
      + * 
      + *  -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u sort by last access time; with -l: show atime -U do not sort; list entries in directory order -v sort by version
      + * 
      + *  -w, --width=COLS assume screen width instead of current value -x list entries by lines instead of by columns -X sort alphabetically by entry extension -1 list one file per line
      + * 
      + *  --help display this help and exit
      + * 
      + *  --version output version information and exit
      + * 
      + *  By default, color is not used to distinguish types of files. That is equivalent to using --color=none. Using the --color option without the optional WHEN argument is equivalent to using --color=always. With --color=auto, color codes are output only if standard output is con- nected to a terminal (tty).
      + * 
      + * + * @author Rob Oxspring + * @author John Keyes + */ +public class LsTest extends TestCase { + + /** Option Builder */ + private static final DefaultOptionBuilder oBuilder = + new DefaultOptionBuilder(); + + /** Argument Builder */ + private static final ArgumentBuilder aBuilder = new ArgumentBuilder(); + + /** Group Builder */ + private static final GroupBuilder gBuilder = new GroupBuilder(); + + private static Group options; + + public static Test suite() { + return new TestSuite(LsTest.class); + } + + /** + * Required ctor. + * + * @param name + * the name of the TestCase + */ + public LsTest(final String name) { + super(name); + } + + public void setUp() { + if (LsTest.options == null) { + final Option a = + oBuilder + .withShortName("a") + .withLongName("all") + .withDescription("do not hide entries starting with .") + .create(); + + final Option blockSize = + oBuilder + .withLongName("block-size") + .withRequired(false) + .withDescription("use SIZE-byte blocks") + .withArgument( + aBuilder + .withMaximum(1) + .withMinimum(1) + .withInitialSeparator('=') + .create()) + .create(); + + final Option c = + oBuilder + .withShortName("c") + .withRequired(false) + .withDescription("with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime") + .create(); + + final Set colors = new HashSet(); + colors.add("never"); + colors.add("always"); + colors.add("auto"); + final Option color = + oBuilder + .withLongName("color") + .withRequired(false) + .withDescription("control whether color is used to distinguish file types. WHEN may be `never', `always', or `auto'") + .withArgument( + aBuilder + .withMaximum(1) + .withMinimum(1) + .withInitialSeparator('=') + .withValidator(new EnumValidator(colors)) + .create()) + .create(); + + LsTest.options = + gBuilder + .withOption(a) + .withOption(blockSize) + .withOption(c) + .withOption(color) + .create(); + } + } + + public void testLs() throws OptionException { + // create the command line parser + Parser parser = new Parser(); + parser.setGroup(options); + CommandLine line = + parser.parse(new String[] { "--block-size=10", "--color=never" }); + + assertTrue(line.hasOption("--block-size")); + assertEquals(line.getValue("--block-size"), "10"); + assertFalse(line.hasOption("--ignore-backups")); + } +} diff --git a/src/test/org/apache/commons/cli2/bug/Bug13886Test.java b/src/test/org/apache/commons/cli2/bug/Bug13886Test.java index 6c5cf7ee4..9c2d97881 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug13886Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug13886Test.java @@ -1 +1,89 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;/** * @author John Keyes */public class Bug13886Test extends TestCase { public Bug13886Test(final String name) { super(name); } public void testMandatoryGroup() throws Exception { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Option a = obuilder.withShortName("a").create(); final Option b = obuilder.withShortName("b").create(); final Group options = gbuilder .withOption(a) .withOption(b) .withMaximum(1) .withMinimum(1) .create(); final Parser parser = new Parser(); parser.setGroup(options); try { parser.parse(new String[] { }); fail("Expected MissingOptionException not caught"); } catch (final OptionException exp) { assertEquals("Missing option -a|-b", exp.getMessage()); } try { parser.parse(new String[] { "-a" }); } catch (final OptionException exp) { fail("Unexpected MissingOptionException caught"); } try { parser.parse(new String[] { "-b" }); } catch (final OptionException exp) { fail("Unexpected MissingOptionException caught"); } try { parser.parse(new String[] { "-a", "-b" }); fail("Expected UnexpectedOptionException not caught"); } catch (final OptionException exp) { assertEquals( "Unexpected -b while processing -a|-b", exp.getMessage()); } }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; + +/** + * @author John Keyes + */ +public class Bug13886Test extends TestCase { + + public Bug13886Test(final String name) { + super(name); + } + + public void testMandatoryGroup() throws Exception { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + + final Option a = obuilder.withShortName("a").create(); + + final Option b = obuilder.withShortName("b").create(); + + final Group options = + gbuilder + .withOption(a) + .withOption(b) + .withMaximum(1) + .withMinimum(1) + .create(); + + final Parser parser = new Parser(); + parser.setGroup(options); + + try { + parser.parse(new String[] { + }); + fail("Expected MissingOptionException not caught"); + } + catch (final OptionException exp) { + assertEquals("Missing option -a|-b", exp.getMessage()); + } + + try { + parser.parse(new String[] { "-a" }); + } + catch (final OptionException exp) { + fail("Unexpected MissingOptionException caught"); + } + + try { + parser.parse(new String[] { "-b" }); + } + catch (final OptionException exp) { + fail("Unexpected MissingOptionException caught"); + } + + try { + parser.parse(new String[] { "-a", "-b" }); + fail("Expected UnexpectedOptionException not caught"); + } + catch (final OptionException exp) { + assertEquals( + "Unexpected -b while processing -a|-b", + exp.getMessage()); + } + } +} diff --git a/src/test/org/apache/commons/cli2/bug/Bug13935Test.java b/src/test/org/apache/commons/cli2/bug/Bug13935Test.java index bc68397d8..b76b91c0c 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug13935Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug13935Test.java @@ -1 +1,60 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;/** * @author John Keyes */public class Bug13935Test extends TestCase { public Bug13935Test(final String name) { super(name); } public void testRequiredGroup() throws Exception { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Option testOption = obuilder .withShortName("a") .withArgument(abuilder.withName("quoted string").create()) .create(); final Group options = gbuilder.withOption(testOption).create(); final Parser parser = new Parser(); parser.setGroup(options); final CommandLine cmdLine = parser.parse(new String[] { "-a", "\"two tokens\"" }); assertTrue(cmdLine.hasOption("-a")); assertEquals("two tokens", cmdLine.getValue("-a")); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; + +/** + * @author John Keyes + */ +public class Bug13935Test extends TestCase { + + public Bug13935Test(final String name) { + super(name); + } + + public void testRequiredGroup() throws Exception { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + + final Option testOption = + obuilder + .withShortName("a") + .withArgument(abuilder.withName("quoted string").create()) + .create(); + + final Group options = gbuilder.withOption(testOption).create(); + + final Parser parser = new Parser(); + parser.setGroup(options); + + final CommandLine cmdLine = + parser.parse(new String[] { "-a", "\"two tokens\"" }); + + assertTrue(cmdLine.hasOption("-a")); + assertEquals("two tokens", cmdLine.getValue("-a")); + } +} diff --git a/src/test/org/apache/commons/cli2/bug/Bug15046Test.java b/src/test/org/apache/commons/cli2/bug/Bug15046Test.java index 41a36d498..cf4c324d4 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug15046Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug15046Test.java @@ -1 +1,82 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;/** * @author John Keyes */public class Bug15046Test extends TestCase { public Bug15046Test(String name) { super(name); } public void testParamNamedAsOption() throws Exception { final String[] CLI_ARGS = new String[] { "-z", "c" }; DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); Option option = obuilder .withShortName("z") .withLongName("timezone") .withDescription("affected option") .withArgument(abuilder.withName("timezone").create()) .create(); GroupBuilder gbuilder = new GroupBuilder(); Group options = gbuilder.withName("bug15046").withOption(option).create(); Parser parser = new Parser(); parser.setGroup(options); CommandLine line = parser.parse(CLI_ARGS); assertEquals("c", line.getValue("-z")); Option c = obuilder .withShortName("c") .withLongName("conflict") .withDescription("conflicting option") .withArgument(abuilder.withName("conflict").create()) .create(); options = gbuilder .withName("bug15046") .withOption(option) .withOption(c) .create(); parser.setGroup(options); line = parser.parse(CLI_ARGS); assertEquals("c", line.getValue("-z")); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; + +/** + * @author John Keyes + */ +public class Bug15046Test extends TestCase { + + public Bug15046Test(String name) { + super(name); + } + + public void testParamNamedAsOption() throws Exception { + final String[] CLI_ARGS = new String[] { "-z", "c" }; + + DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + ArgumentBuilder abuilder = new ArgumentBuilder(); + + Option option = + obuilder + .withShortName("z") + .withLongName("timezone") + .withDescription("affected option") + .withArgument(abuilder.withName("timezone").create()) + .create(); + + GroupBuilder gbuilder = new GroupBuilder(); + Group options = + gbuilder.withName("bug15046").withOption(option).create(); + + Parser parser = new Parser(); + parser.setGroup(options); + CommandLine line = parser.parse(CLI_ARGS); + + assertEquals("c", line.getValue("-z")); + + Option c = + obuilder + .withShortName("c") + .withLongName("conflict") + .withDescription("conflicting option") + .withArgument(abuilder.withName("conflict").create()) + .create(); + + options = + gbuilder + .withName("bug15046") + .withOption(option) + .withOption(c) + .create(); + + parser.setGroup(options); + line = parser.parse(CLI_ARGS); + + assertEquals("c", line.getValue("-z")); + } +} diff --git a/src/test/org/apache/commons/cli2/bug/Bug15648Test.java b/src/test/org/apache/commons/cli2/bug/Bug15648Test.java index af905e1bf..1cc0da806 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug15648Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug15648Test.java @@ -1 +1,60 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;/** * @author John Keyes */public class Bug15648Test extends TestCase { public Bug15648Test(final String name) { super(name); } public void testQuotedArgumentValue() throws Exception { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Option testOption = obuilder .withShortName("a") .withArgument(abuilder.withName("quoted string").create()) .create(); final Group options = gbuilder.withOption(testOption).create(); final Parser parser = new Parser(); parser.setGroup(options); final CommandLine cmdLine = parser.parse(new String[] { "-a", "\"two tokens\"" }); assertTrue(cmdLine.hasOption("-a")); assertEquals("two tokens", cmdLine.getValue("-a")); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; + +/** + * @author John Keyes + */ +public class Bug15648Test extends TestCase { + + public Bug15648Test(final String name) { + super(name); + } + + public void testQuotedArgumentValue() throws Exception { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + + final Option testOption = + obuilder + .withShortName("a") + .withArgument(abuilder.withName("quoted string").create()) + .create(); + + final Group options = gbuilder.withOption(testOption).create(); + + final Parser parser = new Parser(); + parser.setGroup(options); + + final CommandLine cmdLine = + parser.parse(new String[] { "-a", "\"two tokens\"" }); + + assertTrue(cmdLine.hasOption("-a")); + assertEquals("two tokens", cmdLine.getValue("-a")); + } +} diff --git a/src/test/org/apache/commons/cli2/bug/Bug27575Test.java b/src/test/org/apache/commons/cli2/bug/Bug27575Test.java index 368218039..fb7a5a900 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug27575Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug27575Test.java @@ -1 +1,41 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import java.util.Iterator;import junit.framework.TestCase;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.PatternBuilder;import org.apache.commons.cli2.option.GroupImpl;public class Bug27575Test extends TestCase { public void testRequiredOptions(){ PatternBuilder builder = new PatternBuilder(); builder.withPattern("hc!<"); Option option = builder.create(); assertTrue(option instanceof GroupImpl); GroupImpl group = (GroupImpl)option; Iterator i = group.getOptions().iterator(); assertEquals("[-h]",i.next().toString()); assertEquals("-c ",i.next().toString()); assertFalse(i.hasNext()); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import java.util.Iterator; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.builder.PatternBuilder; +import org.apache.commons.cli2.option.GroupImpl; + +public class Bug27575Test extends TestCase { + + public void testRequiredOptions(){ + PatternBuilder builder = new PatternBuilder(); + builder.withPattern("hc!<"); + Option option = builder.create(); + assertTrue(option instanceof GroupImpl); + + GroupImpl group = (GroupImpl)option; + Iterator i = group.getOptions().iterator(); + assertEquals("[-h]",i.next().toString()); + assertEquals("-c ",i.next().toString()); + assertFalse(i.hasNext()); + } +} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/Bug28005Test.java b/src/test/org/apache/commons/cli2/bug/Bug28005Test.java index 5671ec5b6..2c81ca302 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug28005Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug28005Test.java @@ -1 +1,79 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.CommandBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import junit.framework.TestCase;public class Bug28005Test extends TestCase { public void testInfiniteLoop() { final DefaultOptionBuilder optionBuilder = new DefaultOptionBuilder(); final ArgumentBuilder argumentBuilder = new ArgumentBuilder(); final GroupBuilder groupBuilder = new GroupBuilder(); final CommandBuilder commandBuilder = new CommandBuilder(); final Option inputFormatOption = optionBuilder .withLongName("input-format") //.withArgument(argumentBuilder.create()) .create(); final Argument argument = argumentBuilder .withName("file") .create(); final Group children = groupBuilder .withName("options") .withOption(inputFormatOption) .create(); final Option command = commandBuilder .withName("convert") .withChildren(children) .withArgument(argument) .create(); final Group root = groupBuilder .withName("commands") .withOption(command) .create(); final Parser parser = new Parser(); parser.setGroup(root); final String[] args = new String[]{"convert", "test.txt", "--input-format", "a"}; try { parser.parse(args); fail("a isn't valid!!"); } catch (OptionException e) { assertEquals("Unexpected a while processing commands",e.getMessage()); } }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.CommandBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import junit.framework.TestCase; + +public class Bug28005Test extends TestCase { + public void testInfiniteLoop() { + final DefaultOptionBuilder optionBuilder = new DefaultOptionBuilder(); + final ArgumentBuilder argumentBuilder = new ArgumentBuilder(); + final GroupBuilder groupBuilder = new GroupBuilder(); + final CommandBuilder commandBuilder = new CommandBuilder(); + + final Option inputFormatOption = + optionBuilder + .withLongName("input-format") + //.withArgument(argumentBuilder.create()) + .create(); + + final Argument argument = + argumentBuilder + .withName("file") + .create(); + + final Group children = + groupBuilder + .withName("options") + .withOption(inputFormatOption) + .create(); + + final Option command = + commandBuilder + .withName("convert") + .withChildren(children) + .withArgument(argument) + .create(); + + final Group root = + groupBuilder + .withName("commands") + .withOption(command) + .create(); + + final Parser parser = new Parser(); + parser.setGroup(root); + final String[] args = new String[]{"convert", "test.txt", + "--input-format", "a"}; + + try { + parser.parse(args); + fail("a isn't valid!!"); + } catch (OptionException e) { + assertEquals("Unexpected a while processing commands",e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/Bug32533Test.java b/src/test/org/apache/commons/cli2/bug/Bug32533Test.java index 19547b0e5..56f337202 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug32533Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug32533Test.java @@ -1 +1,48 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import junit.framework.TestCase;/** * @author roxspring */public class Bug32533Test extends TestCase { public void testBlah() throws OptionException { Option a1 = new DefaultOptionBuilder().withLongName("a1").create(); Option b1 = new DefaultOptionBuilder().withLongName("b1").create(); Option c1 = new DefaultOptionBuilder().withLongName("c1").create(); Group b = new GroupBuilder().withOption(b1).create(); Group c = new GroupBuilder().withOption(c1).create(); Group a = new GroupBuilder().withOption(a1).withOption(b).withOption(c).create(); Parser parser = new Parser(); parser.setGroup(a); parser.parse(new String[]{"--a1","--b1"}); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; + +import junit.framework.TestCase; + +/** + * @author roxspring + */ +public class Bug32533Test extends TestCase { + + public void testBlah() throws OptionException { + + Option a1 = new DefaultOptionBuilder().withLongName("a1").create(); + Option b1 = new DefaultOptionBuilder().withLongName("b1").create(); + Option c1 = new DefaultOptionBuilder().withLongName("c1").create(); + + Group b = new GroupBuilder().withOption(b1).create(); + Group c = new GroupBuilder().withOption(c1).create(); + Group a = new GroupBuilder().withOption(a1).withOption(b).withOption(c).create(); + + Parser parser = new Parser(); + parser.setGroup(a); + parser.parse(new String[]{"--a1","--b1"}); + } + +} diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java index 474954927..5e818e6f3 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java @@ -1 +1,45 @@ -package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.*;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.validation.FileValidator;/** * @author brianegge */public class BugCLI122Test extends TestCase { public void testArgumentWhichStartsWithDash() throws OptionException { Argument wdArg = new ArgumentBuilder() .withName("anything") .withMaximum(1) .withMinimum(1) .withInitialSeparator('=') .create(); Option wdOpt = new DefaultOptionBuilder().withArgument(wdArg) .withDescription("anything, foo or -foo") .withLongName("argument") .withShortName("a") .create(); Group group = new GroupBuilder().withOption(wdOpt).create(); Parser p = new Parser(); p.setGroup(group); CommandLine normal = p.parse (new String[]{"-a", "foo"}); assertNotNull(normal); assertEquals(normal.getValue(wdOpt), "foo"); CommandLine withDash = p.parse (new String[]{"--argument", "\"-foo\""}); assertNotNull(withDash); assertEquals("-foo", withDash.getValue(wdOpt)); CommandLine withDashAndEquals = p.parse (new String[]{"--argument=-foo"}); assertNotNull(withDashAndEquals); assertEquals("-foo", withDashAndEquals.getValue(wdOpt)); }} \ No newline at end of file +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; +import org.apache.commons.cli2.*; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.validation.FileValidator; + +/** + * @author brianegge + */ +public class BugCLI122Test extends TestCase { + public void testArgumentWhichStartsWithDash() throws OptionException { + Argument wdArg = new ArgumentBuilder() + .withName("anything") + .withMaximum(1) + .withMinimum(1) + .withInitialSeparator('=') + .create(); + + Option wdOpt = new DefaultOptionBuilder().withArgument(wdArg) + .withDescription("anything, foo or -foo") + .withLongName("argument") + .withShortName("a") + .create(); + + Group group = new GroupBuilder().withOption(wdOpt).create(); + + Parser p = new Parser(); + p.setGroup(group); + CommandLine normal = p.parse (new String[]{"-a", "foo"}); + assertNotNull(normal); + assertEquals(normal.getValue(wdOpt), "foo"); + + CommandLine withDash = p.parse (new String[]{"--argument", "\"-foo\""}); + assertNotNull(withDash); + assertEquals("-foo", withDash.getValue(wdOpt)); + + CommandLine withDashAndEquals = p.parse (new String[]{"--argument=-foo"}); + assertNotNull(withDashAndEquals); + assertEquals("-foo", withDashAndEquals.getValue(wdOpt)); + } +} diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java index 8f7adae78..fa1a09a16 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java @@ -1 +1,57 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.option.PropertyOption;/** * http://issues.apache.org/jira/browse/CLI-12 */public class BugCLI12Test extends TestCase { public void testBug() { Argument arg = new ArgumentBuilder().withName("file").create(); Option option = new PropertyOption(); Group group = new GroupBuilder().withOption(option).withOption(arg).create(); Parser p = new Parser(); p.setGroup(group); CommandLine cl = p.parseAndHelp( new String[] { "-Dmyprop1=myval1", "-Dmyprop2=myval2", "myfile" } ); if(cl == null) { assertTrue("Couldn't parse valid commandLine", false); } assertEquals( "myval1", cl.getProperty("myprop1")); assertEquals( "myval2", cl.getProperty("myprop2")); String extraArgs = (String) cl.getValue(arg); assertEquals( "myfile", extraArgs); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.option.PropertyOption; + +/** + * http://issues.apache.org/jira/browse/CLI-12 + */ +public class BugCLI12Test extends TestCase { + + public void testBug() { + Argument arg = new ArgumentBuilder().withName("file").create(); + + Option option = new PropertyOption(); + + Group group = new GroupBuilder().withOption(option).withOption(arg).create(); + + Parser p = new Parser(); + p.setGroup(group); + + CommandLine cl = p.parseAndHelp( new String[] { "-Dmyprop1=myval1", "-Dmyprop2=myval2", "myfile" } ); + if(cl == null) { + assertTrue("Couldn't parse valid commandLine", false); + } + + assertEquals( "myval1", cl.getProperty("myprop1")); + assertEquals( "myval2", cl.getProperty("myprop2")); + + String extraArgs = (String) cl.getValue(arg); + assertEquals( "myfile", extraArgs); + } + +} diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI18Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI18Test.java index 331428907..dda88aa61 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI18Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI18Test.java @@ -1 +1,60 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import java.io.PrintWriter;import java.io.StringWriter;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.util.HelpFormatter;import junit.framework.TestCase;/** * http://issues.apache.org/jira/browse/CLI-18 */public class BugCLI18Test extends TestCase { public BugCLI18Test() { super(); } public void testBug() { Option a = new DefaultOptionBuilder().withLongName("aaa").withShortName("a").withDescription("aaaaaaa").create(); Option b = new DefaultOptionBuilder().withLongName("bbb").withDescription("bbbbbbbb dksh fkshd fkhs dkfhsdk fhskd hksdks dhfowehfsdhfkjshf skfhkshf sf jkshfk sfh skfh skf f").create(); Option c = new DefaultOptionBuilder().withLongName("ccc").withShortName("c").withDescription("ccccccc").create(); Group g = new GroupBuilder().withOption(a).withOption(b).withOption(c).create(); HelpFormatter formatter = new HelpFormatter(); StringWriter out = new StringWriter(); formatter.setPrintWriter(new PrintWriter(out)); formatter.setHeader("dsfkfsh kdh hsd hsdh fkshdf ksdh fskdh fsdh fkshfk sfdkjhskjh fkjh fkjsh khsdkj hfskdhf skjdfh ksf khf s"); formatter.setFooter("blort j jgj j jg jhghjghjgjhgjhg jgjhgj jhg jhg hjg jgjhghjg jhg hjg jhgjg jgjhghjg jg jgjhgjgjg jhg jhgjh" + '\r' + '\n' + "rarrr"); formatter.setGroup(g); formatter.setShellCommand("foobar"); formatter.print(); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.util.HelpFormatter; + +import junit.framework.TestCase; + +/** + * http://issues.apache.org/jira/browse/CLI-18 + */ +public class BugCLI18Test extends TestCase { + + public BugCLI18Test() { + super(); + } + + + public void testBug() { + Option a = new DefaultOptionBuilder().withLongName("aaa").withShortName("a").withDescription("aaaaaaa").create(); + Option b = new DefaultOptionBuilder().withLongName("bbb").withDescription("bbbbbbbb dksh fkshd fkhs dkfhsdk fhskd hksdks dhfowehfsdhfkjshf skfhkshf sf jkshfk sfh skfh skf f").create(); + Option c = new DefaultOptionBuilder().withLongName("ccc").withShortName("c").withDescription("ccccccc").create(); + + Group g = new GroupBuilder().withOption(a).withOption(b).withOption(c).create(); + + HelpFormatter formatter = new HelpFormatter(); + StringWriter out = new StringWriter(); + + formatter.setPrintWriter(new PrintWriter(out)); + formatter.setHeader("dsfkfsh kdh hsd hsdh fkshdf ksdh fskdh fsdh fkshfk sfdkjhskjh fkjh fkjsh khsdkj hfskdhf skjdfh ksf khf s"); + formatter.setFooter("blort j jgj j jg jhghjghjgjhgjhg jgjhgj jhg jhg hjg jgjhghjg jhg hjg jhgjg jgjhghjg jg jgjhgjgjg jhg jhgjh" + '\r' + '\n' + "rarrr"); + formatter.setGroup(g); + formatter.setShellCommand("foobar"); + + formatter.print(); + + } +} + diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java index db94fbbd4..13787100a 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI80Test.java @@ -1 +1,67 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.bug;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import junit.framework.TestCase;/** * http://issues.apache.org/jira/browse/CLI-80 */public class BugCLI80Test extends TestCase { public void testBug() { final String optName = "option"; Argument arg = new ArgumentBuilder().withName(optName) .withMaximum(1) .create(); Option option = new DefaultOptionBuilder().withArgument(arg) .withDescription("singular option") .withLongName(optName) .withShortName("o") .create(); Group group = new GroupBuilder().withOption(option).create(); Parser p = new Parser(); p.setGroup(group); CommandLine cl = p.parseAndHelp( new String[] { "-o", "yes" } ); assertNotNull("Couldn't parse valid commandLine", cl); assertEquals("Couldn't look up value by short name", "yes", cl.getValue("-o") ); try { cl = p.parse( new String[] { "-o", "yes", "-o", "jam" } ); fail("Parsed invalid commandLine"); } catch(OptionException e) { // ok } }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; + +import junit.framework.TestCase; + +/** + * http://issues.apache.org/jira/browse/CLI-80 + */ +public class BugCLI80Test extends TestCase { + + public void testBug() { + final String optName = "option"; + + Argument arg = new ArgumentBuilder().withName(optName) + .withMaximum(1) + .create(); + + Option option = new DefaultOptionBuilder().withArgument(arg) + .withDescription("singular option") + .withLongName(optName) + .withShortName("o") + .create(); + + Group group = new GroupBuilder().withOption(option).create(); + + Parser p = new Parser(); + p.setGroup(group); + + CommandLine cl = p.parseAndHelp( new String[] { "-o", "yes" } ); + assertNotNull("Couldn't parse valid commandLine", cl); + + assertEquals("Couldn't look up value by short name", "yes", cl.getValue("-o") ); + + try { + cl = p.parse( new String[] { "-o", "yes", "-o", "jam" } ); + fail("Parsed invalid commandLine"); + } catch(OptionException e) { + // ok + } + } + +} diff --git a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java index 57022582b..f0e6d4d3a 100644 --- a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java +++ b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java @@ -1 +1,79 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.commons.cli2.bug;import junit.framework.TestCase;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.option.SourceDestArgument;/** * The first is a loop in Parser.parse() if I set a non-declared option. This * code goes into a loop in Parser.java method parse this “while” loop runs * endless * * @author Steve Alberty */public class BugLoopingOptionLookAlikeTest extends TestCase { public void testLoopingOptionLookAlike() { final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Group options = gbuilder .withName("ant") .withOption(obuilder.withShortName("help").withDescription("print this message").create()) .withOption(obuilder.withShortName("projecthelp").withDescription("print project help information").create()) .withOption(abuilder.withName("target").create()) .create(); final Parser parser = new Parser(); parser.setGroup(options); try { parser.parse(new String[] { "-abcdef", "testfile.txt ", }); fail("OptionException"); } catch (OptionException e) { assertEquals("Unexpected -abcdef while processing ant",e.getMessage()); } } public void testLoopingOptionLookAlike2() { final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Argument inputfile_opt = abuilder.withName("input").withMinimum(1).withMaximum(1).create(); final Argument outputfile_opt = abuilder.withName("output").withMinimum(1).withMaximum(1).create(); final Argument targets = new SourceDestArgument(inputfile_opt, outputfile_opt); final Group options = gbuilder.withOption(targets).create(); final Parser parser = new Parser(); parser.setGroup(options); try { parser.parse(new String[] { "testfile.txt", "testfile.txt", "testfile.txt", "testfile.txt" }); fail("OptionException"); } catch (OptionException e) { assertEquals("Unexpected testfile.txt while processing ", e.getMessage()); } }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.option.SourceDestArgument; + +/** + * The first is a loop in Parser.parse() if I set a non-declared option. This + * code goes into a loop in Parser.java method parse this “while” loop runs + * endless + * + * @author Steve Alberty + */ +public class BugLoopingOptionLookAlikeTest extends TestCase { + + public void testLoopingOptionLookAlike() { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + final Group options = gbuilder + .withName("ant") + .withOption(obuilder.withShortName("help").withDescription("print this message").create()) + .withOption(obuilder.withShortName("projecthelp").withDescription("print project help information").create()) + .withOption(abuilder.withName("target").create()) + .create(); + + final Parser parser = new Parser(); + parser.setGroup(options); + try { + parser.parse(new String[] { "-abcdef", + "testfile.txt ", }); + fail("OptionException"); + } catch (OptionException e) { + assertEquals("Unexpected -abcdef while processing ant",e.getMessage()); + } + } + + public void testLoopingOptionLookAlike2() { + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + final Argument inputfile_opt = abuilder.withName("input").withMinimum(1).withMaximum(1).create(); + final Argument outputfile_opt = abuilder.withName("output").withMinimum(1).withMaximum(1).create(); + final Argument targets = new SourceDestArgument(inputfile_opt, outputfile_opt); + final Group options = gbuilder.withOption(targets).create(); + final Parser parser = new Parser(); + parser.setGroup(options); + try { + parser.parse(new String[] { "testfile.txt", "testfile.txt", "testfile.txt", "testfile.txt" }); + fail("OptionException"); + } catch (OptionException e) { + assertEquals("Unexpected testfile.txt while processing ", e.getMessage()); + } + } +} diff --git a/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java b/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java index 9761f4c03..877523aaf 100644 --- a/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java +++ b/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java @@ -1 +1,254 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.commons.cli2.builder;import java.util.ArrayList;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.option.ArgumentImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;import org.apache.commons.cli2.validation.DateValidator;import org.apache.commons.cli2.validation.Validator;public class ArgumentBuilderTest extends TestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); private ArgumentBuilder argumentBuilder; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { this.argumentBuilder = new ArgumentBuilder(); } public void testConsumeRemaining() { this.argumentBuilder.withConsumeRemaining("--"); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect consume remaining token", "--", arg.getConsumeRemaining()); } public void testNullConsumeRemaining() { try { this.argumentBuilder.withConsumeRemaining(null); fail("cannot use null consume remaining token"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING), exp.getMessage()); } } public void testEmptyConsumeRemaining() { try { this.argumentBuilder.withConsumeRemaining(""); fail("cannot use empty string consume remaining token"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING), exp.getMessage()); } } public void testDefault() { this.argumentBuilder.withDefault("defaultString"); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect number of default values", 1, arg.getDefaultValues().size()); assertEquals("incorrect default value", "defaultString", arg.getDefaultValues().get(0)); } public void testDefaultX2() { this.argumentBuilder.withDefault("defaultString1"); this.argumentBuilder.withDefault("defaultString2"); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); assertEquals("incorrect default value-1", "defaultString1", arg.getDefaultValues().get(0)); assertEquals("incorrect default value-2", "defaultString2", arg.getDefaultValues().get(1)); } public void testNullDefault() { try { this.argumentBuilder.withDefault(null); fail("cannot use null default"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT), exp.getMessage()); } } public void testDefaults() { final List defaults = new ArrayList(); defaults.add("one"); defaults.add("two"); this.argumentBuilder.withDefaults(defaults); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); assertEquals("incorrect default value-1", "one", arg.getDefaultValues().get(0)); assertEquals("incorrect default value-2", "two", arg.getDefaultValues().get(1)); assertEquals("incorrect default values list", defaults, arg.getDefaultValues()); } public void testNullDefaults() { try { this.argumentBuilder.withDefaults(null); fail("cannot use null defaults"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS), exp.getMessage()); } } public void testId() { this.argumentBuilder.withId(1); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect id", 1, arg.getId()); } public void testInitialSeparator() { this.argumentBuilder.withInitialSeparator(','); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect initial separator", ',', arg.getInitialSeparator()); } public void testMaximum() { this.argumentBuilder.withMaximum(1); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect maximum", 1, arg.getMaximum()); } public void testNegativeMaximum() { try { this.argumentBuilder.withMaximum(-1); fail("cannot use negative maximum"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM), exp.getMessage()); } } public void testMinimum() { this.argumentBuilder.withMinimum(1); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect maximum", 1, arg.getMinimum()); } public void testNegativeMinimum() { try { this.argumentBuilder.withMinimum(-1); fail("cannot use negative minimum"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM), exp.getMessage()); } } public void testName() { this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect preferred name", "arg", arg.getPreferredName()); } public void testNullName() { try { this.argumentBuilder.withName(null); fail("cannot use null name"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME), exp.getMessage()); } } public void testEmptyName() { try { this.argumentBuilder.withName(""); fail("cannot use empty name"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME), exp.getMessage()); } } public void testSubsequentSeparator() { this.argumentBuilder.withSubsequentSeparator(':'); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect subsequent separator", ':', arg.getSubsequentSeparator()); } public void testValidator() { Validator validator = DateValidator.getDateInstance(); this.argumentBuilder.withValidator(validator); this.argumentBuilder.withName("arg"); ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); assertEquals("incorrect validator", validator, arg.getValidator()); } public void testNullValidator() { try { this.argumentBuilder.withValidator(null); fail("cannot use null validator"); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR), exp.getMessage()); } }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.cli2.builder; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.option.ArgumentImpl; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; +import org.apache.commons.cli2.validation.DateValidator; +import org.apache.commons.cli2.validation.Validator; + +public class ArgumentBuilderTest + extends TestCase { + private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); + private ArgumentBuilder argumentBuilder; + + /* + * @see TestCase#setUp() + */ + protected void setUp() + throws Exception { + this.argumentBuilder = new ArgumentBuilder(); + } + + public void testConsumeRemaining() { + this.argumentBuilder.withConsumeRemaining("--"); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect consume remaining token", "--", arg.getConsumeRemaining()); + } + + public void testNullConsumeRemaining() { + try { + this.argumentBuilder.withConsumeRemaining(null); + fail("cannot use null consume remaining token"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING), + exp.getMessage()); + } + } + + public void testEmptyConsumeRemaining() { + try { + this.argumentBuilder.withConsumeRemaining(""); + fail("cannot use empty string consume remaining token"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING), + exp.getMessage()); + } + } + + public void testDefault() { + this.argumentBuilder.withDefault("defaultString"); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect number of default values", 1, arg.getDefaultValues().size()); + assertEquals("incorrect default value", "defaultString", arg.getDefaultValues().get(0)); + } + + public void testDefaultX2() { + this.argumentBuilder.withDefault("defaultString1"); + this.argumentBuilder.withDefault("defaultString2"); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); + assertEquals("incorrect default value-1", "defaultString1", arg.getDefaultValues().get(0)); + assertEquals("incorrect default value-2", "defaultString2", arg.getDefaultValues().get(1)); + } + + public void testNullDefault() { + try { + this.argumentBuilder.withDefault(null); + fail("cannot use null default"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT), + exp.getMessage()); + } + } + + public void testDefaults() { + final List defaults = new ArrayList(); + defaults.add("one"); + defaults.add("two"); + + this.argumentBuilder.withDefaults(defaults); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); + assertEquals("incorrect default value-1", "one", arg.getDefaultValues().get(0)); + assertEquals("incorrect default value-2", "two", arg.getDefaultValues().get(1)); + assertEquals("incorrect default values list", defaults, arg.getDefaultValues()); + + } + + public void testNullDefaults() { + try { + this.argumentBuilder.withDefaults(null); + fail("cannot use null defaults"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS), + exp.getMessage()); + } + } + + public void testId() { + this.argumentBuilder.withId(1); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect id", 1, arg.getId()); + } + + public void testInitialSeparator() { + this.argumentBuilder.withInitialSeparator(','); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect initial separator", ',', arg.getInitialSeparator()); + } + + public void testMaximum() { + this.argumentBuilder.withMaximum(1); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect maximum", 1, arg.getMaximum()); + } + + public void testNegativeMaximum() { + try { + this.argumentBuilder.withMaximum(-1); + fail("cannot use negative maximum"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM), + exp.getMessage()); + } + } + + public void testMinimum() { + this.argumentBuilder.withMinimum(1); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect maximum", 1, arg.getMinimum()); + } + + public void testNegativeMinimum() { + try { + this.argumentBuilder.withMinimum(-1); + fail("cannot use negative minimum"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM), + exp.getMessage()); + } + } + + public void testName() { + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect preferred name", "arg", arg.getPreferredName()); + } + + public void testNullName() { + try { + this.argumentBuilder.withName(null); + fail("cannot use null name"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME), + exp.getMessage()); + } + } + + public void testEmptyName() { + try { + this.argumentBuilder.withName(""); + fail("cannot use empty name"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME), + exp.getMessage()); + } + } + + public void testSubsequentSeparator() { + this.argumentBuilder.withSubsequentSeparator(':'); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect subsequent separator", ':', arg.getSubsequentSeparator()); + } + + public void testValidator() { + Validator validator = DateValidator.getDateInstance(); + this.argumentBuilder.withValidator(validator); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect validator", validator, arg.getValidator()); + } + + public void testNullValidator() { + try { + this.argumentBuilder.withValidator(null); + fail("cannot use null validator"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR), + exp.getMessage()); + } + } +} diff --git a/src/test/org/apache/commons/cli2/builder/DefaultOptionBuilderTest.java b/src/test/org/apache/commons/cli2/builder/DefaultOptionBuilderTest.java index c268798eb..36dcd64e8 100644 --- a/src/test/org/apache/commons/cli2/builder/DefaultOptionBuilderTest.java +++ b/src/test/org/apache/commons/cli2/builder/DefaultOptionBuilderTest.java @@ -1 +1,200 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.builder;import junit.framework.TestCase;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.option.DefaultOption;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;public class DefaultOptionBuilderTest extends TestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); private DefaultOptionBuilder defaultOptionBuilder; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { this.defaultOptionBuilder = new DefaultOptionBuilder(); } /* * Class to test for void DefaultOptionBuilder(String, String, boolean) */ public void testNew_NullShortPrefix() { try { new DefaultOptionBuilder(null, null, false); fail("null short prefix is not permitted"); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX), e.getMessage()); } } /* * Class to test for void DefaultOptionBuilder(String, String, boolean) */ public void testNew_EmptyShortPrefix() { try { new DefaultOptionBuilder("", null, false); fail("empty short prefix is not permitted"); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX), e.getMessage()); } } /* * Class to test for void DefaultOptionBuilder(String, String, boolean) */ public void testNew_NullLongPrefix() { try { new DefaultOptionBuilder("-", null, false); fail("null long prefix is not permitted"); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX), e.getMessage()); } } /* * Class to test for void DefaultOptionBuilder(String, String, boolean) */ public void testNew_EmptyLongPrefix() { try { new DefaultOptionBuilder("-", "", false); fail("empty long prefix is not permitted"); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX), e.getMessage()); } } public void testCreate() { try { this.defaultOptionBuilder.create(); fail("options must have a name"); } catch (IllegalStateException e) { assertEquals(resources.getMessage(ResourceConstants.OPTION_NO_NAME), e.getMessage()); } this.defaultOptionBuilder.withShortName("j"); this.defaultOptionBuilder.create(); this.defaultOptionBuilder.withLongName("jkeyes"); this.defaultOptionBuilder.create(); { DefaultOptionBuilder builder = new DefaultOptionBuilder("-", "--", true); builder.withShortName("mx"); } } public void testName() { // withLongName && this.preferred != null { this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withLongName("apples"); } // withShortName && this.preferred != null { this.defaultOptionBuilder.withLongName("apples"); this.defaultOptionBuilder.withShortName("a"); } // withShortName && this.preferred != null { this.defaultOptionBuilder.withLongName("apples"); this.defaultOptionBuilder.withShortName("a"); } } public void testWithDescription() { String description = "desc"; this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withDescription(description); DefaultOption opt = this.defaultOptionBuilder.create(); assertEquals("wrong description found", description, opt.getDescription()); } public void testWithRequired() { { boolean required = false; this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withRequired(required); DefaultOption opt = this.defaultOptionBuilder.create(); assertEquals("wrong required found", required, opt.isRequired()); } { boolean required = true; this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withRequired(required); DefaultOption opt = this.defaultOptionBuilder.create(); assertEquals("wrong required found", required, opt.isRequired()); } } public void testWithChildren() { GroupBuilder gbuilder = new GroupBuilder(); this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withRequired(true); DefaultOption opt = this.defaultOptionBuilder.create(); Group group = gbuilder.withName("withchildren").withOption(opt).create(); { this.defaultOptionBuilder.withShortName("b"); this.defaultOptionBuilder.withChildren(group); DefaultOption option = this.defaultOptionBuilder.create(); assertEquals("wrong children found", group, option.getChildren()); } } public void testWithArgument() { ArgumentBuilder abuilder = new ArgumentBuilder(); abuilder.withName("myarg"); Argument arg = abuilder.create(); this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withRequired(true); this.defaultOptionBuilder.withArgument(arg); DefaultOption opt = this.defaultOptionBuilder.create(); assertEquals("wrong argument found", arg, opt.getArgument()); } public void testWithId() { this.defaultOptionBuilder.withShortName("a"); this.defaultOptionBuilder.withId(0); DefaultOption opt = this.defaultOptionBuilder.create(); assertEquals("wrong id found", 0, opt.getId()); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.builder; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.option.DefaultOption; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +public class DefaultOptionBuilderTest + extends TestCase { + private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); + private DefaultOptionBuilder defaultOptionBuilder; + + /* + * @see TestCase#setUp() + */ + protected void setUp() + throws Exception { + this.defaultOptionBuilder = new DefaultOptionBuilder(); + } + + /* + * Class to test for void DefaultOptionBuilder(String, String, boolean) + */ + public void testNew_NullShortPrefix() { + try { + new DefaultOptionBuilder(null, null, false); + fail("null short prefix is not permitted"); + } catch (IllegalArgumentException e) { + assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX), + e.getMessage()); + } + } + + /* + * Class to test for void DefaultOptionBuilder(String, String, boolean) + */ + public void testNew_EmptyShortPrefix() { + try { + new DefaultOptionBuilder("", null, false); + fail("empty short prefix is not permitted"); + } catch (IllegalArgumentException e) { + assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_SHORT_PREFIX), + e.getMessage()); + } + } + + /* + * Class to test for void DefaultOptionBuilder(String, String, boolean) + */ + public void testNew_NullLongPrefix() { + try { + new DefaultOptionBuilder("-", null, false); + fail("null long prefix is not permitted"); + } catch (IllegalArgumentException e) { + assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX), + e.getMessage()); + } + } + + /* + * Class to test for void DefaultOptionBuilder(String, String, boolean) + */ + public void testNew_EmptyLongPrefix() { + try { + new DefaultOptionBuilder("-", "", false); + fail("empty long prefix is not permitted"); + } catch (IllegalArgumentException e) { + assertEquals(resources.getMessage(ResourceConstants.OPTION_ILLEGAL_LONG_PREFIX), + e.getMessage()); + } + } + + public void testCreate() { + try { + this.defaultOptionBuilder.create(); + fail("options must have a name"); + } catch (IllegalStateException e) { + assertEquals(resources.getMessage(ResourceConstants.OPTION_NO_NAME), e.getMessage()); + } + + this.defaultOptionBuilder.withShortName("j"); + this.defaultOptionBuilder.create(); + this.defaultOptionBuilder.withLongName("jkeyes"); + this.defaultOptionBuilder.create(); + + { + DefaultOptionBuilder builder = new DefaultOptionBuilder("-", "--", true); + builder.withShortName("mx"); + } + } + + public void testName() { + // withLongName && this.preferred != null + { + this.defaultOptionBuilder.withShortName("a"); + this.defaultOptionBuilder.withLongName("apples"); + } + // withShortName && this.preferred != null + { + this.defaultOptionBuilder.withLongName("apples"); + this.defaultOptionBuilder.withShortName("a"); + } + // withShortName && this.preferred != null + { + this.defaultOptionBuilder.withLongName("apples"); + this.defaultOptionBuilder.withShortName("a"); + } + } + + public void testWithDescription() { + String description = "desc"; + this.defaultOptionBuilder.withShortName("a"); + this.defaultOptionBuilder.withDescription(description); + + DefaultOption opt = this.defaultOptionBuilder.create(); + assertEquals("wrong description found", description, opt.getDescription()); + } + + public void testWithRequired() { + { + boolean required = false; + this.defaultOptionBuilder.withShortName("a"); + this.defaultOptionBuilder.withRequired(required); + + DefaultOption opt = this.defaultOptionBuilder.create(); + assertEquals("wrong required found", required, opt.isRequired()); + } + + { + boolean required = true; + this.defaultOptionBuilder.withShortName("a"); + this.defaultOptionBuilder.withRequired(required); + + DefaultOption opt = this.defaultOptionBuilder.create(); + assertEquals("wrong required found", required, opt.isRequired()); + } + } + + public void testWithChildren() { + GroupBuilder gbuilder = new GroupBuilder(); + + this.defaultOptionBuilder.withShortName("a"); + this.defaultOptionBuilder.withRequired(true); + + DefaultOption opt = this.defaultOptionBuilder.create(); + + Group group = gbuilder.withName("withchildren").withOption(opt).create(); + + { + this.defaultOptionBuilder.withShortName("b"); + this.defaultOptionBuilder.withChildren(group); + + DefaultOption option = this.defaultOptionBuilder.create(); + assertEquals("wrong children found", group, option.getChildren()); + } + } + + public void testWithArgument() { + ArgumentBuilder abuilder = new ArgumentBuilder(); + abuilder.withName("myarg"); + + Argument arg = abuilder.create(); + + this.defaultOptionBuilder.withShortName("a"); + this.defaultOptionBuilder.withRequired(true); + this.defaultOptionBuilder.withArgument(arg); + + DefaultOption opt = this.defaultOptionBuilder.create(); + + assertEquals("wrong argument found", arg, opt.getArgument()); + } + + public void testWithId() { + this.defaultOptionBuilder.withShortName("a"); + this.defaultOptionBuilder.withId(0); + + DefaultOption opt = this.defaultOptionBuilder.create(); + + assertEquals("wrong id found", 0, opt.getId()); + } +} diff --git a/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java b/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java index 4c4c64e53..97be1fc96 100644 --- a/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java +++ b/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java @@ -1 +1,151 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import java.util.Collections;import java.util.Iterator;import java.util.Set;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.CommandLineTestCase;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.builder.DefaultOptionBuilder;/** * @author Rob Oxspring */public class DefaultingCommandLineTest extends CommandLineTestCase { private CommandLine first; private CommandLine second; private Option inFirst = new DefaultOptionBuilder().withLongName("infirst").create(); private Option inBoth = new DefaultOptionBuilder().withLongName("inboth").create(); private Option inSecond = new DefaultOptionBuilder().withLongName("insecond").create(); /* (non-Javadoc) * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() */ protected final CommandLine createCommandLine() { final WriteableCommandLine writeable = new WriteableCommandLineImpl(root, new ArrayList()); writeable.addOption(present); writeable.addProperty("present", "present property"); writeable.addSwitch(bool, true); writeable.addValue(present, "present value"); writeable.addOption(multiple); writeable.addValue(multiple, "value 1"); writeable.addValue(multiple, "value 2"); writeable.addValue(multiple, "value 3"); final DefaultingCommandLine defaults = new DefaultingCommandLine(); defaults.appendCommandLine(writeable); return defaults; } public void setUp() throws Exception { super.setUp(); WriteableCommandLine writeable; writeable = new WriteableCommandLineImpl(root, new ArrayList()); writeable.addOption(inFirst); writeable.addOption(inBoth); writeable.addProperty("infirst", "infirst first value"); writeable.addProperty("inboth", "inboth first value"); writeable.addSwitch(inFirst, true); writeable.addSwitch(inBoth, true); writeable.addValue(inFirst, "infirst first value 1"); writeable.addValue(inFirst, "infirst first value 2"); writeable.addValue(inBoth, "inboth first value 1"); writeable.addValue(inBoth, "inboth first value 2"); first = writeable; writeable = new WriteableCommandLineImpl(root, new ArrayList()); writeable.addOption(inSecond); writeable.addOption(inBoth); writeable.addProperty("insecond", "insecond second value"); writeable.addProperty("inboth", "inboth second value"); writeable.addSwitch(inSecond, true); writeable.addSwitch(inBoth, true); writeable.addValue(inSecond, "insecond second value 1"); writeable.addValue(inSecond, "insecond second value 2"); writeable.addValue(inBoth, "inboth second value 1"); writeable.addValue(inBoth, "inboth second value 2"); second = writeable; } public final void testAppendCommandLine() { final DefaultingCommandLine defaults = new DefaultingCommandLine(); Iterator i; i = defaults.commandLines(); assertFalse(i.hasNext()); defaults.appendCommandLine(first); i = defaults.commandLines(); assertSame(first, i.next()); assertFalse(i.hasNext()); defaults.appendCommandLine(second); i = defaults.commandLines(); assertSame(first, i.next()); assertSame(second, i.next()); assertFalse(i.hasNext()); } public final void testInsertCommandLine() { final DefaultingCommandLine defaults = new DefaultingCommandLine(); Iterator i; i = defaults.commandLines(); assertFalse(i.hasNext()); defaults.insertCommandLine(0, first); i = defaults.commandLines(); assertSame(first, i.next()); assertFalse(i.hasNext()); defaults.insertCommandLine(0, second); i = defaults.commandLines(); assertSame(second, i.next()); assertSame(first, i.next()); assertFalse(i.hasNext()); } public void testTriggers() { final DefaultingCommandLine defaults = new DefaultingCommandLine(); defaults.appendCommandLine(first); defaults.appendCommandLine(second); Set set = defaults.getOptionTriggers(); Iterator iter = set.iterator(); assertEquals("wrong # of triggers", 3, set.size()); assertTrue("cannot find trigger", set.contains("--insecond")); assertTrue("cannot find trigger", set.contains("--inboth")); assertTrue("cannot find trigger", set.contains("--infirst")); } public void testDefaults() { final DefaultingCommandLine defaults = new DefaultingCommandLine(); assertEquals("wrong # of defaults", 0, defaults.getValues("--insecond").size()); assertEquals("wrong Set of defaults", Collections.EMPTY_LIST, defaults.getValues("--insecond", null)); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.Set; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.CommandLineTestCase; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; + +/** + * @author Rob Oxspring + */ +public class DefaultingCommandLineTest + extends CommandLineTestCase { + private CommandLine first; + private CommandLine second; + private Option inFirst = new DefaultOptionBuilder().withLongName("infirst").create(); + private Option inBoth = new DefaultOptionBuilder().withLongName("inboth").create(); + private Option inSecond = new DefaultOptionBuilder().withLongName("insecond").create(); + + /* (non-Javadoc) + * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() + */ + protected final CommandLine createCommandLine() { + final WriteableCommandLine writeable = new WriteableCommandLineImpl(root, new ArrayList()); + writeable.addOption(present); + writeable.addProperty("present", "present property"); + writeable.addSwitch(bool, true); + writeable.addValue(present, "present value"); + writeable.addOption(multiple); + writeable.addValue(multiple, "value 1"); + writeable.addValue(multiple, "value 2"); + writeable.addValue(multiple, "value 3"); + + final DefaultingCommandLine defaults = new DefaultingCommandLine(); + defaults.appendCommandLine(writeable); + + return defaults; + } + + public void setUp() + throws Exception { + super.setUp(); + + WriteableCommandLine writeable; + + writeable = new WriteableCommandLineImpl(root, new ArrayList()); + writeable.addOption(inFirst); + writeable.addOption(inBoth); + writeable.addProperty("infirst", "infirst first value"); + writeable.addProperty("inboth", "inboth first value"); + writeable.addSwitch(inFirst, true); + writeable.addSwitch(inBoth, true); + writeable.addValue(inFirst, "infirst first value 1"); + writeable.addValue(inFirst, "infirst first value 2"); + writeable.addValue(inBoth, "inboth first value 1"); + writeable.addValue(inBoth, "inboth first value 2"); + first = writeable; + + writeable = new WriteableCommandLineImpl(root, new ArrayList()); + writeable.addOption(inSecond); + writeable.addOption(inBoth); + writeable.addProperty("insecond", "insecond second value"); + writeable.addProperty("inboth", "inboth second value"); + writeable.addSwitch(inSecond, true); + writeable.addSwitch(inBoth, true); + writeable.addValue(inSecond, "insecond second value 1"); + writeable.addValue(inSecond, "insecond second value 2"); + writeable.addValue(inBoth, "inboth second value 1"); + writeable.addValue(inBoth, "inboth second value 2"); + second = writeable; + } + + public final void testAppendCommandLine() { + final DefaultingCommandLine defaults = new DefaultingCommandLine(); + Iterator i; + + i = defaults.commandLines(); + assertFalse(i.hasNext()); + + defaults.appendCommandLine(first); + i = defaults.commandLines(); + assertSame(first, i.next()); + assertFalse(i.hasNext()); + + defaults.appendCommandLine(second); + i = defaults.commandLines(); + assertSame(first, i.next()); + assertSame(second, i.next()); + assertFalse(i.hasNext()); + } + + public final void testInsertCommandLine() { + final DefaultingCommandLine defaults = new DefaultingCommandLine(); + Iterator i; + + i = defaults.commandLines(); + assertFalse(i.hasNext()); + + defaults.insertCommandLine(0, first); + i = defaults.commandLines(); + assertSame(first, i.next()); + assertFalse(i.hasNext()); + + defaults.insertCommandLine(0, second); + i = defaults.commandLines(); + assertSame(second, i.next()); + assertSame(first, i.next()); + assertFalse(i.hasNext()); + } + + public void testTriggers() { + final DefaultingCommandLine defaults = new DefaultingCommandLine(); + defaults.appendCommandLine(first); + defaults.appendCommandLine(second); + + Set set = defaults.getOptionTriggers(); + Iterator iter = set.iterator(); + assertEquals("wrong # of triggers", 3, set.size()); + assertTrue("cannot find trigger", set.contains("--insecond")); + assertTrue("cannot find trigger", set.contains("--inboth")); + assertTrue("cannot find trigger", set.contains("--infirst")); + } + + public void testDefaults() { + final DefaultingCommandLine defaults = new DefaultingCommandLine(); + + assertEquals("wrong # of defaults", 0, defaults.getValues("--insecond").size()); + assertEquals("wrong Set of defaults", Collections.EMPTY_LIST, defaults.getValues("--insecond", null)); + } +} diff --git a/src/test/org/apache/commons/cli2/commandline/ParserTest.java b/src/test/org/apache/commons/cli2/commandline/ParserTest.java index 3145f5a0e..0077f5df3 100644 --- a/src/test/org/apache/commons/cli2/commandline/ParserTest.java +++ b/src/test/org/apache/commons/cli2/commandline/ParserTest.java @@ -1 +1,140 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.io.BufferedReader;import java.io.IOException;import java.io.PrintWriter;import java.io.StringReader;import java.io.StringWriter;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.option.DefaultOption;import org.apache.commons.cli2.util.HelpFormatter;import junit.framework.TestCase;public class ParserTest extends TestCase { private Parser parser; private DefaultOption verboseOption; private DefaultOption helpOption; private Group options; private HelpFormatter helpFormatter; private StringWriter out; private BufferedReader in; public void setUp() { parser = new Parser(); final GroupBuilder gBuilder = new GroupBuilder(); final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); helpOption = oBuilder.withLongName("help").withShortName("h").create(); verboseOption = oBuilder.withLongName("verbose").withShortName("v").create(); options = gBuilder.withOption(helpOption).withOption(verboseOption).create(); parser.setGroup(options); helpFormatter = new HelpFormatter(); out = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(out)); parser.setHelpFormatter(helpFormatter); } public void testParse_Successful() throws OptionException { final CommandLine cl = parser.parse(new String[]{"-hv"}); assertTrue(cl.hasOption(helpOption)); assertTrue(cl.hasOption(verboseOption)); assertEquals("--help --verbose",cl.toString()); final WriteableCommandLineImpl wcli = (WriteableCommandLineImpl)cl; assertEquals("[--help, --verbose]",wcli.getNormalised().toString()); } public void testParse_WithUnexpectedOption() { try { parser.parse(new String[]{"--unexpected"}); fail("OptionException"); } catch(OptionException e) { assertEquals(options,e.getOption()); assertEquals("Unexpected --unexpected while processing --help|--verbose",e.getMessage()); } } public void testParseAndHelp_Successful() throws IOException { final CommandLine cl = parser.parseAndHelp(new String[]{"-v"}); assertTrue(cl.hasOption(verboseOption)); assertEquals("",out.getBuffer().toString()); } public void testParseAndHelp_ByHelpOption() throws IOException { parser.setHelpOption(helpOption); assertNull(parser.parseAndHelp(new String[]{"-hv"})); inReader(); assertInReaderUsage(); assertInReaderEOF(); } public void testParseAndHelp_ByHelpTrigger() throws IOException { parser.setHelpTrigger("--help"); assertNull(parser.parseAndHelp(new String[]{"-hv"})); inReader(); assertInReaderUsage(); assertInReaderEOF(); } public void testParseAndHelp_WithUnexpectedOption() throws IOException { assertNull(parser.parseAndHelp(new String[]{"--unexpected"})); inReader(); assertInReaderLine("Unexpected --unexpected while processing --help|--verbose"); assertInReaderUsage(); assertInReaderEOF(); } private void assertInReaderUsage() throws IOException { assertInReaderLine("Usage:"); assertInReaderLine("[--help --verbose]"); assertInReaderLine("--help|--verbose"); assertInReaderLine("--help (-h)"); assertInReaderLine("--verbose (-v)"); } private void assertInReaderLine(final String string) throws IOException { assertEquals(string,in.readLine().trim()); } private void assertInReaderEOF() throws IOException { assertNull(in.readLine()); } private void inReader() { in = new BufferedReader(new StringReader(out.getBuffer().toString())); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.option.DefaultOption; +import org.apache.commons.cli2.util.HelpFormatter; + +import junit.framework.TestCase; + +public class ParserTest extends TestCase { + + private Parser parser; + private DefaultOption verboseOption; + private DefaultOption helpOption; + private Group options; + private HelpFormatter helpFormatter; + private StringWriter out; + private BufferedReader in; + + public void setUp() { + parser = new Parser(); + + final GroupBuilder gBuilder = new GroupBuilder(); + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + + helpOption = oBuilder.withLongName("help").withShortName("h").create(); + verboseOption = oBuilder.withLongName("verbose").withShortName("v").create(); + options = gBuilder.withOption(helpOption).withOption(verboseOption).create(); + parser.setGroup(options); + + helpFormatter = new HelpFormatter(); + out = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(out)); + parser.setHelpFormatter(helpFormatter); + } + + public void testParse_Successful() throws OptionException { + final CommandLine cl = parser.parse(new String[]{"-hv"}); + + assertTrue(cl.hasOption(helpOption)); + assertTrue(cl.hasOption(verboseOption)); + + assertEquals("--help --verbose",cl.toString()); + + final WriteableCommandLineImpl wcli = (WriteableCommandLineImpl)cl; + assertEquals("[--help, --verbose]",wcli.getNormalised().toString()); + } + + public void testParse_WithUnexpectedOption() { + try { + parser.parse(new String[]{"--unexpected"}); + fail("OptionException"); + } + catch(OptionException e) { + assertEquals(options,e.getOption()); + assertEquals("Unexpected --unexpected while processing --help|--verbose",e.getMessage()); + } + } + + public void testParseAndHelp_Successful() throws IOException { + final CommandLine cl = parser.parseAndHelp(new String[]{"-v"}); + + assertTrue(cl.hasOption(verboseOption)); + assertEquals("",out.getBuffer().toString()); + } + + public void testParseAndHelp_ByHelpOption() throws IOException { + parser.setHelpOption(helpOption); + + assertNull(parser.parseAndHelp(new String[]{"-hv"})); + + inReader(); + assertInReaderUsage(); + assertInReaderEOF(); + } + + public void testParseAndHelp_ByHelpTrigger() throws IOException { + parser.setHelpTrigger("--help"); + + assertNull(parser.parseAndHelp(new String[]{"-hv"})); + + inReader(); + assertInReaderUsage(); + assertInReaderEOF(); + } + + public void testParseAndHelp_WithUnexpectedOption() throws IOException { + assertNull(parser.parseAndHelp(new String[]{"--unexpected"})); + + inReader(); + assertInReaderLine("Unexpected --unexpected while processing --help|--verbose"); + assertInReaderUsage(); + assertInReaderEOF(); + } + + private void assertInReaderUsage() throws IOException { + assertInReaderLine("Usage:"); + assertInReaderLine("[--help --verbose]"); + assertInReaderLine("--help|--verbose"); + assertInReaderLine("--help (-h)"); + assertInReaderLine("--verbose (-v)"); + } + + private void assertInReaderLine(final String string) throws IOException { + assertEquals(string,in.readLine().trim()); + } + + private void assertInReaderEOF() throws IOException { + assertNull(in.readLine()); + } + + private void inReader() { + in = new BufferedReader(new StringReader(out.getBuffer().toString())); + } +} diff --git a/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java b/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java index 952b137ee..1526b9230 100644 --- a/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java +++ b/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java @@ -1 +1,106 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.Iterator;import java.util.Set;import java.util.prefs.Preferences;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.CommandLineTestCase;/** * @author Rob Oxspring */public class PreferencesCommandLineTest extends CommandLineTestCase { /* (non-Javadoc) * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() */ protected CommandLine createCommandLine() { // TODO Auto-generated method stub final Preferences props = Preferences.userNodeForPackage(PreferencesCommandLineTest.class); props.put("--present","present value"); props.put("--alsopresent",""); props.put("--multiple","value 1|value 2|value 3"); props.put("--bool","true"); props.put("present","present property"); return new PreferencesCommandLine(root,props,'|'); } protected CommandLine createCommandLineNoSep() { // TODO Auto-generated method stub final Preferences props = Preferences.userNodeForPackage(PreferencesCommandLineTest.class); props.put("--present","present value"); props.put("--alsopresent",""); props.put("--multiple","value 1|value 2|value 3"); props.put("--bool","false"); props.put("present","present property"); return new PreferencesCommandLine(root,props); } public void testPropertyValues() { // nothing to test CommandLine cmdline = createCommandLine(); assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 3, cmdline.getValues("--multiple").size()); assertEquals("wrong value 1", "value 1", cmdline.getValues("--multiple").get(0)); assertEquals("wrong value 2", "value 2", cmdline.getValues("--multiple").get(1)); assertEquals("wrong value 3", "value 3", cmdline.getValues("--multiple").get(2)); } public void testNoSeparator() { // nothing to test CommandLine cmdline = createCommandLineNoSep(); assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 1, cmdline.getValues("--multiple").size()); assertEquals("wrong value", "value 1|value 2|value 3", cmdline.getValue("--multiple")); assertFalse("expected a false", cmdline.getSwitch("--bool").booleanValue()); } public void testNullOption() { // nothing to test CommandLine cmdline = createCommandLine(); assertFalse("should not find null option", cmdline.hasOption((String) null)); assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); } public void testPreferenceTriggers() { // nothing to test CommandLine cmdline = createCommandLine(); Set triggers = cmdline.getOptionTriggers(); Iterator iter = triggers.iterator(); assertEquals("wrong # of triggers", 4, triggers.size()); assertTrue("cannot find trigger", triggers.contains("--bool")); assertTrue("cannot find trigger", triggers.contains("--present")); assertTrue("cannot find trigger", triggers.contains("--multiple")); assertTrue("cannot find trigger", triggers.contains("--alsopresent")); assertFalse("should not find null option", cmdline.hasOption((String) null)); assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.util.Iterator; +import java.util.Set; +import java.util.prefs.Preferences; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.CommandLineTestCase; + +/** + * @author Rob Oxspring + */ +public class PreferencesCommandLineTest extends CommandLineTestCase { + + /* (non-Javadoc) + * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() + */ + protected CommandLine createCommandLine() { + // TODO Auto-generated method stub + final Preferences props = Preferences.userNodeForPackage(PreferencesCommandLineTest.class); + props.put("--present","present value"); + props.put("--alsopresent",""); + props.put("--multiple","value 1|value 2|value 3"); + props.put("--bool","true"); + + props.put("present","present property"); + + return new PreferencesCommandLine(root,props,'|'); + } + + protected CommandLine createCommandLineNoSep() { + // TODO Auto-generated method stub + final Preferences props = Preferences.userNodeForPackage(PreferencesCommandLineTest.class); + props.put("--present","present value"); + props.put("--alsopresent",""); + props.put("--multiple","value 1|value 2|value 3"); + props.put("--bool","false"); + + props.put("present","present property"); + + return new PreferencesCommandLine(root,props); + } + + public void testPropertyValues() { + // nothing to test + CommandLine cmdline = createCommandLine(); + + assertEquals("wrong value", "present value", cmdline.getValue("--present")); + assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); + assertEquals("wrong # of values", 3, cmdline.getValues("--multiple").size()); + assertEquals("wrong value 1", "value 1", cmdline.getValues("--multiple").get(0)); + assertEquals("wrong value 2", "value 2", cmdline.getValues("--multiple").get(1)); + assertEquals("wrong value 3", "value 3", cmdline.getValues("--multiple").get(2)); + } + + public void testNoSeparator() { + // nothing to test + CommandLine cmdline = createCommandLineNoSep(); + + assertEquals("wrong value", "present value", cmdline.getValue("--present")); + assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); + assertEquals("wrong # of values", 1, cmdline.getValues("--multiple").size()); + assertEquals("wrong value", "value 1|value 2|value 3", cmdline.getValue("--multiple")); + assertFalse("expected a false", cmdline.getSwitch("--bool").booleanValue()); + } + + public void testNullOption() { + // nothing to test + CommandLine cmdline = createCommandLine(); + + assertFalse("should not find null option", cmdline.hasOption((String) null)); + assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); + } + + public void testPreferenceTriggers() { + // nothing to test + CommandLine cmdline = createCommandLine(); + + Set triggers = cmdline.getOptionTriggers(); + Iterator iter = triggers.iterator(); + assertEquals("wrong # of triggers", 4, triggers.size()); + assertTrue("cannot find trigger", triggers.contains("--bool")); + assertTrue("cannot find trigger", triggers.contains("--present")); + assertTrue("cannot find trigger", triggers.contains("--multiple")); + assertTrue("cannot find trigger", triggers.contains("--alsopresent")); + + assertFalse("should not find null option", cmdline.hasOption((String) null)); + assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); + } +} diff --git a/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java b/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java index aba69a1d9..664a2252a 100644 --- a/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java +++ b/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java @@ -1 +1,101 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.Iterator;import java.util.Properties;import java.util.Set;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.CommandLineTestCase;/** * @author Rob Oxspring */public class PropertiesCommandLineTest extends CommandLineTestCase { private Properties props = null; protected CommandLine createCommandLine() { props = new Properties(); props.setProperty("--present", "present value"); props.setProperty("--alsopresent", ""); props.setProperty("--multiple", "value 1|value 2|value 3"); props.setProperty("--bool", "true"); props.setProperty("present", "present property"); return new PropertiesCommandLine(root, props, '|'); } protected CommandLine createCommandLineNoSep() { props = new Properties(); props.setProperty("--present", "present value"); props.setProperty("--alsopresent", ""); props.setProperty("--multiple", "value 1|value 2|value 3"); props.setProperty("--bool", "false"); props.setProperty("present", "present property"); return new PropertiesCommandLine(root, props); } public void testPropertyValues() { // nothing to test CommandLine cmdline = createCommandLine(); assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 3, cmdline.getValues("--multiple").size()); assertEquals("wrong value 1", "value 1", cmdline.getValues("--multiple").get(0)); assertEquals("wrong value 2", "value 2", cmdline.getValues("--multiple").get(1)); assertEquals("wrong value 3", "value 3", cmdline.getValues("--multiple").get(2)); } public void testNoSeparator() { // nothing to test CommandLine cmdline = createCommandLineNoSep(); assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 1, cmdline.getValues("--multiple").size()); assertEquals("wrong value", "value 1|value 2|value 3", cmdline.getValue("--multiple")); assertFalse("expected a false", cmdline.getSwitch("--bool").booleanValue()); } public void testNullOption() { // nothing to test CommandLine cmdline = createCommandLine(); assertFalse("should not find null option", cmdline.hasOption((String) null)); assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); } public void testPropertyTriggers() { // nothing to test CommandLine cmdline = createCommandLine(); Set triggers = cmdline.getOptionTriggers(); Iterator iter = triggers.iterator(); assertEquals("wrong # of triggers", 4, triggers.size()); assertTrue("cannot find trigger", triggers.contains("--bool")); assertTrue("cannot find trigger", triggers.contains("--present")); assertTrue("cannot find trigger", triggers.contains("--multiple")); assertTrue("cannot find trigger", triggers.contains("--alsopresent")); assertFalse("should not find null option", cmdline.hasOption((String) null)); assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.CommandLineTestCase; + +/** + * @author Rob Oxspring + */ +public class PropertiesCommandLineTest + extends CommandLineTestCase { + private Properties props = null; + + protected CommandLine createCommandLine() { + props = new Properties(); + props.setProperty("--present", "present value"); + props.setProperty("--alsopresent", ""); + props.setProperty("--multiple", "value 1|value 2|value 3"); + props.setProperty("--bool", "true"); + + props.setProperty("present", "present property"); + return new PropertiesCommandLine(root, props, '|'); + } + + protected CommandLine createCommandLineNoSep() { + props = new Properties(); + props.setProperty("--present", "present value"); + props.setProperty("--alsopresent", ""); + props.setProperty("--multiple", "value 1|value 2|value 3"); + props.setProperty("--bool", "false"); + + props.setProperty("present", "present property"); + return new PropertiesCommandLine(root, props); + } + + public void testPropertyValues() { + // nothing to test + CommandLine cmdline = createCommandLine(); + + assertEquals("wrong value", "present value", cmdline.getValue("--present")); + assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); + assertEquals("wrong # of values", 3, cmdline.getValues("--multiple").size()); + assertEquals("wrong value 1", "value 1", cmdline.getValues("--multiple").get(0)); + assertEquals("wrong value 2", "value 2", cmdline.getValues("--multiple").get(1)); + assertEquals("wrong value 3", "value 3", cmdline.getValues("--multiple").get(2)); + } + + public void testNoSeparator() { + // nothing to test + CommandLine cmdline = createCommandLineNoSep(); + + assertEquals("wrong value", "present value", cmdline.getValue("--present")); + assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); + assertEquals("wrong # of values", 1, cmdline.getValues("--multiple").size()); + assertEquals("wrong value", "value 1|value 2|value 3", cmdline.getValue("--multiple")); + assertFalse("expected a false", cmdline.getSwitch("--bool").booleanValue()); + } + + public void testNullOption() { + // nothing to test + CommandLine cmdline = createCommandLine(); + + assertFalse("should not find null option", cmdline.hasOption((String) null)); + assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); + } + + public void testPropertyTriggers() { + // nothing to test + CommandLine cmdline = createCommandLine(); + + Set triggers = cmdline.getOptionTriggers(); + Iterator iter = triggers.iterator(); + assertEquals("wrong # of triggers", 4, triggers.size()); + assertTrue("cannot find trigger", triggers.contains("--bool")); + assertTrue("cannot find trigger", triggers.contains("--present")); + assertTrue("cannot find trigger", triggers.contains("--multiple")); + assertTrue("cannot find trigger", triggers.contains("--alsopresent")); + + assertFalse("should not find null option", cmdline.hasOption((String) null)); + assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); + } +} diff --git a/src/test/org/apache/commons/cli2/commandline/WriteableCommandLineImplTest.java b/src/test/org/apache/commons/cli2/commandline/WriteableCommandLineImplTest.java index afcaa64a2..73697fad6 100644 --- a/src/test/org/apache/commons/cli2/commandline/WriteableCommandLineImplTest.java +++ b/src/test/org/apache/commons/cli2/commandline/WriteableCommandLineImplTest.java @@ -1 +1,36 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.commandline;import java.util.ArrayList;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.WriteableCommandLineTestCase;public class WriteableCommandLineImplTest extends WriteableCommandLineTestCase { /* (non-Javadoc) * @see org.apache.commons.cli2.WriteableCommandLineTest#createWriteableCommandLine() */ protected WriteableCommandLine createWriteableCommandLine() { return new WriteableCommandLineImpl(root, new ArrayList()); } public void testToMakeEclipseSpotTheTestCase() { // nothing to test }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.util.ArrayList; + +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.WriteableCommandLineTestCase; + +public class WriteableCommandLineImplTest + extends WriteableCommandLineTestCase { + /* (non-Javadoc) + * @see org.apache.commons.cli2.WriteableCommandLineTest#createWriteableCommandLine() + */ + protected WriteableCommandLine createWriteableCommandLine() { + return new WriteableCommandLineImpl(root, new ArrayList()); + } + + public void testToMakeEclipseSpotTheTestCase() { + // nothing to test + } +} diff --git a/src/test/org/apache/commons/cli2/jdepend/JDependTest.java b/src/test/org/apache/commons/cli2/jdepend/JDependTest.java index 4451893dd..45e5612b5 100644 --- a/src/test/org/apache/commons/cli2/jdepend/JDependTest.java +++ b/src/test/org/apache/commons/cli2/jdepend/JDependTest.java @@ -1 +1,109 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.jdepend;import java.io.IOException;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;import jdepend.framework.JDepend;import jdepend.framework.JavaPackage;import junit.framework.TestCase;/** * @author Rob Oxspring */public class JDependTest extends TestCase { private JDepend dependancies = null; public void setUp() throws IOException { dependancies = new JDepend(); dependancies.addDirectory("target/classes"); dependancies.analyze(); } public void testJUnitNotPresent() { // if junit dependancy is found then jdepend has been poluted // with test classes and all tests are meaningless assertNull( "JUnit dependancy found", dependancies.getPackage("junit.framework")); // the same applies to jdepend assertNull( "JDepend dependancy found", dependancies.getPackage("jdepend.framework")); } public void testAcceptableDistance() { Collection packages = dependancies.getPackages(); // only interested in cli2 packages = cli2Packages(packages); // resources is well off the line packages = namedPackages(packages, "org.apache.commons.cli2.resource", false); for (final Iterator i = packages.iterator(); i.hasNext();) { final JavaPackage pkg = (JavaPackage)i.next(); final float distance = pkg.distance(); final String message = pkg.getName() + " too far from line: " + distance; assertTrue( message, distance < 0.21d); } } public void testNoCyclesPresent() { assertEquals("Cycles exist", false, dependancies.containsCycles()); } public void testApiIndependance() { dependancies.analyze(); final JavaPackage apiPackage = dependancies.getPackage("org.apache.commons.cli2"); final Collection dependsUpon = cli2Packages(apiPackage.getEfferents()); assertEquals("Api should depend on one package", 1, dependsUpon.size()); JavaPackage pkg = (JavaPackage) dependsUpon.iterator().next(); assertEquals( "Wrong package name", "org.apache.commons.cli2.resource", pkg.getName()); } private Collection cli2Packages(final Collection incoming) { return namedPackages(incoming, "org.apache.commons.cli2", true); } private Collection namedPackages( final Collection incoming, final String name, final boolean include) { final Collection outgoing = new ArrayList(); for (final Iterator i = incoming.iterator(); i.hasNext();) { final JavaPackage pkg = (JavaPackage)i.next(); if (include ^ !pkg.getName().startsWith(name)) { outgoing.add(pkg); } } return outgoing; }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.jdepend; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import jdepend.framework.JDepend; +import jdepend.framework.JavaPackage; +import junit.framework.TestCase; + +/** + * @author Rob Oxspring + */ +public class JDependTest extends TestCase { + + private JDepend dependancies = null; + + public void setUp() throws IOException { + dependancies = new JDepend(); + dependancies.addDirectory("target/classes"); + dependancies.analyze(); + } + + public void testJUnitNotPresent() { + // if junit dependancy is found then jdepend has been poluted + // with test classes and all tests are meaningless + assertNull( + "JUnit dependancy found", + dependancies.getPackage("junit.framework")); + + // the same applies to jdepend + assertNull( + "JDepend dependancy found", + dependancies.getPackage("jdepend.framework")); + } + + public void testAcceptableDistance() { + Collection packages = dependancies.getPackages(); + // only interested in cli2 + packages = cli2Packages(packages); + // resources is well off the line + packages = + namedPackages(packages, "org.apache.commons.cli2.resource", false); + + for (final Iterator i = packages.iterator(); i.hasNext();) { + final JavaPackage pkg = (JavaPackage)i.next(); + final float distance = pkg.distance(); + final String message = pkg.getName() + " too far from line: " + distance; + assertTrue( + message, + distance < 0.21d); + } + } + + public void testNoCyclesPresent() { + assertEquals("Cycles exist", false, dependancies.containsCycles()); + } + + public void testApiIndependance() { + dependancies.analyze(); + + final JavaPackage apiPackage = + dependancies.getPackage("org.apache.commons.cli2"); + final Collection dependsUpon = cli2Packages(apiPackage.getEfferents()); + + assertEquals("Api should depend on one package", 1, dependsUpon.size()); + + JavaPackage pkg = (JavaPackage) dependsUpon.iterator().next(); + assertEquals( + "Wrong package name", + "org.apache.commons.cli2.resource", + pkg.getName()); + } + + private Collection cli2Packages(final Collection incoming) { + return namedPackages(incoming, "org.apache.commons.cli2", true); + } + + private Collection namedPackages( + final Collection incoming, + final String name, + final boolean include) { + final Collection outgoing = new ArrayList(); + for (final Iterator i = incoming.iterator(); i.hasNext();) { + final JavaPackage pkg = (JavaPackage)i.next(); + if (include ^ !pkg.getName().startsWith(name)) { + outgoing.add(pkg); + } + } + return outgoing; + } +} diff --git a/src/test/org/apache/commons/cli2/option/ArgumentTest.java b/src/test/org/apache/commons/cli2/option/ArgumentTest.java index 3e607482b..4b6f92c0a 100644 --- a/src/test/org/apache/commons/cli2/option/ArgumentTest.java +++ b/src/test/org/apache/commons/cli2/option/ArgumentTest.java @@ -1 +1,646 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.text.ParseException;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;import org.apache.commons.cli2.validation.DateValidator;import org.apache.commons.cli2.validation.DateValidatorTest;/** * @author Rob Oxspring */public class ArgumentTest extends ArgumentTestCase { private ResourceHelper resources = ResourceHelper.getResourceHelper(); public static Argument buildUsernameArgument() { return new ArgumentImpl("username", "The user to connect as", 1, 1, '\0', '\0', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, null, 0); } public static Argument buildHostArgument() { return new ArgumentImpl("host", "The host name", 2, 3, '\0', ',', null, null, null, 0); } public static Argument buildPathArgument() { return new ArgumentImpl("path", "The place to look for files", 1, Integer.MAX_VALUE, '=', ';', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, null, 0); } public static Argument buildDateLimitArgument() { return new ArgumentImpl("limit", "the last acceptable date", 0, 1, '=', '\0', new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); } public static Argument buildTargetsArgument() { return new ArgumentImpl("target", "The targets ant should build", 0, Integer.MAX_VALUE, '\0', ',', null, null, null, 0); } public static Argument buildSizeArgument() { List defaults = new ArrayList(); defaults.add("10"); return new ArgumentImpl("size", "The number of units", 1, 1, '\0', '\0', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); } public static Argument buildBoundsArgument() { List defaults = new ArrayList(); defaults.add("5"); defaults.add("10"); return new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); } public void testNew() { try { new ArgumentImpl("limit", "the last acceptable date", 10, 5, '=', '\0', new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage("Argument.minimum.exceeds.maximum"), e.getMessage()); } { ArgumentImpl arg = new ArgumentImpl(null, "the last acceptable date", 5, 5, '=', '\0', new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); assertEquals("wrong arg name", "arg", arg.getPreferredName()); } { List defaults = new ArrayList(); try { new ArgumentImpl(null, "the last acceptable date", 1, 1, '=', '\0', new DateValidator(DateValidatorTest.YYYY_MM_DD), null, defaults, 0); } catch (IllegalArgumentException exp) { assertEquals(resources.getMessage("Argument.too.few.defaults"), exp.getMessage()); } } try { List defaults = new ArrayList(); defaults.add("1"); defaults.add("2"); new ArgumentImpl(null, "the last acceptable date", 1, 1, '=', '\0', new DateValidator(DateValidatorTest.YYYY_MM_DD), null, defaults, 0); } catch (IllegalArgumentException exp) { assertEquals(resources.getMessage("Argument.too.many.defaults"), exp.getMessage()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.ArgumentTestCase#testProcessValues() */ public void testProcessValues() throws OptionException { final Argument option = buildUsernameArgument(); final List args = list("rob"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processValues(commandLine, iterator, option); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("username")); assertEquals("rob", commandLine.getValue(option)); } public void testProcessValues_BoundaryQuotes() throws OptionException { final Argument option = buildUsernameArgument(); final List args = list("\"rob\""); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processValues(commandLine, iterator, option); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("username")); assertEquals("rob", commandLine.getValue(option)); } public void testProcessValues_SpareValues() throws OptionException { final Argument option = buildUsernameArgument(); final List args = list("rob", "secret"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processValues(commandLine, iterator, option); assertTrue(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("username")); assertEquals("rob", commandLine.getValue(option)); } public void testProcessValues_Optional() { final Argument option = buildTargetsArgument(); final List args = list(); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.processValues(commandLine, iterator, option); } catch (final OptionException mve) { assertEquals(option, mve.getOption()); assertEquals("Missing value(s) target [target ...]", mve.getMessage()); } assertFalse(iterator.hasNext()); assertFalse(commandLine.hasOption(option)); assertFalse(commandLine.hasOption("username")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcessValues_Multiple() throws OptionException { final Argument option = buildTargetsArgument(); final List args = list("compile", "test", "docs"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processValues(commandLine, iterator, option); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("target")); assertFalse(commandLine.getValues(option).isEmpty()); assertListContentsEqual(args, commandLine.getValues(option)); } public void testProcessValues_Contracted() throws OptionException { final Argument option = buildTargetsArgument(); final List args = list("compile,test,javadoc", "checkstyle,jdepend"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processValues(commandLine, iterator, option); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("target")); assertListContentsEqual(list("compile", "test", "javadoc", "checkstyle", "jdepend"), commandLine.getValues(option)); } public void testProcessValues_ContractedTooFew() { final Argument option = buildHostArgument(); final List args = list("box1"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.processValues(commandLine, iterator, option); option.validate(commandLine); fail("Expected MissingValueException"); } catch (OptionException mve) { assertSame(option, mve.getOption()); } } public void testProcessValues_ContractedTooMany() { final Argument option = buildHostArgument(); final List args = list("box1,box2,box3,box4"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.processValues(commandLine, iterator, option); option.validate(commandLine); fail("Expected MissingValueException"); } catch (OptionException mve) { assertSame(option, mve.getOption()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Argument option = buildTargetsArgument(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "any value")); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Argument option = buildTargetsArgument(); assertTrue(option.getPrefixes().isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { final Argument option = buildPathArgument(); final List args = list("-path=/lib;/usr/lib;/usr/local/lib"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("path")); assertListContentsEqual(list("-path=/lib", "/usr/lib", "/usr/local/lib"), commandLine.getValues(option)); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Argument option = buildTargetsArgument(); assertTrue(option.getTriggers().isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() throws OptionException { final Argument option = buildUsernameArgument(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addValue(option, "rob"); option.validate(commandLine); } public void testValidate_Minimum() { final Argument option = buildUsernameArgument(); final WriteableCommandLine commandLine = commandLine(option, list()); try { option.validate(commandLine); fail("UnexpectedValue"); } catch (OptionException mve) { assertEquals(option, mve.getOption()); } } public void testRequired() { { final Argument arg = buildBoundsArgument(); assertTrue("not required", arg.isRequired()); } { final Argument arg = buildTargetsArgument(); assertFalse("should not be required", arg.isRequired()); } } public void testValidate_Maximum() { final Argument option = buildUsernameArgument(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addValue(option, "rob"); commandLine.addValue(option, "oxspring"); try { option.validate(commandLine); fail("UnexpectedValue"); } catch (OptionException uve) { assertEquals(option, uve.getOption()); } } public void testValidate_Validator() throws OptionException, ParseException { final Argument option = buildDateLimitArgument(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addValue(option, "2004-01-01"); option.validate(commandLine, option); assertContentsEqual(Arrays.asList(new Object[] { DateValidatorTest.YYYY_MM_DD.parse("2004-01-01") }), commandLine.getValues(option)); } public void testValidate_ValidatorInvalidDate() throws OptionException, ParseException { final Argument option = buildDateLimitArgument(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addValue(option, "12-12-2004"); try { option.validate(commandLine, option); } catch (OptionException exp) { OptionException e = new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, "12-12-2004"); assertEquals("wrong exception message", e.getMessage(), exp.getMessage()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildUsernameArgument(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("", buffer.toString()); } public void testAppendUsage_Infinite() { final Option option = buildTargetsArgument(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("[ [ ...]]", buffer.toString()); } public void testAppendUsage_InfiniteNoOptional() { final Option option = buildTargetsArgument(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_OPTIONAL); option.appendUsage(buffer, settings, null); assertEquals(" [ ...]", buffer.toString()); } public void testAppendUsage_InfiniteNoNumbering() { final Option option = buildTargetsArgument(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); option.appendUsage(buffer, settings, null); assertEquals("[ [ ...]]", buffer.toString()); } public void testAppendUsage_Minimum() { final Option option = buildHostArgument(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals(" []", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildPathArgument(); assertEquals("path", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildHostArgument(); assertEquals("The host name", option.getDescription()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { final Option option = buildHostArgument(); final List lines = option.helpLines(0, DisplaySetting.ALL, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); assertFalse(i.hasNext()); } public void testCanProcess_ConsumeRemaining() { final Option option = buildUsernameArgument(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "--")); } public void testProcess_ConsumeRemaining() throws OptionException { final Option option = buildPathArgument(); final List args = list("options", "--", "--ignored", "-Dprop=val"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); final List values = commandLine.getValues(option); assertTrue(values.contains("options")); assertTrue(values.contains("--ignored")); assertTrue(values.contains("-Dprop=val")); assertEquals(3, values.size()); assertFalse(iterator.hasNext()); } public void testProcess_ConsumeNothing() { final Option option = buildPathArgument(); final List args = list("--"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.process(commandLine, iterator); option.validate(commandLine); fail("Missing Value!"); } catch (OptionException mve) { assertEquals(option, mve.getOption()); assertEquals("Missing value(s) path [path ...]", mve.getMessage()); } assertTrue(commandLine.getValues(option).isEmpty()); assertFalse(iterator.hasNext()); } // public void testProcess_DefinedDefaultValue() throws OptionException { // final Option size = buildSizeArgument(); // final List args = list(); // final WriteableCommandLine commandLine = commandLine(size, args); // final ListIterator iterator = args.listIterator(); // // size.process(commandLine, iterator); // // assertEquals("10", commandLine.getValue(size)); // } // // public void testProcess_DefinedDefaultValues() throws OptionException { // final Option bounds = buildBoundsArgument(); // final List args = list(); // final WriteableCommandLine commandLine = commandLine(bounds, args); // final ListIterator iterator = args.listIterator(); // // bounds.process(commandLine, iterator); // // List values = new ArrayList(); // values.add("5"); // values.add("10"); // assertEquals(values, commandLine.getValues(bounds)); // } public void testProcess_InterrogatedDefaultValue() throws OptionException { final Option size = buildSizeArgument(); final List args = list(); final WriteableCommandLine commandLine = commandLine(size, args); final ListIterator iterator = args.listIterator(); size.process(commandLine, iterator); assertEquals(new Integer(20), commandLine.getValue(size, new Integer(20))); } public void testTooFewDefaults() { List defaults = new ArrayList(); defaults.add("5"); try { new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_FEW_DEFAULTS), exp.getMessage()); } } public void testTooManyDefaults() { List defaults = new ArrayList(); defaults.add("5"); defaults.add("10"); defaults.add("15"); try { new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_MANY_DEFAULTS), exp.getMessage()); } } public void testProcess_InterrogatedDefaultValues() throws OptionException { final Option bounds = buildBoundsArgument(); final List args = list(); final WriteableCommandLine commandLine = commandLine(bounds, args); final ListIterator iterator = args.listIterator(); bounds.process(commandLine, iterator); // test with values List values = new ArrayList(); values.add("50"); values.add("100"); assertEquals(values, commandLine.getValues(bounds, values)); // test without values assertEquals(Collections.EMPTY_LIST, commandLine.getValues(bounds, null)); } public void testProcess_StripBoundaryQuotes() throws OptionException { final Option bounds = buildBoundsArgument(); final List args = list(); final WriteableCommandLine commandLine = commandLine(bounds, args); final ListIterator iterator = args.listIterator(); bounds.process(commandLine, iterator); List values = new ArrayList(); values.add("50\""); values.add("\"100"); assertEquals(values, commandLine.getValues(bounds, values)); } public void testSourceDestArgument() { final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); final Argument inputfiles = abuilder.withName("input").withMinimum(0).withMaximum(0).create(); final Argument bad_outputfile = abuilder.withName("output").withMinimum(1).withMaximum(2).create(); try { final Argument targets = new SourceDestArgument(inputfiles, bad_outputfile); } catch (final IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SOURCE_DEST_MUST_ENFORCE_VALUES), exp.getMessage()); } final Argument outputfile = abuilder.withName("output").withMinimum(1).withMaximum(1).create(); final Argument targets = new SourceDestArgument(inputfiles, outputfile); final StringBuffer buffer = new StringBuffer("test content"); targets.appendUsage(buffer, Collections.EMPTY_SET, null); assertTrue("buffer not added", buffer.toString().startsWith("test content")); assertFalse("space added", buffer.charAt(12) == ' '); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.text.ParseException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.HelpLine; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; +import org.apache.commons.cli2.validation.DateValidator; +import org.apache.commons.cli2.validation.DateValidatorTest; + +/** + * @author Rob Oxspring + */ +public class ArgumentTest + extends ArgumentTestCase { + private ResourceHelper resources = ResourceHelper.getResourceHelper(); + + public static Argument buildUsernameArgument() { + return new ArgumentImpl("username", "The user to connect as", 1, 1, '\0', '\0', null, + ArgumentImpl.DEFAULT_CONSUME_REMAINING, null, 0); + } + + public static Argument buildHostArgument() { + return new ArgumentImpl("host", "The host name", 2, 3, '\0', ',', null, null, null, 0); + } + + public static Argument buildPathArgument() { + return new ArgumentImpl("path", "The place to look for files", 1, Integer.MAX_VALUE, '=', + ';', null, ArgumentImpl.DEFAULT_CONSUME_REMAINING, null, 0); + } + + public static Argument buildDateLimitArgument() { + return new ArgumentImpl("limit", "the last acceptable date", 0, 1, '=', '\0', + new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); + } + + public static Argument buildTargetsArgument() { + return new ArgumentImpl("target", "The targets ant should build", 0, Integer.MAX_VALUE, + '\0', ',', null, null, null, 0); + } + + public static Argument buildSizeArgument() { + List defaults = new ArrayList(); + defaults.add("10"); + + return new ArgumentImpl("size", "The number of units", 1, 1, '\0', '\0', null, + ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); + } + + public static Argument buildBoundsArgument() { + List defaults = new ArrayList(); + defaults.add("5"); + defaults.add("10"); + + return new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, + ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); + } + + public void testNew() { + try { + new ArgumentImpl("limit", "the last acceptable date", 10, 5, '=', '\0', + new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); + } catch (IllegalArgumentException e) { + assertEquals(resources.getMessage("Argument.minimum.exceeds.maximum"), e.getMessage()); + } + + { + ArgumentImpl arg = + new ArgumentImpl(null, "the last acceptable date", 5, 5, '=', '\0', + new DateValidator(DateValidatorTest.YYYY_MM_DD), null, null, 0); + assertEquals("wrong arg name", "arg", arg.getPreferredName()); + } + + { + List defaults = new ArrayList(); + + try { + new ArgumentImpl(null, "the last acceptable date", 1, 1, '=', '\0', + new DateValidator(DateValidatorTest.YYYY_MM_DD), null, defaults, 0); + } catch (IllegalArgumentException exp) { + assertEquals(resources.getMessage("Argument.too.few.defaults"), exp.getMessage()); + } + } + + try { + List defaults = new ArrayList(); + defaults.add("1"); + defaults.add("2"); + + new ArgumentImpl(null, "the last acceptable date", 1, 1, '=', '\0', + new DateValidator(DateValidatorTest.YYYY_MM_DD), null, defaults, 0); + } catch (IllegalArgumentException exp) { + assertEquals(resources.getMessage("Argument.too.many.defaults"), exp.getMessage()); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.ArgumentTestCase#testProcessValues() + */ + public void testProcessValues() + throws OptionException { + final Argument option = buildUsernameArgument(); + final List args = list("rob"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processValues(commandLine, iterator, option); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("username")); + assertEquals("rob", commandLine.getValue(option)); + } + + public void testProcessValues_BoundaryQuotes() + throws OptionException { + final Argument option = buildUsernameArgument(); + final List args = list("\"rob\""); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processValues(commandLine, iterator, option); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("username")); + assertEquals("rob", commandLine.getValue(option)); + } + + public void testProcessValues_SpareValues() + throws OptionException { + final Argument option = buildUsernameArgument(); + final List args = list("rob", "secret"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processValues(commandLine, iterator, option); + + assertTrue(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("username")); + assertEquals("rob", commandLine.getValue(option)); + } + + public void testProcessValues_Optional() { + final Argument option = buildTargetsArgument(); + final List args = list(); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + try { + option.processValues(commandLine, iterator, option); + } catch (final OptionException mve) { + assertEquals(option, mve.getOption()); + assertEquals("Missing value(s) target [target ...]", mve.getMessage()); + } + + assertFalse(iterator.hasNext()); + assertFalse(commandLine.hasOption(option)); + assertFalse(commandLine.hasOption("username")); + assertTrue(commandLine.getValues(option).isEmpty()); + } + + public void testProcessValues_Multiple() + throws OptionException { + final Argument option = buildTargetsArgument(); + final List args = list("compile", "test", "docs"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processValues(commandLine, iterator, option); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("target")); + assertFalse(commandLine.getValues(option).isEmpty()); + assertListContentsEqual(args, commandLine.getValues(option)); + } + + public void testProcessValues_Contracted() + throws OptionException { + final Argument option = buildTargetsArgument(); + final List args = list("compile,test,javadoc", "checkstyle,jdepend"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processValues(commandLine, iterator, option); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("target")); + assertListContentsEqual(list("compile", "test", "javadoc", "checkstyle", "jdepend"), + commandLine.getValues(option)); + } + + public void testProcessValues_ContractedTooFew() { + final Argument option = buildHostArgument(); + final List args = list("box1"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + try { + option.processValues(commandLine, iterator, option); + option.validate(commandLine); + fail("Expected MissingValueException"); + } catch (OptionException mve) { + assertSame(option, mve.getOption()); + } + } + + public void testProcessValues_ContractedTooMany() { + final Argument option = buildHostArgument(); + final List args = list("box1,box2,box3,box4"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + try { + option.processValues(commandLine, iterator, option); + option.validate(commandLine); + fail("Expected MissingValueException"); + } catch (OptionException mve) { + assertSame(option, mve.getOption()); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() + */ + public void testCanProcess() { + final Argument option = buildTargetsArgument(); + assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "any value")); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() + */ + public void testPrefixes() { + final Argument option = buildTargetsArgument(); + assertTrue(option.getPrefixes().isEmpty()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testProcess() + */ + public void testProcess() + throws OptionException { + final Argument option = buildPathArgument(); + final List args = list("-path=/lib;/usr/lib;/usr/local/lib"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.process(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("path")); + assertListContentsEqual(list("-path=/lib", "/usr/lib", "/usr/local/lib"), + commandLine.getValues(option)); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testTriggers() + */ + public void testTriggers() { + final Argument option = buildTargetsArgument(); + assertTrue(option.getTriggers().isEmpty()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testValidate() + */ + public void testValidate() + throws OptionException { + final Argument option = buildUsernameArgument(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + commandLine.addValue(option, "rob"); + + option.validate(commandLine); + } + + public void testValidate_Minimum() { + final Argument option = buildUsernameArgument(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + try { + option.validate(commandLine); + fail("UnexpectedValue"); + } catch (OptionException mve) { + assertEquals(option, mve.getOption()); + } + } + + public void testRequired() { + { + final Argument arg = buildBoundsArgument(); + + assertTrue("not required", arg.isRequired()); + } + + { + final Argument arg = buildTargetsArgument(); + + assertFalse("should not be required", arg.isRequired()); + } + } + + public void testValidate_Maximum() { + final Argument option = buildUsernameArgument(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + commandLine.addValue(option, "rob"); + commandLine.addValue(option, "oxspring"); + + try { + option.validate(commandLine); + fail("UnexpectedValue"); + } catch (OptionException uve) { + assertEquals(option, uve.getOption()); + } + } + + public void testValidate_Validator() + throws OptionException, ParseException { + final Argument option = buildDateLimitArgument(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + commandLine.addValue(option, "2004-01-01"); + + option.validate(commandLine, option); + assertContentsEqual(Arrays.asList(new Object[] { + DateValidatorTest.YYYY_MM_DD.parse("2004-01-01") + }), commandLine.getValues(option)); + } + + public void testValidate_ValidatorInvalidDate() + throws OptionException, ParseException { + final Argument option = buildDateLimitArgument(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + commandLine.addValue(option, "12-12-2004"); + + try { + option.validate(commandLine, option); + } catch (OptionException exp) { + OptionException e = + new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, + "12-12-2004"); + assertEquals("wrong exception message", e.getMessage(), exp.getMessage()); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() + */ + public void testAppendUsage() { + final Option option = buildUsernameArgument(); + final StringBuffer buffer = new StringBuffer(); + option.appendUsage(buffer, DisplaySetting.ALL, null); + + assertEquals("", buffer.toString()); + } + + public void testAppendUsage_Infinite() { + final Option option = buildTargetsArgument(); + final StringBuffer buffer = new StringBuffer(); + option.appendUsage(buffer, DisplaySetting.ALL, null); + + assertEquals("[ [ ...]]", buffer.toString()); + } + + public void testAppendUsage_InfiniteNoOptional() { + final Option option = buildTargetsArgument(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_OPTIONAL); + option.appendUsage(buffer, settings, null); + + assertEquals(" [ ...]", buffer.toString()); + } + + public void testAppendUsage_InfiniteNoNumbering() { + final Option option = buildTargetsArgument(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); + option.appendUsage(buffer, settings, null); + + assertEquals("[ [ ...]]", buffer.toString()); + } + + public void testAppendUsage_Minimum() { + final Option option = buildHostArgument(); + final StringBuffer buffer = new StringBuffer(); + option.appendUsage(buffer, DisplaySetting.ALL, null); + + assertEquals(" []", buffer.toString()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() + */ + public void testGetPreferredName() { + final Option option = buildPathArgument(); + assertEquals("path", option.getPreferredName()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() + */ + public void testGetDescription() { + final Option option = buildHostArgument(); + assertEquals("The host name", option.getDescription()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() + */ + public void testHelpLines() { + final Option option = buildHostArgument(); + final List lines = option.helpLines(0, DisplaySetting.ALL, null); + final Iterator i = lines.iterator(); + + final HelpLine line1 = (HelpLine) i.next(); + assertEquals(0, line1.getIndent()); + assertEquals(option, line1.getOption()); + + assertFalse(i.hasNext()); + } + + public void testCanProcess_ConsumeRemaining() { + final Option option = buildUsernameArgument(); + + assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "--")); + } + + public void testProcess_ConsumeRemaining() + throws OptionException { + final Option option = buildPathArgument(); + final List args = list("options", "--", "--ignored", "-Dprop=val"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + option.process(commandLine, iterator); + + final List values = commandLine.getValues(option); + assertTrue(values.contains("options")); + assertTrue(values.contains("--ignored")); + assertTrue(values.contains("-Dprop=val")); + assertEquals(3, values.size()); + assertFalse(iterator.hasNext()); + } + + public void testProcess_ConsumeNothing() { + final Option option = buildPathArgument(); + final List args = list("--"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + try { + option.process(commandLine, iterator); + option.validate(commandLine); + fail("Missing Value!"); + } catch (OptionException mve) { + assertEquals(option, mve.getOption()); + assertEquals("Missing value(s) path [path ...]", mve.getMessage()); + } + + assertTrue(commandLine.getValues(option).isEmpty()); + assertFalse(iterator.hasNext()); + } + + // public void testProcess_DefinedDefaultValue() throws OptionException { + // final Option size = buildSizeArgument(); + // final List args = list(); + // final WriteableCommandLine commandLine = commandLine(size, args); + // final ListIterator iterator = args.listIterator(); + // + // size.process(commandLine, iterator); + // + // assertEquals("10", commandLine.getValue(size)); + // } + // + // public void testProcess_DefinedDefaultValues() throws OptionException { + // final Option bounds = buildBoundsArgument(); + // final List args = list(); + // final WriteableCommandLine commandLine = commandLine(bounds, args); + // final ListIterator iterator = args.listIterator(); + // + // bounds.process(commandLine, iterator); + // + // List values = new ArrayList(); + // values.add("5"); + // values.add("10"); + // assertEquals(values, commandLine.getValues(bounds)); + // } + public void testProcess_InterrogatedDefaultValue() + throws OptionException { + final Option size = buildSizeArgument(); + final List args = list(); + final WriteableCommandLine commandLine = commandLine(size, args); + final ListIterator iterator = args.listIterator(); + + size.process(commandLine, iterator); + + assertEquals(new Integer(20), commandLine.getValue(size, new Integer(20))); + } + + public void testTooFewDefaults() { + List defaults = new ArrayList(); + defaults.add("5"); + + try { + new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, + ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_FEW_DEFAULTS), + exp.getMessage()); + } + } + + public void testTooManyDefaults() { + List defaults = new ArrayList(); + defaults.add("5"); + defaults.add("10"); + defaults.add("15"); + + try { + new ArgumentImpl("size", "The number of units", 2, 2, '\0', '\0', null, + ArgumentImpl.DEFAULT_CONSUME_REMAINING, defaults, 0); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.ARGUMENT_TOO_MANY_DEFAULTS), + exp.getMessage()); + } + } + + public void testProcess_InterrogatedDefaultValues() + throws OptionException { + final Option bounds = buildBoundsArgument(); + final List args = list(); + final WriteableCommandLine commandLine = commandLine(bounds, args); + final ListIterator iterator = args.listIterator(); + + bounds.process(commandLine, iterator); + + // test with values + List values = new ArrayList(); + values.add("50"); + values.add("100"); + assertEquals(values, commandLine.getValues(bounds, values)); + + // test without values + assertEquals(Collections.EMPTY_LIST, commandLine.getValues(bounds, null)); + } + + public void testProcess_StripBoundaryQuotes() + throws OptionException { + final Option bounds = buildBoundsArgument(); + final List args = list(); + final WriteableCommandLine commandLine = commandLine(bounds, args); + final ListIterator iterator = args.listIterator(); + + bounds.process(commandLine, iterator); + + List values = new ArrayList(); + values.add("50\""); + values.add("\"100"); + assertEquals(values, commandLine.getValues(bounds, values)); + } + + public void testSourceDestArgument() { + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + final Argument inputfiles = + abuilder.withName("input").withMinimum(0).withMaximum(0).create(); + final Argument bad_outputfile = + abuilder.withName("output").withMinimum(1).withMaximum(2).create(); + + try { + final Argument targets = new SourceDestArgument(inputfiles, bad_outputfile); + } catch (final IllegalArgumentException exp) { + assertEquals("wrong exception message", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SOURCE_DEST_MUST_ENFORCE_VALUES), + exp.getMessage()); + } + + final Argument outputfile = + abuilder.withName("output").withMinimum(1).withMaximum(1).create(); + + final Argument targets = new SourceDestArgument(inputfiles, outputfile); + final StringBuffer buffer = new StringBuffer("test content"); + targets.appendUsage(buffer, Collections.EMPTY_SET, null); + + assertTrue("buffer not added", buffer.toString().startsWith("test content")); + assertFalse("space added", buffer.charAt(12) == ' '); + } +} diff --git a/src/test/org/apache/commons/cli2/option/ArgumentTestCase.java b/src/test/org/apache/commons/cli2/option/ArgumentTestCase.java index 769a4af53..eab24f852 100644 --- a/src/test/org/apache/commons/cli2/option/ArgumentTestCase.java +++ b/src/test/org/apache/commons/cli2/option/ArgumentTestCase.java @@ -1 +1,28 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import org.apache.commons.cli2.OptionException;/** * @author Rob Oxspring */public abstract class ArgumentTestCase extends OptionTestCase { public abstract void testProcessValues() throws OptionException;} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import org.apache.commons.cli2.OptionException; + +/** + * @author Rob Oxspring + */ +public abstract class ArgumentTestCase extends OptionTestCase { + + public abstract void testProcessValues() throws OptionException; + +} diff --git a/src/test/org/apache/commons/cli2/option/CommandTest.java b/src/test/org/apache/commons/cli2/option/CommandTest.java index 75900de07..2b78f1f91 100644 --- a/src/test/org/apache/commons/cli2/option/CommandTest.java +++ b/src/test/org/apache/commons/cli2/option/CommandTest.java @@ -1 +1,249 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Collections;import java.util.HashSet;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.Parent;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * @author Rob Oxspring * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */public class CommandTest extends ParentTestCase { public static Command buildStartCommand() { return new Command("start", "Begins the process", Collections.singleton("go"), false, null, null, 0); } public static Command buildCommitCommand() { return new Command("commit", "Commit the changes to the database", null, true, null, null, 0); } public static Command buildLoginCommand() { return new Command("login", "Initiates a session for the user", null, false, ArgumentTest.buildUsernameArgument(), null, 0); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() */ public void testProcessParent() throws OptionException { final Command option = buildStartCommand(); final List args = list("go"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("start")); assertTrue(commandLine.hasOption("go")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcessParent_Spare() throws OptionException { final Command option = buildLoginCommand(); final List args = list("login", "rob"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertEquals("rob", iterator.next()); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("login")); assertTrue(commandLine.getValues(option).isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Command option = buildStartCommand(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "start")); } public void testCanProcess_BadMatch() { final Command option = buildStartCommand(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "stop")); } public void testCanProcess_Alias() { final Command option = buildStartCommand(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "go")); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Command option = buildStartCommand(); assertTrue(option.getPrefixes().isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { final Command option = buildLoginCommand(); final List args = list("login", "rob"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("login")); assertEquals("rob", commandLine.getValue(option)); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Command option = buildStartCommand(); final Set triggers = option.getTriggers(); assertContentsEqual(list("start", "go"), triggers); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() { final Parent option = buildCommitCommand(); final WriteableCommandLine commandLine = commandLine(option, list()); try { option.validate(commandLine); fail("Missing an option"); } catch (OptionException moe) { assertSame(option, moe.getOption()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildStartCommand(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("[start (go)]", buffer.toString()); } public void testNullPreferredName() { try { new Command(null, "", Collections.singleton("go"), false, null, null, 0); } catch (IllegalArgumentException exp) { assertEquals("wrong exception name", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT), exp.getMessage()); } } public void testEmotyPreferredName() { try { new Command("", "", Collections.singleton("go"), false, null, null, 0); } catch (IllegalArgumentException exp) { assertEquals("wrong exception name", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT), exp.getMessage()); } } public void testAppendUsage_NoOptional() { final Option option = buildStartCommand(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_OPTIONAL); option.appendUsage(buffer, settings, null); assertEquals("start (go)", buffer.toString()); } public void testAppendUsage_NoAlias() { final Option option = buildStartCommand(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_ALIASES); option.appendUsage(buffer, settings, null); assertEquals("[start]", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildStartCommand(); assertEquals("start", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildLoginCommand(); assertEquals("Initiates a session for the user", option.getDescription()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { // TODO Auto-generated method stub }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.Parent; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * @author Rob Oxspring + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class CommandTest + extends ParentTestCase { + public static Command buildStartCommand() { + return new Command("start", "Begins the process", Collections.singleton("go"), false, null, + null, 0); + } + + public static Command buildCommitCommand() { + return new Command("commit", "Commit the changes to the database", null, true, null, null, 0); + } + + public static Command buildLoginCommand() { + return new Command("login", "Initiates a session for the user", null, false, + ArgumentTest.buildUsernameArgument(), null, 0); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() + */ + public void testProcessParent() + throws OptionException { + final Command option = buildStartCommand(); + final List args = list("go"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processParent(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("start")); + assertTrue(commandLine.hasOption("go")); + assertTrue(commandLine.getValues(option).isEmpty()); + } + + public void testProcessParent_Spare() + throws OptionException { + final Command option = buildLoginCommand(); + final List args = list("login", "rob"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processParent(commandLine, iterator); + + assertEquals("rob", iterator.next()); + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("login")); + assertTrue(commandLine.getValues(option).isEmpty()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() + */ + public void testCanProcess() { + final Command option = buildStartCommand(); + assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "start")); + } + + public void testCanProcess_BadMatch() { + final Command option = buildStartCommand(); + assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "stop")); + } + + public void testCanProcess_Alias() { + final Command option = buildStartCommand(); + assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "go")); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() + */ + public void testPrefixes() { + final Command option = buildStartCommand(); + assertTrue(option.getPrefixes().isEmpty()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testProcess() + */ + public void testProcess() + throws OptionException { + final Command option = buildLoginCommand(); + final List args = list("login", "rob"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.process(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("login")); + assertEquals("rob", commandLine.getValue(option)); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testTriggers() + */ + public void testTriggers() { + final Command option = buildStartCommand(); + final Set triggers = option.getTriggers(); + assertContentsEqual(list("start", "go"), triggers); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testValidate() + */ + public void testValidate() { + final Parent option = buildCommitCommand(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + try { + option.validate(commandLine); + fail("Missing an option"); + } catch (OptionException moe) { + assertSame(option, moe.getOption()); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() + */ + public void testAppendUsage() { + final Option option = buildStartCommand(); + final StringBuffer buffer = new StringBuffer(); + option.appendUsage(buffer, DisplaySetting.ALL, null); + + assertEquals("[start (go)]", buffer.toString()); + } + + public void testNullPreferredName() { + try { + new Command(null, "", Collections.singleton("go"), false, null, null, 0); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception name", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT), + exp.getMessage()); + } + } + + public void testEmotyPreferredName() { + try { + new Command("", "", Collections.singleton("go"), false, null, null, 0); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception name", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT), + exp.getMessage()); + } + } + + public void testAppendUsage_NoOptional() { + final Option option = buildStartCommand(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_OPTIONAL); + option.appendUsage(buffer, settings, null); + + assertEquals("start (go)", buffer.toString()); + } + + public void testAppendUsage_NoAlias() { + final Option option = buildStartCommand(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_ALIASES); + option.appendUsage(buffer, settings, null); + + assertEquals("[start]", buffer.toString()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() + */ + public void testGetPreferredName() { + final Option option = buildStartCommand(); + assertEquals("start", option.getPreferredName()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() + */ + public void testGetDescription() { + final Option option = buildLoginCommand(); + assertEquals("Initiates a session for the user", option.getDescription()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() + */ + public void testHelpLines() { + // TODO Auto-generated method stub + } +} diff --git a/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java b/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java index e4eb7a837..2cdbe34b4 100644 --- a/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java +++ b/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java @@ -1 +1,227 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.HashSet;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.Parent;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;/** * @author roberto * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */public class DefaultOptionTest extends ParentTestCase { public static DefaultOption buildHelpOption() { final Set aliases = new HashSet(list("-h", "-?")); return new DefaultOption( "-", "--", true, "--help", "Displays the help", aliases, aliases, false, null, null, 'h'); } public static DefaultOption buildXOption() { return new DefaultOption( "-", "--", true, "-X", "This is needed", null, null, true, null, null, 'X'); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() */ public void testProcessParent() throws OptionException { final DefaultOption option = buildHelpOption(); final List args = list("--help"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("--help")); assertTrue(commandLine.hasOption("-?")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcessParent_Burst() throws OptionException { final DefaultOption option = buildHelpOption(); final List args = list("-help"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertEquals("-elp", iterator.next()); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("--help")); assertTrue(commandLine.hasOption("-?")); assertTrue(commandLine.getValues(option).isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final DefaultOption option = buildHelpOption(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option,null), "-?")); } public void testCanProcess_BadMatch() { final DefaultOption option = buildHelpOption(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), "-H")); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final DefaultOption option = buildHelpOption(); assertContentsEqual(list("-", "--"), option.getPrefixes()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final DefaultOption option = buildHelpOption(); assertContentsEqual(list("-?", "-h", "--help"), option.getTriggers()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() { final Parent option = buildXOption(); final WriteableCommandLine commandLine = commandLine(option, list()); try { option.validate(commandLine); fail("Missing an option"); } catch (OptionException moe) { assertSame(option, moe.getOption()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildHelpOption(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("[--help (-?,-h)]", buffer.toString()); } public void testAppendUsage_NoOptional() { final Option option = buildHelpOption(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_OPTIONAL); option.appendUsage(buffer, settings, null); assertEquals("--help (-?,-h)", buffer.toString()); } public void testAppendUsage_NoAlias() { final Option option = buildHelpOption(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_ALIASES); option.appendUsage(buffer, settings, null); assertEquals("[--help]", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildHelpOption(); assertEquals("--help", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildHelpOption(); assertEquals("Displays the help", option.getDescription()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { // TODO Auto-generated method stub }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.HashSet; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.Parent; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; + +/** + * @author roberto + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class DefaultOptionTest extends ParentTestCase { + + public static DefaultOption buildHelpOption() { + final Set aliases = new HashSet(list("-h", "-?")); + return new DefaultOption( + "-", + "--", + true, + "--help", + "Displays the help", + aliases, + aliases, + false, + null, + null, + 'h'); + } + + public static DefaultOption buildXOption() { + return new DefaultOption( + "-", + "--", + true, + "-X", + "This is needed", + null, + null, + true, + null, + null, + 'X'); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() + */ + public void testProcessParent() throws OptionException { + final DefaultOption option = buildHelpOption(); + final List args = list("--help"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processParent(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("--help")); + assertTrue(commandLine.hasOption("-?")); + assertTrue(commandLine.getValues(option).isEmpty()); + } + + public void testProcessParent_Burst() throws OptionException { + final DefaultOption option = buildHelpOption(); + final List args = list("-help"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processParent(commandLine, iterator); + + assertEquals("-elp", iterator.next()); + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("--help")); + assertTrue(commandLine.hasOption("-?")); + assertTrue(commandLine.getValues(option).isEmpty()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() + */ + public void testCanProcess() { + final DefaultOption option = buildHelpOption(); + assertTrue(option.canProcess(new WriteableCommandLineImpl(option,null), "-?")); + } + + public void testCanProcess_BadMatch() { + final DefaultOption option = buildHelpOption(); + assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), "-H")); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() + */ + public void testPrefixes() { + final DefaultOption option = buildHelpOption(); + assertContentsEqual(list("-", "--"), option.getPrefixes()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testProcess() + */ + public void testProcess() { + // TODO Auto-generated method stub + + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testTriggers() + */ + public void testTriggers() { + final DefaultOption option = buildHelpOption(); + assertContentsEqual(list("-?", "-h", "--help"), option.getTriggers()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testValidate() + */ + public void testValidate() { + final Parent option = buildXOption(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + try { + option.validate(commandLine); + fail("Missing an option"); + } + catch (OptionException moe) { + assertSame(option, moe.getOption()); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() + */ + public void testAppendUsage() { + final Option option = buildHelpOption(); + final StringBuffer buffer = new StringBuffer(); + option.appendUsage(buffer, DisplaySetting.ALL, null); + + assertEquals("[--help (-?,-h)]", buffer.toString()); + } + + public void testAppendUsage_NoOptional() { + final Option option = buildHelpOption(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_OPTIONAL); + option.appendUsage(buffer, settings, null); + + assertEquals("--help (-?,-h)", buffer.toString()); + } + + public void testAppendUsage_NoAlias() { + final Option option = buildHelpOption(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_ALIASES); + option.appendUsage(buffer, settings, null); + + assertEquals("[--help]", buffer.toString()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() + */ + public void testGetPreferredName() { + final Option option = buildHelpOption(); + assertEquals("--help", option.getPreferredName()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() + */ + public void testGetDescription() { + final Option option = buildHelpOption(); + assertEquals("Displays the help", option.getDescription()); + } + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() + */ + public void testHelpLines() { + // TODO Auto-generated method stub + } +} diff --git a/src/test/org/apache/commons/cli2/option/GroupTest.java b/src/test/org/apache/commons/cli2/option/GroupTest.java index 379e7f5ff..32cc36f48 100644 --- a/src/test/org/apache/commons/cli2/option/GroupTest.java +++ b/src/test/org/apache/commons/cli2/option/GroupTest.java @@ -1 +1,440 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;/** * @author Rob Oxspring */public class GroupTest extends GroupTestCase { public static final Command COMMAND_START = new Command("start", "Starts the server", null, false, null, null, 0); public static final Command COMMAND_STOP = new Command("stop", "Stops the server", null, false, null, null, 0); public static final Command COMMAND_RESTART = new Command("restart", "Stops and starts the server", null, false, null, null, 0); public static final Command COMMAND_GRACEFUL = new Command("graceful", "Restarts the server without interruption", null, false, null, null, 0); public static Group buildApacheCommandGroup() { final List options = new ArrayList(); options.add(COMMAND_GRACEFUL); options.add(COMMAND_RESTART); options.add(COMMAND_START); options.add(COMMAND_STOP); return new GroupImpl(options, "httpd-cmds", "The command to pass to the server", 1, 1); } public static Group buildApachectlGroup() { final List options = new ArrayList(); options.add(DefaultOptionTest.buildHelpOption()); options.add(ParentTest.buildKParent()); return new GroupImpl(options, "apachectl", "Controls the apache http deamon", 0, Integer.MAX_VALUE); } public static Group buildAntGroup() { final List options = new ArrayList(); options.add(DefaultOptionTest.buildHelpOption()); options.add(ArgumentTest.buildTargetsArgument()); return new GroupImpl(options, "ant", "The options for ant", 0, Integer.MAX_VALUE); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.GroupTestCase#testProcessAnonymousArguments() */ public void testProcessAnonymousArguments() throws OptionException { final Group option = buildAntGroup(); final List args = list("compile,test", "dist"); final ListIterator iterator = args.listIterator(); final WriteableCommandLine commandLine = commandLine(option, args); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption("target")); assertListContentsEqual(commandLine.getValues("target"), args); assertListContentsEqual(list("compile", "test", "dist"), args); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.GroupTestCase#testProcessOptions() */ public void testProcessOptions() throws OptionException { final Group option = buildApachectlGroup(); final List args = list("-?", "-k"); final ListIterator iterator = args.listIterator(); final WriteableCommandLine commandLine = commandLine(option, args); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption("--help")); assertTrue(commandLine.hasOption("-k")); assertFalse(commandLine.hasOption("start")); assertListContentsEqual(list("--help", "-k"), args); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Group option = buildApacheCommandGroup(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "start")); } public void testCanProcess_BadMatch() { final Group option = buildApacheCommandGroup(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "begin")); } public void testCanProcess_NullMatch() { final Group option = buildApacheCommandGroup(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), (String) null)); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Group option = buildApachectlGroup(); assertContentsEqual(list("-", "--"), option.getPrefixes()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { final Group option = buildAntGroup(); final List args = list("--help", "compile,test", "dist"); final ListIterator iterator = args.listIterator(); final WriteableCommandLine commandLine = commandLine(option, args); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption("-?")); assertListContentsEqual(list("compile", "test", "dist"), commandLine.getValues("target")); } public void testProcess_Nested() throws OptionException { final Group option = buildApachectlGroup(); final List args = list("-h", "-k", "graceful"); final ListIterator iterator = args.listIterator(); final WriteableCommandLine commandLine = commandLine(option, args); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption("-?")); assertTrue(commandLine.hasOption("-k")); assertTrue(commandLine.hasOption("graceful")); assertFalse(commandLine.hasOption("stop")); assertTrue(commandLine.getValues("start").isEmpty()); assertListContentsEqual(list("--help", "-k", "graceful"), args); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Group option = buildApachectlGroup(); assertContentsEqual(list("--help", "-?", "-h", "-k"), option.getTriggers()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() throws OptionException { final Group option = buildApacheCommandGroup(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addOption(COMMAND_RESTART); option.validate(commandLine); } public void testValidate_UnexpectedOption() { final Group option = buildApacheCommandGroup(); final WriteableCommandLine commandLine = commandLine(option, list()); commandLine.addOption(COMMAND_RESTART); commandLine.addOption(COMMAND_GRACEFUL); try { option.validate(commandLine); fail("Too many options"); } catch (OptionException uoe) { assertEquals(option, uoe.getOption()); } } public void testValidate_MissingOption() { final Group option = buildApacheCommandGroup(); final WriteableCommandLine commandLine = commandLine(option, list()); try { option.validate(commandLine); fail("Missing an option"); } catch (OptionException moe) { assertEquals(option, moe.getOption()); } } public void testValidate_RequiredChild() throws OptionException { final Option required = new DefaultOptionBuilder().withLongName("required").withRequired(true).create(); final Option optional = new DefaultOptionBuilder().withLongName("optional").withRequired(false).create(); final Group group = new GroupBuilder().withOption(required).withOption(optional).withMinimum(1).create(); WriteableCommandLine commandLine; commandLine = commandLine(group, list()); try { group.validate(commandLine); fail("Missing option 'required'"); } catch (OptionException moe) { assertEquals(required, moe.getOption()); } commandLine = commandLine(group, list()); commandLine.addOption(optional); try { group.validate(commandLine); fail("Missing option 'required'"); } catch (OptionException moe) { assertEquals(required, moe.getOption()); } commandLine = commandLine(group, list()); commandLine.addOption(required); group.validate(commandLine); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildApacheCommandGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); //settings.remove(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); option.appendUsage(buffer, settings, null); assertEquals("httpd-cmds (graceful|restart|start|stop)", buffer.toString()); } public void testAppendUsage_NoOptional() { final Option option = buildApacheCommandGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_OPTIONAL); option.appendUsage(buffer, settings, null); assertEquals("httpd-cmds (graceful|restart|start|stop)", buffer.toString()); } public void testAppendUsage_NoExpand() { final Option option = buildApacheCommandGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); option.appendUsage(buffer, settings, null); assertEquals("httpd-cmds", buffer.toString()); } public void testAppendUsage_NoExpandOrName() { final Option option = buildApacheCommandGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); option.appendUsage(buffer, settings, null); assertEquals("httpd-cmds", buffer.toString()); } public void testAppendUsage_NoName() { final Option option = buildApacheCommandGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); option.appendUsage(buffer, settings, null); assertEquals("graceful|restart|start|stop", buffer.toString()); } public void testAppendUsage_WithArgs() { final Option option = buildAntGroup(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); option.appendUsage(buffer, settings, null); assertEquals("[ant (--help (-?,-h)) [ [ ...]]]", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildAntGroup(); assertEquals("ant", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildApachectlGroup(); assertEquals("Controls the apache http deamon", option.getDescription()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { final Option option = buildApacheCommandGroup(); final List lines = option.helpLines(0, DisplaySetting.ALL, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); final HelpLine line2 = (HelpLine) i.next(); assertEquals(1, line2.getIndent()); assertEquals(COMMAND_GRACEFUL, line2.getOption()); final HelpLine line3 = (HelpLine) i.next(); assertEquals(1, line3.getIndent()); assertEquals(COMMAND_RESTART, line3.getOption()); final HelpLine line4 = (HelpLine) i.next(); assertEquals(1, line4.getIndent()); assertEquals(COMMAND_START, line4.getOption()); final HelpLine line5 = (HelpLine) i.next(); assertEquals(1, line5.getIndent()); assertEquals(COMMAND_STOP, line5.getOption()); assertFalse(i.hasNext()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines_NoExpanded() { final Option option = buildApacheCommandGroup(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); final List lines = option.helpLines(0, settings, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); assertFalse(i.hasNext()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines_NoName() { final Option option = buildApacheCommandGroup(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); final List lines = option.helpLines(0, settings, null); final Iterator i = lines.iterator(); final HelpLine line2 = (HelpLine) i.next(); assertEquals(1, line2.getIndent()); assertEquals(COMMAND_GRACEFUL, line2.getOption()); final HelpLine line3 = (HelpLine) i.next(); assertEquals(1, line3.getIndent()); assertEquals(COMMAND_RESTART, line3.getOption()); final HelpLine line4 = (HelpLine) i.next(); assertEquals(1, line4.getIndent()); assertEquals(COMMAND_START, line4.getOption()); final HelpLine line5 = (HelpLine) i.next(); assertEquals(1, line5.getIndent()); assertEquals(COMMAND_STOP, line5.getOption()); assertFalse(i.hasNext()); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.HelpLine; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; + +/** + * @author Rob Oxspring + */ +public class GroupTest + extends GroupTestCase { + public static final Command COMMAND_START = + new Command("start", "Starts the server", null, false, null, null, 0); + public static final Command COMMAND_STOP = + new Command("stop", "Stops the server", null, false, null, null, 0); + public static final Command COMMAND_RESTART = + new Command("restart", "Stops and starts the server", null, false, null, null, 0); + public static final Command COMMAND_GRACEFUL = + new Command("graceful", "Restarts the server without interruption", null, false, null, + null, 0); + + public static Group buildApacheCommandGroup() { + final List options = new ArrayList(); + options.add(COMMAND_GRACEFUL); + options.add(COMMAND_RESTART); + options.add(COMMAND_START); + options.add(COMMAND_STOP); + + return new GroupImpl(options, "httpd-cmds", "The command to pass to the server", 1, 1); + } + + public static Group buildApachectlGroup() { + final List options = new ArrayList(); + options.add(DefaultOptionTest.buildHelpOption()); + options.add(ParentTest.buildKParent()); + + return new GroupImpl(options, "apachectl", "Controls the apache http deamon", 0, + Integer.MAX_VALUE); + } + + public static Group buildAntGroup() { + final List options = new ArrayList(); + options.add(DefaultOptionTest.buildHelpOption()); + options.add(ArgumentTest.buildTargetsArgument()); + + return new GroupImpl(options, "ant", "The options for ant", 0, Integer.MAX_VALUE); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.GroupTestCase#testProcessAnonymousArguments() + */ + public void testProcessAnonymousArguments() + throws OptionException { + final Group option = buildAntGroup(); + final List args = list("compile,test", "dist"); + final ListIterator iterator = args.listIterator(); + final WriteableCommandLine commandLine = commandLine(option, args); + option.process(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption("target")); + assertListContentsEqual(commandLine.getValues("target"), args); + assertListContentsEqual(list("compile", "test", "dist"), args); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.GroupTestCase#testProcessOptions() + */ + public void testProcessOptions() + throws OptionException { + final Group option = buildApachectlGroup(); + final List args = list("-?", "-k"); + final ListIterator iterator = args.listIterator(); + final WriteableCommandLine commandLine = commandLine(option, args); + option.process(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption("--help")); + assertTrue(commandLine.hasOption("-k")); + assertFalse(commandLine.hasOption("start")); + assertListContentsEqual(list("--help", "-k"), args); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() + */ + public void testCanProcess() { + final Group option = buildApacheCommandGroup(); + assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "start")); + } + + public void testCanProcess_BadMatch() { + final Group option = buildApacheCommandGroup(); + assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "begin")); + } + + public void testCanProcess_NullMatch() { + final Group option = buildApacheCommandGroup(); + assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), (String) null)); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() + */ + public void testPrefixes() { + final Group option = buildApachectlGroup(); + assertContentsEqual(list("-", "--"), option.getPrefixes()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testProcess() + */ + public void testProcess() + throws OptionException { + final Group option = buildAntGroup(); + final List args = list("--help", "compile,test", "dist"); + final ListIterator iterator = args.listIterator(); + final WriteableCommandLine commandLine = commandLine(option, args); + option.process(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption("-?")); + assertListContentsEqual(list("compile", "test", "dist"), commandLine.getValues("target")); + } + + public void testProcess_Nested() + throws OptionException { + final Group option = buildApachectlGroup(); + final List args = list("-h", "-k", "graceful"); + final ListIterator iterator = args.listIterator(); + final WriteableCommandLine commandLine = commandLine(option, args); + option.process(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption("-?")); + assertTrue(commandLine.hasOption("-k")); + assertTrue(commandLine.hasOption("graceful")); + assertFalse(commandLine.hasOption("stop")); + assertTrue(commandLine.getValues("start").isEmpty()); + assertListContentsEqual(list("--help", "-k", "graceful"), args); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testTriggers() + */ + public void testTriggers() { + final Group option = buildApachectlGroup(); + assertContentsEqual(list("--help", "-?", "-h", "-k"), option.getTriggers()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testValidate() + */ + public void testValidate() + throws OptionException { + final Group option = buildApacheCommandGroup(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + commandLine.addOption(COMMAND_RESTART); + + option.validate(commandLine); + } + + public void testValidate_UnexpectedOption() { + final Group option = buildApacheCommandGroup(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + commandLine.addOption(COMMAND_RESTART); + commandLine.addOption(COMMAND_GRACEFUL); + + try { + option.validate(commandLine); + fail("Too many options"); + } catch (OptionException uoe) { + assertEquals(option, uoe.getOption()); + } + } + + public void testValidate_MissingOption() { + final Group option = buildApacheCommandGroup(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + try { + option.validate(commandLine); + fail("Missing an option"); + } catch (OptionException moe) { + assertEquals(option, moe.getOption()); + } + } + + public void testValidate_RequiredChild() + throws OptionException { + final Option required = + new DefaultOptionBuilder().withLongName("required").withRequired(true).create(); + final Option optional = + new DefaultOptionBuilder().withLongName("optional").withRequired(false).create(); + final Group group = + new GroupBuilder().withOption(required).withOption(optional).withMinimum(1).create(); + + WriteableCommandLine commandLine; + + commandLine = commandLine(group, list()); + + try { + group.validate(commandLine); + fail("Missing option 'required'"); + } catch (OptionException moe) { + assertEquals(required, moe.getOption()); + } + + commandLine = commandLine(group, list()); + commandLine.addOption(optional); + + try { + group.validate(commandLine); + fail("Missing option 'required'"); + } catch (OptionException moe) { + assertEquals(required, moe.getOption()); + } + + commandLine = commandLine(group, list()); + commandLine.addOption(required); + group.validate(commandLine); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() + */ + public void testAppendUsage() { + final Option option = buildApacheCommandGroup(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + + //settings.remove(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); + option.appendUsage(buffer, settings, null); + + assertEquals("httpd-cmds (graceful|restart|start|stop)", buffer.toString()); + } + + public void testAppendUsage_NoOptional() { + final Option option = buildApacheCommandGroup(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_OPTIONAL); + option.appendUsage(buffer, settings, null); + + assertEquals("httpd-cmds (graceful|restart|start|stop)", buffer.toString()); + } + + public void testAppendUsage_NoExpand() { + final Option option = buildApacheCommandGroup(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); + option.appendUsage(buffer, settings, null); + + assertEquals("httpd-cmds", buffer.toString()); + } + + public void testAppendUsage_NoExpandOrName() { + final Option option = buildApacheCommandGroup(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); + settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); + option.appendUsage(buffer, settings, null); + + assertEquals("httpd-cmds", buffer.toString()); + } + + public void testAppendUsage_NoName() { + final Option option = buildApacheCommandGroup(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); + option.appendUsage(buffer, settings, null); + + assertEquals("graceful|restart|start|stop", buffer.toString()); + } + + public void testAppendUsage_WithArgs() { + final Option option = buildAntGroup(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); + option.appendUsage(buffer, settings, null); + + assertEquals("[ant (--help (-?,-h)) [ [ ...]]]", buffer.toString()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() + */ + public void testGetPreferredName() { + final Option option = buildAntGroup(); + assertEquals("ant", option.getPreferredName()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() + */ + public void testGetDescription() { + final Option option = buildApachectlGroup(); + assertEquals("Controls the apache http deamon", option.getDescription()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() + */ + public void testHelpLines() { + final Option option = buildApacheCommandGroup(); + final List lines = option.helpLines(0, DisplaySetting.ALL, null); + final Iterator i = lines.iterator(); + + final HelpLine line1 = (HelpLine) i.next(); + assertEquals(0, line1.getIndent()); + assertEquals(option, line1.getOption()); + + final HelpLine line2 = (HelpLine) i.next(); + assertEquals(1, line2.getIndent()); + assertEquals(COMMAND_GRACEFUL, line2.getOption()); + + final HelpLine line3 = (HelpLine) i.next(); + assertEquals(1, line3.getIndent()); + assertEquals(COMMAND_RESTART, line3.getOption()); + + final HelpLine line4 = (HelpLine) i.next(); + assertEquals(1, line4.getIndent()); + assertEquals(COMMAND_START, line4.getOption()); + + final HelpLine line5 = (HelpLine) i.next(); + assertEquals(1, line5.getIndent()); + assertEquals(COMMAND_STOP, line5.getOption()); + + assertFalse(i.hasNext()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() + */ + public void testHelpLines_NoExpanded() { + final Option option = buildApacheCommandGroup(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); + + final List lines = option.helpLines(0, settings, null); + final Iterator i = lines.iterator(); + + final HelpLine line1 = (HelpLine) i.next(); + assertEquals(0, line1.getIndent()); + assertEquals(option, line1.getOption()); + + assertFalse(i.hasNext()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() + */ + public void testHelpLines_NoName() { + final Option option = buildApacheCommandGroup(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_GROUP_NAME); + + final List lines = option.helpLines(0, settings, null); + final Iterator i = lines.iterator(); + + final HelpLine line2 = (HelpLine) i.next(); + assertEquals(1, line2.getIndent()); + assertEquals(COMMAND_GRACEFUL, line2.getOption()); + + final HelpLine line3 = (HelpLine) i.next(); + assertEquals(1, line3.getIndent()); + assertEquals(COMMAND_RESTART, line3.getOption()); + + final HelpLine line4 = (HelpLine) i.next(); + assertEquals(1, line4.getIndent()); + assertEquals(COMMAND_START, line4.getOption()); + + final HelpLine line5 = (HelpLine) i.next(); + assertEquals(1, line5.getIndent()); + assertEquals(COMMAND_STOP, line5.getOption()); + + assertFalse(i.hasNext()); + } +} diff --git a/src/test/org/apache/commons/cli2/option/GroupTestCase.java b/src/test/org/apache/commons/cli2/option/GroupTestCase.java index 2a8ca5733..203a3a17b 100644 --- a/src/test/org/apache/commons/cli2/option/GroupTestCase.java +++ b/src/test/org/apache/commons/cli2/option/GroupTestCase.java @@ -1 +1,31 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import org.apache.commons.cli2.OptionException;/** * @author Rob Oxspring */public abstract class GroupTestCase extends OptionTestCase { public abstract void testProcessOptions() throws OptionException; public abstract void testProcessAnonymousArguments() throws OptionException;} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import org.apache.commons.cli2.OptionException; + +/** + * @author Rob Oxspring + */ +public abstract class GroupTestCase + extends OptionTestCase { + public abstract void testProcessOptions() + throws OptionException; + + public abstract void testProcessAnonymousArguments() + throws OptionException; +} diff --git a/src/test/org/apache/commons/cli2/option/NestedGroupTest.java b/src/test/org/apache/commons/cli2/option/NestedGroupTest.java index 13622f7bb..5fd8219bb 100644 --- a/src/test/org/apache/commons/cli2/option/NestedGroupTest.java +++ b/src/test/org/apache/commons/cli2/option/NestedGroupTest.java @@ -1 +1,192 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import org.apache.commons.cli2.CLITestCase;import org.apache.commons.cli2.CommandLine;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.Parser;import org.apache.commons.cli2.util.HelpFormatter;import java.io.BufferedReader;import java.io.IOException;import java.io.PrintWriter;import java.io.StringReader;import java.io.StringWriter;import java.util.ArrayList;import java.util.List;/** * Test to exercise nested groups developed to demonstrate bug 32533 */public class NestedGroupTest extends CLITestCase { final static DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final static ArgumentBuilder abuilder = new ArgumentBuilder(); final static GroupBuilder gbuilder = new GroupBuilder(); static Group buildActionGroup() { return gbuilder.withName("Action").withDescription("Action") .withMinimum(1).withMaximum(1) .withOption(obuilder.withId(5).withShortName("e") .withLongName("encrypt") .withDescription("Encrypt input") .create()) .withOption(obuilder.withId(6).withShortName("d") .withLongName("decrypt") .withDescription("Decrypt input") .create()).create(); } static Group buildAlgorithmGroup() { return gbuilder.withName("Algorithm") .withDescription("Encryption Algorithm").withMaximum(1) .withOption(obuilder.withId(0).withShortName("b") .withLongName("blowfish") .withDescription("Blowfish").create()) .withOption(obuilder.withId(1).withShortName("3") .withLongName("3DES") .withDescription("Triple DES") .create()).create(); } static Group buildInputGroup() { return gbuilder.withName("Input").withDescription("Input").withMinimum(1) .withMaximum(1) .withOption(obuilder.withId(2).withShortName("f") .withLongName("file") .withDescription("Input file") .withArgument(abuilder.withName( "file").withMinimum(1).withMaximum(1).create()).create()) .withOption(obuilder.withId(3).withShortName("s") .withLongName("string") .withDescription("Input string") .withArgument(abuilder.withName( "string").withMinimum(1).withMaximum(1).create()).create()) .create(); } static Group buildEncryptionServiceGroup(Group[] nestedGroups) { gbuilder.withName("encryptionService") .withOption(obuilder.withId(4).withShortName("h") .withLongName("help") .withDescription("Print this message") .create()).withOption(obuilder.withShortName( "k").withLongName("key").withDescription("Encryption key") .create()); for (int i = 0; i < nestedGroups.length; i++) { gbuilder.withOption(nestedGroups[i]); } return gbuilder.create(); } public void testNestedGroup() throws OptionException { final String[] args = { "-eb", "--file", "/tmp/filename.txt" }; Group[] nestedGroups = { buildActionGroup(), buildAlgorithmGroup(), buildInputGroup() }; Parser parser = new Parser(); parser.setGroup(buildEncryptionServiceGroup(nestedGroups)); CommandLine commandLine = parser.parse(args); assertTrue("/tmp/filename.txt".equals(commandLine.getValue("-f"))); assertTrue(commandLine.hasOption("-e")); assertTrue(commandLine.hasOption("-b")); assertFalse(commandLine.hasOption("-d")); } public void testNestedGroupHelp() { Group[] nestedGroups = { buildActionGroup(), buildAlgorithmGroup(), buildInputGroup() }; HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setGroup(buildEncryptionServiceGroup(nestedGroups)); final StringWriter out = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(out)); try { helpFormatter.print(); final BufferedReader bufferedReader = new BufferedReader(new StringReader( out.toString())); final String[] expected = new String[] { "Usage: ", " [-h -k -e|-d -b|-3 -f |-s ] ", "encryptionService ", " -h (--help) Print this message ", " -k (--key) Encryption key ", " Action Action ", " -e (--encrypt) Encrypt input ", " -d (--decrypt) Decrypt input ", " Algorithm Encryption Algorithm ", " -b (--blowfish) Blowfish ", " -3 (--3DES) Triple DES ", " Input Input ", " -f (--file) file Input file ", " -s (--string) string Input string " }; List actual = new ArrayList(expected.length); String input; while ((input = bufferedReader.readLine()) != null) { actual.add(input); } // Show they are the same number of lines assertEquals("Help text lines should be " + expected.length, actual.size(), expected.length); for (int i = 0; i < expected.length; i++) { if (!expected[i].equals(actual.get(i))) { for (int x = 0; x < expected.length; i++) { System.out.println(" " + expected[i]); System.out.println((expected[i].equals(actual.get(i)) ? "== " : "!= ") + actual.get(i)); } } assertEquals(expected[i], actual.get(i)); } } catch (IOException e) { fail(e.getLocalizedMessage()); } }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import org.apache.commons.cli2.CLITestCase; +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.util.HelpFormatter; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; + +import java.util.ArrayList; +import java.util.List; + + +/** + * Test to exercise nested groups developed to demonstrate bug 32533 + */ +public class NestedGroupTest extends CLITestCase { + final static DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final static ArgumentBuilder abuilder = new ArgumentBuilder(); + final static GroupBuilder gbuilder = new GroupBuilder(); + + static Group buildActionGroup() { + return gbuilder.withName("Action").withDescription("Action") + .withMinimum(1).withMaximum(1) + .withOption(obuilder.withId(5).withShortName("e") + .withLongName("encrypt") + .withDescription("Encrypt input") + .create()) + .withOption(obuilder.withId(6).withShortName("d") + .withLongName("decrypt") + .withDescription("Decrypt input") + .create()).create(); + } + + static Group buildAlgorithmGroup() { + return gbuilder.withName("Algorithm") + .withDescription("Encryption Algorithm").withMaximum(1) + .withOption(obuilder.withId(0).withShortName("b") + .withLongName("blowfish") + .withDescription("Blowfish").create()) + .withOption(obuilder.withId(1).withShortName("3") + .withLongName("3DES") + .withDescription("Triple DES") + .create()).create(); + } + + static Group buildInputGroup() { + return gbuilder.withName("Input").withDescription("Input").withMinimum(1) + .withMaximum(1) + .withOption(obuilder.withId(2).withShortName("f") + .withLongName("file") + .withDescription("Input file") + .withArgument(abuilder.withName( + "file").withMinimum(1).withMaximum(1).create()).create()) + .withOption(obuilder.withId(3).withShortName("s") + .withLongName("string") + .withDescription("Input string") + .withArgument(abuilder.withName( + "string").withMinimum(1).withMaximum(1).create()).create()) + .create(); + } + + static Group buildEncryptionServiceGroup(Group[] nestedGroups) { + gbuilder.withName("encryptionService") + .withOption(obuilder.withId(4).withShortName("h") + .withLongName("help") + .withDescription("Print this message") + .create()).withOption(obuilder.withShortName( + "k").withLongName("key").withDescription("Encryption key") + .create()); + + for (int i = 0; i < nestedGroups.length; i++) { + gbuilder.withOption(nestedGroups[i]); + } + + return gbuilder.create(); + } + + public void testNestedGroup() + throws OptionException { + final String[] args = { + "-eb", + "--file", + "/tmp/filename.txt" + }; + + Group[] nestedGroups = { + buildActionGroup(), + buildAlgorithmGroup(), + buildInputGroup() + }; + + Parser parser = new Parser(); + parser.setGroup(buildEncryptionServiceGroup(nestedGroups)); + + CommandLine commandLine = parser.parse(args); + + assertTrue("/tmp/filename.txt".equals(commandLine.getValue("-f"))); + assertTrue(commandLine.hasOption("-e")); + assertTrue(commandLine.hasOption("-b")); + assertFalse(commandLine.hasOption("-d")); + } + + public void testNestedGroupHelp() { + Group[] nestedGroups = { + buildActionGroup(), + buildAlgorithmGroup(), + buildInputGroup() + }; + + HelpFormatter helpFormatter = new HelpFormatter(); + helpFormatter.setGroup(buildEncryptionServiceGroup(nestedGroups)); + + final StringWriter out = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(out)); + + try { + helpFormatter.print(); + + final BufferedReader bufferedReader = new BufferedReader(new StringReader( + out.toString())); + final String[] expected = new String[] { + "Usage: ", + " [-h -k -e|-d -b|-3 -f |-s ] ", + "encryptionService ", + " -h (--help) Print this message ", + " -k (--key) Encryption key ", + " Action Action ", + " -e (--encrypt) Encrypt input ", + " -d (--decrypt) Decrypt input ", + " Algorithm Encryption Algorithm ", + " -b (--blowfish) Blowfish ", + " -3 (--3DES) Triple DES ", + " Input Input ", + " -f (--file) file Input file ", + " -s (--string) string Input string " + }; + + List actual = new ArrayList(expected.length); + String input; + + while ((input = bufferedReader.readLine()) != null) { + actual.add(input); + } + + // Show they are the same number of lines + assertEquals("Help text lines should be " + expected.length, + actual.size(), expected.length); + + for (int i = 0; i < expected.length; i++) { + if (!expected[i].equals(actual.get(i))) { + for (int x = 0; x < expected.length; i++) { + System.out.println(" " + expected[i]); + System.out.println((expected[i].equals(actual.get(i)) + ? "== " + : "!= ") + actual.get(i)); + } + } + + assertEquals(expected[i], actual.get(i)); + } + } + catch (IOException e) { + fail(e.getLocalizedMessage()); + } + } +} diff --git a/src/test/org/apache/commons/cli2/option/OptionTestCase.java b/src/test/org/apache/commons/cli2/option/OptionTestCase.java index e0018e6e5..8555aae04 100644 --- a/src/test/org/apache/commons/cli2/option/OptionTestCase.java +++ b/src/test/org/apache/commons/cli2/option/OptionTestCase.java @@ -1 +1,55 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.List;import org.apache.commons.cli2.CLITestCase;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;/** * @author Rob Oxspring */public abstract class OptionTestCase extends CLITestCase { public static WriteableCommandLine commandLine( final Option option, final List args) { return new WriteableCommandLineImpl(option, args); } public abstract void testTriggers(); public abstract void testPrefixes(); public abstract void testCanProcess(); public abstract void testProcess() throws OptionException; public abstract void testValidate() throws OptionException; public abstract void testAppendUsage() throws OptionException; public abstract void testGetPreferredName(); public abstract void testGetDescription(); public abstract void testHelpLines();} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.List; + +import org.apache.commons.cli2.CLITestCase; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; + +/** + * @author Rob Oxspring + */ +public abstract class OptionTestCase extends CLITestCase { + + public static WriteableCommandLine commandLine( + final Option option, + final List args) { + return new WriteableCommandLineImpl(option, args); + } + + public abstract void testTriggers(); + + public abstract void testPrefixes(); + + public abstract void testCanProcess(); + + public abstract void testProcess() throws OptionException; + + public abstract void testValidate() throws OptionException; + + public abstract void testAppendUsage() throws OptionException; + + public abstract void testGetPreferredName(); + + public abstract void testGetDescription(); + + public abstract void testHelpLines(); +} diff --git a/src/test/org/apache/commons/cli2/option/ParentTest.java b/src/test/org/apache/commons/cli2/option/ParentTest.java index 8fa8d8ca0..94a8a83ad 100644 --- a/src/test/org/apache/commons/cli2/option/ParentTest.java +++ b/src/test/org/apache/commons/cli2/option/ParentTest.java @@ -1 +1,419 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.Parent;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.builder.ArgumentBuilder;import org.apache.commons.cli2.builder.CommandBuilder;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * @author Rob Oxspring */public class ParentTest extends ParentTestCase { public static final Argument COMPLEX_ARGUMENT = new ArgumentBuilder().withName("username").withMinimum(1).withMaximum(1).create(); public static final Option COMPLEX_CHILD_SSL = new DefaultOptionBuilder().withLongName("ssl").withShortName("s").create(); public static final Option COMPLEX_CHILD_BASIC = new DefaultOptionBuilder().withLongName("basic").withShortName("b").create(); public static final Option COMPLEX_CHILD_DIGEST = new DefaultOptionBuilder().withLongName("digest").withShortName("d").create(); public static final Group COMPLEX_CHILDREN = new GroupBuilder().withName("login-opts").withOption(COMPLEX_CHILD_BASIC) .withOption(COMPLEX_CHILD_DIGEST).withOption(COMPLEX_CHILD_SSL).create(); public static Parent buildLibParent() { final Argument argument = ArgumentTest.buildPathArgument(); return new DefaultOption("-", "--", false, "--lib", "Specifies library search path", null, null, false, argument, null, 'l'); } public static Parent buildKParent() { final Group children = GroupTest.buildApacheCommandGroup(); return new DefaultOption("-", "--", false, "-k", "desc", null, null, false, null, children, 'k'); } public static Parent buildComplexParent() { return new CommandBuilder().withName("login").withName("lo").withName("l") .withArgument(COMPLEX_ARGUMENT).withChildren(COMPLEX_CHILDREN) .create(); } /* (non-Javadoc) * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() */ public void testProcessParent() throws OptionException { final Parent option = buildKParent(); final List args = list("-k", "start"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertEquals("start", iterator.next()); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("-k")); assertTrue(commandLine.getValues(option).isEmpty()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Parent option = buildKParent(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "-k")); } public void testCanProcess_BadMatch() { final Parent option = buildKParent(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "-K")); } public void testCanProcess_ContractedArgument() { final Parent option = buildLibParent(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "--lib=/usr/lib")); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Parent option = buildKParent(); assertContentsEqual(list("-", "--"), option.getPrefixes()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { final Parent option = CommandTest.buildStartCommand(); final List args = list("start"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("start")); assertFalse(commandLine.hasOption("stop")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcess_NoMatch() throws OptionException { final Parent option = CommandTest.buildStartCommand(); final List args = list("whatever"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.process(commandLine, iterator); fail("unexpected token not thrown"); } catch (OptionException exp) { OptionException e = new OptionException(option, ResourceConstants.UNEXPECTED_TOKEN, "whatever"); assertEquals("wrong exception message", e.getMessage(), exp.getMessage()); } } public void testProcess_Children() throws OptionException { final Parent option = buildKParent(); final List args = list("-k", "start"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertNull(option.findOption("whatever")); assertNotNull(option.findOption("start")); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("-k")); assertTrue(commandLine.hasOption("start")); assertFalse(commandLine.hasOption("stop")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcess_Argument() throws OptionException { final Parent option = buildLibParent(); final List args = list("--lib=C:\\WINDOWS;C:\\WINNT;C:\\"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("--lib")); assertContentsEqual(list("C:\\WINDOWS", "C:\\WINNT", "C:\\"), commandLine.getValues(option)); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Parent option = buildKParent(); assertContentsEqual(list("-k"), option.getTriggers()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() throws OptionException { final Parent option = CommandTest.buildStartCommand(); final WriteableCommandLine commandLine = commandLine(option, list()); option.validate(commandLine); commandLine.addOption(option); option.validate(commandLine); } public void testValidate_Children() throws OptionException { final Parent option = buildKParent(); final WriteableCommandLine commandLine = commandLine(option, list()); option.validate(commandLine); commandLine.addOption(option); try { option.validate(commandLine); fail("Missing a command"); } catch (OptionException moe) { assertNotNull(moe.getOption()); assertNotSame(option, moe.getOption()); } } public void testValidate_Argument() throws OptionException { final Command option = CommandTest.buildLoginCommand(); final WriteableCommandLine commandLine = commandLine(option, list()); option.validate(commandLine); commandLine.addOption(option); try { option.validate(commandLine); fail("Missing a value"); } catch (OptionException moe) { assertSame(option, moe.getOption()); } } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildComplexParent(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); option.appendUsage(buffer, settings, null); assertEquals("[login (l,lo) [login-opts (--basic (-b)|--digest (-d)|--ssl (-s))]]", buffer.toString()); } public void testAppendUsage_NoArguments() { final Option option = buildComplexParent(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); option.appendUsage(buffer, settings, null); assertEquals("[login (l,lo) [login-opts (--basic (-b)|--digest (-d)|--ssl (-s))]]", buffer.toString()); } public void testAppendUsage_NoChildren() { final Option option = buildComplexParent(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); option.appendUsage(buffer, settings, null); assertEquals("[login (l,lo) ]", buffer.toString()); } public void testAppendUsage_NoArgumentsOrChildren() { final Option option = buildComplexParent(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); option.appendUsage(buffer, settings, null); assertEquals("[login (l,lo)]", buffer.toString()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildLibParent(); assertEquals("--lib", option.getPreferredName()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildLibParent(); assertEquals("Specifies library search path", option.getDescription()); } /* (non-Javadoc) * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { final Option option = buildComplexParent(); final List lines = option.helpLines(0, DisplaySetting.ALL, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); final HelpLine line2 = (HelpLine) i.next(); assertEquals(1, line2.getIndent()); assertEquals(COMPLEX_ARGUMENT, line2.getOption()); final HelpLine line3 = (HelpLine) i.next(); assertEquals(1, line3.getIndent()); assertEquals(COMPLEX_CHILDREN, line3.getOption()); final HelpLine line4 = (HelpLine) i.next(); assertEquals(2, line4.getIndent()); assertEquals(COMPLEX_CHILD_BASIC, line4.getOption()); final HelpLine line5 = (HelpLine) i.next(); assertEquals(2, line5.getIndent()); assertEquals(COMPLEX_CHILD_DIGEST, line5.getOption()); final HelpLine line6 = (HelpLine) i.next(); assertEquals(2, line6.getIndent()); assertEquals(COMPLEX_CHILD_SSL, line6.getOption()); assertFalse(i.hasNext()); } public void testHelpLines_NoArgument() { final Option option = buildComplexParent(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); final List lines = option.helpLines(0, settings, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); final HelpLine line3 = (HelpLine) i.next(); assertEquals(1, line3.getIndent()); assertEquals(COMPLEX_CHILDREN, line3.getOption()); final HelpLine line4 = (HelpLine) i.next(); assertEquals(2, line4.getIndent()); assertEquals(COMPLEX_CHILD_BASIC, line4.getOption()); final HelpLine line5 = (HelpLine) i.next(); assertEquals(2, line5.getIndent()); assertEquals(COMPLEX_CHILD_DIGEST, line5.getOption()); final HelpLine line6 = (HelpLine) i.next(); assertEquals(2, line6.getIndent()); assertEquals(COMPLEX_CHILD_SSL, line6.getOption()); assertFalse(i.hasNext()); } public void testHelpLines_NoChildren() { final Option option = buildComplexParent(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); final List lines = option.helpLines(0, settings, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine) i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); final HelpLine line2 = (HelpLine) i.next(); assertEquals(1, line2.getIndent()); assertEquals(COMPLEX_ARGUMENT, line2.getOption()); assertFalse(i.hasNext()); } public void testNullPreferredName() { try { new CommandBuilder().create(); } catch (IllegalStateException exp) { assertEquals(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME), exp.getMessage()); } } public void testRequired() { Command cmd = new CommandBuilder().withRequired(true).withName("blah").create(); assertTrue("cmd is not required", cmd.isRequired()); assertEquals("id is incorrect", 0, cmd.getId()); } public void testID() { Command cmd = new CommandBuilder().withId('c').withName("blah").create(); assertEquals("id is incorrect", 'c', cmd.getId()); } public void testGetId() { assertEquals('h', DefaultOptionTest.buildHelpOption().getId()); assertEquals('X', DefaultOptionTest.buildXOption().getId()); assertEquals(0, CommandTest.buildStartCommand().getId()); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.HelpLine; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.Parent; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.CommandBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * @author Rob Oxspring + */ +public class ParentTest + extends ParentTestCase { + public static final Argument COMPLEX_ARGUMENT = + new ArgumentBuilder().withName("username").withMinimum(1).withMaximum(1).create(); + public static final Option COMPLEX_CHILD_SSL = + new DefaultOptionBuilder().withLongName("ssl").withShortName("s").create(); + public static final Option COMPLEX_CHILD_BASIC = + new DefaultOptionBuilder().withLongName("basic").withShortName("b").create(); + public static final Option COMPLEX_CHILD_DIGEST = + new DefaultOptionBuilder().withLongName("digest").withShortName("d").create(); + public static final Group COMPLEX_CHILDREN = + new GroupBuilder().withName("login-opts").withOption(COMPLEX_CHILD_BASIC) + .withOption(COMPLEX_CHILD_DIGEST).withOption(COMPLEX_CHILD_SSL).create(); + + public static Parent buildLibParent() { + final Argument argument = ArgumentTest.buildPathArgument(); + + return new DefaultOption("-", "--", false, "--lib", "Specifies library search path", null, + null, false, argument, null, 'l'); + } + + public static Parent buildKParent() { + final Group children = GroupTest.buildApacheCommandGroup(); + + return new DefaultOption("-", "--", false, "-k", "desc", null, null, false, null, children, + 'k'); + } + + public static Parent buildComplexParent() { + return new CommandBuilder().withName("login").withName("lo").withName("l") + .withArgument(COMPLEX_ARGUMENT).withChildren(COMPLEX_CHILDREN) + .create(); + } + + /* (non-Javadoc) + * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() + */ + public void testProcessParent() + throws OptionException { + final Parent option = buildKParent(); + final List args = list("-k", "start"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processParent(commandLine, iterator); + + assertEquals("start", iterator.next()); + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("-k")); + assertTrue(commandLine.getValues(option).isEmpty()); + } + + /* (non-Javadoc) + * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() + */ + public void testCanProcess() { + final Parent option = buildKParent(); + assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "-k")); + } + + public void testCanProcess_BadMatch() { + final Parent option = buildKParent(); + assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "-K")); + } + + public void testCanProcess_ContractedArgument() { + final Parent option = buildLibParent(); + assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "--lib=/usr/lib")); + } + + /* (non-Javadoc) + * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() + */ + public void testPrefixes() { + final Parent option = buildKParent(); + assertContentsEqual(list("-", "--"), option.getPrefixes()); + } + + /* (non-Javadoc) + * @see org.apache.commons.cli2.OptionTestCase#testProcess() + */ + public void testProcess() + throws OptionException { + final Parent option = CommandTest.buildStartCommand(); + final List args = list("start"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.process(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("start")); + assertFalse(commandLine.hasOption("stop")); + assertTrue(commandLine.getValues(option).isEmpty()); + } + + public void testProcess_NoMatch() + throws OptionException { + final Parent option = CommandTest.buildStartCommand(); + final List args = list("whatever"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + try { + option.process(commandLine, iterator); + fail("unexpected token not thrown"); + } catch (OptionException exp) { + OptionException e = + new OptionException(option, ResourceConstants.UNEXPECTED_TOKEN, "whatever"); + assertEquals("wrong exception message", e.getMessage(), exp.getMessage()); + } + } + + public void testProcess_Children() + throws OptionException { + final Parent option = buildKParent(); + final List args = list("-k", "start"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.process(commandLine, iterator); + + assertNull(option.findOption("whatever")); + assertNotNull(option.findOption("start")); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("-k")); + assertTrue(commandLine.hasOption("start")); + assertFalse(commandLine.hasOption("stop")); + assertTrue(commandLine.getValues(option).isEmpty()); + } + + public void testProcess_Argument() + throws OptionException { + final Parent option = buildLibParent(); + final List args = list("--lib=C:\\WINDOWS;C:\\WINNT;C:\\"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.process(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("--lib")); + assertContentsEqual(list("C:\\WINDOWS", "C:\\WINNT", "C:\\"), commandLine.getValues(option)); + } + + /* (non-Javadoc) + * @see org.apache.commons.cli2.OptionTestCase#testTriggers() + */ + public void testTriggers() { + final Parent option = buildKParent(); + assertContentsEqual(list("-k"), option.getTriggers()); + } + + /* (non-Javadoc) + * @see org.apache.commons.cli2.OptionTestCase#testValidate() + */ + public void testValidate() + throws OptionException { + final Parent option = CommandTest.buildStartCommand(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + option.validate(commandLine); + + commandLine.addOption(option); + + option.validate(commandLine); + } + + public void testValidate_Children() + throws OptionException { + final Parent option = buildKParent(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + option.validate(commandLine); + commandLine.addOption(option); + + try { + option.validate(commandLine); + fail("Missing a command"); + } catch (OptionException moe) { + assertNotNull(moe.getOption()); + assertNotSame(option, moe.getOption()); + } + } + + public void testValidate_Argument() + throws OptionException { + final Command option = CommandTest.buildLoginCommand(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + option.validate(commandLine); + + commandLine.addOption(option); + + try { + option.validate(commandLine); + fail("Missing a value"); + } catch (OptionException moe) { + assertSame(option, moe.getOption()); + } + } + + /* (non-Javadoc) + * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() + */ + public void testAppendUsage() { + final Option option = buildComplexParent(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); + option.appendUsage(buffer, settings, null); + + assertEquals("[login (l,lo) [login-opts (--basic (-b)|--digest (-d)|--ssl (-s))]]", + buffer.toString()); + } + + public void testAppendUsage_NoArguments() { + final Option option = buildComplexParent(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); + settings.remove(DisplaySetting.DISPLAY_GROUP_OUTER); + option.appendUsage(buffer, settings, null); + + assertEquals("[login (l,lo) [login-opts (--basic (-b)|--digest (-d)|--ssl (-s))]]", + buffer.toString()); + } + + public void testAppendUsage_NoChildren() { + final Option option = buildComplexParent(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); + option.appendUsage(buffer, settings, null); + + assertEquals("[login (l,lo) ]", buffer.toString()); + } + + public void testAppendUsage_NoArgumentsOrChildren() { + final Option option = buildComplexParent(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); + settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); + option.appendUsage(buffer, settings, null); + + assertEquals("[login (l,lo)]", buffer.toString()); + } + + /* (non-Javadoc) + * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() + */ + public void testGetPreferredName() { + final Option option = buildLibParent(); + assertEquals("--lib", option.getPreferredName()); + } + + /* (non-Javadoc) + * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() + */ + public void testGetDescription() { + final Option option = buildLibParent(); + assertEquals("Specifies library search path", option.getDescription()); + } + + /* (non-Javadoc) + * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() + */ + public void testHelpLines() { + final Option option = buildComplexParent(); + final List lines = option.helpLines(0, DisplaySetting.ALL, null); + final Iterator i = lines.iterator(); + + final HelpLine line1 = (HelpLine) i.next(); + assertEquals(0, line1.getIndent()); + assertEquals(option, line1.getOption()); + + final HelpLine line2 = (HelpLine) i.next(); + assertEquals(1, line2.getIndent()); + assertEquals(COMPLEX_ARGUMENT, line2.getOption()); + + final HelpLine line3 = (HelpLine) i.next(); + assertEquals(1, line3.getIndent()); + assertEquals(COMPLEX_CHILDREN, line3.getOption()); + + final HelpLine line4 = (HelpLine) i.next(); + assertEquals(2, line4.getIndent()); + assertEquals(COMPLEX_CHILD_BASIC, line4.getOption()); + + final HelpLine line5 = (HelpLine) i.next(); + assertEquals(2, line5.getIndent()); + assertEquals(COMPLEX_CHILD_DIGEST, line5.getOption()); + + final HelpLine line6 = (HelpLine) i.next(); + assertEquals(2, line6.getIndent()); + assertEquals(COMPLEX_CHILD_SSL, line6.getOption()); + + assertFalse(i.hasNext()); + } + + public void testHelpLines_NoArgument() { + final Option option = buildComplexParent(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT); + + final List lines = option.helpLines(0, settings, null); + final Iterator i = lines.iterator(); + + final HelpLine line1 = (HelpLine) i.next(); + assertEquals(0, line1.getIndent()); + assertEquals(option, line1.getOption()); + + final HelpLine line3 = (HelpLine) i.next(); + assertEquals(1, line3.getIndent()); + assertEquals(COMPLEX_CHILDREN, line3.getOption()); + + final HelpLine line4 = (HelpLine) i.next(); + assertEquals(2, line4.getIndent()); + assertEquals(COMPLEX_CHILD_BASIC, line4.getOption()); + + final HelpLine line5 = (HelpLine) i.next(); + assertEquals(2, line5.getIndent()); + assertEquals(COMPLEX_CHILD_DIGEST, line5.getOption()); + + final HelpLine line6 = (HelpLine) i.next(); + assertEquals(2, line6.getIndent()); + assertEquals(COMPLEX_CHILD_SSL, line6.getOption()); + + assertFalse(i.hasNext()); + } + + public void testHelpLines_NoChildren() { + final Option option = buildComplexParent(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_PARENT_CHILDREN); + + final List lines = option.helpLines(0, settings, null); + final Iterator i = lines.iterator(); + + final HelpLine line1 = (HelpLine) i.next(); + assertEquals(0, line1.getIndent()); + assertEquals(option, line1.getOption()); + + final HelpLine line2 = (HelpLine) i.next(); + assertEquals(1, line2.getIndent()); + assertEquals(COMPLEX_ARGUMENT, line2.getOption()); + + assertFalse(i.hasNext()); + } + + public void testNullPreferredName() { + try { + new CommandBuilder().create(); + } catch (IllegalStateException exp) { + assertEquals(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.OPTION_NO_NAME), exp.getMessage()); + } + } + + public void testRequired() { + Command cmd = new CommandBuilder().withRequired(true).withName("blah").create(); + assertTrue("cmd is not required", cmd.isRequired()); + assertEquals("id is incorrect", 0, cmd.getId()); + } + + public void testID() { + Command cmd = new CommandBuilder().withId('c').withName("blah").create(); + assertEquals("id is incorrect", 'c', cmd.getId()); + } + + public void testGetId() { + assertEquals('h', DefaultOptionTest.buildHelpOption().getId()); + assertEquals('X', DefaultOptionTest.buildXOption().getId()); + assertEquals(0, CommandTest.buildStartCommand().getId()); + } +} diff --git a/src/test/org/apache/commons/cli2/option/ParentTestCase.java b/src/test/org/apache/commons/cli2/option/ParentTestCase.java index d4d19770c..e6e0db717 100644 --- a/src/test/org/apache/commons/cli2/option/ParentTestCase.java +++ b/src/test/org/apache/commons/cli2/option/ParentTestCase.java @@ -1 +1,26 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import org.apache.commons.cli2.OptionException;/** * @author Rob Oxspring */public abstract class ParentTestCase extends OptionTestCase { public abstract void testProcessParent() throws OptionException;} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import org.apache.commons.cli2.OptionException; + +/** + * @author Rob Oxspring + */ +public abstract class ParentTestCase extends OptionTestCase { + public abstract void testProcessParent() throws OptionException; +} diff --git a/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java b/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java index 4116ddb22..196e315a8 100644 --- a/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java +++ b/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java @@ -1 +1,233 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;/** * @author Rob Oxspring */public class PropertyOptionTest extends OptionTestCase { /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Option option = new PropertyOption(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option,null), "-Dmyprop=myval")); } public void testCanProcess_Null() { final Option option = new PropertyOption(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), (String) null)); } public void testCanProcess_TooShort() { final Option option = new PropertyOption(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), "-D")); } public void testCanProcess_BadMatch() { final Option option = new PropertyOption(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null),"-dump")); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Option option = new PropertyOption(); assertContentsEqual(list("-D"), option.getPrefixes()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { final Option option = new PropertyOption(); final List args = list("-Dmyprop=myvalue"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertEquals("myvalue", commandLine.getProperty("myprop")); assertFalse(iterator.hasNext()); assertEquals(1, commandLine.getProperties().size()); } public void testProcess_UnexpectedOptionException() { final Option option = new PropertyOption(); final List args = list("--help"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); try { option.process(commandLine, iterator); fail("UnexpectedOption"); } catch (final OptionException uoe) { assertEquals(option, uoe.getOption()); assertEquals( "Unexpected --help while processing -Dproperty=value", uoe.getMessage()); } } public void testProcess_BadPropertyException() throws OptionException { final Option option = new PropertyOption(); final List args = list("-Dmyprop"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertEquals("true", commandLine.getProperty("myprop")); } public void testProcess_SetToEmpty() throws OptionException { final Option option = new PropertyOption(); final List args = list("-Dmyprop="); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertEquals("", commandLine.getProperty("myprop")); assertFalse(iterator.hasNext()); assertEquals(1, commandLine.getProperties().size()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Option option = new PropertyOption(); assertContentsEqual(list("-D"), option.getTriggers()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() throws OptionException { final Option option = new PropertyOption(); final List args = list("-Dproperty=value"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); option.validate(commandLine); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = new PropertyOption(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("-D=", buffer.toString()); } public void testAppendUsage_Hidden() { final Option option = new PropertyOption(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PROPERTY_OPTION); option.appendUsage(buffer, settings, null); assertEquals("", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = new PropertyOption(); assertEquals("-D", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = new PropertyOption(); assertEquals( "Passes properties and values to the application", option.getDescription()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { final Option option = new PropertyOption(); final List lines = option.helpLines(0, DisplaySetting.ALL, null); final Iterator i = lines.iterator(); final HelpLine line1 = (HelpLine)i.next(); assertEquals(0, line1.getIndent()); assertEquals(option, line1.getOption()); assertFalse(i.hasNext()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines_NoDisplay() { final Option option = new PropertyOption(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_PROPERTY_OPTION); final List lines = option.helpLines(0, settings, null); final Iterator i = lines.iterator(); assertFalse(i.hasNext()); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.HelpLine; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; + +/** + * @author Rob Oxspring + */ +public class PropertyOptionTest extends OptionTestCase { + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() + */ + public void testCanProcess() { + final Option option = new PropertyOption(); + assertTrue(option.canProcess(new WriteableCommandLineImpl(option,null), "-Dmyprop=myval")); + } + + public void testCanProcess_Null() { + final Option option = new PropertyOption(); + assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), (String) null)); + } + + public void testCanProcess_TooShort() { + final Option option = new PropertyOption(); + assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null), "-D")); + } + + public void testCanProcess_BadMatch() { + final Option option = new PropertyOption(); + assertFalse(option.canProcess(new WriteableCommandLineImpl(option,null),"-dump")); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() + */ + public void testPrefixes() { + final Option option = new PropertyOption(); + assertContentsEqual(list("-D"), option.getPrefixes()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testProcess() + */ + public void testProcess() throws OptionException { + final Option option = new PropertyOption(); + final List args = list("-Dmyprop=myvalue"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + option.process(commandLine, iterator); + assertEquals("myvalue", commandLine.getProperty("myprop")); + assertFalse(iterator.hasNext()); + assertEquals(1, commandLine.getProperties().size()); + } + + public void testProcess_UnexpectedOptionException() { + final Option option = new PropertyOption(); + final List args = list("--help"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + try { + option.process(commandLine, iterator); + fail("UnexpectedOption"); + } + catch (final OptionException uoe) { + assertEquals(option, uoe.getOption()); + assertEquals( + "Unexpected --help while processing -Dproperty=value", + uoe.getMessage()); + } + } + + public void testProcess_BadPropertyException() throws OptionException { + final Option option = new PropertyOption(); + final List args = list("-Dmyprop"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + option.process(commandLine, iterator); + + assertEquals("true", commandLine.getProperty("myprop")); + } + + public void testProcess_SetToEmpty() throws OptionException { + final Option option = new PropertyOption(); + final List args = list("-Dmyprop="); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + option.process(commandLine, iterator); + assertEquals("", commandLine.getProperty("myprop")); + assertFalse(iterator.hasNext()); + assertEquals(1, commandLine.getProperties().size()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testTriggers() + */ + public void testTriggers() { + final Option option = new PropertyOption(); + + assertContentsEqual(list("-D"), option.getTriggers()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testValidate() + */ + public void testValidate() throws OptionException { + final Option option = new PropertyOption(); + final List args = list("-Dproperty=value"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + + option.process(commandLine, iterator); + + option.validate(commandLine); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() + */ + public void testAppendUsage() { + final Option option = new PropertyOption(); + final StringBuffer buffer = new StringBuffer(); + option.appendUsage(buffer, DisplaySetting.ALL, null); + + assertEquals("-D=", buffer.toString()); + } + + public void testAppendUsage_Hidden() { + final Option option = new PropertyOption(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_PROPERTY_OPTION); + option.appendUsage(buffer, settings, null); + + assertEquals("", buffer.toString()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() + */ + public void testGetPreferredName() { + final Option option = new PropertyOption(); + assertEquals("-D", option.getPreferredName()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() + */ + public void testGetDescription() { + final Option option = new PropertyOption(); + assertEquals( + "Passes properties and values to the application", + option.getDescription()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() + */ + public void testHelpLines() { + final Option option = new PropertyOption(); + final List lines = option.helpLines(0, DisplaySetting.ALL, null); + final Iterator i = lines.iterator(); + + final HelpLine line1 = (HelpLine)i.next(); + assertEquals(0, line1.getIndent()); + assertEquals(option, line1.getOption()); + + assertFalse(i.hasNext()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() + */ + public void testHelpLines_NoDisplay() { + final Option option = new PropertyOption(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_PROPERTY_OPTION); + final List lines = option.helpLines(0, settings, null); + final Iterator i = lines.iterator(); + + assertFalse(i.hasNext()); + } +} diff --git a/src/test/org/apache/commons/cli2/option/SwitchTest.java b/src/test/org/apache/commons/cli2/option/SwitchTest.java index 20a75aa8b..b3dd9658c 100644 --- a/src/test/org/apache/commons/cli2/option/SwitchTest.java +++ b/src/test/org/apache/commons/cli2/option/SwitchTest.java @@ -1 +1,308 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.HashSet;import java.util.List;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.Parent;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * @author Rob Oxspring * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */public class SwitchTest extends ParentTestCase { public static Switch buildDisplaySwitch() { final Set aliases = new HashSet(); aliases.add("d"); aliases.add("disp"); return new Switch("+", "-", "display", aliases, "Sets whether to display to screen", true, null, null, 'd', null); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() */ public void testProcessParent() throws OptionException { final Switch option = buildDisplaySwitch(); final List args = list("+d"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.processParent(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("+d")); assertTrue(commandLine.hasOption("-display")); assertEquals(Boolean.TRUE, commandLine.getSwitch("-d")); assertTrue(commandLine.getValues(option).isEmpty()); } public void testProcessParent_Disabled() throws OptionException { final Switch option = buildDisplaySwitch(); final List args = list("-disp"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); assertFalse(iterator.hasNext()); assertTrue(commandLine.hasOption(option)); assertTrue(commandLine.hasOption("+d")); assertTrue(commandLine.hasOption("-display")); assertEquals(Boolean.FALSE, commandLine.getSwitch("-d")); assertTrue(commandLine.getValues(option).isEmpty()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { final Switch option = buildDisplaySwitch(); assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "+d")); } public void testCanProcess_BadMatch() { final Switch option = buildDisplaySwitch(); assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "-dont")); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { final Switch option = buildDisplaySwitch(); assertContentsEqual(list("-", "+"), option.getPrefixes()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { final Switch option = buildDisplaySwitch(); assertContentsEqual(list("-d", "+d", "-disp", "+disp", "+display", "-display"), option.getTriggers()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() { final Parent option = buildDisplaySwitch(); final WriteableCommandLine commandLine = commandLine(option, list()); try { option.validate(commandLine); fail("Missing an option"); } catch (OptionException moe) { assertSame(option, moe.getOption()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { final Option option = buildDisplaySwitch(); final StringBuffer buffer = new StringBuffer(); option.appendUsage(buffer, DisplaySetting.ALL, null); assertEquals("+display|-display (+d|-d,+disp|-disp)", buffer.toString()); } public void testAppendUsage_NoAlias() { final Option option = buildDisplaySwitch(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_ALIASES); option.appendUsage(buffer, settings, null); assertEquals("+display|-display", buffer.toString()); } public void testAppendUsage_NoDisabled() { final Option option = buildDisplaySwitch(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_SWITCH_DISABLED); option.appendUsage(buffer, settings, null); assertEquals("+display (+d,+disp)", buffer.toString()); } public void testAppendUsage_NoEnabled() { final Option option = buildDisplaySwitch(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_SWITCH_ENABLED); option.appendUsage(buffer, settings, null); assertEquals("-display (-d,-disp)", buffer.toString()); } public void testAppendUsage_NoDisabledOrEnabled() { final Option option = buildDisplaySwitch(); final StringBuffer buffer = new StringBuffer(); final Set settings = new HashSet(DisplaySetting.ALL); settings.remove(DisplaySetting.DISPLAY_SWITCH_DISABLED); settings.remove(DisplaySetting.DISPLAY_SWITCH_ENABLED); option.appendUsage(buffer, settings, null); assertEquals("+display (+d,+disp)", buffer.toString()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { final Option option = buildDisplaySwitch(); assertEquals("+display", option.getPreferredName()); } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { final Option option = buildDisplaySwitch(); assertEquals("Sets whether to display to screen", option.getDescription()); } public void testNullPreferredName() { try { new Switch("+", "-", null, null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), exp.getMessage()); } } public void testEmptyPreferredName() { try { new Switch("+", "-", "", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), exp.getMessage()); } } public void testNullAliases() { try { new Switch("+", "-", "display", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), exp.getMessage()); } } public void testNullEnablePrefix() { try { new Switch(null, "-", "display", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_NO_ENABLED_PREFIX), exp.getMessage()); } } public void testNullDisablePrefix() { try { new Switch("+", null, "display", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_NO_DISABLED_PREFIX), exp.getMessage()); } } public void testEnabledPrefixStartsWithDisabledPrefix() { try { new Switch("-", "-", "display", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ENABLED_STARTS_WITH_DISABLED), exp.getMessage()); } } public void testDisabledPrefixStartsWithEnabledPrefix() { try { new Switch("o", "on", "display", null, "Sets whether to display to screen", true, null, null, 'd', null); } catch (IllegalArgumentException exp) { assertEquals("wrong exception message", ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_DISABLED_STARTWS_WITH_ENABLED), exp.getMessage()); } } /* * (non-Javadoc) * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { // TODO Auto-generated method stub }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.option; + +import java.util.HashSet; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.Parent; +import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.commandline.WriteableCommandLineImpl; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * @author Rob Oxspring + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class SwitchTest + extends ParentTestCase { + public static Switch buildDisplaySwitch() { + final Set aliases = new HashSet(); + aliases.add("d"); + aliases.add("disp"); + + return new Switch("+", "-", "display", aliases, "Sets whether to display to screen", true, + null, null, 'd', null); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() + */ + public void testProcessParent() + throws OptionException { + final Switch option = buildDisplaySwitch(); + final List args = list("+d"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.processParent(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("+d")); + assertTrue(commandLine.hasOption("-display")); + assertEquals(Boolean.TRUE, commandLine.getSwitch("-d")); + assertTrue(commandLine.getValues(option).isEmpty()); + } + + public void testProcessParent_Disabled() + throws OptionException { + final Switch option = buildDisplaySwitch(); + final List args = list("-disp"); + final WriteableCommandLine commandLine = commandLine(option, args); + final ListIterator iterator = args.listIterator(); + option.process(commandLine, iterator); + + assertFalse(iterator.hasNext()); + assertTrue(commandLine.hasOption(option)); + assertTrue(commandLine.hasOption("+d")); + assertTrue(commandLine.hasOption("-display")); + assertEquals(Boolean.FALSE, commandLine.getSwitch("-d")); + assertTrue(commandLine.getValues(option).isEmpty()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() + */ + public void testCanProcess() { + final Switch option = buildDisplaySwitch(); + assertTrue(option.canProcess(new WriteableCommandLineImpl(option, null), "+d")); + } + + public void testCanProcess_BadMatch() { + final Switch option = buildDisplaySwitch(); + assertFalse(option.canProcess(new WriteableCommandLineImpl(option, null), "-dont")); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() + */ + public void testPrefixes() { + final Switch option = buildDisplaySwitch(); + assertContentsEqual(list("-", "+"), option.getPrefixes()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testProcess() + */ + public void testProcess() { + // TODO Auto-generated method stub + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testTriggers() + */ + public void testTriggers() { + final Switch option = buildDisplaySwitch(); + assertContentsEqual(list("-d", "+d", "-disp", "+disp", "+display", "-display"), + option.getTriggers()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testValidate() + */ + public void testValidate() { + final Parent option = buildDisplaySwitch(); + final WriteableCommandLine commandLine = commandLine(option, list()); + + try { + option.validate(commandLine); + fail("Missing an option"); + } catch (OptionException moe) { + assertSame(option, moe.getOption()); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() + */ + public void testAppendUsage() { + final Option option = buildDisplaySwitch(); + final StringBuffer buffer = new StringBuffer(); + option.appendUsage(buffer, DisplaySetting.ALL, null); + + assertEquals("+display|-display (+d|-d,+disp|-disp)", buffer.toString()); + } + + public void testAppendUsage_NoAlias() { + final Option option = buildDisplaySwitch(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_ALIASES); + option.appendUsage(buffer, settings, null); + + assertEquals("+display|-display", buffer.toString()); + } + + public void testAppendUsage_NoDisabled() { + final Option option = buildDisplaySwitch(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_SWITCH_DISABLED); + option.appendUsage(buffer, settings, null); + + assertEquals("+display (+d,+disp)", buffer.toString()); + } + + public void testAppendUsage_NoEnabled() { + final Option option = buildDisplaySwitch(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_SWITCH_ENABLED); + option.appendUsage(buffer, settings, null); + + assertEquals("-display (-d,-disp)", buffer.toString()); + } + + public void testAppendUsage_NoDisabledOrEnabled() { + final Option option = buildDisplaySwitch(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_SWITCH_DISABLED); + settings.remove(DisplaySetting.DISPLAY_SWITCH_ENABLED); + option.appendUsage(buffer, settings, null); + + assertEquals("+display (+d,+disp)", buffer.toString()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() + */ + public void testGetPreferredName() { + final Option option = buildDisplaySwitch(); + assertEquals("+display", option.getPreferredName()); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() + */ + public void testGetDescription() { + final Option option = buildDisplaySwitch(); + assertEquals("Sets whether to display to screen", option.getDescription()); + } + + public void testNullPreferredName() { + try { + new Switch("+", "-", null, null, "Sets whether to display to screen", true, null, null, + 'd', null); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), + exp.getMessage()); + } + } + + public void testEmptyPreferredName() { + try { + new Switch("+", "-", "", null, "Sets whether to display to screen", true, null, null, + 'd', null); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), + exp.getMessage()); + } + } + + public void testNullAliases() { + try { + new Switch("+", "-", "display", null, "Sets whether to display to screen", true, null, + null, 'd', null); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT), + exp.getMessage()); + } + } + + public void testNullEnablePrefix() { + try { + new Switch(null, "-", "display", null, "Sets whether to display to screen", true, null, + null, 'd', null); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_NO_ENABLED_PREFIX), + exp.getMessage()); + } + } + + public void testNullDisablePrefix() { + try { + new Switch("+", null, "display", null, "Sets whether to display to screen", true, null, + null, 'd', null); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_NO_DISABLED_PREFIX), + exp.getMessage()); + } + } + + public void testEnabledPrefixStartsWithDisabledPrefix() { + try { + new Switch("-", "-", "display", null, "Sets whether to display to screen", true, null, + null, 'd', null); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_ENABLED_STARTS_WITH_DISABLED), + exp.getMessage()); + } + } + + public void testDisabledPrefixStartsWithEnabledPrefix() { + try { + new Switch("o", "on", "display", null, "Sets whether to display to screen", true, null, + null, 'd', null); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SWITCH_DISABLED_STARTWS_WITH_ENABLED), + exp.getMessage()); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() + */ + public void testHelpLines() { + // TODO Auto-generated method stub + } +} diff --git a/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java b/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java index 2fd3cdd08..38223d79b 100644 --- a/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java +++ b/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java @@ -1 +1,84 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.commons.cli2.resource;import java.util.Locale;import java.util.MissingResourceException;import java.util.ResourceBundle;import junit.framework.TestCase;/** * A utility class used to provide internationalisation support. * * @author John Keyes */public class ResourceHelperTest extends TestCase { /** system property */ private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle"; private static ResourceHelper helper; /** resource bundle */ private ResourceBundle bundle; public void setUp() { System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.TestBundle"); helper = ResourceHelper.getResourceHelper(); } public void tearDown() { System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.CLIMessageBundle_en_US.properties"); } /** * Create a new ResourceHelper for the specified class. * * @param clazz the Class that requires some resources */ public ResourceHelperTest() { super("ResourceHelperTest"); } public void testOverridden() { assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); } public void testNewMessage1Param() { assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message")); } public void testNewMessage2Params() { assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some")); } public void testNewMessage3Params() { assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might")); } public void testNewMessage4Params() { assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might", "say")); } public void testDefaultBundle() { System.setProperty(PROP_LOCALE, "madeupname.properties"); helper = ResourceHelper.getResourceHelper(); assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.cli2.resource; + +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +import junit.framework.TestCase; + +/** + * A utility class used to provide internationalisation support. + * + * @author John Keyes + */ +public class ResourceHelperTest extends TestCase { + /** system property */ + private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle"; + + private static ResourceHelper helper; + + /** resource bundle */ + private ResourceBundle bundle; + + public void setUp() { + System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.TestBundle"); + helper = ResourceHelper.getResourceHelper(); + } + + public void tearDown() { + System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.CLIMessageBundle_en_US.properties"); + } + + /** + * Create a new ResourceHelper for the specified class. + * + * @param clazz the Class that requires some resources + */ + public ResourceHelperTest() { + super("ResourceHelperTest"); + } + + public void testOverridden() { + assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); + } + + public void testNewMessage1Param() { + assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message")); + } + + public void testNewMessage2Params() { + assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some")); + } + + public void testNewMessage3Params() { + assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might")); + } + + public void testNewMessage4Params() { + assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might", "say")); + } + + public void testDefaultBundle() { + System.setProperty(PROP_LOCALE, "madeupname.properties"); + helper = ResourceHelper.getResourceHelper(); + assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); + } +} diff --git a/src/test/org/apache/commons/cli2/util/ComparatorsTest.java b/src/test/org/apache/commons/cli2/util/ComparatorsTest.java index 5d53ec2c5..b8e0a25cf 100644 --- a/src/test/org/apache/commons/cli2/util/ComparatorsTest.java +++ b/src/test/org/apache/commons/cli2/util/ComparatorsTest.java @@ -1 +1,221 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.util;import java.util.Collections;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.CLITestCase;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.option.CommandTest;import org.apache.commons.cli2.option.DefaultOptionTest;import org.apache.commons.cli2.option.GroupTest;import org.apache.commons.cli2.option.ParentTest;import org.apache.commons.cli2.option.SwitchTest;/** * @author Rob Oxspring */public class ComparatorsTest extends TestCase { public void testGroupFirst() { final Option o1 = GroupTest.buildAntGroup(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.groupFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testGroupLast() { final Option o1 = GroupTest.buildAntGroup(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.groupLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testSwitchFirst() { final Option o1 = SwitchTest.buildDisplaySwitch(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.switchFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testSwitchLast() { final Option o1 = SwitchTest.buildDisplaySwitch(); final Option o2 = ParentTest.buildLibParent(); //final Option o3 = new SwitchBuilder().withName("hidden").create(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.switchLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testCommandFirst() { final Option o1 = CommandTest.buildCommitCommand(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.commandFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testCommandLast() { final Option o1 = CommandTest.buildCommitCommand(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.commandLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testDefaultOptionFirst() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = CommandTest.buildCommitCommand(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.defaultOptionFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testDefaultOptionLast() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = CommandTest.buildCommitCommand(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.defaultOptionLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testNamedFirst() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.namedFirst("--help")); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testNamedLast() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.namedLast("--help")); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testPreferredNameFirst() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.preferredNameFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testPreferredNameLast() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = ParentTest.buildLibParent(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.preferredNameLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testRequiredFirst() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = DefaultOptionTest.buildXOption(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.requiredFirst()); CLITestCase.assertListContentsEqual( CLITestCase.list(o2, o1), list); } public void testRequiredLast() { final Option o1 = DefaultOptionTest.buildHelpOption(); final Option o2 = DefaultOptionTest.buildXOption(); final List list = CLITestCase.list(o1, o2); Collections.sort(list, Comparators.requiredLast()); CLITestCase.assertListContentsEqual( CLITestCase.list(o1, o2), list); } public void testChained() { final Option o1 = CommandTest.buildCommitCommand(); final Option o2 = SwitchTest.buildDisplaySwitch(); final Option o3 = DefaultOptionTest.buildHelpOption(); final List list = CLITestCase.list(o1, o2, o3); Collections.sort( list, Comparators.chain( Comparators.namedFirst("--help"), Comparators.commandFirst())); CLITestCase.assertListContentsEqual( CLITestCase.list(o3, o1, o2), list); }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.util; + +import java.util.Collections; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.CLITestCase; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.option.CommandTest; +import org.apache.commons.cli2.option.DefaultOptionTest; +import org.apache.commons.cli2.option.GroupTest; +import org.apache.commons.cli2.option.ParentTest; +import org.apache.commons.cli2.option.SwitchTest; + +/** + * @author Rob Oxspring + */ +public class ComparatorsTest extends TestCase { + public void testGroupFirst() { + final Option o1 = GroupTest.buildAntGroup(); + final Option o2 = ParentTest.buildLibParent(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.groupFirst()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o1, o2), + list); + } + + public void testGroupLast() { + final Option o1 = GroupTest.buildAntGroup(); + final Option o2 = ParentTest.buildLibParent(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.groupLast()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o2, o1), + list); + } + + public void testSwitchFirst() { + final Option o1 = SwitchTest.buildDisplaySwitch(); + final Option o2 = ParentTest.buildLibParent(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.switchFirst()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o1, o2), + list); + } + + public void testSwitchLast() { + final Option o1 = SwitchTest.buildDisplaySwitch(); + final Option o2 = ParentTest.buildLibParent(); + //final Option o3 = new SwitchBuilder().withName("hidden").create(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.switchLast()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o2, o1), + list); + } + + public void testCommandFirst() { + final Option o1 = CommandTest.buildCommitCommand(); + final Option o2 = ParentTest.buildLibParent(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.commandFirst()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o1, o2), + list); + } + + public void testCommandLast() { + final Option o1 = CommandTest.buildCommitCommand(); + final Option o2 = ParentTest.buildLibParent(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.commandLast()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o2, o1), + list); + } + + public void testDefaultOptionFirst() { + final Option o1 = DefaultOptionTest.buildHelpOption(); + final Option o2 = CommandTest.buildCommitCommand(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.defaultOptionFirst()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o1, o2), + list); + } + + public void testDefaultOptionLast() { + final Option o1 = DefaultOptionTest.buildHelpOption(); + final Option o2 = CommandTest.buildCommitCommand(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.defaultOptionLast()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o2, o1), + list); + } + + public void testNamedFirst() { + final Option o1 = DefaultOptionTest.buildHelpOption(); + final Option o2 = ParentTest.buildLibParent(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.namedFirst("--help")); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o1, o2), + list); + } + + public void testNamedLast() { + final Option o1 = DefaultOptionTest.buildHelpOption(); + final Option o2 = ParentTest.buildLibParent(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.namedLast("--help")); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o2, o1), + list); + } + + public void testPreferredNameFirst() { + final Option o1 = DefaultOptionTest.buildHelpOption(); + final Option o2 = ParentTest.buildLibParent(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.preferredNameFirst()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o1, o2), + list); + } + + public void testPreferredNameLast() { + final Option o1 = DefaultOptionTest.buildHelpOption(); + final Option o2 = ParentTest.buildLibParent(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.preferredNameLast()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o2, o1), + list); + } + + public void testRequiredFirst() { + final Option o1 = DefaultOptionTest.buildHelpOption(); + final Option o2 = DefaultOptionTest.buildXOption(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.requiredFirst()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o2, o1), + list); + } + + public void testRequiredLast() { + final Option o1 = DefaultOptionTest.buildHelpOption(); + final Option o2 = DefaultOptionTest.buildXOption(); + final List list = CLITestCase.list(o1, o2); + + Collections.sort(list, Comparators.requiredLast()); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o1, o2), + list); + } + + public void testChained() { + final Option o1 = CommandTest.buildCommitCommand(); + final Option o2 = SwitchTest.buildDisplaySwitch(); + final Option o3 = DefaultOptionTest.buildHelpOption(); + final List list = CLITestCase.list(o1, o2, o3); + + Collections.sort( + list, + Comparators.chain( + Comparators.namedFirst("--help"), + Comparators.commandFirst())); + + CLITestCase.assertListContentsEqual( + CLITestCase.list(o3, o1, o2), + list); + } +} diff --git a/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java b/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java index 62dd7b755..4b2d8e4dc 100644 --- a/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java +++ b/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java @@ -1 +1,545 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.commons.cli2.util;import java.io.BufferedReader;import java.io.IOException;import java.io.PrintWriter;import java.io.StringReader;import java.io.StringWriter;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;import junit.framework.TestCase;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.builder.DefaultOptionBuilder;import org.apache.commons.cli2.builder.GroupBuilder;import org.apache.commons.cli2.option.ArgumentTest;import org.apache.commons.cli2.option.DefaultOptionTest;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;public class HelpFormatterTest extends TestCase { private ResourceHelper resources = ResourceHelper.getResourceHelper(); private HelpFormatter helpFormatter; private Option verbose; private Group options; public void setUp() { helpFormatter = new HelpFormatter("|*", "*-*", "*|", 80); helpFormatter.setDivider("+------------------------------------------------------------------------------+"); helpFormatter.setHeader("Apache Commons CLI"); helpFormatter.setFooter("Copyright 2003\nApache Software Foundation"); helpFormatter.setShellCommand("ant"); verbose = new DefaultOptionBuilder().withLongName("verbose") .withDescription("print the version information and exit") .create(); options = new GroupBuilder().withName("options").withOption(DefaultOptionTest.buildHelpOption()) .withOption(ArgumentTest.buildTargetsArgument()) .withOption(new DefaultOptionBuilder().withLongName("diagnostics") .withDescription("print information that might be helpful to diagnose or report problems.") .create()) .withOption(new DefaultOptionBuilder().withLongName("projecthelp") .withDescription("print project help information") .create()).withOption(verbose) .create(); helpFormatter.setGroup(options); } public void testPrint() throws IOException { final StringWriter writer = new StringWriter(); final PrintWriter pw = new PrintWriter(writer); helpFormatter.setPrintWriter(pw); helpFormatter.print(); // test shell assertEquals("incorrect shell command", "ant", helpFormatter.getShellCommand()); // test group assertEquals("incorrect group", this.options, helpFormatter.getGroup()); // test pagewidth assertEquals("incorrect page width", 76, helpFormatter.getPageWidth()); // test pw assertEquals("incorrect print writer", pw, helpFormatter.getPrintWriter()); // test divider assertEquals("incorrect divider", "+------------------------------------------------------------------------------+", helpFormatter.getDivider()); // test header assertEquals("incorrect header", "Apache Commons CLI", helpFormatter.getHeader()); // test footer assertEquals("incorrect footer", "Copyright 2003\nApache Software Foundation", helpFormatter.getFooter()); // test gutters assertEquals("incorrect left gutter", "|*", helpFormatter.getGutterLeft()); assertEquals("incorrect right gutter", "*|", helpFormatter.getGutterRight()); assertEquals("incorrect center gutter", "*-*", helpFormatter.getGutterCenter()); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Apache Commons CLI *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Usage: *|", reader.readLine()); assertEquals("|*ant [--help --diagnostics --projecthelp --verbose] [ [ *|", reader.readLine()); assertEquals("|*...]] *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*options *-* *|", reader.readLine()); assertEquals("|* --help (-?,-h) *-*Displays the help *|", reader.readLine()); assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", reader.readLine()); assertEquals("|* *-*or report problems. *|", reader.readLine()); assertEquals("|* --projecthelp *-*print project help information *|", reader.readLine()); assertEquals("|* --verbose *-*print the version information and exit *|", reader.readLine()); assertEquals("|* target [target ...]*-*The targets ant should build *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Copyright 2003 *|", reader.readLine()); assertEquals("|*Apache Software Foundation *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testComparator() throws IOException { final StringWriter writer = new StringWriter(); final PrintWriter pw = new PrintWriter(writer); helpFormatter.setPrintWriter(pw); final Comparator comparator = new OptionComparator(); helpFormatter.setComparator(comparator); helpFormatter.print(); // test comparator assertEquals("invalid comparator", comparator, helpFormatter.getComparator()); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Apache Commons CLI *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Usage: *|", reader.readLine()); assertEquals("|*ant [--verbose --projecthelp --help --diagnostics] [ [ *|", reader.readLine()); assertEquals("|*...]] *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*options *-* *|", reader.readLine()); assertEquals("|* --verbose *-*print the version information and exit *|", reader.readLine()); assertEquals("|* --projecthelp *-*print project help information *|", reader.readLine()); assertEquals("|* --help (-?,-h) *-*Displays the help *|", reader.readLine()); assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", reader.readLine()); assertEquals("|* *-*or report problems. *|", reader.readLine()); assertEquals("|* target [target ...]*-*The targets ant should build *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Copyright 2003 *|", reader.readLine()); assertEquals("|*Apache Software Foundation *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testPrintHelp() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printHelp(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*options *-* *|", reader.readLine()); assertEquals("|* --help (-?,-h) *-*Displays the help *|", reader.readLine()); assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", reader.readLine()); assertEquals("|* *-*or report problems. *|", reader.readLine()); assertEquals("|* --projecthelp *-*print project help information *|", reader.readLine()); assertEquals("|* --verbose *-*print the version information and exit *|", reader.readLine()); assertEquals("|* target [target ...]*-*The targets ant should build *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testPrintHelp_WithException() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.setException(new OptionException(verbose)); helpFormatter.printHelp(); //System.out.println(writer); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*--verbose*-*print the version information and exit *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testPrintHelp_TooNarrow() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter = new HelpFormatter("<", "=", ">", 4); helpFormatter.setGroup(options); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printHelp(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("", reader.readLine()); assertEquals("< --help (-?,-h) =D>", reader.readLine()); assertEquals("< =i>", reader.readLine()); // lots more lines unchecked } public void testPrintException() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.setException(new OptionException(verbose, ResourceConstants.MISSING_OPTION)); helpFormatter.printException(); //System.out.println(writer); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Missing option --verbose *|", reader.readLine()); assertNull(reader.readLine()); } public void testPrintUsage() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printUsage(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Usage: *|", reader.readLine()); assertEquals("|*ant [--help --diagnostics --projecthelp --verbose] [ [ *|", reader.readLine()); assertEquals("|*...]] *|", reader.readLine()); assertNull(reader.readLine()); } public void testPrintHeader() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printHeader(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertEquals("|*Apache Commons CLI *|", reader.readLine()); assertNull(reader.readLine()); } public void testPrintFooter() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printFooter(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("|*Copyright 2003 *|", reader.readLine()); assertEquals("|*Apache Software Foundation *|", reader.readLine()); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testPrintDivider() throws IOException { final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.printDivider(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("+------------------------------------------------------------------------------+", reader.readLine()); assertNull(reader.readLine()); } public void testWrap() { final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 30).iterator(); assertEquals("Apache Software Foundation", i.next()); assertFalse(i.hasNext()); } public void testWrap_WrapNeeded() { final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 20).iterator(); assertEquals("Apache Software", i.next()); assertEquals("Foundation", i.next()); assertFalse(i.hasNext()); } public void testWrap_BeforeSpace() { final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 16).iterator(); assertEquals("Apache Software", i.next()); assertEquals("Foundation", i.next()); assertFalse(i.hasNext()); } public void testWrap_AfterSpace() { final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 17).iterator(); assertEquals("Apache Software", i.next()); assertEquals("Foundation", i.next()); assertFalse(i.hasNext()); } public void testWrap_InWord() { final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 8).iterator(); assertEquals("Apache", i.next()); assertEquals("Software", i.next()); assertEquals("Foundati", i.next()); assertEquals("on", i.next()); assertFalse(i.hasNext()); } public void testWrap_NewLine() { final Iterator i = HelpFormatter.wrap("\nApache Software Foundation\n", 30).iterator(); assertEquals("", i.next()); assertEquals("Apache Software Foundation", i.next()); assertEquals("", i.next()); assertFalse(i.hasNext()); } public void testWrap_NewLine2() { List wrapped = HelpFormatter.wrap("A really quite long general description of the option with specific alternatives documented:\n" + " Indented special case\n" + " Alternative scenario", 30); final Iterator i = wrapped.iterator(); assertEquals("A really quite long general", i.next()); assertEquals("description of the option", i.next()); assertEquals("with specific alternatives", i.next()); assertEquals("documented:", i.next()); assertEquals(" Indented special case", i.next()); assertEquals(" Alternative scenario", i.next()); assertFalse(i.hasNext()); } public void testWrap_Below1Length() { try { HelpFormatter.wrap("Apache Software Foundation", -1); fail("IllegalArgumentException"); } catch (IllegalArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.HELPFORMATTER_WIDTH_TOO_NARROW, new Object[] { new Integer(-1) }), e.getMessage()); } } public void testPad() throws IOException { final StringWriter writer = new StringWriter(); HelpFormatter.pad("hello", 10, new PrintWriter(writer)); assertEquals("hello ", writer.toString()); } public void testPad_Null() throws IOException { final StringWriter writer = new StringWriter(); HelpFormatter.pad(null, 10, new PrintWriter(writer)); assertEquals(" ", writer.toString()); } public void testPad_TooLong() throws IOException { final StringWriter writer = new StringWriter(); HelpFormatter.pad("hello world", 10, new PrintWriter(writer)); assertEquals("hello world", writer.toString()); } public void testPad_TooShort() throws IOException { final StringWriter writer = new StringWriter(); HelpFormatter.pad("hello world", -5, new PrintWriter(writer)); assertEquals("hello world", writer.toString()); } public void testGutters() throws IOException { helpFormatter = new HelpFormatter(null, null, null, 80); helpFormatter.setShellCommand("ant"); final Set lusage = new HashSet(); lusage.add(DisplaySetting.DISPLAY_ALIASES); lusage.add(DisplaySetting.DISPLAY_GROUP_NAME); helpFormatter.setLineUsageSettings(lusage); // test line usage assertEquals("incorrect line usage", lusage, helpFormatter.getLineUsageSettings()); final Set fusage = new HashSet(); fusage.add(DisplaySetting.DISPLAY_PARENT_CHILDREN); fusage.add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); fusage.add(DisplaySetting.DISPLAY_GROUP_OUTER); fusage.add(DisplaySetting.DISPLAY_GROUP_EXPANDED); fusage.add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); fusage.add(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); fusage.add(DisplaySetting.DISPLAY_SWITCH_ENABLED); fusage.add(DisplaySetting.DISPLAY_SWITCH_DISABLED); fusage.add(DisplaySetting.DISPLAY_PROPERTY_OPTION); fusage.add(DisplaySetting.DISPLAY_PARENT_CHILDREN); fusage.add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); fusage.add(DisplaySetting.DISPLAY_OPTIONAL); helpFormatter.setFullUsageSettings(fusage); // test line usage assertEquals("incorrect full usage", fusage, helpFormatter.getFullUsageSettings()); final Set dsettings = new HashSet(); dsettings.add(DisplaySetting.DISPLAY_GROUP_NAME); dsettings.add(DisplaySetting.DISPLAY_GROUP_EXPANDED); dsettings.add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); helpFormatter.setDisplaySettings(dsettings); verbose = new DefaultOptionBuilder().withLongName("verbose") .withDescription("print the version information and exit") .create(); options = new GroupBuilder().withName("options").withOption(DefaultOptionTest.buildHelpOption()) .withOption(ArgumentTest.buildTargetsArgument()) .withOption(new DefaultOptionBuilder().withLongName("diagnostics") .withDescription("print information that might be helpful to diagnose or report problems.") .create()) .withOption(new DefaultOptionBuilder().withLongName("projecthelp") .withDescription("print project help information") .create()).withOption(verbose) .create(); helpFormatter.setGroup(options); // test default gutters assertEquals("incorrect left gutter", HelpFormatter.DEFAULT_GUTTER_LEFT, helpFormatter.getGutterLeft()); assertEquals("incorrect right gutter", HelpFormatter.DEFAULT_GUTTER_RIGHT, helpFormatter.getGutterRight()); assertEquals("incorrect center gutter", HelpFormatter.DEFAULT_GUTTER_CENTER, helpFormatter.getGutterCenter()); final StringWriter writer = new StringWriter(); helpFormatter.setPrintWriter(new PrintWriter(writer)); helpFormatter.print(); final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); assertEquals("Usage: ", reader.readLine()); assertEquals("ant [--help --diagnostics --projecthelp --verbose] [ [ ...]] ", reader.readLine()); assertEquals("options ", reader.readLine()); assertEquals(" --help (-?,-h) Displays the help ", reader.readLine()); assertEquals(" --diagnostics print information that might be helpful to diagnose or ", reader.readLine()); assertEquals(" report problems. ", reader.readLine()); assertEquals(" --projecthelp print project help information ", reader.readLine()); assertEquals(" --verbose print the version information and exit ", reader.readLine()); assertEquals(" target [target ...] The targets ant should build ", reader.readLine()); assertNull(reader.readLine()); }}class OptionComparator implements Comparator { public int compare(Object o1, Object o2) { Option opt1 = (Option) o1; Option opt2 = (Option) o2; return -opt1.getPreferredName().compareTo(opt2.getPreferredName()); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.cli2.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; + +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.DisplaySetting; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.option.ArgumentTest; +import org.apache.commons.cli2.option.DefaultOptionTest; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +public class HelpFormatterTest + extends TestCase { + private ResourceHelper resources = ResourceHelper.getResourceHelper(); + private HelpFormatter helpFormatter; + private Option verbose; + private Group options; + + public void setUp() { + helpFormatter = new HelpFormatter("|*", "*-*", "*|", 80); + helpFormatter.setDivider("+------------------------------------------------------------------------------+"); + helpFormatter.setHeader("Apache Commons CLI"); + helpFormatter.setFooter("Copyright 2003\nApache Software Foundation"); + helpFormatter.setShellCommand("ant"); + + verbose = + new DefaultOptionBuilder().withLongName("verbose") + .withDescription("print the version information and exit") + .create(); + + options = + new GroupBuilder().withName("options").withOption(DefaultOptionTest.buildHelpOption()) + .withOption(ArgumentTest.buildTargetsArgument()) + .withOption(new DefaultOptionBuilder().withLongName("diagnostics") + .withDescription("print information that might be helpful to diagnose or report problems.") + .create()) + .withOption(new DefaultOptionBuilder().withLongName("projecthelp") + .withDescription("print project help information") + .create()).withOption(verbose) + .create(); + + helpFormatter.setGroup(options); + } + + public void testPrint() + throws IOException { + final StringWriter writer = new StringWriter(); + final PrintWriter pw = new PrintWriter(writer); + helpFormatter.setPrintWriter(pw); + helpFormatter.print(); + + // test shell + assertEquals("incorrect shell command", "ant", helpFormatter.getShellCommand()); + + // test group + assertEquals("incorrect group", this.options, helpFormatter.getGroup()); + + // test pagewidth + assertEquals("incorrect page width", 76, helpFormatter.getPageWidth()); + + // test pw + assertEquals("incorrect print writer", pw, helpFormatter.getPrintWriter()); + + // test divider + assertEquals("incorrect divider", + "+------------------------------------------------------------------------------+", + helpFormatter.getDivider()); + + // test header + assertEquals("incorrect header", "Apache Commons CLI", helpFormatter.getHeader()); + + // test footer + assertEquals("incorrect footer", "Copyright 2003\nApache Software Foundation", + helpFormatter.getFooter()); + + // test gutters + assertEquals("incorrect left gutter", "|*", helpFormatter.getGutterLeft()); + assertEquals("incorrect right gutter", "*|", helpFormatter.getGutterRight()); + assertEquals("incorrect center gutter", "*-*", helpFormatter.getGutterCenter()); + + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*Apache Commons CLI *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*Usage: *|", + reader.readLine()); + assertEquals("|*ant [--help --diagnostics --projecthelp --verbose] [ [ *|", + reader.readLine()); + assertEquals("|*...]] *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*options *-* *|", + reader.readLine()); + assertEquals("|* --help (-?,-h) *-*Displays the help *|", + reader.readLine()); + assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", + reader.readLine()); + assertEquals("|* *-*or report problems. *|", + reader.readLine()); + assertEquals("|* --projecthelp *-*print project help information *|", + reader.readLine()); + assertEquals("|* --verbose *-*print the version information and exit *|", + reader.readLine()); + assertEquals("|* target [target ...]*-*The targets ant should build *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*Copyright 2003 *|", + reader.readLine()); + assertEquals("|*Apache Software Foundation *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertNull(reader.readLine()); + } + + public void testComparator() + throws IOException { + final StringWriter writer = new StringWriter(); + final PrintWriter pw = new PrintWriter(writer); + helpFormatter.setPrintWriter(pw); + + final Comparator comparator = new OptionComparator(); + helpFormatter.setComparator(comparator); + helpFormatter.print(); + + // test comparator + assertEquals("invalid comparator", comparator, helpFormatter.getComparator()); + + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*Apache Commons CLI *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*Usage: *|", + reader.readLine()); + assertEquals("|*ant [--verbose --projecthelp --help --diagnostics] [ [ *|", + reader.readLine()); + assertEquals("|*...]] *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*options *-* *|", + reader.readLine()); + assertEquals("|* --verbose *-*print the version information and exit *|", + reader.readLine()); + assertEquals("|* --projecthelp *-*print project help information *|", + reader.readLine()); + assertEquals("|* --help (-?,-h) *-*Displays the help *|", + reader.readLine()); + assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", + reader.readLine()); + assertEquals("|* *-*or report problems. *|", + reader.readLine()); + assertEquals("|* target [target ...]*-*The targets ant should build *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*Copyright 2003 *|", + reader.readLine()); + assertEquals("|*Apache Software Foundation *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertNull(reader.readLine()); + } + + public void testPrintHelp() + throws IOException { + final StringWriter writer = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(writer)); + helpFormatter.printHelp(); + + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*options *-* *|", + reader.readLine()); + assertEquals("|* --help (-?,-h) *-*Displays the help *|", + reader.readLine()); + assertEquals("|* --diagnostics *-*print information that might be helpful to diagnose *|", + reader.readLine()); + assertEquals("|* *-*or report problems. *|", + reader.readLine()); + assertEquals("|* --projecthelp *-*print project help information *|", + reader.readLine()); + assertEquals("|* --verbose *-*print the version information and exit *|", + reader.readLine()); + assertEquals("|* target [target ...]*-*The targets ant should build *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertNull(reader.readLine()); + } + + public void testPrintHelp_WithException() + throws IOException { + final StringWriter writer = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(writer)); + helpFormatter.setException(new OptionException(verbose)); + helpFormatter.printHelp(); + + //System.out.println(writer); + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*--verbose*-*print the version information and exit *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertNull(reader.readLine()); + } + + public void testPrintHelp_TooNarrow() + throws IOException { + final StringWriter writer = new StringWriter(); + helpFormatter = new HelpFormatter("<", "=", ">", 4); + helpFormatter.setGroup(options); + helpFormatter.setPrintWriter(new PrintWriter(writer)); + helpFormatter.printHelp(); + + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("", reader.readLine()); + assertEquals("< --help (-?,-h) =D>", reader.readLine()); + assertEquals("< =i>", reader.readLine()); + + // lots more lines unchecked + } + + public void testPrintException() + throws IOException { + final StringWriter writer = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(writer)); + helpFormatter.setException(new OptionException(verbose, ResourceConstants.MISSING_OPTION)); + helpFormatter.printException(); + + //System.out.println(writer); + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*Missing option --verbose *|", + reader.readLine()); + assertNull(reader.readLine()); + } + + public void testPrintUsage() + throws IOException { + final StringWriter writer = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(writer)); + helpFormatter.printUsage(); + + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*Usage: *|", + reader.readLine()); + assertEquals("|*ant [--help --diagnostics --projecthelp --verbose] [ [ *|", + reader.readLine()); + assertEquals("|*...]] *|", + reader.readLine()); + assertNull(reader.readLine()); + } + + public void testPrintHeader() + throws IOException { + final StringWriter writer = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(writer)); + helpFormatter.printHeader(); + + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertEquals("|*Apache Commons CLI *|", + reader.readLine()); + assertNull(reader.readLine()); + } + + public void testPrintFooter() + throws IOException { + final StringWriter writer = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(writer)); + helpFormatter.printFooter(); + + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("|*Copyright 2003 *|", + reader.readLine()); + assertEquals("|*Apache Software Foundation *|", + reader.readLine()); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertNull(reader.readLine()); + } + + public void testPrintDivider() + throws IOException { + final StringWriter writer = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(writer)); + helpFormatter.printDivider(); + + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("+------------------------------------------------------------------------------+", + reader.readLine()); + assertNull(reader.readLine()); + } + + public void testWrap() { + final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 30).iterator(); + assertEquals("Apache Software Foundation", i.next()); + assertFalse(i.hasNext()); + } + + public void testWrap_WrapNeeded() { + final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 20).iterator(); + assertEquals("Apache Software", i.next()); + assertEquals("Foundation", i.next()); + assertFalse(i.hasNext()); + } + + public void testWrap_BeforeSpace() { + final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 16).iterator(); + assertEquals("Apache Software", i.next()); + assertEquals("Foundation", i.next()); + assertFalse(i.hasNext()); + } + + public void testWrap_AfterSpace() { + final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 17).iterator(); + assertEquals("Apache Software", i.next()); + assertEquals("Foundation", i.next()); + assertFalse(i.hasNext()); + } + + public void testWrap_InWord() { + final Iterator i = HelpFormatter.wrap("Apache Software Foundation", 8).iterator(); + assertEquals("Apache", i.next()); + assertEquals("Software", i.next()); + assertEquals("Foundati", i.next()); + assertEquals("on", i.next()); + assertFalse(i.hasNext()); + } + + public void testWrap_NewLine() { + final Iterator i = HelpFormatter.wrap("\nApache Software Foundation\n", 30).iterator(); + assertEquals("", i.next()); + assertEquals("Apache Software Foundation", i.next()); + assertEquals("", i.next()); + assertFalse(i.hasNext()); + } + + public void testWrap_NewLine2() { + List wrapped = + HelpFormatter.wrap("A really quite long general description of the option with specific alternatives documented:\n" + + " Indented special case\n" + " Alternative scenario", 30); + + final Iterator i = wrapped.iterator(); + + assertEquals("A really quite long general", i.next()); + assertEquals("description of the option", i.next()); + assertEquals("with specific alternatives", i.next()); + assertEquals("documented:", i.next()); + assertEquals(" Indented special case", i.next()); + assertEquals(" Alternative scenario", i.next()); + assertFalse(i.hasNext()); + } + + public void testWrap_Below1Length() { + try { + HelpFormatter.wrap("Apache Software Foundation", -1); + fail("IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertEquals(resources.getMessage(ResourceConstants.HELPFORMATTER_WIDTH_TOO_NARROW, + new Object[] { new Integer(-1) }), e.getMessage()); + } + } + + public void testPad() + throws IOException { + final StringWriter writer = new StringWriter(); + HelpFormatter.pad("hello", 10, new PrintWriter(writer)); + assertEquals("hello ", writer.toString()); + } + + public void testPad_Null() + throws IOException { + final StringWriter writer = new StringWriter(); + HelpFormatter.pad(null, 10, new PrintWriter(writer)); + assertEquals(" ", writer.toString()); + } + + public void testPad_TooLong() + throws IOException { + final StringWriter writer = new StringWriter(); + HelpFormatter.pad("hello world", 10, new PrintWriter(writer)); + assertEquals("hello world", writer.toString()); + } + + public void testPad_TooShort() + throws IOException { + final StringWriter writer = new StringWriter(); + HelpFormatter.pad("hello world", -5, new PrintWriter(writer)); + assertEquals("hello world", writer.toString()); + } + + public void testGutters() + throws IOException { + helpFormatter = new HelpFormatter(null, null, null, 80); + helpFormatter.setShellCommand("ant"); + + final Set lusage = new HashSet(); + lusage.add(DisplaySetting.DISPLAY_ALIASES); + lusage.add(DisplaySetting.DISPLAY_GROUP_NAME); + helpFormatter.setLineUsageSettings(lusage); + + // test line usage + assertEquals("incorrect line usage", lusage, helpFormatter.getLineUsageSettings()); + + final Set fusage = new HashSet(); + fusage.add(DisplaySetting.DISPLAY_PARENT_CHILDREN); + fusage.add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); + fusage.add(DisplaySetting.DISPLAY_GROUP_OUTER); + fusage.add(DisplaySetting.DISPLAY_GROUP_EXPANDED); + fusage.add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); + fusage.add(DisplaySetting.DISPLAY_ARGUMENT_NUMBERED); + fusage.add(DisplaySetting.DISPLAY_SWITCH_ENABLED); + fusage.add(DisplaySetting.DISPLAY_SWITCH_DISABLED); + fusage.add(DisplaySetting.DISPLAY_PROPERTY_OPTION); + fusage.add(DisplaySetting.DISPLAY_PARENT_CHILDREN); + fusage.add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); + fusage.add(DisplaySetting.DISPLAY_OPTIONAL); + helpFormatter.setFullUsageSettings(fusage); + + // test line usage + assertEquals("incorrect full usage", fusage, helpFormatter.getFullUsageSettings()); + + final Set dsettings = new HashSet(); + dsettings.add(DisplaySetting.DISPLAY_GROUP_NAME); + dsettings.add(DisplaySetting.DISPLAY_GROUP_EXPANDED); + dsettings.add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); + + helpFormatter.setDisplaySettings(dsettings); + + verbose = + new DefaultOptionBuilder().withLongName("verbose") + .withDescription("print the version information and exit") + .create(); + + options = + new GroupBuilder().withName("options").withOption(DefaultOptionTest.buildHelpOption()) + .withOption(ArgumentTest.buildTargetsArgument()) + .withOption(new DefaultOptionBuilder().withLongName("diagnostics") + .withDescription("print information that might be helpful to diagnose or report problems.") + .create()) + .withOption(new DefaultOptionBuilder().withLongName("projecthelp") + .withDescription("print project help information") + .create()).withOption(verbose) + .create(); + + helpFormatter.setGroup(options); + + // test default gutters + assertEquals("incorrect left gutter", HelpFormatter.DEFAULT_GUTTER_LEFT, + helpFormatter.getGutterLeft()); + assertEquals("incorrect right gutter", HelpFormatter.DEFAULT_GUTTER_RIGHT, + helpFormatter.getGutterRight()); + assertEquals("incorrect center gutter", HelpFormatter.DEFAULT_GUTTER_CENTER, + helpFormatter.getGutterCenter()); + + final StringWriter writer = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(writer)); + helpFormatter.print(); + + final BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); + assertEquals("Usage: ", + reader.readLine()); + assertEquals("ant [--help --diagnostics --projecthelp --verbose] [ [ ...]] ", + reader.readLine()); + assertEquals("options ", + reader.readLine()); + assertEquals(" --help (-?,-h) Displays the help ", + reader.readLine()); + assertEquals(" --diagnostics print information that might be helpful to diagnose or ", + reader.readLine()); + assertEquals(" report problems. ", + reader.readLine()); + assertEquals(" --projecthelp print project help information ", + reader.readLine()); + assertEquals(" --verbose print the version information and exit ", + reader.readLine()); + assertEquals(" target [target ...] The targets ant should build ", + reader.readLine()); + assertNull(reader.readLine()); + } +} + + +class OptionComparator implements Comparator { + public int compare(Object o1, + Object o2) { + Option opt1 = (Option) o1; + Option opt2 = (Option) o2; + + return -opt1.getPreferredName().compareTo(opt2.getPreferredName()); + } +} diff --git a/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java b/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java index e67706023..1c89b1b12 100644 --- a/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java @@ -1 +1,248 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.net.URL;import java.net.URLClassLoader;import java.util.Arrays;import java.util.Iterator;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.resource.ResourceHelper;public class ClassValidatorTest extends TestCase { private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); private ClassValidator validator; protected void setUp() { validator = new ClassValidator(); } public void testValidName() throws InvalidArgumentException { final Object[] array = new Object[] { "MyApp", "org.apache.ant.Main" }; final List list = Arrays.asList(array); validator.validate(list); assertEquals("Name is incorrect", "MyApp", list.get(0)); assertEquals("Name is incorrect", "org.apache.ant.Main", list.get(1)); } public void testNameBadStart() { final String className = "1stClass"; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); try { validator.validate(list); fail("Class name cannot start with a number."); } catch (InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.bad.classname", className), ive.getMessage()); } } public void testNameBadEnd() { final String className = "My.Class."; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); try { validator.validate(list); fail("Trailing period not permitted."); } catch (InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.bad.classname", className), ive.getMessage()); } } public void testNameBadMiddle() { final String className = "My..Class"; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); try { validator.validate(list); fail("Two consecutive periods is not permitted."); } catch (InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.bad.classname", className), ive.getMessage()); } } public void testIllegalNameChar() { final String className = "My?Class"; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); try { validator.validate(list); fail("Illegal character not allowed in Class name."); } catch (InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.bad.classname", className), ive.getMessage()); } } public void testLoadable() { assertFalse("Validator is loadable", validator.isLoadable()); validator.setLoadable(true); assertTrue("Validator is NOT loadable", validator.isLoadable()); validator.setLoadable(false); assertFalse("Validator is loadable", validator.isLoadable()); } public void testLoadValid() throws InvalidArgumentException { final Object[] array = new Object[] { "org.apache.commons.cli2.Option", "java.util.Vector" }; final List list = Arrays.asList(array); validator.setLoadable(true); validator.validate(list); final Iterator i = list.iterator(); assertEquals( "org.apache.commons.cli2.Option", ((Class) i.next()).getName()); assertEquals("java.util.Vector", ((Class) i.next()).getName()); assertFalse(i.hasNext()); } public void testLoadInvalid() { final String className = "org.apache.commons.cli2.NonOption"; final Object[] array = new Object[] { className, "java.util.Vectors" }; final List list = Arrays.asList(array); validator.setLoadable(true); try { validator.validate(list); fail("Class Not Found"); } catch (InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.class.notfound", className), ive.getMessage()); } } public void testInstantiate() { assertFalse("Validator creates instances", validator.isInstance()); validator.setInstance(true); assertTrue( "Validator does NOT create instances", validator.isInstance()); validator.setInstance(false); assertFalse("Validator creates instances", validator.isInstance()); } public void testCreateClassInstance() throws InvalidArgumentException { final Object[] array = new Object[] { "java.util.Vector" }; final List list = Arrays.asList(array); validator.setInstance(true); validator.validate(list); assertTrue( "Vector instance NOT found", list.get(0) instanceof java.util.Vector); } public void testCreateInterfaceInstance() { final String className = "java.util.Map"; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); validator.setInstance(true); try { validator.validate(list); fail("It's not possible to create a '" + className + "'"); } catch (final InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.class.create", className), ive.getMessage()); } } public void testCreateProtectedInstance() { final String className = "org.apache.commons.cli2.validation.protect.ProtectedClass"; final Object[] array = new Object[] { className }; final List list = Arrays.asList(array); validator.setInstance(true); try { validator.validate(list); fail("It's not possible to create a '" + className + "'"); } catch (final InvalidArgumentException ive) { assertEquals( resources.getMessage( "ClassValidator.class.access", className, "Class org.apache.commons.cli2.validation.ClassValidator " + "can not access a member of class " + "org.apache.commons.cli2.validation.protect.ProtectedClass " + "with modifiers \"protected\""), ive.getMessage()); } } public void testClassloader() { assertEquals( "Wrong classloader found", validator.getClass().getClassLoader(), validator.getClassLoader()); URLClassLoader classloader = new URLClassLoader(new URL[] { }); validator.setClassLoader(classloader); assertEquals( "Wrong classloader found", classloader, validator.getClassLoader()); }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.resource.ResourceHelper; + +public class ClassValidatorTest extends TestCase { + + private final static ResourceHelper resources = + ResourceHelper.getResourceHelper(); + + private ClassValidator validator; + + protected void setUp() { + validator = new ClassValidator(); + } + + public void testValidName() throws InvalidArgumentException { + final Object[] array = new Object[] { "MyApp", "org.apache.ant.Main" }; + final List list = Arrays.asList(array); + + validator.validate(list); + + assertEquals("Name is incorrect", "MyApp", list.get(0)); + assertEquals("Name is incorrect", "org.apache.ant.Main", list.get(1)); + } + + public void testNameBadStart() { + final String className = "1stClass"; + final Object[] array = new Object[] { className }; + final List list = Arrays.asList(array); + + try { + validator.validate(list); + fail("Class name cannot start with a number."); + } catch (InvalidArgumentException ive) { + assertEquals( + resources.getMessage( + "ClassValidator.bad.classname", + className), + ive.getMessage()); + } + } + + public void testNameBadEnd() { + final String className = "My.Class."; + + final Object[] array = new Object[] { className }; + final List list = Arrays.asList(array); + + try { + validator.validate(list); + fail("Trailing period not permitted."); + } catch (InvalidArgumentException ive) { + assertEquals( + resources.getMessage( + "ClassValidator.bad.classname", + className), + ive.getMessage()); + } + } + + public void testNameBadMiddle() { + final String className = "My..Class"; + + final Object[] array = new Object[] { className }; + final List list = Arrays.asList(array); + + try { + validator.validate(list); + fail("Two consecutive periods is not permitted."); + } catch (InvalidArgumentException ive) { + assertEquals( + resources.getMessage( + "ClassValidator.bad.classname", + className), + ive.getMessage()); + } + } + + public void testIllegalNameChar() { + final String className = "My?Class"; + + final Object[] array = new Object[] { className }; + final List list = Arrays.asList(array); + + try { + validator.validate(list); + fail("Illegal character not allowed in Class name."); + } catch (InvalidArgumentException ive) { + assertEquals( + resources.getMessage( + "ClassValidator.bad.classname", + className), + ive.getMessage()); + } + } + + public void testLoadable() { + assertFalse("Validator is loadable", validator.isLoadable()); + validator.setLoadable(true); + assertTrue("Validator is NOT loadable", validator.isLoadable()); + validator.setLoadable(false); + assertFalse("Validator is loadable", validator.isLoadable()); + } + + public void testLoadValid() throws InvalidArgumentException { + final Object[] array = + new Object[] { + "org.apache.commons.cli2.Option", + "java.util.Vector" }; + final List list = Arrays.asList(array); + + validator.setLoadable(true); + validator.validate(list); + + final Iterator i = list.iterator(); + assertEquals( + "org.apache.commons.cli2.Option", + ((Class) i.next()).getName()); + assertEquals("java.util.Vector", ((Class) i.next()).getName()); + assertFalse(i.hasNext()); + } + + public void testLoadInvalid() { + final String className = "org.apache.commons.cli2.NonOption"; + + final Object[] array = new Object[] { className, "java.util.Vectors" }; + final List list = Arrays.asList(array); + + validator.setLoadable(true); + + try { + validator.validate(list); + fail("Class Not Found"); + } catch (InvalidArgumentException ive) { + assertEquals( + resources.getMessage( + "ClassValidator.class.notfound", + className), + ive.getMessage()); + } + } + + public void testInstantiate() { + assertFalse("Validator creates instances", validator.isInstance()); + validator.setInstance(true); + assertTrue( + "Validator does NOT create instances", + validator.isInstance()); + validator.setInstance(false); + assertFalse("Validator creates instances", validator.isInstance()); + } + + public void testCreateClassInstance() throws InvalidArgumentException { + final Object[] array = new Object[] { "java.util.Vector" }; + final List list = Arrays.asList(array); + + validator.setInstance(true); + + validator.validate(list); + assertTrue( + "Vector instance NOT found", + list.get(0) instanceof java.util.Vector); + } + + public void testCreateInterfaceInstance() { + final String className = "java.util.Map"; + final Object[] array = new Object[] { className }; + final List list = Arrays.asList(array); + + validator.setInstance(true); + + try { + validator.validate(list); + fail("It's not possible to create a '" + className + "'"); + } + catch (final InvalidArgumentException ive) { + assertEquals( + resources.getMessage( + "ClassValidator.class.create", + className), + ive.getMessage()); + } + } + + public void testCreateProtectedInstance() { + final String className = "org.apache.commons.cli2.validation.protect.ProtectedClass"; + final Object[] array = new Object[] { className }; + final List list = Arrays.asList(array); + + validator.setInstance(true); + + try { + validator.validate(list); + fail("It's not possible to create a '" + className + "'"); + } + catch (final InvalidArgumentException ive) { + assertEquals( + resources.getMessage( + "ClassValidator.class.access", + className, + "Class org.apache.commons.cli2.validation.ClassValidator " + + "can not access a member of class " + + "org.apache.commons.cli2.validation.protect.ProtectedClass " + + "with modifiers \"protected\""), + ive.getMessage()); + } + } + + public void testClassloader() { + assertEquals( + "Wrong classloader found", + validator.getClass().getClassLoader(), + validator.getClassLoader()); + + URLClassLoader classloader = new URLClassLoader(new URL[] { + }); + validator.setClassLoader(classloader); + + assertEquals( + "Wrong classloader found", + classloader, + validator.getClassLoader()); + } +} diff --git a/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java b/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java index 68284dfd8..ba5112c50 100644 --- a/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java @@ -1 +1,220 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.text.DateFormat;import java.text.DateFormatSymbols;import java.text.SimpleDateFormat;import java.util.Arrays;import java.util.Calendar;import java.util.Date;import java.util.Iterator;import java.util.List;import junit.framework.Test;import junit.framework.TestCase;import junit.framework.TestSuite;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * JUnit test case for DateValidator. * * @author Rob Oxspring * @author John Keyes */public class DateValidatorTest extends TestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); public static final DateFormat D_M_YY = new SimpleDateFormat("d/M/yy"); public static final DateFormat YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd"); private List formats = Arrays.asList(new Object[] { D_M_YY, YYYY_MM_DD }); public void testSingleFormatValidate() throws InvalidArgumentException { final Object[] array = new Object[] { "23/12/03" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator(D_M_YY); validator.validate(list); final Iterator i = list.iterator(); assertEquals("2003-12-23", YYYY_MM_DD.format((Date) i.next())); assertFalse(i.hasNext()); } public void testDefaultDateFormatValidate() throws InvalidArgumentException { DateFormatSymbols symbols = new DateFormatSymbols(); final Object[] array = new Object[] { "23-" + symbols.getShortMonths()[11] + "-2003" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator( new SimpleDateFormat("dd-MMM-yyyy") ); validator.validate(list); final Iterator i = list.iterator(); // CLI-40: For some reason, the YYYY_MM_DD object gets quite // confused here and returns 2003-12-22. If we make a new one // there is no problem. assertEquals("2003-12-23", new SimpleDateFormat("yyyy-MM-dd").format((Date) i.next())); assertFalse(i.hasNext()); } public void testDefaultTimeFormatValidate() throws InvalidArgumentException { final Object[] array = new Object[] { "18:00:00" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator( new SimpleDateFormat("HH:mm:ss") ); validator.validate(list); final Iterator i = list.iterator(); final DateFormat df = new SimpleDateFormat("HH:mm:ss"); assertEquals("18:00:00", df.format((Date) i.next())); assertFalse(i.hasNext()); } public void testDefaultDateTimeFormatValidate() throws InvalidArgumentException { DateFormatSymbols symbols = new DateFormatSymbols(); final Object[] array = new Object[] { "23-" + symbols.getShortMonths()[0] + "-2003 18:00:00" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator( new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss") ); validator.validate(list); final Iterator i = list.iterator(); final DateFormat df = new SimpleDateFormat("yyyy/M/dd HH:mm:ss"); assertEquals("2003/1/23 18:00:00", df.format((Date) i.next())); assertFalse(i.hasNext()); } public void testDefaultValidator() throws InvalidArgumentException { final Object[] array = new Object[] { "23/01/03 18:00" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator(new SimpleDateFormat("dd/MM/yy HH:mm")); validator.validate(list); final Iterator i = list.iterator(); final DateFormat df = new SimpleDateFormat("yyyy/M/dd HH:mm:ss"); assertEquals("2003/1/23 18:00:00", df.format((Date) i.next())); assertFalse(i.hasNext()); } public void testValidate() throws InvalidArgumentException { final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; final List list = Arrays.asList(array); final Validator validator = new DateValidator(formats); validator.validate(list); final Iterator i = list.iterator(); assertEquals("2003-12-23", YYYY_MM_DD.format((Date) i.next())); assertEquals("2002-10-12", YYYY_MM_DD.format((Date) i.next())); assertFalse(i.hasNext()); } public void testMinimumBounds() throws InvalidArgumentException { final DateValidator validator = new DateValidator(formats); final Calendar cal = Calendar.getInstance(); { final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; final List list = Arrays.asList(array); cal.set(2002, 1, 12); final Date min = cal.getTime(); validator.setMinimum(min); assertTrue("maximum bound is set", validator.getMaximum() == null); assertEquals("minimum bound is incorrect", min, validator.getMinimum()); validator.validate(list); } { final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; final List list = Arrays.asList(array); cal.set(2003, 1, 12); final Date min = cal.getTime(); validator.setMinimum(min); try { validator.validate(list); fail("minimum out of bounds exception not caught"); } catch (final InvalidArgumentException exp) { assertEquals(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, new Object[] { "2002-10-12" }), exp.getMessage()); } } } public void testFormats() throws InvalidArgumentException { final DateValidator validator = new DateValidator(formats); assertEquals("date format is incorrect", ((SimpleDateFormat) formats.get(0)).toPattern(), ((SimpleDateFormat) validator.getFormats()[0]).toPattern()); assertEquals("date format is incorrect", ((SimpleDateFormat) formats.get(1)).toPattern(), ((SimpleDateFormat) validator.getFormats()[1]).toPattern()); } public void testMaximumBounds() throws InvalidArgumentException { final DateValidator validator = new DateValidator(formats); final Calendar cal = Calendar.getInstance(); { final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; final List list = Arrays.asList(array); cal.set(2004, 1, 12); final Date max = cal.getTime(); validator.setMaximum(max); assertTrue("minimum bound is set", validator.getMinimum() == null); assertEquals("maximum bound is incorrect", max, validator.getMaximum()); validator.validate(list); } { final Object[] array = new Object[] { "23/12/03", "2004-10-12" }; final List list = Arrays.asList(array); cal.set(2004, 1, 12); final Date max = cal.getTime(); validator.setMaximum(max); try { validator.validate(list); fail("maximum out of bounds exception not caught"); } catch (final InvalidArgumentException exp) { assertEquals(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, new Object[] { "2004-10-12" }), exp.getMessage()); } } } public static Test suite() { Test result = new TestSuite(DateValidatorTest.class); // default behavior result = new TimeZoneTestSuite("EST", result); // ensure it runs in EST timezone return result; }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.text.DateFormat; +import java.text.DateFormatSymbols; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * JUnit test case for DateValidator. + * + * @author Rob Oxspring + * @author John Keyes + */ +public class DateValidatorTest + extends TestCase { + private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); + public static final DateFormat D_M_YY = new SimpleDateFormat("d/M/yy"); + public static final DateFormat YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd"); + private List formats = Arrays.asList(new Object[] { D_M_YY, YYYY_MM_DD }); + + public void testSingleFormatValidate() + throws InvalidArgumentException { + final Object[] array = new Object[] { "23/12/03" }; + final List list = Arrays.asList(array); + final Validator validator = new DateValidator(D_M_YY); + + validator.validate(list); + + final Iterator i = list.iterator(); + assertEquals("2003-12-23", YYYY_MM_DD.format((Date) i.next())); + assertFalse(i.hasNext()); + } + + public void testDefaultDateFormatValidate() + throws InvalidArgumentException { + DateFormatSymbols symbols = new DateFormatSymbols(); + final Object[] array = new Object[] { "23-" + symbols.getShortMonths()[11] + "-2003" }; + final List list = Arrays.asList(array); + final Validator validator = new DateValidator( new SimpleDateFormat("dd-MMM-yyyy") ); + + validator.validate(list); + + final Iterator i = list.iterator(); + // CLI-40: For some reason, the YYYY_MM_DD object gets quite + // confused here and returns 2003-12-22. If we make a new one + // there is no problem. + assertEquals("2003-12-23", new SimpleDateFormat("yyyy-MM-dd").format((Date) i.next())); + assertFalse(i.hasNext()); + } + + public void testDefaultTimeFormatValidate() + throws InvalidArgumentException { + final Object[] array = new Object[] { "18:00:00" }; + final List list = Arrays.asList(array); + final Validator validator = new DateValidator( new SimpleDateFormat("HH:mm:ss") ); + + validator.validate(list); + + final Iterator i = list.iterator(); + final DateFormat df = new SimpleDateFormat("HH:mm:ss"); + assertEquals("18:00:00", df.format((Date) i.next())); + assertFalse(i.hasNext()); + } + + public void testDefaultDateTimeFormatValidate() + throws InvalidArgumentException { + DateFormatSymbols symbols = new DateFormatSymbols(); + final Object[] array = new Object[] { "23-" + symbols.getShortMonths()[0] + "-2003 18:00:00" }; + final List list = Arrays.asList(array); + final Validator validator = new DateValidator( new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss") ); + + validator.validate(list); + + final Iterator i = list.iterator(); + final DateFormat df = new SimpleDateFormat("yyyy/M/dd HH:mm:ss"); + assertEquals("2003/1/23 18:00:00", df.format((Date) i.next())); + assertFalse(i.hasNext()); + } + + public void testDefaultValidator() + throws InvalidArgumentException { + final Object[] array = new Object[] { "23/01/03 18:00" }; + final List list = Arrays.asList(array); + final Validator validator = new DateValidator(new SimpleDateFormat("dd/MM/yy HH:mm")); + + validator.validate(list); + + final Iterator i = list.iterator(); + final DateFormat df = new SimpleDateFormat("yyyy/M/dd HH:mm:ss"); + assertEquals("2003/1/23 18:00:00", df.format((Date) i.next())); + assertFalse(i.hasNext()); + } + + public void testValidate() + throws InvalidArgumentException { + final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; + final List list = Arrays.asList(array); + final Validator validator = new DateValidator(formats); + + validator.validate(list); + + final Iterator i = list.iterator(); + assertEquals("2003-12-23", YYYY_MM_DD.format((Date) i.next())); + assertEquals("2002-10-12", YYYY_MM_DD.format((Date) i.next())); + assertFalse(i.hasNext()); + } + + public void testMinimumBounds() + throws InvalidArgumentException { + final DateValidator validator = new DateValidator(formats); + final Calendar cal = Calendar.getInstance(); + + { + final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; + final List list = Arrays.asList(array); + cal.set(2002, 1, 12); + + final Date min = cal.getTime(); + validator.setMinimum(min); + assertTrue("maximum bound is set", validator.getMaximum() == null); + assertEquals("minimum bound is incorrect", min, validator.getMinimum()); + validator.validate(list); + } + + { + final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; + final List list = Arrays.asList(array); + cal.set(2003, 1, 12); + + final Date min = cal.getTime(); + validator.setMinimum(min); + + try { + validator.validate(list); + fail("minimum out of bounds exception not caught"); + } catch (final InvalidArgumentException exp) { + assertEquals(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, + new Object[] { "2002-10-12" }), exp.getMessage()); + } + } + } + + public void testFormats() + throws InvalidArgumentException { + final DateValidator validator = new DateValidator(formats); + assertEquals("date format is incorrect", ((SimpleDateFormat) formats.get(0)).toPattern(), + ((SimpleDateFormat) validator.getFormats()[0]).toPattern()); + assertEquals("date format is incorrect", ((SimpleDateFormat) formats.get(1)).toPattern(), + ((SimpleDateFormat) validator.getFormats()[1]).toPattern()); + } + + public void testMaximumBounds() + throws InvalidArgumentException { + final DateValidator validator = new DateValidator(formats); + final Calendar cal = Calendar.getInstance(); + + { + final Object[] array = new Object[] { "23/12/03", "2002-10-12" }; + final List list = Arrays.asList(array); + cal.set(2004, 1, 12); + + final Date max = cal.getTime(); + validator.setMaximum(max); + assertTrue("minimum bound is set", validator.getMinimum() == null); + assertEquals("maximum bound is incorrect", max, validator.getMaximum()); + validator.validate(list); + } + + { + final Object[] array = new Object[] { "23/12/03", "2004-10-12" }; + final List list = Arrays.asList(array); + cal.set(2004, 1, 12); + + final Date max = cal.getTime(); + validator.setMaximum(max); + + try { + validator.validate(list); + fail("maximum out of bounds exception not caught"); + } catch (final InvalidArgumentException exp) { + assertEquals(resources.getMessage(ResourceConstants.DATEVALIDATOR_DATE_OUTOFRANGE, + new Object[] { "2004-10-12" }), exp.getMessage()); + } + } + } + + public static Test suite() { + Test result = new TestSuite(DateValidatorTest.class); // default behavior + result = new TimeZoneTestSuite("EST", result); // ensure it runs in EST timezone + + return result; + } +} diff --git a/src/test/org/apache/commons/cli2/validation/EnumValidatorTest.java b/src/test/org/apache/commons/cli2/validation/EnumValidatorTest.java index 4da542db7..53673f11a 100644 --- a/src/test/org/apache/commons/cli2/validation/EnumValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/EnumValidatorTest.java @@ -1 +1,66 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.util.Arrays;import java.util.Iterator;import java.util.List;import java.util.Set;import java.util.TreeSet;import junit.framework.TestCase;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;public class EnumValidatorTest extends TestCase { private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); private final Set enumSet = new TreeSet(Arrays.asList(new Object[] { "red", "green", "blue" })); public void testValidate() throws InvalidArgumentException { final Object[] array = new Object[] { "red", "green" }; { final List list = Arrays.asList(array); final EnumValidator validator = new EnumValidator(enumSet); assertEquals("valid values are incorrect", enumSet, validator.getValidValues()); validator.validate(list); final Iterator i = list.iterator(); assertEquals("red", i.next()); assertEquals("green", i.next()); assertFalse(i.hasNext()); } } public void testNonMember() { final Object[] array = new Object[] { "red", "pink" }; final List list = Arrays.asList(array); final EnumValidator validator = new EnumValidator(enumSet); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.ENUM_ILLEGAL_VALUE, new Object[] { "pink", validator.getValuesAsString() }), e.getMessage()); } }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +public class EnumValidatorTest + extends TestCase { + private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); + private final Set enumSet = new TreeSet(Arrays.asList(new Object[] { "red", "green", "blue" })); + + public void testValidate() + throws InvalidArgumentException { + final Object[] array = new Object[] { "red", "green" }; + + { + final List list = Arrays.asList(array); + final EnumValidator validator = new EnumValidator(enumSet); + assertEquals("valid values are incorrect", enumSet, validator.getValidValues()); + validator.validate(list); + + final Iterator i = list.iterator(); + assertEquals("red", i.next()); + assertEquals("green", i.next()); + assertFalse(i.hasNext()); + } + } + + public void testNonMember() { + final Object[] array = new Object[] { "red", "pink" }; + final List list = Arrays.asList(array); + final EnumValidator validator = new EnumValidator(enumSet); + + try { + validator.validate(list); + fail("InvalidArgumentException"); + } catch (InvalidArgumentException e) { + assertEquals(resources.getMessage(ResourceConstants.ENUM_ILLEGAL_VALUE, + new Object[] { "pink", validator.getValuesAsString() }), + e.getMessage()); + } + } +} diff --git a/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java b/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java index 912086eaa..16744ca65 100644 --- a/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java @@ -1 +1,196 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.io.File;import java.io.IOException;import java.util.Arrays;import java.util.Iterator;import java.util.List;import junit.framework.TestCase;/** * JUnit test case for the FileValidator. * * @author Rob Oxspring * @author John Keyes */public class FileValidatorTest extends TestCase { public void testValidate() throws InvalidArgumentException { final Object[] array = new Object[] { "src", "project.xml", "veryunlikelyfilename" }; final List list = Arrays.asList(array); final FileValidator validator = new FileValidator(); validator.validate(list); final Iterator i = list.iterator(); assertEquals(new File("src"), i.next()); assertEquals(new File("project.xml"), i.next()); assertEquals(new File("veryunlikelyfilename"), i.next()); assertFalse(i.hasNext()); } public void testValidate_Directory() { final Object[] array = new Object[] { "src", "project.xml" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator .getExistingDirectoryInstance(); assertTrue("is a directory validator", validator.isDirectory()); assertFalse("is not a file validator", validator.isFile()); assertTrue("is an existing file validator", validator.isExisting()); assertFalse("is not a hidden file validator", validator.isHidden()); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("project.xml", e.getMessage()); } } public void testValidate_ReadableFile() { // make file readonly File file = new File("src/test/data/readable.txt"); file.setReadOnly(); final Object[] array = new Object[] { "src/test/data/readable.txt", "src/test/data/notreadable.txt" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator.getExistingFileInstance(); validator.setReadable(true); assertFalse("is not a directory validator", validator.isDirectory()); assertTrue("is a file validator", validator.isFile()); assertTrue("is an existing file validator", validator.isExisting()); assertFalse("is not a hidden file validator", validator.isHidden()); assertTrue("is a readable file validator", validator.isReadable()); assertFalse("is not a writable file validator", validator.isWritable()); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("src/test/data/notreadable.txt", e.getMessage()); } } public void testValidate_WritableFile() { // make file readonly File file = new File("src/test/data/readable.txt"); file.setReadOnly(); final Object[] array = new Object[] { "src/test/data/writable.txt", "src/test/data/readable.txt" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator.getExistingFileInstance(); validator.setWritable(true); assertFalse("is not a directory validator", validator.isDirectory()); assertTrue("is a file validator", validator.isFile()); assertTrue("is an existing file validator", validator.isExisting()); assertFalse("is not a hidden file validator", validator.isHidden()); assertFalse("is not a readable file validator", validator.isReadable()); assertTrue("is a writable file validator", validator.isWritable()); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("src/test/data/readable.txt", e.getMessage()); } } public void testValidate_HiddenFile() throws InvalidArgumentException { // make file hidden on Windows attribute("H"); final Object[] array = new Object[] { "src/test/data/.hidden.txt", "src" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator.getExistingFileInstance(); validator.setHidden(true); assertFalse("is not a directory validator", validator.isDirectory()); assertTrue("is a file validator", validator.isFile()); assertTrue("is an existing file validator", validator.isExisting()); assertTrue("is a hidden file validator", validator.isHidden()); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("src", e.getMessage()); } } private void attribute(String attr) { final String os = System.getProperty("os.name").toLowerCase(); // if the test is run on windows, run the attrib program // to set the hidden attribute if (os.indexOf("windows") != -1) { // windows try { Process proc = Runtime.getRuntime().exec( "attrib.exe +" + attr + " src/test/data/.hidden.txt", null, new File(".")); proc.waitFor(); } catch (InterruptedException e) { System.out.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } public void testValidate_Existing() { final Object[] array = new Object[] { "project.xml", "veryunlikelyfilename" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator.getExistingInstance(); assertFalse("is not a directory validator", validator.isDirectory()); assertFalse("is not a file validator", validator.isFile()); assertTrue("is an existing file validator", validator.isExisting()); assertFalse("is not a hidden file validator", validator.isHidden()); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("veryunlikelyfilename", e.getMessage()); } } public void testValidate_File() { final Object[] array = new Object[] { "project.xml", "src" }; final List list = Arrays.asList(array); final Validator validator = FileValidator.getExistingFileInstance(); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("src", e.getMessage()); } }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import junit.framework.TestCase; + +/** + * JUnit test case for the FileValidator. + * + * @author Rob Oxspring + * @author John Keyes + */ +public class FileValidatorTest extends TestCase { + + public void testValidate() throws InvalidArgumentException { + final Object[] array = new Object[] { "src", "project.xml", + "veryunlikelyfilename" }; + final List list = Arrays.asList(array); + final FileValidator validator = new FileValidator(); + + validator.validate(list); + + final Iterator i = list.iterator(); + assertEquals(new File("src"), i.next()); + assertEquals(new File("project.xml"), i.next()); + assertEquals(new File("veryunlikelyfilename"), i.next()); + assertFalse(i.hasNext()); + } + + public void testValidate_Directory() { + final Object[] array = new Object[] { "src", "project.xml" }; + final List list = Arrays.asList(array); + final FileValidator validator = FileValidator + .getExistingDirectoryInstance(); + + assertTrue("is a directory validator", validator.isDirectory()); + assertFalse("is not a file validator", validator.isFile()); + assertTrue("is an existing file validator", validator.isExisting()); + assertFalse("is not a hidden file validator", validator.isHidden()); + + try { + validator.validate(list); + fail("InvalidArgumentException"); + } catch (InvalidArgumentException e) { + assertEquals("project.xml", e.getMessage()); + } + } + + public void testValidate_ReadableFile() { + // make file readonly + File file = new File("src/test/data/readable.txt"); + file.setReadOnly(); + + final Object[] array = new Object[] { "src/test/data/readable.txt", + "src/test/data/notreadable.txt" }; + final List list = Arrays.asList(array); + final FileValidator validator = FileValidator.getExistingFileInstance(); + validator.setReadable(true); + + assertFalse("is not a directory validator", validator.isDirectory()); + assertTrue("is a file validator", validator.isFile()); + assertTrue("is an existing file validator", validator.isExisting()); + assertFalse("is not a hidden file validator", validator.isHidden()); + assertTrue("is a readable file validator", validator.isReadable()); + assertFalse("is not a writable file validator", validator.isWritable()); + + try { + validator.validate(list); + fail("InvalidArgumentException"); + } catch (InvalidArgumentException e) { + assertEquals("src/test/data/notreadable.txt", e.getMessage()); + } + } + + public void testValidate_WritableFile() { + // make file readonly + File file = new File("src/test/data/readable.txt"); + file.setReadOnly(); + + final Object[] array = new Object[] { "src/test/data/writable.txt", + "src/test/data/readable.txt" }; + final List list = Arrays.asList(array); + final FileValidator validator = FileValidator.getExistingFileInstance(); + validator.setWritable(true); + + assertFalse("is not a directory validator", validator.isDirectory()); + assertTrue("is a file validator", validator.isFile()); + assertTrue("is an existing file validator", validator.isExisting()); + assertFalse("is not a hidden file validator", validator.isHidden()); + assertFalse("is not a readable file validator", validator.isReadable()); + assertTrue("is a writable file validator", validator.isWritable()); + + try { + validator.validate(list); + fail("InvalidArgumentException"); + } catch (InvalidArgumentException e) { + assertEquals("src/test/data/readable.txt", e.getMessage()); + } + } + + public void testValidate_HiddenFile() throws InvalidArgumentException { + // make file hidden on Windows + attribute("H"); + + final Object[] array = new Object[] { "src/test/data/.hidden.txt", "src" }; + final List list = Arrays.asList(array); + final FileValidator validator = FileValidator.getExistingFileInstance(); + validator.setHidden(true); + + assertFalse("is not a directory validator", validator.isDirectory()); + assertTrue("is a file validator", validator.isFile()); + assertTrue("is an existing file validator", validator.isExisting()); + assertTrue("is a hidden file validator", validator.isHidden()); + + try { + validator.validate(list); + fail("InvalidArgumentException"); + } catch (InvalidArgumentException e) { + assertEquals("src", e.getMessage()); + } + } + + private void attribute(String attr) { + final String os = System.getProperty("os.name").toLowerCase(); + + // if the test is run on windows, run the attrib program + // to set the hidden attribute + if (os.indexOf("windows") != -1) { + // windows + try { + Process proc = Runtime.getRuntime().exec( + "attrib.exe +" + attr + " src/test/data/.hidden.txt", + null, new File(".")); + proc.waitFor(); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + } + + public void testValidate_Existing() { + final Object[] array = new Object[] { "project.xml", + "veryunlikelyfilename" }; + final List list = Arrays.asList(array); + final FileValidator validator = FileValidator.getExistingInstance(); + + assertFalse("is not a directory validator", validator.isDirectory()); + assertFalse("is not a file validator", validator.isFile()); + assertTrue("is an existing file validator", validator.isExisting()); + assertFalse("is not a hidden file validator", validator.isHidden()); + + try { + validator.validate(list); + fail("InvalidArgumentException"); + } catch (InvalidArgumentException e) { + assertEquals("veryunlikelyfilename", e.getMessage()); + } + } + + public void testValidate_File() { + final Object[] array = new Object[] { "project.xml", "src" }; + final List list = Arrays.asList(array); + final Validator validator = FileValidator.getExistingFileInstance(); + + try { + validator.validate(list); + fail("InvalidArgumentException"); + } catch (InvalidArgumentException e) { + assertEquals("src", e.getMessage()); + } + } +} diff --git a/src/test/org/apache/commons/cli2/validation/NumberValidatorTest.java b/src/test/org/apache/commons/cli2/validation/NumberValidatorTest.java index d1595364f..b63957d7c 100644 --- a/src/test/org/apache/commons/cli2/validation/NumberValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/NumberValidatorTest.java @@ -1 +1,168 @@ -/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.text.NumberFormat;import java.util.Arrays;import java.util.Iterator;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * JUnit test case for NumberValidator. * * @author Rob Oxspring * @author John Keyes */public class NumberValidatorTest extends TestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); public void testValidate_Number() throws InvalidArgumentException { final NumberFormat format = NumberFormat.getNumberInstance(); final Object[] array = new Object[] { format.format(1d), format.format(1.07d), format.format(-.45d) }; { final List list = Arrays.asList(array); final Validator validator = NumberValidator.getNumberInstance(); validator.validate(list); final Iterator i = list.iterator(); assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); assertFalse(i.hasNext()); } } public void testValidate_Currency() throws InvalidArgumentException { NumberFormat format = NumberFormat.getCurrencyInstance(); final Object[] array = new Object[] { format.format(1d), format.format(1.07), format.format(-0.45) }; final List list = Arrays.asList(array); final NumberValidator validator = NumberValidator.getCurrencyInstance(); assertEquals("incorrect currency format", format, validator.getFormat()); validator.validate(list); final Iterator i = list.iterator(); assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); assertFalse(i.hasNext()); } public void testValidate_Percent() throws InvalidArgumentException { final NumberFormat format = NumberFormat.getPercentInstance(); final Object[] array = new Object[] { format.format(.01), format.format(1.07), format.format(-.45), format.format(0.001) }; final List list = Arrays.asList(array); final Validator validator = NumberValidator.getPercentInstance(); validator.validate(list); final Iterator i = list.iterator(); assertEquals(0.01d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(0.00001d, ((Number) i.next()).doubleValue(), 0.0001); assertFalse(i.hasNext()); } public void testValidate_Integer() throws InvalidArgumentException { final Object[] array = new Object[] { "1", "107", "-45" }; final List list = Arrays.asList(array); final Validator validator = NumberValidator.getIntegerInstance(); validator.validate(list); final Iterator i = list.iterator(); assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(107d, ((Number) i.next()).doubleValue(), 0.0001); assertEquals(-45d, ((Number) i.next()).doubleValue(), 0.0001); assertFalse(i.hasNext()); } public void testValidate_ExcessChars() { final Object[] array = new Object[] { "10DowningStreet" }; final List list = Arrays.asList(array); final Validator validator = NumberValidator.getIntegerInstance(); try { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("10DowningStreet", e.getMessage()); } } public void testValidate_Maximum() { final Object[] array = new Object[] { "1", "107" }; final List list = Arrays.asList(array); final NumberValidator validator = NumberValidator.getIntegerInstance(); Integer max = new Integer(100); validator.setMaximum(max); assertTrue("no minimum set", validator.getMinimum() == null); assertEquals("incorrect maximum value", max, validator.getMaximum()); try { validator.validate(list); fail("107 too big"); } catch (InvalidArgumentException ive) { assertEquals(resources.getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, "107"), ive.getMessage()); } } public void testValidate_Minimum() { final Object[] array = new Object[] { "107", "1" }; final List list = Arrays.asList(array); final NumberValidator validator = NumberValidator.getIntegerInstance(); Integer min = new Integer(100); validator.setMinimum(min); assertTrue("no maximum set", validator.getMaximum() == null); assertEquals("incorrect minimum value", min, validator.getMinimum()); try { validator.validate(list); fail("1 too small"); } catch (InvalidArgumentException ive) { assertEquals(resources.getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, "1"), ive.getMessage()); } }} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.text.NumberFormat; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +/** + * JUnit test case for NumberValidator. + * + * @author Rob Oxspring + * @author John Keyes + */ +public class NumberValidatorTest + extends TestCase { + private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); + + public void testValidate_Number() + throws InvalidArgumentException { + final NumberFormat format = NumberFormat.getNumberInstance(); + + final Object[] array = + new Object[] { format.format(1d), format.format(1.07d), format.format(-.45d) }; + + { + final List list = Arrays.asList(array); + final Validator validator = NumberValidator.getNumberInstance(); + + validator.validate(list); + + final Iterator i = list.iterator(); + assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); + assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); + assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); + assertFalse(i.hasNext()); + } + } + + public void testValidate_Currency() + throws InvalidArgumentException { + NumberFormat format = NumberFormat.getCurrencyInstance(); + final Object[] array = + new Object[] { format.format(1d), format.format(1.07), format.format(-0.45) }; + final List list = Arrays.asList(array); + + final NumberValidator validator = NumberValidator.getCurrencyInstance(); + assertEquals("incorrect currency format", format, validator.getFormat()); + + validator.validate(list); + + final Iterator i = list.iterator(); + assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); + assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); + assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); + assertFalse(i.hasNext()); + } + + public void testValidate_Percent() + throws InvalidArgumentException { + final NumberFormat format = NumberFormat.getPercentInstance(); + + final Object[] array = + new Object[] { + format.format(.01), format.format(1.07), format.format(-.45), + format.format(0.001) + }; + final List list = Arrays.asList(array); + final Validator validator = NumberValidator.getPercentInstance(); + + validator.validate(list); + + final Iterator i = list.iterator(); + assertEquals(0.01d, ((Number) i.next()).doubleValue(), 0.0001); + assertEquals(1.07d, ((Number) i.next()).doubleValue(), 0.0001); + assertEquals(-.45d, ((Number) i.next()).doubleValue(), 0.0001); + assertEquals(0.00001d, ((Number) i.next()).doubleValue(), 0.0001); + assertFalse(i.hasNext()); + } + + public void testValidate_Integer() + throws InvalidArgumentException { + final Object[] array = new Object[] { "1", "107", "-45" }; + final List list = Arrays.asList(array); + final Validator validator = NumberValidator.getIntegerInstance(); + + validator.validate(list); + + final Iterator i = list.iterator(); + assertEquals(1d, ((Number) i.next()).doubleValue(), 0.0001); + assertEquals(107d, ((Number) i.next()).doubleValue(), 0.0001); + assertEquals(-45d, ((Number) i.next()).doubleValue(), 0.0001); + assertFalse(i.hasNext()); + } + + public void testValidate_ExcessChars() { + final Object[] array = new Object[] { "10DowningStreet" }; + final List list = Arrays.asList(array); + final Validator validator = NumberValidator.getIntegerInstance(); + + try { + validator.validate(list); + fail("InvalidArgumentException"); + } catch (InvalidArgumentException e) { + assertEquals("10DowningStreet", e.getMessage()); + } + } + + public void testValidate_Maximum() { + final Object[] array = new Object[] { "1", "107" }; + final List list = Arrays.asList(array); + final NumberValidator validator = NumberValidator.getIntegerInstance(); + Integer max = new Integer(100); + + validator.setMaximum(max); + + assertTrue("no minimum set", validator.getMinimum() == null); + assertEquals("incorrect maximum value", max, validator.getMaximum()); + + try { + validator.validate(list); + fail("107 too big"); + } catch (InvalidArgumentException ive) { + assertEquals(resources.getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, + "107"), ive.getMessage()); + } + } + + public void testValidate_Minimum() { + final Object[] array = new Object[] { "107", "1" }; + final List list = Arrays.asList(array); + final NumberValidator validator = NumberValidator.getIntegerInstance(); + Integer min = new Integer(100); + validator.setMinimum(min); + + assertTrue("no maximum set", validator.getMaximum() == null); + assertEquals("incorrect minimum value", min, validator.getMinimum()); + + try { + validator.validate(list); + fail("1 too small"); + } catch (InvalidArgumentException ive) { + assertEquals(resources.getMessage(ResourceConstants.NUMBERVALIDATOR_NUMBER_OUTOFRANGE, + "1"), ive.getMessage()); + } + } +} diff --git a/src/test/org/apache/commons/cli2/validation/TimeZoneTestSuite.java b/src/test/org/apache/commons/cli2/validation/TimeZoneTestSuite.java index 8484db2d7..4935f4d77 100644 --- a/src/test/org/apache/commons/cli2/validation/TimeZoneTestSuite.java +++ b/src/test/org/apache/commons/cli2/validation/TimeZoneTestSuite.java @@ -1 +1,46 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.util.TimeZone;import junit.extensions.TestDecorator;import junit.framework.Test;import junit.framework.TestResult;public class TimeZoneTestSuite extends TestDecorator { private final TimeZone timeZone; private final TimeZone originalTimeZone; public TimeZoneTestSuite(String timeZone, Test test) { super(test); this.timeZone = TimeZone.getTimeZone(timeZone); this.originalTimeZone = TimeZone.getDefault(); } public void run(TestResult testResult) { try { TimeZone.setDefault(timeZone); super.run(testResult); } finally { TimeZone.setDefault(originalTimeZone); // cleanup } }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.util.TimeZone; + +import junit.extensions.TestDecorator; + +import junit.framework.Test; +import junit.framework.TestResult; + +public class TimeZoneTestSuite + extends TestDecorator { + private final TimeZone timeZone; + private final TimeZone originalTimeZone; + + public TimeZoneTestSuite(String timeZone, + Test test) { + super(test); + this.timeZone = TimeZone.getTimeZone(timeZone); + this.originalTimeZone = TimeZone.getDefault(); + } + + public void run(TestResult testResult) { + try { + TimeZone.setDefault(timeZone); + super.run(testResult); + } finally { + TimeZone.setDefault(originalTimeZone); // cleanup + } + } +} diff --git a/src/test/org/apache/commons/cli2/validation/UrlValidatorTest.java b/src/test/org/apache/commons/cli2/validation/UrlValidatorTest.java index 69cf875f0..16fa753b6 100644 --- a/src/test/org/apache/commons/cli2/validation/UrlValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/UrlValidatorTest.java @@ -1 +1,93 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation;import java.net.MalformedURLException;import java.net.URL;import java.util.Arrays;import java.util.Iterator;import java.util.List;import junit.framework.TestCase;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;public class UrlValidatorTest extends TestCase { private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); public void testValidate() throws InvalidArgumentException, MalformedURLException { final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; final List list = Arrays.asList(array); final Validator validator = new UrlValidator(); validator.validate(list); final Iterator i = list.iterator(); assertEquals(new URL("http://www.apache.org/"), i.next()); assertEquals(new URL("file:///etc"), i.next()); assertFalse(i.hasNext()); } public void testMalformedURL() throws InvalidArgumentException, MalformedURLException { final Object[] array = new Object[] { "www.apache.org" }; final List list = Arrays.asList(array); final Validator validator = new UrlValidator(); try { validator.validate(list); } catch (InvalidArgumentException e) { assertEquals(resources.getMessage(ResourceConstants.URLVALIDATOR_MALFORMED_URL, new Object[] { "www.apache.org" }), e.getMessage()); } } public void testBadProtocol() { { final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; final List list = Arrays.asList(array); final UrlValidator validator = new UrlValidator(); validator.setProtocol("http"); assertEquals("incorrect protocol", "http", validator.getProtocol()); try { validator.validate(list); fail("Expected InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("file:///etc", e.getMessage()); } } { final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; final List list = Arrays.asList(array); final UrlValidator validator = new UrlValidator("http"); try { validator.validate(list); fail("Expected InvalidArgumentException"); } catch (InvalidArgumentException e) { assertEquals("file:///etc", e.getMessage()); } } }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation; + +import java.net.MalformedURLException; +import java.net.URL; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; + +public class UrlValidatorTest + extends TestCase { + private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); + + public void testValidate() + throws InvalidArgumentException, MalformedURLException { + final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; + final List list = Arrays.asList(array); + final Validator validator = new UrlValidator(); + + validator.validate(list); + + final Iterator i = list.iterator(); + assertEquals(new URL("http://www.apache.org/"), i.next()); + assertEquals(new URL("file:///etc"), i.next()); + assertFalse(i.hasNext()); + } + + public void testMalformedURL() + throws InvalidArgumentException, MalformedURLException { + final Object[] array = new Object[] { "www.apache.org" }; + final List list = Arrays.asList(array); + final Validator validator = new UrlValidator(); + + try { + validator.validate(list); + } catch (InvalidArgumentException e) { + assertEquals(resources.getMessage(ResourceConstants.URLVALIDATOR_MALFORMED_URL, + new Object[] { "www.apache.org" }), e.getMessage()); + } + } + + public void testBadProtocol() { + { + final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; + final List list = Arrays.asList(array); + final UrlValidator validator = new UrlValidator(); + validator.setProtocol("http"); + + assertEquals("incorrect protocol", "http", validator.getProtocol()); + + try { + validator.validate(list); + fail("Expected InvalidArgumentException"); + } catch (InvalidArgumentException e) { + assertEquals("file:///etc", e.getMessage()); + } + } + + { + final Object[] array = new Object[] { "http://www.apache.org/", "file:///etc" }; + final List list = Arrays.asList(array); + final UrlValidator validator = new UrlValidator("http"); + + try { + validator.validate(list); + fail("Expected InvalidArgumentException"); + } catch (InvalidArgumentException e) { + assertEquals("file:///etc", e.getMessage()); + } + } + } +} diff --git a/src/test/org/apache/commons/cli2/validation/protect/ProtectedClass.java b/src/test/org/apache/commons/cli2/validation/protect/ProtectedClass.java index e59ffa458..572670230 100644 --- a/src/test/org/apache/commons/cli2/validation/protect/ProtectedClass.java +++ b/src/test/org/apache/commons/cli2/validation/protect/ProtectedClass.java @@ -1 +1,23 @@ -/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.validation.protect;class ProtectedClass { protected ProtectedClass() { // used to test something??? }} \ No newline at end of file +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.validation.protect; + +class ProtectedClass { + protected ProtectedClass() { + // used to test something??? + } +} From d3a34db8cedf5bc9306abf60b9c8d346145e29d0 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 22 Mar 2008 03:13:05 +0000 Subject: [PATCH 0072/1663] Fixing the trailing whitespace with a proper regex this time git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639944 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli2/Argument.java | 10 +- .../org/apache/commons/cli2/CommandLine.java | 102 +++++++++--------- .../apache/commons/cli2/DisplaySetting.java | 34 +++--- src/java/org/apache/commons/cli2/Group.java | 6 +- .../org/apache/commons/cli2/HelpLine.java | 2 +- src/java/org/apache/commons/cli2/Option.java | 44 ++++---- src/java/org/apache/commons/cli2/Parent.java | 4 +- .../commons/cli2/WriteableCommandLine.java | 16 +-- .../commons/cli2/builder/ArgumentBuilder.java | 40 +++---- .../commandline/DefaultingCommandLine.java | 14 +-- .../commons/cli2/commandline/Parser.java | 2 +- .../commandline/PreferencesCommandLine.java | 22 ++-- .../commandline/PropertiesCommandLine.java | 18 ++-- .../commons/cli2/option/ArgumentImpl.java | 6 +- .../apache/commons/cli2/option/GroupImpl.java | 2 +- .../commons/cli2/option/HelpLineImpl.java | 22 ++-- .../commons/cli2/resource/ResourceHelper.java | 8 +- .../apache/commons/cli2/util/Comparators.java | 54 +++++----- .../commons/cli2/util/HelpFormatter.java | 2 +- .../cli2/validation/FileValidator.java | 56 +++++----- .../commons/cli2/validation/Validator.java | 6 +- .../org/apache/commons/cli2/CLITestCase.java | 8 +- .../commons/cli2/CommandLineDefaultsTest.java | 24 ++--- .../commons/cli2/DocumentationTest.java | 50 ++++----- .../cli2/WriteableCommandLineTestCase.java | 16 +-- .../commons/cli2/application/CpTest.java | 58 +++++----- .../commons/cli2/application/LsTest.java | 86 +++++++-------- .../apache/commons/cli2/bug/Bug27575Test.java | 2 +- .../apache/commons/cli2/bug/Bug28005Test.java | 24 ++--- .../apache/commons/cli2/bug/Bug32533Test.java | 10 +- .../DefaultingCommandLineTest.java | 4 +- .../PreferencesCommandLineTest.java | 22 ++-- .../PropertiesCommandLineTest.java | 12 +-- .../commons/cli2/jdepend/JDependTest.java | 4 +- .../cli2/option/DefaultOptionTest.java | 22 ++-- .../cli2/option/PropertyOptionTest.java | 20 ++-- .../commons/cli2/util/ComparatorsTest.java | 6 +- .../cli2/validation/ClassValidatorTest.java | 6 +- .../cli2/validation/DateValidatorTest.java | 4 +- .../cli2/validation/FileValidatorTest.java | 2 +- 40 files changed, 425 insertions(+), 425 deletions(-) diff --git a/src/java/org/apache/commons/cli2/Argument.java b/src/java/org/apache/commons/cli2/Argument.java index 49187da1e..08b240a65 100644 --- a/src/java/org/apache/commons/cli2/Argument.java +++ b/src/java/org/apache/commons/cli2/Argument.java @@ -27,11 +27,11 @@ public interface Argument extends Option { /** * Returns the initial separator character or * '\0' if no character has been set. - * + * * @return char the initial separator character */ char getInitialSeparator(); - + /** * Processes the "README" style element of the argument. * @@ -50,10 +50,10 @@ void processValues( final ListIterator args, final Option option) throws OptionException; - + /** * Adds defaults to a CommandLine. - * + * * @param commandLine * The CommandLine object to store defaults in. * @param option @@ -86,7 +86,7 @@ void validate(final WriteableCommandLine commandLine, final Option option) * * @see #getMinimum() * @see #getMaximum() - * @return true iff the CommandLine will be invalid without at least one + * @return true iff the CommandLine will be invalid without at least one * value */ boolean isRequired(); diff --git a/src/java/org/apache/commons/cli2/CommandLine.java b/src/java/org/apache/commons/cli2/CommandLine.java index 3c2eeba55..5a18848d9 100644 --- a/src/java/org/apache/commons/cli2/CommandLine.java +++ b/src/java/org/apache/commons/cli2/CommandLine.java @@ -24,191 +24,191 @@ * according to the definition supplied to the parser. */ public interface CommandLine { - + /** - * Detects the presence of an option with the specified trigger in this + * Detects the presence of an option with the specified trigger in this * CommandLine. - * + * * @param trigger the trigger to search for * @return true iff an option with this trigger is present */ boolean hasOption(final String trigger); - + /** * Detects the presence of an option in this CommandLine. - * + * * @param option the Option to search for * @return true iff the option is present */ boolean hasOption(final Option option); - + /** * Finds the Option with the specified trigger - * + * * @param trigger the name of the option to retrieve * @return the Option matching the trigger or null if none exists */ Option getOption(final String trigger); - + /** * Retrieves the Argument values associated with the specified Option - * + * * @param trigger a trigger used to lookup the Option * @return a list of values or an empty List if none are found */ List getValues(final String trigger); - + /** * Retrieves the Argument values associated with the specified Option - * + * * @param trigger a trigger used to lookup the Option * @param defaultValues the result to return if no values are found * @return a list of values or defaultValues if none are found */ List getValues(final String trigger, final List defaultValues); - + /** * Retrieves the Argument values associated with the specified Option - * + * * @param option the Option associated with the values * @return a list of values or an empty List if none are found */ List getValues(final Option option); - + /** * Retrieves the Argument values associated with the specified Option - * + * * @param option the Option associated with the values * @param defaultValues the result to return if no values are found * @return a list of values or defaultValues if none are found */ List getValues(final Option option, final List defaultValues); - + /** * Retrieves the single Argument value associated with the specified Option - * + * * @param trigger a trigger used to lookup the Option * @return the matching value or null if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final String trigger) throws IllegalStateException; - + /** * Retrieves the single Argument value associated with the specified Option - * + * * @param trigger a trigger used to lookup the Option * @param defaultValue the result to use if no values are found * @return the matching value or defaultValue if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final String trigger, final Object defaultValue) throws IllegalStateException; - + /** * Retrieves the single Argument value associated with the specified Option - * + * * @param option the Option associated with the value * @return the matching value or null if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final Option option) throws IllegalStateException; - + /** * Retrieves the single Argument value associated with the specified Option - * + * * @param option the Option associated with the value * @param defaultValue the result to use if no values are found * @return the matching value or defaultValue if none exists * @throws IllegalStateException if more than one values are found */ Object getValue(final Option option, final Object defaultValue) throws IllegalStateException; - + /** * Retrieves the Boolean value associated with the specified Switch - * + * * @param trigger a trigger used to lookup the Option * @return the Boolean associated with trigger or null if none exists */ Boolean getSwitch(final String trigger); - + /** * Retrieves the Boolean value associated with the specified Switch - * + * * @param trigger a trigger used to lookup the Option * @param defaultValue the Boolean to use if none match * @return the Boolean associated with trigger or defaultValue if none exists */ Boolean getSwitch(final String trigger, final Boolean defaultValue); - + /** * Retrieves the Boolean value associated with the specified Switch - * + * * @param option the Option associated with the value * @return the Boolean associated with option or null if none exists */ Boolean getSwitch(final Option option); - + /** * Retrieves the Boolean value associated with the specified Switch - * + * * @param option the Option associated with the value * @param defaultValue the Boolean to use if none match * @return the Boolean associated with option or defaultValue if none exists */ Boolean getSwitch(final Option option, final Boolean defaultValue); - - + + /** - * Retrieves the value associated with the specified property - * + * Retrieves the value associated with the specified property + * * @param property the property name to lookup * @return the value of the property or null */ String getProperty(final String property); - + /** - * Retrieves the value associated with the specified property - * + * Retrieves the value associated with the specified property + * * @param property the property name to lookup * @param defaultValue the value to use if no other is found * @return the value of the property or defaultValue */ String getProperty(final String property, final String defaultValue); - + /** * Retrieves the set of all property names associated with this CommandLine - * - * @return a none null set of property names + * + * @return a none null set of property names */ Set getProperties(); - + /** - * Retrieves the number of times the specified Option appeared in this + * Retrieves the number of times the specified Option appeared in this * CommandLine - * + * * @param trigger a trigger used to lookup the Option * @return the number of occurrences of the option */ int getOptionCount(final String trigger); - + /** - * Retrieves the number of times the specified Option appeared in this + * Retrieves the number of times the specified Option appeared in this * CommandLine - * + * * @param option the Option associated to check * @return the number of occurrences of the option */ int getOptionCount(final Option option); - + /** * Retrieves a list of all Options found in this CommandLine - * + * * @return a none null list of Options */ List getOptions(); - + /** * Retrieves a list of all Option triggers found in this CommandLine - * + * * @return a none null list of Option triggers */ Set getOptionTriggers(); diff --git a/src/java/org/apache/commons/cli2/DisplaySetting.java b/src/java/org/apache/commons/cli2/DisplaySetting.java index fc522067d..a8bd71e54 100644 --- a/src/java/org/apache/commons/cli2/DisplaySetting.java +++ b/src/java/org/apache/commons/cli2/DisplaySetting.java @@ -27,102 +27,102 @@ * will be passed to a method that will lookup the presence of the values. */ public class DisplaySetting { - + private static final Set all = new HashSet(); /** * A Set guarenteed to contain all possible DisplaySetting values */ public static final Set ALL = Collections.unmodifiableSet(all); - + /** * A Set guarenteed to contain no DisplaySetting values */ public static final Set NONE = Collections.EMPTY_SET; - + /** * Indicates that aliases should be included */ public static final DisplaySetting DISPLAY_ALIASES = new DisplaySetting("DISPLAY_ALIASES"); - + /** * Indicates that optionality should be included */ public static final DisplaySetting DISPLAY_OPTIONAL = new DisplaySetting("DISPLAY_OPTIONAL"); - + /** * Indicates that property options should be included */ public static final DisplaySetting DISPLAY_PROPERTY_OPTION = new DisplaySetting("DISPLAY_PROPERTY_OPTION"); - + /** * Indicates that switches should be included enabled */ public static final DisplaySetting DISPLAY_SWITCH_ENABLED = new DisplaySetting("DISPLAY_SWITCH_ENABLED"); - + /** * Indicates that switches should be included disabled */ public static final DisplaySetting DISPLAY_SWITCH_DISABLED = new DisplaySetting("DISPLAY_SWITCH_DISABLED"); - + /** * Indicates that group names should be included */ public static final DisplaySetting DISPLAY_GROUP_NAME = new DisplaySetting("DISPLAY_GROUP_NAME"); - + /** * Indicates that groups should be included expanded */ public static final DisplaySetting DISPLAY_GROUP_EXPANDED = new DisplaySetting("DISPLAY_GROUP_EXPANDED"); - + /** * Indicates that group arguments should be included */ public static final DisplaySetting DISPLAY_GROUP_ARGUMENT = new DisplaySetting("DISPLAY_GROUP_ARGUMENT"); - + /** * Indicates that group outer brackets should be included */ public static final DisplaySetting DISPLAY_GROUP_OUTER = new DisplaySetting("DISPLAY_GROUP_OUTER"); - + /** * Indicates that arguments should be included numbered */ public static final DisplaySetting DISPLAY_ARGUMENT_NUMBERED = new DisplaySetting("DISPLAY_ARGUMENT_NUMBERED"); - + /** * Indicates that arguments should be included bracketed */ public static final DisplaySetting DISPLAY_ARGUMENT_BRACKETED = new DisplaySetting("DISPLAY_ARGUMENT_BRACKETED"); - + /** * Indicates that arguments of Parents should be included */ public static final DisplaySetting DISPLAY_PARENT_ARGUMENT = new DisplaySetting("DISPLAY_PARENT_ARGUMENT"); - + /** * Indicates that children of Parents should be included */ public static final DisplaySetting DISPLAY_PARENT_CHILDREN = new DisplaySetting("DISPLAY_PARENT_CHILDREN"); - + /** * The name of the setting */ private final String name; - + /** * The hashCode of the setting */ diff --git a/src/java/org/apache/commons/cli2/Group.java b/src/java/org/apache/commons/cli2/Group.java index 3a3d4c752..fb93f2512 100644 --- a/src/java/org/apache/commons/cli2/Group.java +++ b/src/java/org/apache/commons/cli2/Group.java @@ -26,11 +26,11 @@ public interface Group extends Option { /** * Appends usage information to the specified StringBuffer - * + * * @param buffer the buffer to append to * @param helpSettings a set of display settings @see DisplaySetting * @param comp a comparator used to sort the Options - * @param separator the String used to separate member Options + * @param separator the String used to separate member Options */ void appendUsage( final StringBuffer buffer, @@ -44,7 +44,7 @@ void appendUsage( * * @see #getMinimum() * @see #getMaximum() - * @return true iff the CommandLine will be invalid without at least one + * @return true iff the CommandLine will be invalid without at least one * member option */ boolean isRequired(); diff --git a/src/java/org/apache/commons/cli2/HelpLine.java b/src/java/org/apache/commons/cli2/HelpLine.java index 2043a4841..e7ef6e0fc 100644 --- a/src/java/org/apache/commons/cli2/HelpLine.java +++ b/src/java/org/apache/commons/cli2/HelpLine.java @@ -42,7 +42,7 @@ public interface HelpLine { /** * Builds a usage string for the option using the specified settings and * comparator. - * + * * @param helpSettings * the settings to apply * @param comparator diff --git a/src/java/org/apache/commons/cli2/Option.java b/src/java/org/apache/commons/cli2/Option.java index d0aaaa6c6..e191c2fec 100644 --- a/src/java/org/apache/commons/cli2/Option.java +++ b/src/java/org/apache/commons/cli2/Option.java @@ -29,12 +29,12 @@ public interface Option { /** * Processes String arguments into a CommandLine. - * + * * The iterator will initially point at the first argument to be processed * and at the end of the method should point to the first argument not * processed. This method MUST process at least one argument from the * ListIterator. - * + * * @param commandLine * The CommandLine object to store results in * @param args @@ -46,13 +46,13 @@ void process( final WriteableCommandLine commandLine, final ListIterator args) throws OptionException; - + /** * Adds defaults to a CommandLine. - * - * Any defaults for this option are applied as well as the defaults for + * + * Any defaults for this option are applied as well as the defaults for * any contained options - * + * * @param commandLine * The CommandLine object to store defaults in */ @@ -61,7 +61,7 @@ void process( /** * Indicates whether this Option will be able to process the particular * argument. - * + * * @param argument * The argument to be tested * @return true if the argument can be processed by this Option @@ -72,7 +72,7 @@ void process( * Indicates whether this Option will be able to process the particular * argument. The ListIterator must be restored to the initial state before * returning the boolean. - * + * * @see #canProcess(WriteableCommandLine,String) * @param arguments * the ListIterator over String arguments @@ -84,9 +84,9 @@ void process( * Identifies the argument prefixes that should trigger this option. This * is used to decide which of many Options should be tried when processing * a given argument string. - * + * * The returned Set must not be null. - * + * * @return The set of triggers for this Option */ Set getTriggers(); @@ -96,9 +96,9 @@ void process( * is used to identify whether a given string looks like an option or an * argument value. Typically an option would return the set [--,-] while * switches might offer [-,+]. - * + * * The returned Set must not be null. - * + * * @return The set of prefixes for this Option */ Set getPrefixes(); @@ -106,7 +106,7 @@ void process( /** * Checks that the supplied CommandLine is valid with respect to this * option. - * + * * @param commandLine * The CommandLine to check. * @throws OptionException @@ -117,7 +117,7 @@ void validate(final WriteableCommandLine commandLine) /** * Builds up a list of HelpLineImpl instances to be presented by HelpFormatter. - * + * * @see HelpLine * @see org.apache.commons.cli2.util.HelpFormatter * @param depth @@ -135,7 +135,7 @@ List helpLines( /** * Appends usage information to the specified StringBuffer - * + * * @param buffer the buffer to append to * @param helpSettings a set of display settings @see DisplaySetting * @param comp a comparator used to sort the Options @@ -148,7 +148,7 @@ void appendUsage( /** * The preferred name of an option is used for generating help and usage * information. - * + * * @return The preferred name of the option */ String getPreferredName(); @@ -156,16 +156,16 @@ void appendUsage( /** * Returns a description of the option. This string is used to build help * messages as in the HelpFormatter. - * + * * @see org.apache.commons.cli2.util.HelpFormatter * @return a description of the option. */ String getDescription(); /** - * Returns the id of the option. This can be used in a loop and switch + * Returns the id of the option. This can be used in a loop and switch * construct: - * + * * * for(Option o : cmd.getOptions()){ * switch(o.getId()){ @@ -173,10 +173,10 @@ void appendUsage( * ... * } * } - * - * + * + * * The returned value is not guarenteed to be unique. - * + * * @return the id of the option. */ int getId(); diff --git a/src/java/org/apache/commons/cli2/Parent.java b/src/java/org/apache/commons/cli2/Parent.java index eafad2dc2..d0da6977c 100644 --- a/src/java/org/apache/commons/cli2/Parent.java +++ b/src/java/org/apache/commons/cli2/Parent.java @@ -19,7 +19,7 @@ import java.util.ListIterator; /** - * An Option that can have an argument and/or group of child Options in the form + * An Option that can have an argument and/or group of child Options in the form * "-f <arg> [-a|-b|-c]". */ public interface Parent extends Option { @@ -28,7 +28,7 @@ public interface Parent extends Option { * Processes the parent part of the Option. The combination of parent, * argument and children is handled by the process method. * @see Option#process(WriteableCommandLine, ListIterator) - * + * * @param commandLine the CommandLine to write results to * @param args a ListIterator over argument strings positioned at the next * argument to process diff --git a/src/java/org/apache/commons/cli2/WriteableCommandLine.java b/src/java/org/apache/commons/cli2/WriteableCommandLine.java index dae2a39b5..a8f756d88 100644 --- a/src/java/org/apache/commons/cli2/WriteableCommandLine.java +++ b/src/java/org/apache/commons/cli2/WriteableCommandLine.java @@ -22,13 +22,13 @@ * A CommandLine that detected values and options can be written to. */ public interface WriteableCommandLine extends CommandLine { - + /** * Adds an Option to the CommandLine * @param option the Option to add */ void addOption(final Option option); - + /** * Adds a value to an Option in the CommandLine. * @param option the Option to add to @@ -42,7 +42,7 @@ public interface WriteableCommandLine extends CommandLine { * @param defaultValues the defaults for the option */ void setDefaultValues(final Option option, final List defaultValues); - + /** * Adds a switch value to an Option in the CommandLine. * @param option the Option to add to @@ -50,25 +50,25 @@ public interface WriteableCommandLine extends CommandLine { * @throws IllegalStateException if the switch has already been added */ void addSwitch(final Option option, final boolean value) throws IllegalStateException; - + /** * Sets the default state for a Switch in the CommandLine. * @param option the Option to add to * @param defaultSwitch the defaults state for ths switch */ void setDefaultSwitch(final Option option, final Boolean defaultSwitch); - + /** * Adds a property value to a name in the CommandLine. * Replaces any existing value for the property. - * + * * @param property the name of the property * @param value the value of the property */ void addProperty(final String property, final String value); - + /** - * Detects whether the argument looks like an Option trigger + * Detects whether the argument looks like an Option trigger * @param argument the argument to test * @return true if the argument looks like an Option trigger */ diff --git a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java b/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java index 6c115d170..f0fd8cf2a 100644 --- a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java @@ -32,7 +32,7 @@ public class ArgumentBuilder { /** i18n */ private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); - + /** name of the argument. Used for display and lookups in CommandLine */ private String name; @@ -73,7 +73,7 @@ public ArgumentBuilder() { /** * Creates a new Argument instance using the options specified in this * ArgumentBuilder. - * + * * @return A new Argument instance using the options specified in this * ArgumentBuilder. */ @@ -117,9 +117,9 @@ public final ArgumentBuilder reset() { /** * Sets the name of the argument. The name is used when displaying usage * information and to allow lookups in the CommandLine object. - * + * * @see org.apache.commons.cli2.CommandLine#getValue(String) - * + * * @param newName the name of the argument * @return this ArgumentBuilder */ @@ -136,9 +136,9 @@ public final ArgumentBuilder withName(final String newName) { /** * Sets the description of the argument. - * + * * The description is used when displaying online help. - * + * * @param newDescription a description of the argument * @return this ArgumentBuilder */ @@ -149,7 +149,7 @@ public final ArgumentBuilder withDescription(final String newDescription) { /** * Sets the minimum number of values needed for the argument to be valid. - * + * * @param newMinimum the number of values needed * @return this ArgumentBuilder */ @@ -163,7 +163,7 @@ public final ArgumentBuilder withMinimum(final int newMinimum) { /** * Sets the maximum number of values allowed for the argument to be valid. - * + * * @param newMaximum the number of values allowed * @return this ArgumentBuilder */ @@ -179,8 +179,8 @@ public final ArgumentBuilder withMaximum(final int newMaximum) { * Sets the character used to separate the values from the option. When an * argument is of the form -libs:dir1,dir2,dir3 the initialSeparator would * be ':'. - * - * @param newInitialSeparator the character used to separate the values + * + * @param newInitialSeparator the character used to separate the values * from the option * @return this ArgumentBuilder */ @@ -195,8 +195,8 @@ public final ArgumentBuilder withInitialSeparator( * Sets the character used to separate the values from each other. When an * argument is of the form -libs:dir1,dir2,dir3 the subsequentSeparator * would be ','. - * - * @param newSubsequentSeparator the character used to separate the values + * + * @param newSubsequentSeparator the character used to separate the values * from each other * @return this ArgumentBuilder */ @@ -210,7 +210,7 @@ public final ArgumentBuilder withSubsequentSeparator( /** * Sets the validator instance used to perform validation on the Argument * values. - * + * * @param newValidator a Validator instance * @return this ArgumentBuilder */ @@ -225,15 +225,15 @@ public final ArgumentBuilder withValidator(final Validator newValidator) { /** * Sets the "consume remaining" option, defaults to "--". Use this if you * want to allow values that might be confused with option strings. - * - * @param newConsumeRemaining the string to use for the consume + * + * @param newConsumeRemaining the string to use for the consume * remaining option * @return this ArgumentBuilder */ public final ArgumentBuilder withConsumeRemaining(final String newConsumeRemaining) { if (newConsumeRemaining == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING)); - } + } if ( "".equals(newConsumeRemaining)) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING)); } @@ -243,7 +243,7 @@ public final ArgumentBuilder withConsumeRemaining(final String newConsumeRemaini /** * Sets the default value. - * + * * @param defaultValue the default value for the Argument * @return this ArgumentBuilder */ @@ -251,7 +251,7 @@ public final ArgumentBuilder withDefault(final Object defaultValue) { if (defaultValue == null) { throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT)); } - + if (this.defaultValues == null) { this.defaultValues = new ArrayList(1); } @@ -261,7 +261,7 @@ public final ArgumentBuilder withDefault(final Object defaultValue) { /** * Sets the default values. - * + * * @param newDefaultValues the default values for the Argument * @return this ArgumentBuilder */ @@ -275,7 +275,7 @@ public final ArgumentBuilder withDefaults(final List newDefaultValues) { /** * Sets the id - * + * * @param newId the id of the Argument * @return this ArgumentBuilder */ diff --git a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java b/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java index cb85e1fa7..3ca3e686c 100644 --- a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java @@ -30,10 +30,10 @@ * Manages a queue of default CommandLines. This CommandLine implementation is * backed by a queue of CommandLine instances which are queried in turn until a * suitable result is found. - * + * * CommandLine instances can either be added to the back of the queue or can be * pushed in at a specific position. - * + * * @see #appendCommandLine(CommandLine) * @see #insertCommandLine(int, CommandLine) */ @@ -48,17 +48,17 @@ public class DefaultingCommandLine extends CommandLineImpl { * Adds a CommandLine instance to the back of the queue. The supplied * CommandLine will be used as defaults when all other CommandLines produce * no result - * + * * @param commandLine * the default values to use if all CommandLines */ public void appendCommandLine(final CommandLine commandLine) { commandLines.add(commandLine); } - + /** * Adds a CommandLine instance to a specified position in the queue. - * + * * @param index ths position at which to insert * @param commandLine the CommandLine to insert */ @@ -67,10 +67,10 @@ public void insertCommandLine( final CommandLine commandLine) { commandLines.add(index, commandLine); } - + /** * Builds an iterator over the build in CommandLines. - * + * * @return an unmodifiable iterator */ public Iterator commandLines(){ diff --git a/src/java/org/apache/commons/cli2/commandline/Parser.java b/src/java/org/apache/commons/cli2/commandline/Parser.java index 4dd3f9670..07ecdbabe 100644 --- a/src/java/org/apache/commons/cli2/commandline/Parser.java +++ b/src/java/org/apache/commons/cli2/commandline/Parser.java @@ -61,7 +61,7 @@ public CommandLine parse(final String[] arguments) for (int i = 0; i < arguments.length; i++) { final String argument = arguments[i]; - // ensure non intern'd strings are used + // ensure non intern'd strings are used // so that == comparisons work as expected argumentList.add(new String(argument)); } diff --git a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java b/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java index 5b74f5a09..14e2c9c7d 100644 --- a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java @@ -44,30 +44,30 @@ * * @see java.util.prefs.Preferences * @see org.apache.commons.cli2.commandline.DefaultingCommandLine - * @see org.apache.commons.cli2.Option#getPreferredName() + * @see org.apache.commons.cli2.Option#getPreferredName() */ public class PreferencesCommandLine extends CommandLineImpl { - + private static final char NUL = '\0'; private final Preferences preferences; private final Option root; private final char separator; - + /** * Creates a new PreferencesCommandLine using the specified root Option and * Preferences node. Argument values will be separated using the char 0. - * + * * @param root the CommandLine's root Option * @param preferences the Preferences node to get values from */ public PreferencesCommandLine(final Option root, final Preferences preferences){ this(root,preferences,NUL); } - + /** * Creates a new PreferencesCommandLine using the specified root Option, * Preferences node and value separator. - * + * * @param root the CommandLine's root Option * @param preferences the Preferences node to get values from * @param separator the character to split argument values @@ -77,7 +77,7 @@ public PreferencesCommandLine(final Option root, final Preferences preferences, this.preferences = preferences; this.separator = separator; } - + public boolean hasOption(Option option) { if(option==null){ return false; @@ -97,18 +97,18 @@ public Option getOption(String trigger) { public List getValues(final Option option, final List defaultValues) { final String value = preferences.get(option.getPreferredName(),null); - + if(value==null){ return defaultValues; } else if(separator>NUL){ final List values = new ArrayList(); final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); - + while(tokens.hasMoreTokens()){ values.add(tokens.nextToken()); } - + return values; } else{ @@ -128,7 +128,7 @@ else if("false".equals(value)){ return defaultValue; } } - + public String getProperty(final String property, final String defaultValue) { return preferences.get(property, defaultValue); } diff --git a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java b/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java index 6e04b6728..28cf79279 100644 --- a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java @@ -40,15 +40,15 @@ * * @see java.util.Properties * @see org.apache.commons.cli2.commandline.DefaultingCommandLine - * @see org.apache.commons.cli2.Option#getPreferredName() + * @see org.apache.commons.cli2.Option#getPreferredName() */ public class PropertiesCommandLine extends CommandLineImpl { - + private static final char NUL = '\0'; private final Properties properties; private final Option root; private final char separator; - + /** * Creates a new PropertiesCommandLine using the specified root Option, * Properties instance. The character 0 is used as the value separator. @@ -59,7 +59,7 @@ public class PropertiesCommandLine extends CommandLineImpl { public PropertiesCommandLine(final Option root, final Properties properties){ this(root,properties,NUL); } - + /** * Creates a new PropertiesCommandLine using the specified root Option, * Properties instance and value separator. @@ -73,7 +73,7 @@ public PropertiesCommandLine(final Option root, final Properties properties, fin this.properties = properties; this.separator = separator; } - + public boolean hasOption(Option option) { if(option==null){ @@ -90,18 +90,18 @@ public Option getOption(String trigger) { public List getValues(final Option option, final List defaultValues) { final String value = properties.getProperty(option.getPreferredName()); - + if(value==null){ return defaultValues; } else if(separator>NUL){ final List values = new ArrayList(); final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); - + while(tokens.hasMoreTokens()){ values.add(tokens.nextToken()); } - + return values; } else{ @@ -121,7 +121,7 @@ else if("false".equals(value)){ return defaultValue; } } - + public String getProperty(final String property, final String defaultValue) { return properties.getProperty(property,defaultValue); } diff --git a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java index 066a8ce82..c3fc05cac 100644 --- a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java @@ -217,15 +217,15 @@ public Set getTriggers() { public String getConsumeRemaining() { return this.consumeRemaining; } - + public List getDefaultValues() { return this.defaultValues; } - + public Validator getValidator() { return this.validator; } - + public void validate(final WriteableCommandLine commandLine) throws OptionException { validate(commandLine, this); diff --git a/src/java/org/apache/commons/cli2/option/GroupImpl.java b/src/java/org/apache/commons/cli2/option/GroupImpl.java index e6a84dd51..2a042fa17 100644 --- a/src/java/org/apache/commons/cli2/option/GroupImpl.java +++ b/src/java/org/apache/commons/cli2/option/GroupImpl.java @@ -73,7 +73,7 @@ public GroupImpl(final List options, this.minimum = minimum; this.maximum = maximum; - // store a copy of the options to be used by the + // store a copy of the options to be used by the // help methods this.options = Collections.unmodifiableList(options); diff --git a/src/java/org/apache/commons/cli2/option/HelpLineImpl.java b/src/java/org/apache/commons/cli2/option/HelpLineImpl.java index da938c89e..42b334a5a 100644 --- a/src/java/org/apache/commons/cli2/option/HelpLineImpl.java +++ b/src/java/org/apache/commons/cli2/option/HelpLineImpl.java @@ -35,17 +35,17 @@ public class HelpLineImpl implements HelpLine { /** The help settings used to obtain the previous usage */ private transient Set cachedHelpSettings; - + /** The comparator used to obtain the previous usage */ private transient Comparator cachedComparator; - + /** The previously obtained usage */ private transient String cachedUsage; - + /** * Creates a new HelpLineImpl to represent a particular Option in the online * help. - * + * * @param option * Option that the HelpLineImpl describes * @param indent @@ -76,12 +76,12 @@ public int getIndent() { public Option getOption() { return option; } - + /** - * Builds a usage string for the option using the specified settings and + * Builds a usage string for the option using the specified settings and * comparator. - * - * + * + * * @param helpSettings the settings to apply * @param comparator a comparator to sort options when applicable * @return the usage string @@ -90,18 +90,18 @@ public String usage(final Set helpSettings, final Comparator comparator) { if (cachedUsage == null || cachedHelpSettings != helpSettings || cachedComparator != comparator) { - + // cache the arguments to avoid redoing work cachedHelpSettings = helpSettings; cachedComparator = comparator; - + // build the new buffer final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < indent; ++i) { buffer.append(" "); } option.appendUsage(buffer, helpSettings, comparator); - + // cache the usage string cachedUsage = buffer.toString(); } diff --git a/src/java/org/apache/commons/cli2/resource/ResourceHelper.java b/src/java/org/apache/commons/cli2/resource/ResourceHelper.java index eab71f9e1..804958e70 100644 --- a/src/java/org/apache/commons/cli2/resource/ResourceHelper.java +++ b/src/java/org/apache/commons/cli2/resource/ResourceHelper.java @@ -40,7 +40,7 @@ public class ResourceHelper { private ResourceBundle bundle; private String prop; - + /** * Create a new ResourceHelper for the current locale. */ @@ -52,12 +52,12 @@ private ResourceHelper() { } this.prop = bundleName; - + int firstUnderscore = bundleName.indexOf('_'); int secondUnderscore = bundleName.indexOf('_', firstUnderscore + 1); Locale locale; - if (firstUnderscore != -1) { + if (firstUnderscore != -1) { String language = bundleName.substring(firstUnderscore + 1, secondUnderscore); String country = bundleName.substring(secondUnderscore + 1); locale = new Locale(language, country); @@ -76,7 +76,7 @@ private ResourceHelper() { public String getBundleName() { return this.prop; } - + /** * Gets the ResourceHelper appropriate to the current locale. * @return a ResourceHelper diff --git a/src/java/org/apache/commons/cli2/util/Comparators.java b/src/java/org/apache/commons/cli2/util/Comparators.java index 3cc137e31..3943d8873 100644 --- a/src/java/org/apache/commons/cli2/util/Comparators.java +++ b/src/java/org/apache/commons/cli2/util/Comparators.java @@ -29,15 +29,15 @@ * A collection of Comparators suitable for use with Option instances. */ public class Comparators { - + private Comparators(){ // constructor hiden from potential users } - + /** * Chains comparators together. - * + * * @see #chain(Comparator[]) * @param c0 * a comparator @@ -51,7 +51,7 @@ public static Comparator chain(final Comparator c0, final Comparator c1) { /** * Chains comparators together. - * + * * @see #chain(Comparator[]) * @param c0 * a comparator @@ -70,7 +70,7 @@ public static Comparator chain( /** * Chains comparators together. - * + * * @see #chain(Comparator[]) * @param c0 * a comparator @@ -92,7 +92,7 @@ public static Comparator chain( /** * Chains comparators together. - * + * * @see #chain(Comparator[]) * @param c0 * a comparator @@ -117,7 +117,7 @@ public static Comparator chain( /** * Chains comparators together. - * + * * @see #chain(Comparator[]) * @param comparators * a List of comparators to chain together @@ -133,7 +133,7 @@ public static Comparator chain(final List comparators) { * Chains an array of comparators together. Each Comparator will be called * in turn until one of them return a non-zero value, this value will be * returned. - * + * * @param comparators * the array of comparators * @return a chained comparator @@ -169,7 +169,7 @@ public int compare(final Object left, final Object right) { /** * Reverses a comparator's logic. - * + * * @param wrapped * the Comparator to reverse the logic of * @return a comparator with reverse logic @@ -196,7 +196,7 @@ public int compare(final Object left, final Object right) { /** * Forces Group instances to appear at the beginning of lists - * + * * @see Group * @return a new comparator */ @@ -206,7 +206,7 @@ public static Comparator groupFirst() { /** * Forces Group instances to appear at the end of lists - * + * * @see Group * @return a new comparator */ @@ -231,7 +231,7 @@ public int compare(final Object left, final Object right) { /** * Forces Switch instances to appear at the beginning of lists - * + * * @see Switch * @return a new comparator */ @@ -241,7 +241,7 @@ public static Comparator switchFirst() { /** * Forces Switch instances to appear at the end of lists - * + * * @see Switch * @return a new comparator */ @@ -266,7 +266,7 @@ public int compare(final Object left, final Object right) { /** * Forces Command instances to appear at the beginning of lists - * + * * @see Command * @return a new comparator */ @@ -276,7 +276,7 @@ public static Comparator commandFirst() { /** * Forces Command instances to appear at the end of lists - * + * * @see Command * @return a new comparator */ @@ -301,7 +301,7 @@ public int compare(final Object left, final Object right) { /** * Forces DefaultOption instances to appear at the beginning of lists - * + * * @see DefaultOption * @return a new comparator */ @@ -311,7 +311,7 @@ public static Comparator defaultOptionFirst() { /** * Forces DefaultOption instances to appear at the end of lists - * + * * @see DefaultOption * @return a new comparator */ @@ -337,7 +337,7 @@ public int compare(final Object left, final Object right) { /** * Forces Comparators with a particular trigger to appear at the beginning * of lists - * + * * @param name * the trigger name to select * @see Option#getTriggers() @@ -350,7 +350,7 @@ public static Comparator namedFirst(final String name) { /** * Forces Comparators with a particular trigger to appear at the end of * lists - * + * * @param name * the trigger name to select * @see Option#getTriggers() @@ -362,7 +362,7 @@ public static Comparator namedLast(final String name) { private static class Named implements Comparator { private final String name; - + /** * Creates a Comparator that sorts a particular name high in order * @param name the trigger name to select @@ -389,7 +389,7 @@ public int compare(final Object oleft, final Object oright) { /** * Orders Options by preferredName - * + * * @see Option#getPreferredName() * @return a new comparator */ @@ -399,7 +399,7 @@ public static Comparator preferredNameFirst() { /** * Orders Options by preferredName, reversed - * + * * @see Option#getPreferredName() * @return a new comparator */ @@ -418,29 +418,29 @@ public int compare(final Object oleft, final Object oright) { /** * Orders Options grouping required Options first - * + * * @see Option#isRequired() * @return a new comparator */ public static Comparator requiredFirst() { return new Required(); } - + /** * Orders Options grouping required Options last - * + * * @see Option#isRequired() * @return a new comparator */ public static Comparator requiredLast() { return reverse(requiredFirst()); } - + private static class Required implements Comparator { public int compare(final Object oleft, final Object oright) { final Option left = (Option)oleft; final Option right = (Option)oright; - + final boolean l = left.isRequired(); final boolean r = right.isRequired(); diff --git a/src/java/org/apache/commons/cli2/util/HelpFormatter.java b/src/java/org/apache/commons/cli2/util/HelpFormatter.java index 8f6684f0a..ff24e8c73 100644 --- a/src/java/org/apache/commons/cli2/util/HelpFormatter.java +++ b/src/java/org/apache/commons/cli2/util/HelpFormatter.java @@ -384,7 +384,7 @@ protected static List wrap(final String text, continue; } - // move to the next ideal wrap point + // move to the next ideal wrap point right = (left + width) - 1; // if we have run out of characters diff --git a/src/java/org/apache/commons/cli2/validation/FileValidator.java b/src/java/org/apache/commons/cli2/validation/FileValidator.java index aff1bc5f1..3b1e1319a 100644 --- a/src/java/org/apache/commons/cli2/validation/FileValidator.java +++ b/src/java/org/apache/commons/cli2/validation/FileValidator.java @@ -26,7 +26,7 @@ * the {@link java.util.List} of values is replaced with the * {@link java.io.File} instance. * - * The following attributes can also be specified using the + * The following attributes can also be specified using the * appropriate settors: *
        *
      • writable
      • @@ -47,12 +47,12 @@ * FileValidator validator = FileValidator.getExistingFileInstance(); * validator.setReadable(true); * validator.setWritable(true); - * - * Argument age = + * + * Argument age = * builder.withName("config"); * .withValidator(validator); * - * + * * @author Rob Oxspring * @author John Keyes */ @@ -95,16 +95,16 @@ public static FileValidator getExistingDirectoryInstance() { /** whether the argument value is readable */ private boolean readable = false; - + /** whether the argument value is writable */ private boolean writable = false; - + /** whether the argument value exists */ private boolean existing = false; - + /** whether the argument value is a directory */ private boolean directory = false; - + /** whether the argument value is a file */ private boolean file = false; @@ -115,7 +115,7 @@ public static FileValidator getExistingDirectoryInstance() { * Validate the list of values against the list of permitted values. * If a value is valid, replace the string in the values * {@link java.util.List} with the {@link java.io.File} instance. - * + * * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List) */ public void validate(final List values) throws InvalidArgumentException { @@ -132,7 +132,7 @@ public void validate(final List values) throws InvalidArgumentException { throw new InvalidArgumentException(name); } - + i.set(f); } } @@ -149,7 +149,7 @@ public boolean isDirectory() { /** * Specifies whether the argument values must represent directories. * - * @param directory specifies whether the argument values must + * @param directory specifies whether the argument values must * represent directories. */ public void setDirectory(boolean directory) { @@ -157,10 +157,10 @@ public void setDirectory(boolean directory) { } /** - * Returns whether the argument values must represent existing + * Returns whether the argument values must represent existing * files/directories. * - * @return whether the argument values must represent existing + * @return whether the argument values must represent existing * files/directories. */ public boolean isExisting() { @@ -168,10 +168,10 @@ public boolean isExisting() { } /** - * Specifies whether the argument values must represent existing + * Specifies whether the argument values must represent existing * files/directories. * - * @param existing specifies whether the argument values must + * @param existing specifies whether the argument values must * represent existing files/directories. */ public void setExisting(boolean existing) { @@ -190,7 +190,7 @@ public boolean isFile() { /** * Specifies whether the argument values must represent files. * - * @param file specifies whether the argument values must + * @param file specifies whether the argument values must * represent files. */ public void setFile(boolean file) { @@ -198,10 +198,10 @@ public void setFile(boolean file) { } /** - * Returns whether the argument values must represent hidden + * Returns whether the argument values must represent hidden * files/directories. * - * @return whether the argument values must represent hidden + * @return whether the argument values must represent hidden * files/directories. */ public boolean isHidden() { @@ -209,10 +209,10 @@ public boolean isHidden() { } /** - * Specifies whether the argument values must represent hidden + * Specifies whether the argument values must represent hidden * files/directories. * - * @param hidden specifies whether the argument values must + * @param hidden specifies whether the argument values must * represent hidden files/directories. */ public void setHidden(boolean hidden) { @@ -220,10 +220,10 @@ public void setHidden(boolean hidden) { } /** - * Returns whether the argument values must represent readable + * Returns whether the argument values must represent readable * files/directories. * - * @return whether the argument values must represent readable + * @return whether the argument values must represent readable * files/directories. */ public boolean isReadable() { @@ -231,10 +231,10 @@ public boolean isReadable() { } /** - * Specifies whether the argument values must represent readable + * Specifies whether the argument values must represent readable * files/directories. * - * @param readable specifies whether the argument values must + * @param readable specifies whether the argument values must * represent readable files/directories. */ public void setReadable(boolean readable) { @@ -242,10 +242,10 @@ public void setReadable(boolean readable) { } /** - * Returns whether the argument values must represent writable + * Returns whether the argument values must represent writable * files/directories. * - * @return whether the argument values must represent writable + * @return whether the argument values must represent writable * files/directories. */ public boolean isWritable() { @@ -253,10 +253,10 @@ public boolean isWritable() { } /** - * Specifies whether the argument values must represent writable + * Specifies whether the argument values must represent writable * files/directories. * - * @param writable specifies whether the argument values must + * @param writable specifies whether the argument values must * represent writable files/directories. */ public void setWritable(boolean writable) { diff --git a/src/java/org/apache/commons/cli2/validation/Validator.java b/src/java/org/apache/commons/cli2/validation/Validator.java index 2147dfd28..1e21d4df6 100644 --- a/src/java/org/apache/commons/cli2/validation/Validator.java +++ b/src/java/org/apache/commons/cli2/validation/Validator.java @@ -32,10 +32,10 @@ public interface Validator { /** * Validate the specified values (List of Strings). - * + * * @param values The values to validate. - * - * @throws InvalidArgumentException If any of the + * + * @throws InvalidArgumentException If any of the * specified values are not valid. */ void validate(final List values) throws InvalidArgumentException; diff --git a/src/test/org/apache/commons/cli2/CLITestCase.java b/src/test/org/apache/commons/cli2/CLITestCase.java index e2baf6913..b333d3a41 100644 --- a/src/test/org/apache/commons/cli2/CLITestCase.java +++ b/src/test/org/apache/commons/cli2/CLITestCase.java @@ -60,18 +60,18 @@ public static List list(final Object arg0, final Object arg1, final Object arg2, } public static void assertListContentsEqual(final List expected, final List found) { - + final Iterator e = expected.iterator(); final Iterator f = found.iterator(); - + while (e.hasNext() && f.hasNext()) { assertEquals(e.next(), f.next()); } - + if (e.hasNext()) { fail("Expected more elements"); } - + if (f.hasNext()) { fail("Found more elements"); } diff --git a/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java b/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java index c4f1227cf..2f87282e8 100644 --- a/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java +++ b/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java @@ -28,21 +28,21 @@ /** * Tests the interaction of command line values and defaults supplied in different ways. - * + * * Tests marked _Parsed involve values parsed from a command line. - * + * * Tests marked _Method involve defaults supplied in the query method. - * + * * Tests marked _Option involce defaults specified in the model. - * + * * @author Rob Oxspring */ public class CommandLineDefaultsTest extends TestCase { - + /* - * utils to grab the default from the method + * utils to grab the default from the method */ - + private Object methodSwitch(WriteableCommandLine cl, Option o, Boolean bool) { return cl.getSwitch(o, bool); } @@ -68,9 +68,9 @@ private Object methodValuePresent(WriteableCommandLine cl, Option o) { } /* - * utils to grab the default from the option model + * utils to grab the default from the option model */ - + private Option optionSwitch(Boolean bool) { return new SwitchBuilder().withName("switch").withSwitchDefault(bool) .create(); @@ -98,9 +98,9 @@ private Option optionValuePresent() { } /* - * utils to grab the input from the command line + * utils to grab the input from the command line */ - + private WriteableCommandLine parsedSwitch(Option o, Boolean bool) { final List args; if (bool == null) { @@ -139,7 +139,7 @@ private WriteableCommandLine parsedValuePresent(Option o) { cl.addValue(o, "parsed"); return cl; } - + /* * tests */ diff --git a/src/test/org/apache/commons/cli2/DocumentationTest.java b/src/test/org/apache/commons/cli2/DocumentationTest.java index 4b8fe13a1..74bb9d2c2 100644 --- a/src/test/org/apache/commons/cli2/DocumentationTest.java +++ b/src/test/org/apache/commons/cli2/DocumentationTest.java @@ -47,7 +47,7 @@ public void testBasicUsage() throws IOException, OptionException { /* * --version -? -h --help -log file -s|-q|-v|-d Bursting File/Num/Date * validation Switches Commands Auto help Auto exception help - * + * */ DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); Option version = @@ -149,41 +149,41 @@ public void testBasicUsage() throws IOException, OptionException { uoe.getMessage()); } } - + public void testManualIntroduction() { - + DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); ArgumentBuilder aBuilder = new ArgumentBuilder(); GroupBuilder gBuilder = new GroupBuilder(); - - DefaultOption xmlOption = + + DefaultOption xmlOption = oBuilder .withLongName("xml") .withDescription("Output using xml format") .create(); - - Argument pathArgument = + + Argument pathArgument = aBuilder .withName("path") .withMinimum(1) .withMaximum(1) .create(); - - Group outputChildren = + + Group outputChildren = gBuilder .withOption(xmlOption) .create(); - - Option outputOption = + + Option outputOption = oBuilder .withLongName("output") .withDescription("Outputs to a file") .withArgument(pathArgument) .withChildren(outputChildren) .create(); - + /////////////////////////////////////////////////// - + Group options = outputChildren; HelpFormatter hf = new HelpFormatter(); @@ -195,11 +195,11 @@ public void testManualIntroduction() { if(cl==null) { System.exit(-1); } - + ////////////////////////////////////////////////// - + cl = new WriteableCommandLineImpl(outputChildren,new ArrayList()); - + // if we have --output option if(cl.hasOption("--output")) { // grab the path @@ -209,15 +209,15 @@ public void testManualIntroduction() { // configure the application's output configureOutput(path,xml); } - - - - + + + + } private void configureOutput(String path, boolean xml) { // TODO Auto-generated method stub - + } public void testExampleAnt() throws IOException, OptionException { @@ -396,14 +396,14 @@ public void testExampleAnt() throws IOException, OptionException { .withOption(find) .withOption(targets) .create(); - + ///////////////////////////////////// String[] args = new String[]{}; - + Parser parser = new Parser(); parser.setGroup(options); CommandLine cl = parser.parse(args); - + if(cl.hasOption(help)) { //displayHelp(); return; @@ -421,7 +421,7 @@ public void testExampleAnt() throws IOException, OptionException { String target = (String) i.next(); //doTarget(target); } - + ///////////////////////////////////// HelpFormatter hf = new HelpFormatter(); diff --git a/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java b/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java index eac59b110..df6b4e3ea 100644 --- a/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java +++ b/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java @@ -22,11 +22,11 @@ * @author Rob Oxspring */ public abstract class WriteableCommandLineTestCase extends CommandLineTestCase { - + private WriteableCommandLine writeable; - + protected abstract WriteableCommandLine createWriteableCommandLine(); - + /* (non-Javadoc) * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() */ @@ -42,7 +42,7 @@ protected final CommandLine createCommandLine() { cl.addValue(multiple,"value 3"); return cl; } - + /* * @see CommandLineTest#setUp() */ @@ -60,17 +60,17 @@ public final void testAddValue() { assertTrue(writeable.getValues(present).isEmpty()); writeable.addValue(present,"value"); assertContentsEqual(list("value"),writeable.getValues(present)); - + // most options shouldn't appear due to adding values assertFalse(writeable.hasOption(present)); - + final Argument arg = ArgumentTest.buildHostArgument(); - + assertFalse(writeable.hasOption(arg)); assertTrue(writeable.getValues(arg).isEmpty()); writeable.addValue(arg,"value"); assertContentsEqual(list("value"),writeable.getValues(arg)); - + // Arguments should force the option present assertTrue(writeable.hasOption(arg)); } diff --git a/src/test/org/apache/commons/cli2/application/CpTest.java b/src/test/org/apache/commons/cli2/application/CpTest.java index bdcc9a5ba..1d7964398 100644 --- a/src/test/org/apache/commons/cli2/application/CpTest.java +++ b/src/test/org/apache/commons/cli2/application/CpTest.java @@ -42,68 +42,68 @@ /** *

        Test the cp command. Duplicated Option types are not * tested e.g. -a and -d are the same Option type.

        - * + * *

        The following is the man output for 'cp'. See * http://www.rt.com/man/cp.1.html.

        - * + * *
          *  CP(1) FSF CP(1)
        - * 
        + *
          *  NAME cp - copy files and directories
        - * 
        + *
          *  SYNOPSIS cp [OPTION]... SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY
        - * 
        + *
          *  DESCRIPTION Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.
        - * 
        + *
          *  -a, --archive same as -dpR
        - * 
        + *
          *  -b, --backup make backup before removal
        - * 
        + *
          *  -d, --no-dereference preserve links
        - * 
        + *
          *  -f, --force remove existing destinations, never prompt
        - * 
        + *
          *  -i, --interactive prompt before overwrite
        - * 
        + *
          *  -l, --link link files instead of copying
        - * 
        + *
          *  -p, --preserve preserve file attributes if possible
        - * 
        + *
          *  -P, --parents append source path to DIRECTORY
          * -r copy recursively, non-directories as files
        - * 
        + *
          *  --sparse=WHEN control creation of sparse files
        - * 
        + *
          *  -R, --recursive copy directories recursively
        - * 
        + *
          *  -s, --symbolic-link make symbolic links instead of copying
        - * 
        + *
          *  -S, --suffix=SUFFIX override the usual backup suffix
        - * 
        + *
          *  -u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing
        - * 
        + *
          *  -v, --verbose explain what is being done
        - * 
        + *
          *  -V, --version-control=WORD override the usual version control
        - * 
        + *
          *  -x, --one-file-system stay on this file system
        - * 
        + *
          *  --help display this help and exit
        - * 
        + *
          *  --version output version information and exit
        - * 
        + *
          *  By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file when- ever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files.
        - * 
        + *
          *  The backup suffix is ~, unless set with SIMPLE_BACKUP_SUF- FIX. The version control may be set with VERSION_CONTROL, values are:
          * t, numbered make numbered backups
        - * 
        + *
          *  nil, existing numbered if numbered backups exist, simple other- wise
        - * 
        + *
          *  never, simple always make simple backups
        - * 
        + *
          *  As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. * 
        * - * + * * @author Rob Oxspring * @author John Keyes */ diff --git a/src/test/org/apache/commons/cli2/application/LsTest.java b/src/test/org/apache/commons/cli2/application/LsTest.java index e68a248f5..9f770babd 100644 --- a/src/test/org/apache/commons/cli2/application/LsTest.java +++ b/src/test/org/apache/commons/cli2/application/LsTest.java @@ -36,92 +36,92 @@ /** *

        Test the ls command. Duplicated Option types are not * tested e.g. -a and -d are the same Option type.

        - * + * *

        The following is the man output for 'ls'. See * http://www.rt.com/man/ls.1.html.

        - * + * *
          *  LS(1) FSF LS(1)
        - * 
        + *
          *  NAME ls - list directory contents
        - * 
        + *
          *  SYNOPSIS ls [OPTION]... [FILE]...
        - * 
        + *
          *  DESCRIPTION List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuSUX nor --sort.
        - * 
        + *
          *  -a, --all do not hide entries starting with .
        - * 
        + *
          *  -A, --almost-all do not list implied . and ..
        - * 
        + *
          *  -b, --escape print octal escapes for nongraphic characters
        - * 
        + *
          *  --block-size=SIZE use SIZE-byte blocks
        - * 
        + *
          *  -B, --ignore-backups do not list implied entries ending with ~ -c sort by change time; with -l: show ctime -C list entries by columns
        - * 
        + *
          *  --color[=WHEN] control whether color is used to distinguish file types. WHEN may be `never', `always', or `auto'
        - * 
        + *
          *  -d, --directory list directory entries instead of contents
        - * 
        + *
          *  -D, --dired generate output designed for Emacs' dired mode -f do not sort, enable -aU, disable -lst
        - * 
        + *
          *  -F, --classify append indicator (one of /=@|*) to entries
        - * 
        + *
          *  --format=WORD across -x, commas -m, horizontal -x, long -l, sin- gle-column -1, verbose -l, vertical -C
        - * 
        + *
          *  --full-time list both full date and full time -g (ignored)
        - * 
        + *
          *  -G, --no-group inhibit display of group information
        - * 
        + *
          *  -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)
        - * 
        + *
          *  -H, --si likewise, but use powers of 1000 not 1024
        - * 
        + *
          *  --indicator-style=WORD append indicator with style WORD to entry names: none (default), classify (-F), file-type (-p)
        - * 
        + *
          *  -i, --inode print index number of each file
        - * 
        + *
          *  -I, --ignore=PATTERN do not list implied entries matching shell PATTERN
        - * 
        + *
          *  -k, --kilobytes like --block-size=1024 -l use a long listing format
        - * 
        + *
          *  -L, --dereference list entries pointed to by symbolic links -m fill width with a comma separated list of entries
        - * 
        + *
          *  -n, --numeric-uid-gid list numeric UIDs and GIDs instead of names
        - * 
        + *
          *  -N, --literal print raw entry names (don't treat e.g. control characters specially) -o use long listing format without group info
        - * 
        + *
          *  -p, --file-type append indicator (one of /=@|) to entries
        - * 
        + *
          *  -q, --hide-control-chars print ? instead of non graphic characters
        - * 
        + *
          *  --show-control-chars show non graphic characters as-is (default)
        - * 
        + *
          *  -Q, --quote-name enclose entry names in double quotes
        - * 
        + *
          *  --quoting-style=WORD use quoting style WORD for entry names: literal, shell, shell-always, c, escape
        - * 
        + *
          *  -r, --reverse reverse order while sorting
        - * 
        + *
          *  -R, --recursive list subdirectories recursively
        - * 
        + *
          *  -s, --size print size of each file, in blocks -S sort by file size
        - * 
        + *
          *  --sort=WORD extension -X, none -U, size -S, time -t, version -v status -c, time -t, atime -u, access -u, use -u
        - * 
        + *
          *  --time=WORD show time as WORD instead of modification time: atime, access, use, ctime or status; use specified time as sort key if --sort=time -t sort by modification time
        - * 
        + *
          *  -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u sort by last access time; with -l: show atime -U do not sort; list entries in directory order -v sort by version
        - * 
        + *
          *  -w, --width=COLS assume screen width instead of current value -x list entries by lines instead of by columns -X sort alphabetically by entry extension -1 list one file per line
        - * 
        + *
          *  --help display this help and exit
        - * 
        + *
          *  --version output version information and exit
        - * 
        + *
          *  By default, color is not used to distinguish types of files. That is equivalent to using --color=none. Using the --color option without the optional WHEN argument is equivalent to using --color=always. With --color=auto, color codes are output only if standard output is con- nected to a terminal (tty).
          * 
        - * + * * @author Rob Oxspring * @author John Keyes */ @@ -145,7 +145,7 @@ public static Test suite() { /** * Required ctor. - * + * * @param name * the name of the TestCase */ diff --git a/src/test/org/apache/commons/cli2/bug/Bug27575Test.java b/src/test/org/apache/commons/cli2/bug/Bug27575Test.java index fb7a5a900..d85f77e8d 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug27575Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug27575Test.java @@ -31,7 +31,7 @@ public void testRequiredOptions(){ builder.withPattern("hc!<"); Option option = builder.create(); assertTrue(option instanceof GroupImpl); - + GroupImpl group = (GroupImpl)option; Iterator i = group.getOptions().iterator(); assertEquals("[-h]",i.next().toString()); diff --git a/src/test/org/apache/commons/cli2/bug/Bug28005Test.java b/src/test/org/apache/commons/cli2/bug/Bug28005Test.java index 2c81ca302..b52352c11 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug28005Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug28005Test.java @@ -33,42 +33,42 @@ public void testInfiniteLoop() { final ArgumentBuilder argumentBuilder = new ArgumentBuilder(); final GroupBuilder groupBuilder = new GroupBuilder(); final CommandBuilder commandBuilder = new CommandBuilder(); - - final Option inputFormatOption = + + final Option inputFormatOption = optionBuilder .withLongName("input-format") //.withArgument(argumentBuilder.create()) .create(); - - final Argument argument = + + final Argument argument = argumentBuilder .withName("file") .create(); - - final Group children = + + final Group children = groupBuilder .withName("options") .withOption(inputFormatOption) .create(); - - final Option command = + + final Option command = commandBuilder .withName("convert") .withChildren(children) .withArgument(argument) .create(); - - final Group root = + + final Group root = groupBuilder .withName("commands") .withOption(command) .create(); - + final Parser parser = new Parser(); parser.setGroup(root); final String[] args = new String[]{"convert", "test.txt", "--input-format", "a"}; - + try { parser.parse(args); fail("a isn't valid!!"); diff --git a/src/test/org/apache/commons/cli2/bug/Bug32533Test.java b/src/test/org/apache/commons/cli2/bug/Bug32533Test.java index 56f337202..1d2ba0fe2 100644 --- a/src/test/org/apache/commons/cli2/bug/Bug32533Test.java +++ b/src/test/org/apache/commons/cli2/bug/Bug32533Test.java @@ -29,18 +29,18 @@ * @author roxspring */ public class Bug32533Test extends TestCase { - + public void testBlah() throws OptionException { - + Option a1 = new DefaultOptionBuilder().withLongName("a1").create(); Option b1 = new DefaultOptionBuilder().withLongName("b1").create(); Option c1 = new DefaultOptionBuilder().withLongName("c1").create(); - + Group b = new GroupBuilder().withOption(b1).create(); Group c = new GroupBuilder().withOption(c1).create(); Group a = new GroupBuilder().withOption(a1).withOption(b).withOption(c).create(); - - Parser parser = new Parser(); + + Parser parser = new Parser(); parser.setGroup(a); parser.parse(new String[]{"--a1","--b1"}); } diff --git a/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java b/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java index 97be1fc96..f1fdaed9a 100644 --- a/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java +++ b/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java @@ -128,7 +128,7 @@ public final void testInsertCommandLine() { assertSame(first, i.next()); assertFalse(i.hasNext()); } - + public void testTriggers() { final DefaultingCommandLine defaults = new DefaultingCommandLine(); defaults.appendCommandLine(first); @@ -144,7 +144,7 @@ public void testTriggers() { public void testDefaults() { final DefaultingCommandLine defaults = new DefaultingCommandLine(); - + assertEquals("wrong # of defaults", 0, defaults.getValues("--insecond").size()); assertEquals("wrong Set of defaults", Collections.EMPTY_LIST, defaults.getValues("--insecond", null)); } diff --git a/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java b/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java index 1526b9230..c58ee8df3 100644 --- a/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java +++ b/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java @@ -27,7 +27,7 @@ * @author Rob Oxspring */ public class PreferencesCommandLineTest extends CommandLineTestCase { - + /* (non-Javadoc) * @see org.apache.commons.cli2.CommandLineTest#createCommandLine() */ @@ -38,9 +38,9 @@ protected CommandLine createCommandLine() { props.put("--alsopresent",""); props.put("--multiple","value 1|value 2|value 3"); props.put("--bool","true"); - + props.put("present","present property"); - + return new PreferencesCommandLine(root,props,'|'); } @@ -51,16 +51,16 @@ protected CommandLine createCommandLineNoSep() { props.put("--alsopresent",""); props.put("--multiple","value 1|value 2|value 3"); props.put("--bool","false"); - + props.put("present","present property"); - + return new PreferencesCommandLine(root,props); } - + public void testPropertyValues() { // nothing to test CommandLine cmdline = createCommandLine(); - + assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 3, cmdline.getValues("--multiple").size()); @@ -68,18 +68,18 @@ public void testPropertyValues() { assertEquals("wrong value 2", "value 2", cmdline.getValues("--multiple").get(1)); assertEquals("wrong value 3", "value 3", cmdline.getValues("--multiple").get(2)); } - + public void testNoSeparator() { // nothing to test CommandLine cmdline = createCommandLineNoSep(); - + assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 1, cmdline.getValues("--multiple").size()); assertEquals("wrong value", "value 1|value 2|value 3", cmdline.getValue("--multiple")); assertFalse("expected a false", cmdline.getSwitch("--bool").booleanValue()); } - + public void testNullOption() { // nothing to test CommandLine cmdline = createCommandLine(); @@ -99,7 +99,7 @@ public void testPreferenceTriggers() { assertTrue("cannot find trigger", triggers.contains("--present")); assertTrue("cannot find trigger", triggers.contains("--multiple")); assertTrue("cannot find trigger", triggers.contains("--alsopresent")); - + assertFalse("should not find null option", cmdline.hasOption((String) null)); assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); } diff --git a/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java b/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java index 664a2252a..79ba4d985 100644 --- a/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java +++ b/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java @@ -51,11 +51,11 @@ protected CommandLine createCommandLineNoSep() { props.setProperty("present", "present property"); return new PropertiesCommandLine(root, props); } - + public void testPropertyValues() { // nothing to test CommandLine cmdline = createCommandLine(); - + assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 3, cmdline.getValues("--multiple").size()); @@ -63,18 +63,18 @@ public void testPropertyValues() { assertEquals("wrong value 2", "value 2", cmdline.getValues("--multiple").get(1)); assertEquals("wrong value 3", "value 3", cmdline.getValues("--multiple").get(2)); } - + public void testNoSeparator() { // nothing to test CommandLine cmdline = createCommandLineNoSep(); - + assertEquals("wrong value", "present value", cmdline.getValue("--present")); assertEquals("wrong value", "present value", cmdline.getValue("--alsopresent")); assertEquals("wrong # of values", 1, cmdline.getValues("--multiple").size()); assertEquals("wrong value", "value 1|value 2|value 3", cmdline.getValue("--multiple")); assertFalse("expected a false", cmdline.getSwitch("--bool").booleanValue()); } - + public void testNullOption() { // nothing to test CommandLine cmdline = createCommandLine(); @@ -94,7 +94,7 @@ public void testPropertyTriggers() { assertTrue("cannot find trigger", triggers.contains("--present")); assertTrue("cannot find trigger", triggers.contains("--multiple")); assertTrue("cannot find trigger", triggers.contains("--alsopresent")); - + assertFalse("should not find null option", cmdline.hasOption((String) null)); assertTrue("expected a true", cmdline.getSwitch("--bool").booleanValue()); } diff --git a/src/test/org/apache/commons/cli2/jdepend/JDependTest.java b/src/test/org/apache/commons/cli2/jdepend/JDependTest.java index 45e5612b5..f018642d3 100644 --- a/src/test/org/apache/commons/cli2/jdepend/JDependTest.java +++ b/src/test/org/apache/commons/cli2/jdepend/JDependTest.java @@ -81,10 +81,10 @@ public void testApiIndependance() { final Collection dependsUpon = cli2Packages(apiPackage.getEfferents()); assertEquals("Api should depend on one package", 1, dependsUpon.size()); - + JavaPackage pkg = (JavaPackage) dependsUpon.iterator().next(); assertEquals( - "Wrong package name", + "Wrong package name", "org.apache.commons.cli2.resource", pkg.getName()); } diff --git a/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java b/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java index 2cdbe34b4..d1f569884 100644 --- a/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java +++ b/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java @@ -30,7 +30,7 @@ /** * @author roberto - * + * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ @@ -69,7 +69,7 @@ public static DefaultOption buildXOption() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.ParentTestCase#testProcessParent() */ public void testProcessParent() throws OptionException { @@ -103,7 +103,7 @@ public void testProcessParent_Burst() throws OptionException { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { @@ -118,7 +118,7 @@ public void testCanProcess_BadMatch() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { @@ -128,7 +128,7 @@ public void testPrefixes() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() { @@ -138,7 +138,7 @@ public void testProcess() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { @@ -148,7 +148,7 @@ public void testTriggers() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() { @@ -166,7 +166,7 @@ public void testValidate() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { @@ -199,7 +199,7 @@ public void testAppendUsage_NoAlias() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { @@ -209,7 +209,7 @@ public void testGetPreferredName() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { @@ -218,7 +218,7 @@ public void testGetDescription() { } /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { diff --git a/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java b/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java index 196e315a8..1bd46111a 100644 --- a/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java +++ b/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java @@ -36,7 +36,7 @@ public class PropertyOptionTest extends OptionTestCase { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testCanProcess() */ public void testCanProcess() { @@ -61,7 +61,7 @@ public void testCanProcess_BadMatch() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testPrefixes() */ public void testPrefixes() { @@ -71,7 +71,7 @@ public void testPrefixes() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { @@ -129,7 +129,7 @@ public void testProcess_SetToEmpty() throws OptionException { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testTriggers() */ public void testTriggers() { @@ -140,7 +140,7 @@ public void testTriggers() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testValidate() */ public void testValidate() throws OptionException { @@ -156,7 +156,7 @@ public void testValidate() throws OptionException { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testAppendUsage() */ public void testAppendUsage() { @@ -179,7 +179,7 @@ public void testAppendUsage_Hidden() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testGetPreferredName() */ public void testGetPreferredName() { @@ -189,7 +189,7 @@ public void testGetPreferredName() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testGetDescription() */ public void testGetDescription() { @@ -201,7 +201,7 @@ public void testGetDescription() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines() { @@ -218,7 +218,7 @@ public void testHelpLines() { /* * (non-Javadoc) - * + * * @see org.apache.commons.cli2.OptionTestCase#testHelpLines() */ public void testHelpLines_NoDisplay() { diff --git a/src/test/org/apache/commons/cli2/util/ComparatorsTest.java b/src/test/org/apache/commons/cli2/util/ComparatorsTest.java index b8e0a25cf..5a387b4fe 100644 --- a/src/test/org/apache/commons/cli2/util/ComparatorsTest.java +++ b/src/test/org/apache/commons/cli2/util/ComparatorsTest.java @@ -201,15 +201,15 @@ public void testRequiredLast() { CLITestCase.list(o1, o2), list); } - + public void testChained() { final Option o1 = CommandTest.buildCommitCommand(); final Option o2 = SwitchTest.buildDisplaySwitch(); final Option o3 = DefaultOptionTest.buildHelpOption(); final List list = CLITestCase.list(o1, o2, o3); - + Collections.sort( - list, + list, Comparators.chain( Comparators.namedFirst("--help"), Comparators.commandFirst())); diff --git a/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java b/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java index 1c89b1b12..707ef1e84 100644 --- a/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java @@ -192,7 +192,7 @@ public void testCreateInterfaceInstance() { final List list = Arrays.asList(array); validator.setInstance(true); - + try { validator.validate(list); fail("It's not possible to create a '" + className + "'"); @@ -212,7 +212,7 @@ public void testCreateProtectedInstance() { final List list = Arrays.asList(array); validator.setInstance(true); - + try { validator.validate(list); fail("It's not possible to create a '" + className + "'"); @@ -229,7 +229,7 @@ public void testCreateProtectedInstance() { ive.getMessage()); } } - + public void testClassloader() { assertEquals( "Wrong classloader found", diff --git a/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java b/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java index ba5112c50..e15b1866f 100644 --- a/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java @@ -68,8 +68,8 @@ public void testDefaultDateFormatValidate() validator.validate(list); final Iterator i = list.iterator(); - // CLI-40: For some reason, the YYYY_MM_DD object gets quite - // confused here and returns 2003-12-22. If we make a new one + // CLI-40: For some reason, the YYYY_MM_DD object gets quite + // confused here and returns 2003-12-22. If we make a new one // there is no problem. assertEquals("2003-12-23", new SimpleDateFormat("yyyy-MM-dd").format((Date) i.next())); assertFalse(i.hasNext()); diff --git a/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java b/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java index 16744ca65..8ced24047 100644 --- a/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java @@ -26,7 +26,7 @@ /** * JUnit test case for the FileValidator. - * + * * @author Rob Oxspring * @author John Keyes */ From 1bf3907588350c531c1619ad8f23a4b599f37518 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 22 Mar 2008 10:52:20 +0000 Subject: [PATCH 0073/1663] Enabling checkstyle/findbugs. Not sure why checkstyle isn't picking up the config git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639971 13f79535-47bb-0310-9956-ffa450edef68 --- project.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/project.xml b/project.xml index c7d9c028a..525514f1d 100644 --- a/project.xml +++ b/project.xml @@ -195,13 +195,13 @@ maven-changes-plugin maven-jdepend-plugin - + maven-checkstyle-plugin maven-javadoc-plugin maven-jdepend-plugin maven-junit-report-plugin maven-jxr-plugin maven-license-plugin maven-pmd-plugin - + maven-findbugs-plugin From 47b2fa57db0f54d71ea4822fdb44b10656002890 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Sat, 22 Mar 2008 11:08:56 +0000 Subject: [PATCH 0074/1663] Add missing svn:eol-style and svn:keywords properties git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639976 13f79535-47bb-0310-9956-ffa450edef68 --- .../CLIMessageBundle_en_US.properties | 114 ++-- .../cli2/resource/ResourceConstants.java | 140 ++--- .../commons/cli2/validation/package.html | 30 +- .../bug/BugLoopingOptionLookAlikeTest.java | 158 +++--- .../cli2/builder/ArgumentBuilderTest.java | 508 +++++++++--------- .../commons/cli2/commandline/ParserTest.java | 280 +++++----- .../cli2/resource/TestBundle.properties | 20 +- 7 files changed, 625 insertions(+), 625 deletions(-) diff --git a/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties b/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties index 81121984a..443616288 100644 --- a/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties +++ b/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties @@ -1,57 +1,57 @@ -ClassValidator.bad.classname = The class name "{0}" is invalid. -ClassValidator.class.notfound = The class "{0}" could not be found. -ClassValidator.class.access = The class "{0}" could not be accessed. Reason: {1}. -ClassValidator.class.create = The class "{0}" could not be created. - -DateValidator.date.OutOfRange = Date ''{0}'' is out of range. - -NumberValidator.number.OutOfRange = Number ''{0}'' is out of range. - -URLValidator.malformed.URL = Cannot understand URL: ''{0}''. - -Argument.unexpected.value = Unexpected value "{0}" found while processing -Argument.minimum.exceeds.maximum = Minimum number of values must not exceed maximum number -Argument.too.few.defaults = Not enough default values. -Argument.too.many.defaults = Too many default values. -Argument.missing.values = Missing value(s) -Argument.too.many.values = More than one value was supplied. - -Option.trigger.needs.prefix = Trigger {0} must be prefixed with a value from {1} -Option.missing.required = Missing required option -Option.no.name = An option must have at least one name. -Option.illegal.short.prefix = The shortPrefix MUST be at least 1 character long. -Option.illegal.long.prefix = The longPrefix MUST be at least 1 character long. - -Command.preferredName.too.short = The preferredName MUST be at least 1 character long. - -SourceDest.must.enforce.values = The dest argument must enforce a fixed number of values. - -Switch.illegal.enabled.prefix = The enabledPrefix MUST be at least 1 character long. -Switch.illegal.disabled.prefix = The disabledPrefix MUST be at least 1 character long. -Switch.identical.prefixes = The disabledPrefix and enabledPrefix MUST be different. -Switch.already.set = Switch already set. -Switch.no.enabledPrefix = An enabledPrefix must be supplied. -Switch.no.disabledPrefix = A disabledPrefix must be supplied. -Switch.enabled.startsWith.disabled = The enabledPrefix cannot start the same as disabledPrefix. -Switch.disabled.startsWith.enabled = The disabledPrefix cannot start the same as enabledPrefix. -Switch.preferredName.too.short = The preferredName MUST be at least 1 character long. - -HelpFormatter.gutter.too.long = The gutter strings leave no space for output! \ - Supply shorter gutters or more width. -HelpFormatter.width.too.narrow = The HelpFormatter width is too narrow: "{0}". - -Enum.illegal.value = ''{0}'' is not allowed. Permitted values are: {1} - -Unexpected.token = Unexpected {0} while processing -Missing.option = Missing option -Cannot.burst = Could not burst "{0}" while processing - -ArgumentBuilder.null.consume.remaining = Cannot use 'null' as the consume remaining token. -ArgumentBuilder.empty.consume.remaining = Cannot use an empty string as the consume remaining token. -ArgumentBuilder.null.defaults = Cannot use 'null' defaults. -ArgumentBuilder.null.default = Cannot use 'null' default. -ArgumentBuilder.negative.maximum = Cannot use a negative maximum value. -ArgumentBuilder.negative.minimum = Cannot use a negative minimum value. -ArgumentBuilder.null.name = Cannot use 'null' as a name. -ArgumentBuilder.empty.name = Cannot use an empty string as a name. -ArgumentBuilder.null.validator = Cannot use 'null' as a validator. +ClassValidator.bad.classname = The class name "{0}" is invalid. +ClassValidator.class.notfound = The class "{0}" could not be found. +ClassValidator.class.access = The class "{0}" could not be accessed. Reason: {1}. +ClassValidator.class.create = The class "{0}" could not be created. + +DateValidator.date.OutOfRange = Date ''{0}'' is out of range. + +NumberValidator.number.OutOfRange = Number ''{0}'' is out of range. + +URLValidator.malformed.URL = Cannot understand URL: ''{0}''. + +Argument.unexpected.value = Unexpected value "{0}" found while processing +Argument.minimum.exceeds.maximum = Minimum number of values must not exceed maximum number +Argument.too.few.defaults = Not enough default values. +Argument.too.many.defaults = Too many default values. +Argument.missing.values = Missing value(s) +Argument.too.many.values = More than one value was supplied. + +Option.trigger.needs.prefix = Trigger {0} must be prefixed with a value from {1} +Option.missing.required = Missing required option +Option.no.name = An option must have at least one name. +Option.illegal.short.prefix = The shortPrefix MUST be at least 1 character long. +Option.illegal.long.prefix = The longPrefix MUST be at least 1 character long. + +Command.preferredName.too.short = The preferredName MUST be at least 1 character long. + +SourceDest.must.enforce.values = The dest argument must enforce a fixed number of values. + +Switch.illegal.enabled.prefix = The enabledPrefix MUST be at least 1 character long. +Switch.illegal.disabled.prefix = The disabledPrefix MUST be at least 1 character long. +Switch.identical.prefixes = The disabledPrefix and enabledPrefix MUST be different. +Switch.already.set = Switch already set. +Switch.no.enabledPrefix = An enabledPrefix must be supplied. +Switch.no.disabledPrefix = A disabledPrefix must be supplied. +Switch.enabled.startsWith.disabled = The enabledPrefix cannot start the same as disabledPrefix. +Switch.disabled.startsWith.enabled = The disabledPrefix cannot start the same as enabledPrefix. +Switch.preferredName.too.short = The preferredName MUST be at least 1 character long. + +HelpFormatter.gutter.too.long = The gutter strings leave no space for output! \ + Supply shorter gutters or more width. +HelpFormatter.width.too.narrow = The HelpFormatter width is too narrow: "{0}". + +Enum.illegal.value = ''{0}'' is not allowed. Permitted values are: {1} + +Unexpected.token = Unexpected {0} while processing +Missing.option = Missing option +Cannot.burst = Could not burst "{0}" while processing + +ArgumentBuilder.null.consume.remaining = Cannot use 'null' as the consume remaining token. +ArgumentBuilder.empty.consume.remaining = Cannot use an empty string as the consume remaining token. +ArgumentBuilder.null.defaults = Cannot use 'null' defaults. +ArgumentBuilder.null.default = Cannot use 'null' default. +ArgumentBuilder.negative.maximum = Cannot use a negative maximum value. +ArgumentBuilder.negative.minimum = Cannot use a negative minimum value. +ArgumentBuilder.null.name = Cannot use 'null' as a name. +ArgumentBuilder.empty.name = Cannot use an empty string as a name. +ArgumentBuilder.null.validator = Cannot use 'null' as a validator. diff --git a/src/java/org/apache/commons/cli2/resource/ResourceConstants.java b/src/java/org/apache/commons/cli2/resource/ResourceConstants.java index c0b286f70..19e4bb055 100644 --- a/src/java/org/apache/commons/cli2/resource/ResourceConstants.java +++ b/src/java/org/apache/commons/cli2/resource/ResourceConstants.java @@ -1,70 +1,70 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.commons.cli2.resource; - -public abstract class ResourceConstants { - public static final String CLASSVALIDATOR_BAD_CLASSNAME = "ClassValidator.bad.classname"; - public static final String CLASSVALIDATOR_CLASS_NOTFOUND = "ClassValidator.class.notfound"; - public static final String CLASSVALIDATOR_CLASS_ACCESS = "ClassValidator.class.access"; - public static final String CLASSVALIDATOR_CLASS_CREATE = "ClassValidator.class.create"; - public static final String DATEVALIDATOR_DATE_OUTOFRANGE = "DateValidator.date.OutOfRange"; - public static final String URLVALIDATOR_MALFORMED_URL = "URLValidator.malformed.URL"; - public static final String NUMBERVALIDATOR_NUMBER_OUTOFRANGE = - "NumberValidator.number.OutOfRange"; - public static final String ARGUMENT_UNEXPECTED_VALUE = "Argument.unexpected.value"; - public static final String ARGUMENT_MIN_EXCEEDS_MAX = "Argument.minimum.exceeds.maximum"; - public static final String ARGUMENT_TOO_FEW_DEFAULTS = "Argument.too.few.defaults"; - public static final String ARGUMENT_TOO_MANY_DEFAULTS = "Argument.too.many.defaults"; - public static final String ARGUMENT_MISSING_VALUES = "Argument.missing.values"; - public static final String ARGUMENT_TOO_MANY_VALUES = "Argument.too.many.values"; - public static final String OPTION_TRIGGER_NEEDS_PREFIX = "Option.trigger.needs.prefix"; - public static final String OPTION_MISSING_REQUIRED = "Option.missing.required"; - public static final String OPTION_NO_NAME = "Option.no.name"; - public static final String OPTION_ILLEGAL_LONG_PREFIX = "Option.illegal.long.prefix"; - public static final String OPTION_ILLEGAL_SHORT_PREFIX = "Option.illegal.short.prefix"; - public static final String UNEXPECTED_TOKEN = "Unexpected.token"; - public static final String MISSING_OPTION = "Missing.option"; - public static final String CANNOT_BURST = "Cannot.burst"; - public static final String COMMAND_PREFERRED_NAME_TOO_SHORT = "Command.preferredName.too.short"; - public static final String SWITCH_ILLEGAL_ENABLED_PREFIX = "Option.illegal.enabled.prefix"; - public static final String SWITCH_ILLEGAL_DISABLED_PREFIX = "Option.illegal.disabled.prefix"; - public static final String SWITCH_IDENTICAL_PREFIXES = "Option.identical.prefixes"; - public static final String SWITCH_ALREADY_SET = "Switch.already.set"; - public static final String SWITCH_NO_ENABLED_PREFIX = "Switch.no.enabledPrefix"; - public static final String SWITCH_NO_DISABLED_PREFIX = "Switch.no.disabledPrefix"; - public static final String SWITCH_ENABLED_STARTS_WITH_DISABLED = - "Switch.enabled.startsWith.disabled"; - public static final String SWITCH_DISABLED_STARTWS_WITH_ENABLED = - "Switch.disabled.startsWith.enabled"; - public static final String SWITCH_PREFERRED_NAME_TOO_SHORT = "Switch.preferredName.too.short"; - public static final String SOURCE_DEST_MUST_ENFORCE_VALUES = "SourceDest.must.enforce.values"; - public static final String HELPFORMATTER_GUTTER_TOO_LONG = "HelpFormatter.gutter.too.long"; - public static final String HELPFORMATTER_WIDTH_TOO_NARROW = "HelpFormatter.width.too.narrow"; - public static final String ENUM_ILLEGAL_VALUE = "Enum.illegal.value"; - public static final String ARGUMENT_BUILDER_NULL_CONSUME_REMAINING = "ArgumentBuilder.null.consume.remaining"; - public static final String ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING = "ArgumentBuilder.empty.consume.remaining"; - public static final String ARGUMENT_BUILDER_NULL_DEFAULT = "ArgumentBuilder.null.default"; - public static final String ARGUMENT_BUILDER_NULL_DEFAULTS = "ArgumentBuilder.null.defaults"; - public static final String ARGUMENT_BUILDER_NEGATIVE_MAXIMUM = "ArgumentBuilder.negative.maximum"; - public static final String ARGUMENT_BUILDER_NEGATIVE_MINIMUM = "ArgumentBuilder.negative.minimum"; - public static final String ARGUMENT_BUILDER_NULL_NAME = "ArgumentBuilder.null.name"; - public static final String ARGUMENT_BUILDER_EMPTY_NAME = "ArgumentBuilder.empty.name"; - public static final String ARGUMENT_BUILDER_NULL_VALIDATOR = "ArgumentBuilder.null.validator"; - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.cli2.resource; + +public abstract class ResourceConstants { + public static final String CLASSVALIDATOR_BAD_CLASSNAME = "ClassValidator.bad.classname"; + public static final String CLASSVALIDATOR_CLASS_NOTFOUND = "ClassValidator.class.notfound"; + public static final String CLASSVALIDATOR_CLASS_ACCESS = "ClassValidator.class.access"; + public static final String CLASSVALIDATOR_CLASS_CREATE = "ClassValidator.class.create"; + public static final String DATEVALIDATOR_DATE_OUTOFRANGE = "DateValidator.date.OutOfRange"; + public static final String URLVALIDATOR_MALFORMED_URL = "URLValidator.malformed.URL"; + public static final String NUMBERVALIDATOR_NUMBER_OUTOFRANGE = + "NumberValidator.number.OutOfRange"; + public static final String ARGUMENT_UNEXPECTED_VALUE = "Argument.unexpected.value"; + public static final String ARGUMENT_MIN_EXCEEDS_MAX = "Argument.minimum.exceeds.maximum"; + public static final String ARGUMENT_TOO_FEW_DEFAULTS = "Argument.too.few.defaults"; + public static final String ARGUMENT_TOO_MANY_DEFAULTS = "Argument.too.many.defaults"; + public static final String ARGUMENT_MISSING_VALUES = "Argument.missing.values"; + public static final String ARGUMENT_TOO_MANY_VALUES = "Argument.too.many.values"; + public static final String OPTION_TRIGGER_NEEDS_PREFIX = "Option.trigger.needs.prefix"; + public static final String OPTION_MISSING_REQUIRED = "Option.missing.required"; + public static final String OPTION_NO_NAME = "Option.no.name"; + public static final String OPTION_ILLEGAL_LONG_PREFIX = "Option.illegal.long.prefix"; + public static final String OPTION_ILLEGAL_SHORT_PREFIX = "Option.illegal.short.prefix"; + public static final String UNEXPECTED_TOKEN = "Unexpected.token"; + public static final String MISSING_OPTION = "Missing.option"; + public static final String CANNOT_BURST = "Cannot.burst"; + public static final String COMMAND_PREFERRED_NAME_TOO_SHORT = "Command.preferredName.too.short"; + public static final String SWITCH_ILLEGAL_ENABLED_PREFIX = "Option.illegal.enabled.prefix"; + public static final String SWITCH_ILLEGAL_DISABLED_PREFIX = "Option.illegal.disabled.prefix"; + public static final String SWITCH_IDENTICAL_PREFIXES = "Option.identical.prefixes"; + public static final String SWITCH_ALREADY_SET = "Switch.already.set"; + public static final String SWITCH_NO_ENABLED_PREFIX = "Switch.no.enabledPrefix"; + public static final String SWITCH_NO_DISABLED_PREFIX = "Switch.no.disabledPrefix"; + public static final String SWITCH_ENABLED_STARTS_WITH_DISABLED = + "Switch.enabled.startsWith.disabled"; + public static final String SWITCH_DISABLED_STARTWS_WITH_ENABLED = + "Switch.disabled.startsWith.enabled"; + public static final String SWITCH_PREFERRED_NAME_TOO_SHORT = "Switch.preferredName.too.short"; + public static final String SOURCE_DEST_MUST_ENFORCE_VALUES = "SourceDest.must.enforce.values"; + public static final String HELPFORMATTER_GUTTER_TOO_LONG = "HelpFormatter.gutter.too.long"; + public static final String HELPFORMATTER_WIDTH_TOO_NARROW = "HelpFormatter.width.too.narrow"; + public static final String ENUM_ILLEGAL_VALUE = "Enum.illegal.value"; + public static final String ARGUMENT_BUILDER_NULL_CONSUME_REMAINING = "ArgumentBuilder.null.consume.remaining"; + public static final String ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING = "ArgumentBuilder.empty.consume.remaining"; + public static final String ARGUMENT_BUILDER_NULL_DEFAULT = "ArgumentBuilder.null.default"; + public static final String ARGUMENT_BUILDER_NULL_DEFAULTS = "ArgumentBuilder.null.defaults"; + public static final String ARGUMENT_BUILDER_NEGATIVE_MAXIMUM = "ArgumentBuilder.negative.maximum"; + public static final String ARGUMENT_BUILDER_NEGATIVE_MINIMUM = "ArgumentBuilder.negative.minimum"; + public static final String ARGUMENT_BUILDER_NULL_NAME = "ArgumentBuilder.null.name"; + public static final String ARGUMENT_BUILDER_EMPTY_NAME = "ArgumentBuilder.empty.name"; + public static final String ARGUMENT_BUILDER_NULL_VALIDATOR = "ArgumentBuilder.null.validator"; + +} diff --git a/src/java/org/apache/commons/cli2/validation/package.html b/src/java/org/apache/commons/cli2/validation/package.html index 63bc28b1d..d54223cac 100644 --- a/src/java/org/apache/commons/cli2/validation/package.html +++ b/src/java/org/apache/commons/cli2/validation/package.html @@ -1,16 +1,16 @@ - - -Provides classes and interfaces for validating argument values. - -These classes are capable of validating argument values of the following type: - -
          -
        • file/directory
        • -
        • number
        • -
        • date/time
        • -
        • URL
        • -
        • enumeration
        • -
        • class
        • -
        - + + +Provides classes and interfaces for validating argument values. + +These classes are capable of validating argument values of the following type: + +
          +
        • file/directory
        • +
        • number
        • +
        • date/time
        • +
        • URL
        • +
        • enumeration
        • +
        • class
        • +
        + \ No newline at end of file diff --git a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java index f0e6d4d3a..aa684554b 100644 --- a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java +++ b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java @@ -1,79 +1,79 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.commons.cli2.bug; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.Argument; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.ArgumentBuilder; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.commandline.Parser; -import org.apache.commons.cli2.option.SourceDestArgument; - -/** - * The first is a loop in Parser.parse() if I set a non-declared option. This - * code goes into a loop in Parser.java method parse this “while” loop runs - * endless - * - * @author Steve Alberty - */ -public class BugLoopingOptionLookAlikeTest extends TestCase { - - public void testLoopingOptionLookAlike() { - final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - final Group options = gbuilder - .withName("ant") - .withOption(obuilder.withShortName("help").withDescription("print this message").create()) - .withOption(obuilder.withShortName("projecthelp").withDescription("print project help information").create()) - .withOption(abuilder.withName("target").create()) - .create(); - - final Parser parser = new Parser(); - parser.setGroup(options); - try { - parser.parse(new String[] { "-abcdef", - "testfile.txt ", }); - fail("OptionException"); - } catch (OptionException e) { - assertEquals("Unexpected -abcdef while processing ant",e.getMessage()); - } - } - - public void testLoopingOptionLookAlike2() { - final ArgumentBuilder abuilder = new ArgumentBuilder(); - final GroupBuilder gbuilder = new GroupBuilder(); - final Argument inputfile_opt = abuilder.withName("input").withMinimum(1).withMaximum(1).create(); - final Argument outputfile_opt = abuilder.withName("output").withMinimum(1).withMaximum(1).create(); - final Argument targets = new SourceDestArgument(inputfile_opt, outputfile_opt); - final Group options = gbuilder.withOption(targets).create(); - final Parser parser = new Parser(); - parser.setGroup(options); - try { - parser.parse(new String[] { "testfile.txt", "testfile.txt", "testfile.txt", "testfile.txt" }); - fail("OptionException"); - } catch (OptionException e) { - assertEquals("Unexpected testfile.txt while processing ", e.getMessage()); - } - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.option.SourceDestArgument; + +/** + * The first is a loop in Parser.parse() if I set a non-declared option. This + * code goes into a loop in Parser.java method parse this “while” loop runs + * endless + * + * @author Steve Alberty + */ +public class BugLoopingOptionLookAlikeTest extends TestCase { + + public void testLoopingOptionLookAlike() { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + final Group options = gbuilder + .withName("ant") + .withOption(obuilder.withShortName("help").withDescription("print this message").create()) + .withOption(obuilder.withShortName("projecthelp").withDescription("print project help information").create()) + .withOption(abuilder.withName("target").create()) + .create(); + + final Parser parser = new Parser(); + parser.setGroup(options); + try { + parser.parse(new String[] { "-abcdef", + "testfile.txt ", }); + fail("OptionException"); + } catch (OptionException e) { + assertEquals("Unexpected -abcdef while processing ant",e.getMessage()); + } + } + + public void testLoopingOptionLookAlike2() { + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + final Argument inputfile_opt = abuilder.withName("input").withMinimum(1).withMaximum(1).create(); + final Argument outputfile_opt = abuilder.withName("output").withMinimum(1).withMaximum(1).create(); + final Argument targets = new SourceDestArgument(inputfile_opt, outputfile_opt); + final Group options = gbuilder.withOption(targets).create(); + final Parser parser = new Parser(); + parser.setGroup(options); + try { + parser.parse(new String[] { "testfile.txt", "testfile.txt", "testfile.txt", "testfile.txt" }); + fail("OptionException"); + } catch (OptionException e) { + assertEquals("Unexpected testfile.txt while processing ", e.getMessage()); + } + } +} diff --git a/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java b/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java index 877523aaf..efe5288ea 100644 --- a/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java +++ b/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java @@ -1,254 +1,254 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.commons.cli2.builder; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.commons.cli2.option.ArgumentImpl; -import org.apache.commons.cli2.resource.ResourceConstants; -import org.apache.commons.cli2.resource.ResourceHelper; -import org.apache.commons.cli2.validation.DateValidator; -import org.apache.commons.cli2.validation.Validator; - -public class ArgumentBuilderTest - extends TestCase { - private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); - private ArgumentBuilder argumentBuilder; - - /* - * @see TestCase#setUp() - */ - protected void setUp() - throws Exception { - this.argumentBuilder = new ArgumentBuilder(); - } - - public void testConsumeRemaining() { - this.argumentBuilder.withConsumeRemaining("--"); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect consume remaining token", "--", arg.getConsumeRemaining()); - } - - public void testNullConsumeRemaining() { - try { - this.argumentBuilder.withConsumeRemaining(null); - fail("cannot use null consume remaining token"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING), - exp.getMessage()); - } - } - - public void testEmptyConsumeRemaining() { - try { - this.argumentBuilder.withConsumeRemaining(""); - fail("cannot use empty string consume remaining token"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING), - exp.getMessage()); - } - } - - public void testDefault() { - this.argumentBuilder.withDefault("defaultString"); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect number of default values", 1, arg.getDefaultValues().size()); - assertEquals("incorrect default value", "defaultString", arg.getDefaultValues().get(0)); - } - - public void testDefaultX2() { - this.argumentBuilder.withDefault("defaultString1"); - this.argumentBuilder.withDefault("defaultString2"); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); - assertEquals("incorrect default value-1", "defaultString1", arg.getDefaultValues().get(0)); - assertEquals("incorrect default value-2", "defaultString2", arg.getDefaultValues().get(1)); - } - - public void testNullDefault() { - try { - this.argumentBuilder.withDefault(null); - fail("cannot use null default"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT), - exp.getMessage()); - } - } - - public void testDefaults() { - final List defaults = new ArrayList(); - defaults.add("one"); - defaults.add("two"); - - this.argumentBuilder.withDefaults(defaults); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); - assertEquals("incorrect default value-1", "one", arg.getDefaultValues().get(0)); - assertEquals("incorrect default value-2", "two", arg.getDefaultValues().get(1)); - assertEquals("incorrect default values list", defaults, arg.getDefaultValues()); - - } - - public void testNullDefaults() { - try { - this.argumentBuilder.withDefaults(null); - fail("cannot use null defaults"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS), - exp.getMessage()); - } - } - - public void testId() { - this.argumentBuilder.withId(1); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect id", 1, arg.getId()); - } - - public void testInitialSeparator() { - this.argumentBuilder.withInitialSeparator(','); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect initial separator", ',', arg.getInitialSeparator()); - } - - public void testMaximum() { - this.argumentBuilder.withMaximum(1); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect maximum", 1, arg.getMaximum()); - } - - public void testNegativeMaximum() { - try { - this.argumentBuilder.withMaximum(-1); - fail("cannot use negative maximum"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM), - exp.getMessage()); - } - } - - public void testMinimum() { - this.argumentBuilder.withMinimum(1); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect maximum", 1, arg.getMinimum()); - } - - public void testNegativeMinimum() { - try { - this.argumentBuilder.withMinimum(-1); - fail("cannot use negative minimum"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM), - exp.getMessage()); - } - } - - public void testName() { - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect preferred name", "arg", arg.getPreferredName()); - } - - public void testNullName() { - try { - this.argumentBuilder.withName(null); - fail("cannot use null name"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME), - exp.getMessage()); - } - } - - public void testEmptyName() { - try { - this.argumentBuilder.withName(""); - fail("cannot use empty name"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME), - exp.getMessage()); - } - } - - public void testSubsequentSeparator() { - this.argumentBuilder.withSubsequentSeparator(':'); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect subsequent separator", ':', arg.getSubsequentSeparator()); - } - - public void testValidator() { - Validator validator = DateValidator.getDateInstance(); - this.argumentBuilder.withValidator(validator); - this.argumentBuilder.withName("arg"); - - ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); - - assertEquals("incorrect validator", validator, arg.getValidator()); - } - - public void testNullValidator() { - try { - this.argumentBuilder.withValidator(null); - fail("cannot use null validator"); - } catch (IllegalArgumentException exp) { - assertEquals("wrong exception message", - resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR), - exp.getMessage()); - } - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.cli2.builder; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.option.ArgumentImpl; +import org.apache.commons.cli2.resource.ResourceConstants; +import org.apache.commons.cli2.resource.ResourceHelper; +import org.apache.commons.cli2.validation.DateValidator; +import org.apache.commons.cli2.validation.Validator; + +public class ArgumentBuilderTest + extends TestCase { + private static final ResourceHelper resources = ResourceHelper.getResourceHelper(); + private ArgumentBuilder argumentBuilder; + + /* + * @see TestCase#setUp() + */ + protected void setUp() + throws Exception { + this.argumentBuilder = new ArgumentBuilder(); + } + + public void testConsumeRemaining() { + this.argumentBuilder.withConsumeRemaining("--"); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect consume remaining token", "--", arg.getConsumeRemaining()); + } + + public void testNullConsumeRemaining() { + try { + this.argumentBuilder.withConsumeRemaining(null); + fail("cannot use null consume remaining token"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING), + exp.getMessage()); + } + } + + public void testEmptyConsumeRemaining() { + try { + this.argumentBuilder.withConsumeRemaining(""); + fail("cannot use empty string consume remaining token"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING), + exp.getMessage()); + } + } + + public void testDefault() { + this.argumentBuilder.withDefault("defaultString"); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect number of default values", 1, arg.getDefaultValues().size()); + assertEquals("incorrect default value", "defaultString", arg.getDefaultValues().get(0)); + } + + public void testDefaultX2() { + this.argumentBuilder.withDefault("defaultString1"); + this.argumentBuilder.withDefault("defaultString2"); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); + assertEquals("incorrect default value-1", "defaultString1", arg.getDefaultValues().get(0)); + assertEquals("incorrect default value-2", "defaultString2", arg.getDefaultValues().get(1)); + } + + public void testNullDefault() { + try { + this.argumentBuilder.withDefault(null); + fail("cannot use null default"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT), + exp.getMessage()); + } + } + + public void testDefaults() { + final List defaults = new ArrayList(); + defaults.add("one"); + defaults.add("two"); + + this.argumentBuilder.withDefaults(defaults); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect number of default values", 2, arg.getDefaultValues().size()); + assertEquals("incorrect default value-1", "one", arg.getDefaultValues().get(0)); + assertEquals("incorrect default value-2", "two", arg.getDefaultValues().get(1)); + assertEquals("incorrect default values list", defaults, arg.getDefaultValues()); + + } + + public void testNullDefaults() { + try { + this.argumentBuilder.withDefaults(null); + fail("cannot use null defaults"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS), + exp.getMessage()); + } + } + + public void testId() { + this.argumentBuilder.withId(1); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect id", 1, arg.getId()); + } + + public void testInitialSeparator() { + this.argumentBuilder.withInitialSeparator(','); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect initial separator", ',', arg.getInitialSeparator()); + } + + public void testMaximum() { + this.argumentBuilder.withMaximum(1); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect maximum", 1, arg.getMaximum()); + } + + public void testNegativeMaximum() { + try { + this.argumentBuilder.withMaximum(-1); + fail("cannot use negative maximum"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM), + exp.getMessage()); + } + } + + public void testMinimum() { + this.argumentBuilder.withMinimum(1); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect maximum", 1, arg.getMinimum()); + } + + public void testNegativeMinimum() { + try { + this.argumentBuilder.withMinimum(-1); + fail("cannot use negative minimum"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM), + exp.getMessage()); + } + } + + public void testName() { + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect preferred name", "arg", arg.getPreferredName()); + } + + public void testNullName() { + try { + this.argumentBuilder.withName(null); + fail("cannot use null name"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME), + exp.getMessage()); + } + } + + public void testEmptyName() { + try { + this.argumentBuilder.withName(""); + fail("cannot use empty name"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME), + exp.getMessage()); + } + } + + public void testSubsequentSeparator() { + this.argumentBuilder.withSubsequentSeparator(':'); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect subsequent separator", ':', arg.getSubsequentSeparator()); + } + + public void testValidator() { + Validator validator = DateValidator.getDateInstance(); + this.argumentBuilder.withValidator(validator); + this.argumentBuilder.withName("arg"); + + ArgumentImpl arg = (ArgumentImpl) this.argumentBuilder.create(); + + assertEquals("incorrect validator", validator, arg.getValidator()); + } + + public void testNullValidator() { + try { + this.argumentBuilder.withValidator(null); + fail("cannot use null validator"); + } catch (IllegalArgumentException exp) { + assertEquals("wrong exception message", + resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR), + exp.getMessage()); + } + } +} diff --git a/src/test/org/apache/commons/cli2/commandline/ParserTest.java b/src/test/org/apache/commons/cli2/commandline/ParserTest.java index 0077f5df3..e6e46eb3e 100644 --- a/src/test/org/apache/commons/cli2/commandline/ParserTest.java +++ b/src/test/org/apache/commons/cli2/commandline/ParserTest.java @@ -1,140 +1,140 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.cli2.commandline; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; -import java.io.StringWriter; - -import org.apache.commons.cli2.CommandLine; -import org.apache.commons.cli2.Group; -import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.builder.DefaultOptionBuilder; -import org.apache.commons.cli2.builder.GroupBuilder; -import org.apache.commons.cli2.option.DefaultOption; -import org.apache.commons.cli2.util.HelpFormatter; - -import junit.framework.TestCase; - -public class ParserTest extends TestCase { - - private Parser parser; - private DefaultOption verboseOption; - private DefaultOption helpOption; - private Group options; - private HelpFormatter helpFormatter; - private StringWriter out; - private BufferedReader in; - - public void setUp() { - parser = new Parser(); - - final GroupBuilder gBuilder = new GroupBuilder(); - final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); - - helpOption = oBuilder.withLongName("help").withShortName("h").create(); - verboseOption = oBuilder.withLongName("verbose").withShortName("v").create(); - options = gBuilder.withOption(helpOption).withOption(verboseOption).create(); - parser.setGroup(options); - - helpFormatter = new HelpFormatter(); - out = new StringWriter(); - helpFormatter.setPrintWriter(new PrintWriter(out)); - parser.setHelpFormatter(helpFormatter); - } - - public void testParse_Successful() throws OptionException { - final CommandLine cl = parser.parse(new String[]{"-hv"}); - - assertTrue(cl.hasOption(helpOption)); - assertTrue(cl.hasOption(verboseOption)); - - assertEquals("--help --verbose",cl.toString()); - - final WriteableCommandLineImpl wcli = (WriteableCommandLineImpl)cl; - assertEquals("[--help, --verbose]",wcli.getNormalised().toString()); - } - - public void testParse_WithUnexpectedOption() { - try { - parser.parse(new String[]{"--unexpected"}); - fail("OptionException"); - } - catch(OptionException e) { - assertEquals(options,e.getOption()); - assertEquals("Unexpected --unexpected while processing --help|--verbose",e.getMessage()); - } - } - - public void testParseAndHelp_Successful() throws IOException { - final CommandLine cl = parser.parseAndHelp(new String[]{"-v"}); - - assertTrue(cl.hasOption(verboseOption)); - assertEquals("",out.getBuffer().toString()); - } - - public void testParseAndHelp_ByHelpOption() throws IOException { - parser.setHelpOption(helpOption); - - assertNull(parser.parseAndHelp(new String[]{"-hv"})); - - inReader(); - assertInReaderUsage(); - assertInReaderEOF(); - } - - public void testParseAndHelp_ByHelpTrigger() throws IOException { - parser.setHelpTrigger("--help"); - - assertNull(parser.parseAndHelp(new String[]{"-hv"})); - - inReader(); - assertInReaderUsage(); - assertInReaderEOF(); - } - - public void testParseAndHelp_WithUnexpectedOption() throws IOException { - assertNull(parser.parseAndHelp(new String[]{"--unexpected"})); - - inReader(); - assertInReaderLine("Unexpected --unexpected while processing --help|--verbose"); - assertInReaderUsage(); - assertInReaderEOF(); - } - - private void assertInReaderUsage() throws IOException { - assertInReaderLine("Usage:"); - assertInReaderLine("[--help --verbose]"); - assertInReaderLine("--help|--verbose"); - assertInReaderLine("--help (-h)"); - assertInReaderLine("--verbose (-v)"); - } - - private void assertInReaderLine(final String string) throws IOException { - assertEquals(string,in.readLine().trim()); - } - - private void assertInReaderEOF() throws IOException { - assertNull(in.readLine()); - } - - private void inReader() { - in = new BufferedReader(new StringReader(out.getBuffer().toString())); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.commandline; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.option.DefaultOption; +import org.apache.commons.cli2.util.HelpFormatter; + +import junit.framework.TestCase; + +public class ParserTest extends TestCase { + + private Parser parser; + private DefaultOption verboseOption; + private DefaultOption helpOption; + private Group options; + private HelpFormatter helpFormatter; + private StringWriter out; + private BufferedReader in; + + public void setUp() { + parser = new Parser(); + + final GroupBuilder gBuilder = new GroupBuilder(); + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + + helpOption = oBuilder.withLongName("help").withShortName("h").create(); + verboseOption = oBuilder.withLongName("verbose").withShortName("v").create(); + options = gBuilder.withOption(helpOption).withOption(verboseOption).create(); + parser.setGroup(options); + + helpFormatter = new HelpFormatter(); + out = new StringWriter(); + helpFormatter.setPrintWriter(new PrintWriter(out)); + parser.setHelpFormatter(helpFormatter); + } + + public void testParse_Successful() throws OptionException { + final CommandLine cl = parser.parse(new String[]{"-hv"}); + + assertTrue(cl.hasOption(helpOption)); + assertTrue(cl.hasOption(verboseOption)); + + assertEquals("--help --verbose",cl.toString()); + + final WriteableCommandLineImpl wcli = (WriteableCommandLineImpl)cl; + assertEquals("[--help, --verbose]",wcli.getNormalised().toString()); + } + + public void testParse_WithUnexpectedOption() { + try { + parser.parse(new String[]{"--unexpected"}); + fail("OptionException"); + } + catch(OptionException e) { + assertEquals(options,e.getOption()); + assertEquals("Unexpected --unexpected while processing --help|--verbose",e.getMessage()); + } + } + + public void testParseAndHelp_Successful() throws IOException { + final CommandLine cl = parser.parseAndHelp(new String[]{"-v"}); + + assertTrue(cl.hasOption(verboseOption)); + assertEquals("",out.getBuffer().toString()); + } + + public void testParseAndHelp_ByHelpOption() throws IOException { + parser.setHelpOption(helpOption); + + assertNull(parser.parseAndHelp(new String[]{"-hv"})); + + inReader(); + assertInReaderUsage(); + assertInReaderEOF(); + } + + public void testParseAndHelp_ByHelpTrigger() throws IOException { + parser.setHelpTrigger("--help"); + + assertNull(parser.parseAndHelp(new String[]{"-hv"})); + + inReader(); + assertInReaderUsage(); + assertInReaderEOF(); + } + + public void testParseAndHelp_WithUnexpectedOption() throws IOException { + assertNull(parser.parseAndHelp(new String[]{"--unexpected"})); + + inReader(); + assertInReaderLine("Unexpected --unexpected while processing --help|--verbose"); + assertInReaderUsage(); + assertInReaderEOF(); + } + + private void assertInReaderUsage() throws IOException { + assertInReaderLine("Usage:"); + assertInReaderLine("[--help --verbose]"); + assertInReaderLine("--help|--verbose"); + assertInReaderLine("--help (-h)"); + assertInReaderLine("--verbose (-v)"); + } + + private void assertInReaderLine(final String string) throws IOException { + assertEquals(string,in.readLine().trim()); + } + + private void assertInReaderEOF() throws IOException { + assertNull(in.readLine()); + } + + private void inReader() { + in = new BufferedReader(new StringReader(out.getBuffer().toString())); + } +} diff --git a/src/test/org/apache/commons/cli2/resource/TestBundle.properties b/src/test/org/apache/commons/cli2/resource/TestBundle.properties index 3ae6d180e..b005ad339 100644 --- a/src/test/org/apache/commons/cli2/resource/TestBundle.properties +++ b/src/test/org/apache/commons/cli2/resource/TestBundle.properties @@ -1,10 +1,10 @@ -ClassValidator.bad.classname = The class name "{0}" is invalid. - -test.message = Some might say we will find a brighter day. - -test.message1 = {0} might say we will find a brighter day. - -test.message2 = {0} {1} say we will find a brighter day. - -test.message3 = {0} {1} {2} we will find a brighter day. - +ClassValidator.bad.classname = The class name "{0}" is invalid. + +test.message = Some might say we will find a brighter day. + +test.message1 = {0} might say we will find a brighter day. + +test.message2 = {0} {1} say we will find a brighter day. + +test.message3 = {0} {1} {2} we will find a brighter day. + From d7868443b4071ef79e31b8f1b18501d7ad3e8ded Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Sat, 22 Mar 2008 11:14:26 +0000 Subject: [PATCH 0075/1663] Add source file headers to reduce the noise from the RAT report git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639978 13f79535-47bb-0310-9956-ffa450edef68 --- doap_cli.rdf | 16 ++++++++++++++++ project.properties | 15 +++++++++++++++ .../resource/CLIMessageBundle_en_US.properties | 15 +++++++++++++++ .../apache/commons/cli2/validation/package.html | 16 ++++++++++++++++ .../apache/commons/cli2/bug/BugCLI122Test.java | 16 ++++++++++++++++ .../commons/cli2/resource/TestBundle.properties | 15 +++++++++++++++ 6 files changed, 93 insertions(+) diff --git a/doap_cli.rdf b/doap_cli.rdf index 5b246e680..5fa977356 100644 --- a/doap_cli.rdf +++ b/doap_cli.rdf @@ -1,4 +1,20 @@ + Apache Commons CLI diff --git a/project.properties b/project.properties index c4e10c2b0..0dbaa684a 100644 --- a/project.properties +++ b/project.properties @@ -1,3 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + # ------------------------------------------------------------------- # P R O J E C T P R O P E R T I E S # ------------------------------------------------------------------- diff --git a/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties b/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties index 443616288..e7b5ff753 100644 --- a/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties +++ b/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties @@ -1,3 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + ClassValidator.bad.classname = The class name "{0}" is invalid. ClassValidator.class.notfound = The class "{0}" could not be found. ClassValidator.class.access = The class "{0}" could not be accessed. Reason: {1}. diff --git a/src/java/org/apache/commons/cli2/validation/package.html b/src/java/org/apache/commons/cli2/validation/package.html index d54223cac..eb7d89bbb 100644 --- a/src/java/org/apache/commons/cli2/validation/package.html +++ b/src/java/org/apache/commons/cli2/validation/package.html @@ -1,3 +1,19 @@ + Provides classes and interfaces for validating argument values. diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java index 5e818e6f3..61effe668 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI122Test.java @@ -1,3 +1,19 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.commons.cli2.bug; import junit.framework.TestCase; diff --git a/src/test/org/apache/commons/cli2/resource/TestBundle.properties b/src/test/org/apache/commons/cli2/resource/TestBundle.properties index b005ad339..3bb321552 100644 --- a/src/test/org/apache/commons/cli2/resource/TestBundle.properties +++ b/src/test/org/apache/commons/cli2/resource/TestBundle.properties @@ -1,3 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + ClassValidator.bad.classname = The class name "{0}" is invalid. test.message = Some might say we will find a brighter day. From 6e11746375c1f3738a1ffb5982b320affb92c0bd Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Sat, 22 Mar 2008 11:17:55 +0000 Subject: [PATCH 0076/1663] Add checkstyle, findbugs and cobertura reports git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639979 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/pom.xml b/pom.xml index 6c3dc05dd..f3745f628 100644 --- a/pom.xml +++ b/pom.xml @@ -198,6 +198,29 @@ + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.1 + + checkstyle.xml + false + + + + org.codehaus.mojo + findbugs-maven-plugin + 1.1.1 + + Normal + Default + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.2 + From c851091864d903229ebd16656a40b28de6e56846 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Sat, 22 Mar 2008 12:00:48 +0000 Subject: [PATCH 0077/1663] Remove tab characters git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639981 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli2/Option.java | 14 +- .../commons/cli2/builder/ArgumentBuilder.java | 58 ++--- .../commandline/DefaultingCommandLine.java | 6 +- .../commandline/PreferencesCommandLine.java | 212 +++++++++--------- .../commandline/PropertiesCommandLine.java | 182 +++++++-------- .../commons/cli2/option/ArgumentImpl.java | 6 +- .../commons/cli2/resource/ResourceHelper.java | 10 +- .../apache/commons/cli2/util/Comparators.java | 6 +- 8 files changed, 247 insertions(+), 247 deletions(-) diff --git a/src/java/org/apache/commons/cli2/Option.java b/src/java/org/apache/commons/cli2/Option.java index e191c2fec..96c50c601 100644 --- a/src/java/org/apache/commons/cli2/Option.java +++ b/src/java/org/apache/commons/cli2/Option.java @@ -181,13 +181,13 @@ void appendUsage( */ int getId(); - /** - * Recursively searches for an option with the supplied trigger. - * - * @param trigger the trigger to search for. - * @return the matching option or null. - */ - Option findOption(final String trigger); + /** + * Recursively searches for an option with the supplied trigger. + * + * @param trigger the trigger to search for. + * @return the matching option or null. + */ + Option findOption(final String trigger); /** * Indicates whether this option is required to be present. diff --git a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java b/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java index f0fd8cf2a..c0f28fd27 100644 --- a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java @@ -30,8 +30,8 @@ */ public class ArgumentBuilder { - /** i18n */ - private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); + /** i18n */ + private final static ResourceHelper resources = ResourceHelper.getResourceHelper(); /** name of the argument. Used for display and lookups in CommandLine */ private String name; @@ -124,12 +124,12 @@ public final ArgumentBuilder reset() { * @return this ArgumentBuilder */ public final ArgumentBuilder withName(final String newName) { - if (newName == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME)); - } - if ("".equals(newName)) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME)); - } + if (newName == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_NAME)); + } + if ("".equals(newName)) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_NAME)); + } this.name = newName; return this; } @@ -154,9 +154,9 @@ public final ArgumentBuilder withDescription(final String newDescription) { * @return this ArgumentBuilder */ public final ArgumentBuilder withMinimum(final int newMinimum) { - if (newMinimum < 0) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM)); - } + if (newMinimum < 0) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MINIMUM)); + } this.minimum = newMinimum; return this; } @@ -168,9 +168,9 @@ public final ArgumentBuilder withMinimum(final int newMinimum) { * @return this ArgumentBuilder */ public final ArgumentBuilder withMaximum(final int newMaximum) { - if (newMaximum < 0) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM)); - } + if (newMaximum < 0) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NEGATIVE_MAXIMUM)); + } this.maximum = newMaximum; return this; } @@ -215,9 +215,9 @@ public final ArgumentBuilder withSubsequentSeparator( * @return this ArgumentBuilder */ public final ArgumentBuilder withValidator(final Validator newValidator) { - if (newValidator == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR)); - } + if (newValidator == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_VALIDATOR)); + } this.validator = newValidator; return this; } @@ -231,12 +231,12 @@ public final ArgumentBuilder withValidator(final Validator newValidator) { * @return this ArgumentBuilder */ public final ArgumentBuilder withConsumeRemaining(final String newConsumeRemaining) { - if (newConsumeRemaining == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING)); - } - if ( "".equals(newConsumeRemaining)) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING)); - } + if (newConsumeRemaining == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_CONSUME_REMAINING)); + } + if ( "".equals(newConsumeRemaining)) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_EMPTY_CONSUME_REMAINING)); + } this.consumeRemaining = newConsumeRemaining; return this; } @@ -248,9 +248,9 @@ public final ArgumentBuilder withConsumeRemaining(final String newConsumeRemaini * @return this ArgumentBuilder */ public final ArgumentBuilder withDefault(final Object defaultValue) { - if (defaultValue == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT)); - } + if (defaultValue == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULT)); + } if (this.defaultValues == null) { this.defaultValues = new ArrayList(1); @@ -266,9 +266,9 @@ public final ArgumentBuilder withDefault(final Object defaultValue) { * @return this ArgumentBuilder */ public final ArgumentBuilder withDefaults(final List newDefaultValues) { - if (newDefaultValues == null) { - throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS)); - } + if (newDefaultValues == null) { + throw new IllegalArgumentException(resources.getMessage(ResourceConstants.ARGUMENT_BUILDER_NULL_DEFAULTS)); + } this.defaultValues = newDefaultValues; return this; } diff --git a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java b/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java index 3ca3e686c..d9f74329b 100644 --- a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java @@ -74,7 +74,7 @@ public void insertCommandLine( * @return an unmodifiable iterator */ public Iterator commandLines(){ - return Collections.unmodifiableList(commandLines).iterator(); + return Collections.unmodifiableList(commandLines).iterator(); } public Option getOption(String trigger) { @@ -132,10 +132,10 @@ public List getValues(Option option, List defaultValues) { } } if(defaultValues==null){ - return Collections.EMPTY_LIST; + return Collections.EMPTY_LIST; } else{ - return defaultValues; + return defaultValues; } } diff --git a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java b/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java index 14e2c9c7d..65448e9b9 100644 --- a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java @@ -48,21 +48,21 @@ */ public class PreferencesCommandLine extends CommandLineImpl { - private static final char NUL = '\0'; - private final Preferences preferences; - private final Option root; - private final char separator; + private static final char NUL = '\0'; + private final Preferences preferences; + private final Option root; + private final char separator; - /** + /** * Creates a new PreferencesCommandLine using the specified root Option and * Preferences node. Argument values will be separated using the char 0. * - * @param root the CommandLine's root Option - * @param preferences the Preferences node to get values from - */ - public PreferencesCommandLine(final Option root, final Preferences preferences){ - this(root,preferences,NUL); - } + * @param root the CommandLine's root Option + * @param preferences the Preferences node to get values from + */ + public PreferencesCommandLine(final Option root, final Preferences preferences){ + this(root,preferences,NUL); + } /** * Creates a new PreferencesCommandLine using the specified root Option, @@ -72,99 +72,99 @@ public PreferencesCommandLine(final Option root, final Preferences preferences){ * @param preferences the Preferences node to get values from * @param separator the character to split argument values */ - public PreferencesCommandLine(final Option root, final Preferences preferences, final char separator){ - this.root = root; - this.preferences = preferences; - this.separator = separator; - } - - public boolean hasOption(Option option) { - if(option==null){ - return false; - } - else{ - try { - return Arrays.asList(preferences.keys()).contains(option.getPreferredName()); - } catch (BackingStoreException e) { - return false; - } - } - } - - public Option getOption(String trigger) { - return root.findOption(trigger); - } - - public List getValues(final Option option, final List defaultValues) { - final String value = preferences.get(option.getPreferredName(),null); - - if(value==null){ - return defaultValues; - } - else if(separator>NUL){ - final List values = new ArrayList(); - final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); - - while(tokens.hasMoreTokens()){ - values.add(tokens.nextToken()); - } - - return values; - } - else{ - return Collections.singletonList(value); - } - } - - public Boolean getSwitch(final Option option, final Boolean defaultValue) { - final String value = preferences.get(option.getPreferredName(),null); - if("true".equals(value)){ - return Boolean.TRUE; - } - else if("false".equals(value)){ - return Boolean.FALSE; - } - else{ - return defaultValue; - } - } - - public String getProperty(final String property, final String defaultValue) { - return preferences.get(property, defaultValue); - } - - public Set getProperties() { - try { - return new HashSet(Arrays.asList(preferences.keys())); - } catch (BackingStoreException e) { - return Collections.EMPTY_SET; - } - } - - public List getOptions() { - try { - final List options = new ArrayList(); - final Iterator keys = Arrays.asList(preferences.keys()).iterator(); - while (keys.hasNext()) { - final String trigger = (String) keys.next(); - final Option option = root.findOption(trigger); - if (option != null) { - options.add(option); - } - } - return Collections.unmodifiableList(options); - } catch (BackingStoreException e) { - return Collections.EMPTY_LIST; - } - } - - public Set getOptionTriggers() { - final Set triggers = new HashSet(); - final Iterator options = getOptions().iterator(); - while(options.hasNext()){ - final Option option = (Option)options.next(); - triggers.addAll(option.getTriggers()); - } - return Collections.unmodifiableSet(triggers); - } + public PreferencesCommandLine(final Option root, final Preferences preferences, final char separator){ + this.root = root; + this.preferences = preferences; + this.separator = separator; + } + + public boolean hasOption(Option option) { + if(option==null){ + return false; + } + else{ + try { + return Arrays.asList(preferences.keys()).contains(option.getPreferredName()); + } catch (BackingStoreException e) { + return false; + } + } + } + + public Option getOption(String trigger) { + return root.findOption(trigger); + } + + public List getValues(final Option option, final List defaultValues) { + final String value = preferences.get(option.getPreferredName(),null); + + if(value==null){ + return defaultValues; + } + else if(separator>NUL){ + final List values = new ArrayList(); + final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); + + while(tokens.hasMoreTokens()){ + values.add(tokens.nextToken()); + } + + return values; + } + else{ + return Collections.singletonList(value); + } + } + + public Boolean getSwitch(final Option option, final Boolean defaultValue) { + final String value = preferences.get(option.getPreferredName(),null); + if("true".equals(value)){ + return Boolean.TRUE; + } + else if("false".equals(value)){ + return Boolean.FALSE; + } + else{ + return defaultValue; + } + } + + public String getProperty(final String property, final String defaultValue) { + return preferences.get(property, defaultValue); + } + + public Set getProperties() { + try { + return new HashSet(Arrays.asList(preferences.keys())); + } catch (BackingStoreException e) { + return Collections.EMPTY_SET; + } + } + + public List getOptions() { + try { + final List options = new ArrayList(); + final Iterator keys = Arrays.asList(preferences.keys()).iterator(); + while (keys.hasNext()) { + final String trigger = (String) keys.next(); + final Option option = root.findOption(trigger); + if (option != null) { + options.add(option); + } + } + return Collections.unmodifiableList(options); + } catch (BackingStoreException e) { + return Collections.EMPTY_LIST; + } + } + + public Set getOptionTriggers() { + final Set triggers = new HashSet(); + final Iterator options = getOptions().iterator(); + while(options.hasNext()){ + final Option option = (Option)options.next(); + triggers.addAll(option.getTriggers()); + } + return Collections.unmodifiableSet(triggers); + } } diff --git a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java b/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java index 28cf79279..f019d1ac9 100644 --- a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java @@ -44,10 +44,10 @@ */ public class PropertiesCommandLine extends CommandLineImpl { - private static final char NUL = '\0'; - private final Properties properties; - private final Option root; - private final char separator; + private static final char NUL = '\0'; + private final Properties properties; + private final Option root; + private final char separator; /** * Creates a new PropertiesCommandLine using the specified root Option, @@ -56,9 +56,9 @@ public class PropertiesCommandLine extends CommandLineImpl { * @param root the CommandLine's root Option * @param properties the Properties instance to get values from */ - public PropertiesCommandLine(final Option root, final Properties properties){ - this(root,properties,NUL); - } + public PropertiesCommandLine(final Option root, final Properties properties){ + this(root,properties,NUL); + } /** * Creates a new PropertiesCommandLine using the specified root Option, @@ -68,88 +68,88 @@ public PropertiesCommandLine(final Option root, final Properties properties){ * @param properties the Properties instance to get values from * @param separator the character to split argument values */ - public PropertiesCommandLine(final Option root, final Properties properties, final char separator){ - this.root = root; - this.properties = properties; - this.separator = separator; - } - - - public boolean hasOption(Option option) { - if(option==null){ - return false; - } - else{ - return properties.containsKey(option.getPreferredName()); - } - } - - public Option getOption(String trigger) { - return root.findOption(trigger); - } - - public List getValues(final Option option, final List defaultValues) { - final String value = properties.getProperty(option.getPreferredName()); - - if(value==null){ - return defaultValues; - } - else if(separator>NUL){ - final List values = new ArrayList(); - final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); - - while(tokens.hasMoreTokens()){ - values.add(tokens.nextToken()); - } - - return values; - } - else{ - return Collections.singletonList(value); - } - } - - public Boolean getSwitch(final Option option, final Boolean defaultValue) { - final String value = properties.getProperty(option.getPreferredName()); - if("true".equals(value)){ - return Boolean.TRUE; - } - else if("false".equals(value)){ - return Boolean.FALSE; - } - else{ - return defaultValue; - } - } - - public String getProperty(final String property, final String defaultValue) { - return properties.getProperty(property,defaultValue); - } - - public Set getProperties() { - return properties.keySet(); - } - - public List getOptions() { - final List options = new ArrayList(); - final Iterator keys = properties.keySet().iterator(); - while(keys.hasNext()){ - final String trigger = (String)keys.next(); - final Option option = root.findOption(trigger); - if(option!=null){ - options.add(option); - } - } - return Collections.unmodifiableList(options); - } - - public Set getOptionTriggers() { - final Set triggers = new HashSet(); - final Iterator options = getOptions().iterator(); - while(options.hasNext()){ - final Option option = (Option)options.next(); - triggers.addAll(option.getTriggers()); - } - return Collections.unmodifiableSet(triggers); - } + public PropertiesCommandLine(final Option root, final Properties properties, final char separator){ + this.root = root; + this.properties = properties; + this.separator = separator; + } + + + public boolean hasOption(Option option) { + if(option==null){ + return false; + } + else{ + return properties.containsKey(option.getPreferredName()); + } + } + + public Option getOption(String trigger) { + return root.findOption(trigger); + } + + public List getValues(final Option option, final List defaultValues) { + final String value = properties.getProperty(option.getPreferredName()); + + if(value==null){ + return defaultValues; + } + else if(separator>NUL){ + final List values = new ArrayList(); + final StringTokenizer tokens = new StringTokenizer(value,String.valueOf(separator)); + + while(tokens.hasMoreTokens()){ + values.add(tokens.nextToken()); + } + + return values; + } + else{ + return Collections.singletonList(value); + } + } + + public Boolean getSwitch(final Option option, final Boolean defaultValue) { + final String value = properties.getProperty(option.getPreferredName()); + if("true".equals(value)){ + return Boolean.TRUE; + } + else if("false".equals(value)){ + return Boolean.FALSE; + } + else{ + return defaultValue; + } + } + + public String getProperty(final String property, final String defaultValue) { + return properties.getProperty(property,defaultValue); + } + + public Set getProperties() { + return properties.keySet(); + } + + public List getOptions() { + final List options = new ArrayList(); + final Iterator keys = properties.keySet().iterator(); + while(keys.hasNext()){ + final String trigger = (String)keys.next(); + final Option option = root.findOption(trigger); + if(option!=null){ + options.add(option); + } + } + return Collections.unmodifiableList(options); + } + + public Set getOptionTriggers() { + final Set triggers = new HashSet(); + final Iterator options = getOptions().iterator(); + while(options.hasNext()){ + final Option option = (Option)options.next(); + triggers.addAll(option.getTriggers()); + } + return Collections.unmodifiableSet(triggers); + } } diff --git a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java index c3fc05cac..089099162 100644 --- a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java @@ -215,15 +215,15 @@ public Set getTriggers() { } public String getConsumeRemaining() { - return this.consumeRemaining; + return this.consumeRemaining; } public List getDefaultValues() { - return this.defaultValues; + return this.defaultValues; } public Validator getValidator() { - return this.validator; + return this.validator; } public void validate(final WriteableCommandLine commandLine) diff --git a/src/java/org/apache/commons/cli2/resource/ResourceHelper.java b/src/java/org/apache/commons/cli2/resource/ResourceHelper.java index 804958e70..92c4c9e1e 100644 --- a/src/java/org/apache/commons/cli2/resource/ResourceHelper.java +++ b/src/java/org/apache/commons/cli2/resource/ResourceHelper.java @@ -58,12 +58,12 @@ private ResourceHelper() { Locale locale; if (firstUnderscore != -1) { - String language = bundleName.substring(firstUnderscore + 1, secondUnderscore); - String country = bundleName.substring(secondUnderscore + 1); - locale = new Locale(language, country); + String language = bundleName.substring(firstUnderscore + 1, secondUnderscore); + String country = bundleName.substring(secondUnderscore + 1); + locale = new Locale(language, country); } else { - locale = Locale.getDefault(); + locale = Locale.getDefault(); } // initialize the bundle try { @@ -74,7 +74,7 @@ private ResourceHelper() { } public String getBundleName() { - return this.prop; + return this.prop; } /** diff --git a/src/java/org/apache/commons/cli2/util/Comparators.java b/src/java/org/apache/commons/cli2/util/Comparators.java index 3943d8873..ed88dfda4 100644 --- a/src/java/org/apache/commons/cli2/util/Comparators.java +++ b/src/java/org/apache/commons/cli2/util/Comparators.java @@ -30,9 +30,9 @@ */ public class Comparators { - private Comparators(){ - // constructor hiden from potential users - } + private Comparators(){ + // constructor hiden from potential users + } /** From ec2631b8e2fbcd359073f5385852c50229959372 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Sat, 22 Mar 2008 12:10:28 +0000 Subject: [PATCH 0078/1663] Correct property name which changed in last release of commons-parent git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@639982 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f3745f628..9be02d1a5 100644 --- a/pom.xml +++ b/pom.xml @@ -131,7 +131,7 @@ cli - org.apache.commons.cli2 + org.apache.commons.cli2 1.1 CLI From c221842ad13b572d9ab6e896664e3c09ce57e4a6 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Fri, 25 Apr 2008 11:12:33 +0000 Subject: [PATCH 0079/1663] CLI-153 set svn:eol-style to native - thanks to Benjamin Bentmann for the patch git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@651574 13f79535-47bb-0310-9956-ffa450edef68 --- .../cli2/resource/ResourceHelperTest.java | 168 +++++++++--------- 1 file changed, 84 insertions(+), 84 deletions(-) diff --git a/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java b/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java index 38223d79b..1bc28873d 100644 --- a/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java +++ b/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java @@ -1,84 +1,84 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.commons.cli2.resource; - -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -import junit.framework.TestCase; - -/** - * A utility class used to provide internationalisation support. - * - * @author John Keyes - */ -public class ResourceHelperTest extends TestCase { - /** system property */ - private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle"; - - private static ResourceHelper helper; - - /** resource bundle */ - private ResourceBundle bundle; - - public void setUp() { - System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.TestBundle"); - helper = ResourceHelper.getResourceHelper(); - } - - public void tearDown() { - System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.CLIMessageBundle_en_US.properties"); - } - - /** - * Create a new ResourceHelper for the specified class. - * - * @param clazz the Class that requires some resources - */ - public ResourceHelperTest() { - super("ResourceHelperTest"); - } - - public void testOverridden() { - assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); - } - - public void testNewMessage1Param() { - assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message")); - } - - public void testNewMessage2Params() { - assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some")); - } - - public void testNewMessage3Params() { - assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might")); - } - - public void testNewMessage4Params() { - assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might", "say")); - } - - public void testDefaultBundle() { - System.setProperty(PROP_LOCALE, "madeupname.properties"); - helper = ResourceHelper.getResourceHelper(); - assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.cli2.resource; + +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +import junit.framework.TestCase; + +/** + * A utility class used to provide internationalisation support. + * + * @author John Keyes + */ +public class ResourceHelperTest extends TestCase { + /** system property */ + private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle"; + + private static ResourceHelper helper; + + /** resource bundle */ + private ResourceBundle bundle; + + public void setUp() { + System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.TestBundle"); + helper = ResourceHelper.getResourceHelper(); + } + + public void tearDown() { + System.setProperty(PROP_LOCALE, "org.apache.commons.cli2.resource.CLIMessageBundle_en_US.properties"); + } + + /** + * Create a new ResourceHelper for the specified class. + * + * @param clazz the Class that requires some resources + */ + public ResourceHelperTest() { + super("ResourceHelperTest"); + } + + public void testOverridden() { + assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); + } + + public void testNewMessage1Param() { + assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message")); + } + + public void testNewMessage2Params() { + assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some")); + } + + public void testNewMessage3Params() { + assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might")); + } + + public void testNewMessage4Params() { + assertEquals("wrong message", "Some might say we will find a brighter day.", helper.getMessage("test.message", "Some", "might", "say")); + } + + public void testDefaultBundle() { + System.setProperty(PROP_LOCALE, "madeupname.properties"); + helper = ResourceHelper.getResourceHelper(); + assertEquals("wrong message", "The class name \"ResourceHelper\" is invalid.", helper.getMessage("ClassValidator.bad.classname", "ResourceHelper")); + } +} From bc4c9009dc179277dbf3eab6296f198d75034fb1 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Thu, 8 May 2008 06:59:48 +0000 Subject: [PATCH 0080/1663] Fixing getValue to getOptionValue as per CLI-154 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@654432 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/usage.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xdocs/usage.xml b/xdocs/usage.xml index 0335fe37d..dcbc7a305 100644 --- a/xdocs/usage.xml +++ b/xdocs/usage.xml @@ -260,12 +260,12 @@ options.addOption( property );

        To see if an option has been passed the hasOption method is used. The argument value can be retrieved using - the getValue method. + the getOptionValue method.

        // has the buildfile argument been passed? if( line.hasOption( "buildfile" ) ) { // initialise the member variable - this.buildfile = line.getValue( "buildfile" ); + this.buildfile = line.getOptionValue( "buildfile" ); } From 71b23e2a506797386c28d0062231c07106325962 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Thu, 8 May 2008 11:43:09 +0000 Subject: [PATCH 0081/1663] Upgrade to commons-parent-10 pom git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@654484 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9be02d1a5..018f2c76b 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.apache.commons commons-parent - 9 + 10 4.0.0 commons-cli From 0d1361a0b4c95f8961d249e86578748f3a9295c3 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Fri, 23 May 2008 06:10:00 +0000 Subject: [PATCH 0082/1663] COMMONSSITE-30 - fix the checkstyle configuration to work for multi-module and review/update plugin version numbers for the poms being changed. - pom's need to use ${basedir} for configuration files as the multi-module profile is run from commons-parent, so if not specified it can't find those files - the checkstyle configuration file needs to use ${checkstyle.header.file} for the headerFile property and element added to the plugin config in the pom.xml - fix m1 checkstyle config to reflect the above where appropriate (specify header file property) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@659438 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 018f2c76b..3aeaa73eb 100644 --- a/pom.xml +++ b/pom.xml @@ -186,6 +186,7 @@ org.apache.maven.plugins maven-changes-plugin + 2.0 ${basedir}/xdocs/changes.xml %URL%/%ISSUE% @@ -203,14 +204,14 @@ maven-checkstyle-plugin 2.1 - checkstyle.xml + ${basedir}/checkstyle.xml false org.codehaus.mojo findbugs-maven-plugin - 1.1.1 + 1.2 Normal Default From 53afe2b8584ad1b033e10eab8575591346c9f693 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Wed, 28 May 2008 08:38:06 +0000 Subject: [PATCH 0083/1663] Never released, so might as well be org.apache.commons git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@660860 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3aeaa73eb..9fa674200 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ 10 4.0.0 - commons-cli + org.apache.commons.commons-cli commons-cli 2.0-SNAPSHOT Commons CLI From 1444af426be482392ac423020bc2e11f95d03adb Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Wed, 28 May 2008 08:55:45 +0000 Subject: [PATCH 0084/1663] Commenting out findbugs as it OOMs for me git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@660868 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index 9fa674200..161842c13 100644 --- a/pom.xml +++ b/pom.xml @@ -208,6 +208,7 @@ false + org.codehaus.mojo cobertura-maven-plugin From 10135cb5a2ec40168207b6f4abe903ee4d795fc7 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Wed, 28 May 2008 16:02:54 +0000 Subject: [PATCH 0085/1663] Removing extra commons-cli - thanks Rahul git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@660997 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 161842c13..2b992eed0 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ 10 4.0.0 - org.apache.commons.commons-cli + org.apache.commons commons-cli 2.0-SNAPSHOT Commons CLI From f836d0e59f34fdf383211e3c5f2febd6c74d523e Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Thu, 29 May 2008 11:02:07 +0000 Subject: [PATCH 0086/1663] Added an external link to the JDK for the javadoc git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@661291 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pom.xml b/pom.xml index 2b992eed0..d1abf1452 100644 --- a/pom.xml +++ b/pom.xml @@ -183,6 +183,16 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + + true + + http://java.sun.com/javase/6/docs/api + + + org.apache.maven.plugins maven-changes-plugin From d0897140df5a26a5c0580c5ccf062017de5814dc Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Thu, 29 May 2008 11:56:41 +0000 Subject: [PATCH 0087/1663] Updated the changelog for CLI 1.x git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@661307 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/changes.xml | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/xdocs/changes.xml b/xdocs/changes.xml index c3e400a7e..88186179b 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -21,8 +21,29 @@ Commons CLI Release Notes
        - + + + + The ordering of options can be defined in help messages. + + + The line wrapping in HelpFormatter now works properly. + + + The message of MissingOptionException has been improved. + + + Option.toString() now reports arguments properly. + + + The Parser class has been changed to be more easily extendable. + + + The following classes are now serializable: Option, OptionGroup, CommandLine and Options. + + + + Wrong usage summary. Dependecy on commons-lang-2.0 but commons-lang-1.0 is obtained. From 8021d1259124c4f7e0bb54c44d16a30aca853ee6 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Thu, 29 May 2008 13:59:17 +0000 Subject: [PATCH 0088/1663] Updated changes.xml for the fix for CLI-156 applied on the 1.x branch git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@661336 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/changes.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 88186179b..f9d877460 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -23,6 +23,9 @@ + + Required options are properly checked if an Options instance is used twice to parse a command line. + The ordering of options can be defined in help messages. From 2b4fb79570bb7f14c8bfe8c634c0f7d9fe7d0af7 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Fri, 30 May 2008 06:10:14 +0000 Subject: [PATCH 0089/1663] Switching the documentation from .hasArg to .hasArgs as per CLI-154 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@661573 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/usage.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xdocs/usage.xml b/xdocs/usage.xml index dcbc7a305..970245f2b 100644 --- a/xdocs/usage.xml +++ b/xdocs/usage.xml @@ -200,7 +200,7 @@ Option find = OptionBuilder.withArgName( "file" ) using the OptionBuilder.

        Option property = OptionBuilder.withArgName( "property=value" ) - .hasArg() + .hasArgs() .withValueSeparator() .withDescription( "use value for given property" ) .create( "D" ); From e2ba946ea0e01c36c84f97f483e1d22cfd64b917 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 9 Jun 2008 07:27:02 +0000 Subject: [PATCH 0090/1663] Applying Brian Egge's patch to CLI-145, fixing things so the withMinimum/withMaximum works correctly git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@664644 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli2/OptionException.java | 8 ++ .../commons/cli2/option/ArgumentImpl.java | 3 +- .../commons/cli2/bug/BugCLI145Test.java | 118 ++++++++++++++++++ .../bug/BugLoopingOptionLookAlikeTest.java | 5 +- 4 files changed, 131 insertions(+), 3 deletions(-) create mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI145Test.java diff --git a/src/java/org/apache/commons/cli2/OptionException.java b/src/java/org/apache/commons/cli2/OptionException.java index 15b408ba9..4617f3a39 100644 --- a/src/java/org/apache/commons/cli2/OptionException.java +++ b/src/java/org/apache/commons/cli2/OptionException.java @@ -43,6 +43,9 @@ public class OptionException /** The message explaining the Exception */ private final String message; + /** The id of the message */ + private final String messageKey; + /** * Creates a new OptionException. * @@ -73,6 +76,7 @@ public OptionException(final Option option, final String messageKey, final String value) { this.option = option; + this.messageKey = messageKey; if (messageKey != null) { final StringBuffer buffer = new StringBuffer(); @@ -104,4 +108,8 @@ public Option getOption() { public String getMessage() { return message; } + + public String getMessageKey() { + return messageKey; + } } diff --git a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java index 089099162..0b05ad7b8 100644 --- a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java @@ -140,7 +140,8 @@ public void processValues(final WriteableCommandLine commandLine, final ListIterator arguments, final Option option) throws OptionException { - int argumentCount = commandLine.getValues(option, Collections.EMPTY_LIST).size(); + // count of arguments processed for this option. + int argumentCount = 0; while (arguments.hasNext() && (argumentCount < maximum)) { final String allValuesQuoted = (String) arguments.next(); diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI145Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI145Test.java new file mode 100644 index 000000000..2206fa76e --- /dev/null +++ b/src/test/org/apache/commons/cli2/bug/BugCLI145Test.java @@ -0,0 +1,118 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.option.DefaultOption; + +import java.util.List; + +/** + * ArgumentBuilder.withMaximum causes parse errors: Unexpeced while processing options + * + * @author David Biesack + * @author brianegge + */ +public class BugCLI145Test extends TestCase { + public void testWithMaximum() { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + DefaultOption aOption = obuilder// + .withShortName("a") + .withLongName("a") + .withArgument(abuilder + .withName("a") + .withDefault("10") + .create()) + .create(); + DefaultOption bOption = obuilder + .withShortName("b") + .withLongName("b") + .withArgument(abuilder + .withName("b") + .withMinimum(2) + .withMaximum(4) + .withDefault("100") + .withDefault("1000") + .withDefault("10000") + .withDefault("1000000") + .create()) + .create(); + Group options = gbuilder + .withName("options") + .withOption(aOption) + .withOption(bOption) + .create(); + Parser parser = new Parser(); + parser.setHelpTrigger("--help"); + parser.setGroup(options); + CommandLine cl = parser.parseAndHelp("-a 0 -b 1 2 3 4".split(" ")); + assertNotNull(cl); + int a = Integer.parseInt(cl.getValue(aOption).toString()); + List b = cl.getValues(bOption); + assertEquals(0, a); + assertEquals(4, b.size()); + } + + public void testWithMaximumUsingDefaultValues() { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + DefaultOption aOption = obuilder// + .withShortName("a") + .withLongName("a") + .withArgument(abuilder + .withName("a") + .withDefault("10") + .create()) + .create(); + DefaultOption bOption = obuilder + .withShortName("b") + .withLongName("b") + .withArgument(abuilder + .withName("b") + .withMinimum(2) + .withMaximum(4) + .withDefault("100") + .withDefault("1000") + .withDefault("10000") + .create()) + .create(); + Group options = gbuilder + .withName("options") + .withOption(aOption) + .withOption(bOption) + .create(); + Parser parser = new Parser(); + parser.setHelpTrigger("--help"); + parser.setGroup(options); + CommandLine cl = parser.parseAndHelp("-a -b".split(" ")); + assertNotNull(cl); + int a = Integer.parseInt(cl.getValue(aOption).toString()); + List b = cl.getValues(bOption); + assertEquals(10, a); + assertEquals(3, b.size()); + assertEquals("10000", b.get(2)); + } +} diff --git a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java index aa684554b..4c577acf7 100644 --- a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java +++ b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java @@ -23,6 +23,7 @@ import org.apache.commons.cli2.Argument; import org.apache.commons.cli2.Group; import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.resource.ResourceConstants; import org.apache.commons.cli2.builder.ArgumentBuilder; import org.apache.commons.cli2.builder.DefaultOptionBuilder; import org.apache.commons.cli2.builder.GroupBuilder; @@ -31,7 +32,7 @@ /** * The first is a loop in Parser.parse() if I set a non-declared option. This - * code goes into a loop in Parser.java method parse this “while” loop runs + * code goes into a loop in Parser.java method parse this 'while' loop runs * endless * * @author Steve Alberty @@ -73,7 +74,7 @@ public void testLoopingOptionLookAlike2() { parser.parse(new String[] { "testfile.txt", "testfile.txt", "testfile.txt", "testfile.txt" }); fail("OptionException"); } catch (OptionException e) { - assertEquals("Unexpected testfile.txt while processing ", e.getMessage()); + assertEquals(ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, e.getMessageKey()); } } } From 538fb6889f0387a40b821cfb315685e929110736 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 9 Jun 2008 07:37:19 +0000 Subject: [PATCH 0091/1663] Applying Andrew's fix to CLI-61 and rolling back the getMessageKey addition to OptionException that was applied from CLI-145 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@664646 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli2/OptionException.java | 7 ------- .../apache/commons/cli2/WriteableCommandLine.java | 10 ++++++++++ .../cli2/commandline/WriteableCommandLineImpl.java | 12 ++++++++++++ .../org/apache/commons/cli2/option/ArgumentImpl.java | 2 +- .../cli2/bug/BugLoopingOptionLookAlikeTest.java | 3 +-- 5 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/java/org/apache/commons/cli2/OptionException.java b/src/java/org/apache/commons/cli2/OptionException.java index 4617f3a39..e5f867b03 100644 --- a/src/java/org/apache/commons/cli2/OptionException.java +++ b/src/java/org/apache/commons/cli2/OptionException.java @@ -43,9 +43,6 @@ public class OptionException /** The message explaining the Exception */ private final String message; - /** The id of the message */ - private final String messageKey; - /** * Creates a new OptionException. * @@ -76,7 +73,6 @@ public OptionException(final Option option, final String messageKey, final String value) { this.option = option; - this.messageKey = messageKey; if (messageKey != null) { final StringBuffer buffer = new StringBuffer(); @@ -109,7 +105,4 @@ public String getMessage() { return message; } - public String getMessageKey() { - return messageKey; - } } diff --git a/src/java/org/apache/commons/cli2/WriteableCommandLine.java b/src/java/org/apache/commons/cli2/WriteableCommandLine.java index a8f756d88..a70c8d620 100644 --- a/src/java/org/apache/commons/cli2/WriteableCommandLine.java +++ b/src/java/org/apache/commons/cli2/WriteableCommandLine.java @@ -36,6 +36,16 @@ public interface WriteableCommandLine extends CommandLine { */ void addValue(final Option option, final Object value); + /** + * Retrieves the Argument values specified on the command line for the + * specified Option, this doesn't return any values supplied + * programmatically as defaults. + * + * @param option the Option associated with the values + * @return a list of values or an empty List if none are found + */ + List getUndefaultedValues(final Option option); + /** * Sets the default values for an Option in the CommandLine * @param option the Option to add to diff --git a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java index bb1610e16..97a5d1124 100644 --- a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java @@ -129,6 +129,18 @@ public List getValues(final Option option, return valueList; } + public List getUndefaultedValues(Option option) { + // First grab the command line values + List valueList = (List) values.get(option); + + // Finally use an empty list + if (valueList == null) { + valueList = Collections.EMPTY_LIST; + } + + return valueList; + } + public Boolean getSwitch(final Option option, final Boolean defaultValue) { // First grab the command line values diff --git a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java index 0b05ad7b8..f776f7e9d 100644 --- a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java +++ b/src/java/org/apache/commons/cli2/option/ArgumentImpl.java @@ -141,7 +141,7 @@ public void processValues(final WriteableCommandLine commandLine, final Option option) throws OptionException { // count of arguments processed for this option. - int argumentCount = 0; + int argumentCount = commandLine.getUndefaultedValues(option).size(); while (arguments.hasNext() && (argumentCount < maximum)) { final String allValuesQuoted = (String) arguments.next(); diff --git a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java index 4c577acf7..08bf81b78 100644 --- a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java +++ b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java @@ -23,7 +23,6 @@ import org.apache.commons.cli2.Argument; import org.apache.commons.cli2.Group; import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.resource.ResourceConstants; import org.apache.commons.cli2.builder.ArgumentBuilder; import org.apache.commons.cli2.builder.DefaultOptionBuilder; import org.apache.commons.cli2.builder.GroupBuilder; @@ -74,7 +73,7 @@ public void testLoopingOptionLookAlike2() { parser.parse(new String[] { "testfile.txt", "testfile.txt", "testfile.txt", "testfile.txt" }); fail("OptionException"); } catch (OptionException e) { - assertEquals(ResourceConstants.ARGUMENT_UNEXPECTED_VALUE, e.getMessageKey()); + assertEquals("Unexpected testfile.txt while processing ", e.getMessage()); } } } From 5f6912337a7e7903dff33dd206a1d3d93db1c225 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Fri, 13 Jun 2008 15:43:58 +0000 Subject: [PATCH 0092/1663] Changed the documentation for Java property like options to use hasArgs(2) instead of hasArgs() (CLI-154) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@667573 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/usage.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xdocs/usage.xml b/xdocs/usage.xml index 970245f2b..79e47b557 100644 --- a/xdocs/usage.xml +++ b/xdocs/usage.xml @@ -200,7 +200,7 @@ Option find = OptionBuilder.withArgName( "file" ) using the OptionBuilder.

        Option property = OptionBuilder.withArgName( "property=value" ) - .hasArgs() + .hasArgs(2) .withValueSeparator() .withDescription( "use value for given property" ) .create( "D" ); From 5a7598201dbf249dfe7efd5c65d392bbfb0b3a52 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Fri, 13 Jun 2008 17:14:42 +0000 Subject: [PATCH 0093/1663] Added a reference to the getOptionProperties() method in the usage documentation git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@667597 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/usage.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/xdocs/usage.xml b/xdocs/usage.xml index 79e47b557..6a6139549 100644 --- a/xdocs/usage.xml +++ b/xdocs/usage.xml @@ -204,6 +204,10 @@ Option find = OptionBuilder.withArgName( "file" ) .withValueSeparator() .withDescription( "use value for given property" ) .create( "D" ); + + The map of properties specified by this option can later be retrieved by + calling getOptionProperties("D") on the CommandLine. +

        From 50bf111b2d47b25e5bc4d8c88f771d6741ba043b Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Mon, 21 Jul 2008 17:43:58 +0000 Subject: [PATCH 0094/1663] change commons-parent to version 11 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@678495 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d1abf1452..04a007b85 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.apache.commons commons-parent - 10 + 11 4.0.0 org.apache.commons From f989927a7b8a425a5d400b9f21c5df895b141b83 Mon Sep 17 00:00:00 2001 From: Oliver Heger Date: Tue, 22 Jul 2008 20:06:34 +0000 Subject: [PATCH 0095/1663] Added myself as developer. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@678880 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 10 ++++++++++ project.xml | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/pom.xml b/pom.xml index 04a007b85..5e2cdffc4 100644 --- a/pom.xml +++ b/pom.xml @@ -83,6 +83,16 @@ designed CLI2 + + Oliver Heger + oheger + oheger@apache.org + Agfa HealthCare + +1 + + Java Developer + + diff --git a/project.xml b/project.xml index 525514f1d..6f5448df8 100644 --- a/project.xml +++ b/project.xml @@ -105,6 +105,16 @@ designed CLI2 + + Oliver Heger + oheger + oheger@apache.org + Agfa HealthCare + +1 + + Java Developer + + From 2391d4701954389c3b51ac2357202cc335225189 Mon Sep 17 00:00:00 2001 From: Oliver Heger Date: Tue, 22 Jul 2008 20:27:09 +0000 Subject: [PATCH 0096/1663] CLI-126: Applied patch from Brian Egge git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@678886 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli2/CommandLine.java | 24 ++++++++++-- .../commons/cli2/WriteableCommandLine.java | 10 +++++ .../cli2/commandline/CommandLineImpl.java | 4 +- .../commandline/DefaultingCommandLine.java | 17 +++++++-- .../commandline/PreferencesCommandLine.java | 13 ++++++- .../commandline/PropertiesCommandLine.java | 13 ++++++- .../commandline/WriteableCommandLineImpl.java | 37 +++++++++++++++++-- .../commons/cli2/option/PropertyOption.java | 2 +- .../commons/cli2/CommandLineTestCase.java | 26 ++++++------- .../cli2/WriteableCommandLineTestCase.java | 9 +++-- .../commons/cli2/bug/BugCLI126Test.java | 32 ++++++++++++++++ .../apache/commons/cli2/bug/BugCLI12Test.java | 6 +-- .../DefaultingCommandLineTest.java | 3 +- .../cli2/option/PropertyOptionTest.java | 16 ++++---- 14 files changed, 165 insertions(+), 47 deletions(-) create mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI126Test.java diff --git a/src/java/org/apache/commons/cli2/CommandLine.java b/src/java/org/apache/commons/cli2/CommandLine.java index 5a18848d9..71ab4dd7e 100644 --- a/src/java/org/apache/commons/cli2/CommandLine.java +++ b/src/java/org/apache/commons/cli2/CommandLine.java @@ -158,7 +158,7 @@ public interface CommandLine { /** - * Retrieves the value associated with the specified property + * Retrieves the value associated with the specified property for the default property set * * @param property the property name to lookup * @return the value of the property or null @@ -168,14 +168,32 @@ public interface CommandLine { /** * Retrieves the value associated with the specified property * + * @param option the option i.e., -D + * @param property the property name to lookup + * @return the value of the property or null + */ + String getProperty(final Option option, final String property); + + /** + * Retrieves the value associated with the specified property + * + * @param option the option i.e., -D * @param property the property name to lookup * @param defaultValue the value to use if no other is found * @return the value of the property or defaultValue */ - String getProperty(final String property, final String defaultValue); + String getProperty(final Option option, final String property, final String defaultValue); + + /** + * Retrieves the set of all property names associated with this option + * + * @param option the option i.e., -D + * @return a none null set of property names + */ + Set getProperties(final Option option); /** - * Retrieves the set of all property names associated with this CommandLine + * Retrieves the set of all property names associated with the default property option * * @return a none null set of property names */ diff --git a/src/java/org/apache/commons/cli2/WriteableCommandLine.java b/src/java/org/apache/commons/cli2/WriteableCommandLine.java index a70c8d620..a4e45d610 100644 --- a/src/java/org/apache/commons/cli2/WriteableCommandLine.java +++ b/src/java/org/apache/commons/cli2/WriteableCommandLine.java @@ -72,6 +72,16 @@ public interface WriteableCommandLine extends CommandLine { * Adds a property value to a name in the CommandLine. * Replaces any existing value for the property. * + * @param option the Option to add to + * @param property the name of the property + * @param value the value of the property + */ + void addProperty(final Option option, final String property, final String value); + + /** + * Adds a property value to the default property set. + * Replaces any existing value for the property. + * * @param property the name of the property * @param value the value of the property */ diff --git a/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java index 37f8b37b6..2619aaa8f 100644 --- a/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java @@ -94,8 +94,8 @@ public final Boolean getSwitch(final Option option) { return getSwitch(option, null); } - public final String getProperty(final String property) { - return getProperty(property, null); + public final String getProperty(final Option option, final String property) { + return getProperty(option, property, null); } public final int getOptionCount(final String trigger) { diff --git a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java b/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java index d9f74329b..539bfc6aa 100644 --- a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java @@ -25,6 +25,7 @@ import org.apache.commons.cli2.CommandLine; import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.option.PropertyOption; /** * Manages a queue of default CommandLines. This CommandLine implementation is @@ -150,10 +151,14 @@ public Boolean getSwitch(Option option, Boolean defaultValue) { return defaultValue; } - public String getProperty(String property, String defaultValue) { + public String getProperty(final String property) { + return getProperty(new PropertyOption(), property); + } + + public String getProperty(final Option option, String property, String defaultValue) { for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); - final String actual = commandLine.getProperty(property); + final String actual = commandLine.getProperty(option, property); if (actual != null) { return actual; } @@ -161,12 +166,16 @@ public String getProperty(String property, String defaultValue) { return defaultValue; } - public Set getProperties() { + public Set getProperties(final Option option) { final Set all = new HashSet(); for (final Iterator i = commandLines.iterator(); i.hasNext();) { final CommandLine commandLine = (CommandLine)i.next(); - all.addAll(commandLine.getProperties()); + all.addAll(commandLine.getProperties(option)); } return Collections.unmodifiableSet(all); } + + public Set getProperties() { + return getProperties(new PropertyOption()); + } } diff --git a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java b/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java index 65448e9b9..99fe6f3ab 100644 --- a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java @@ -28,6 +28,7 @@ import java.util.prefs.Preferences; import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.option.PropertyOption; /** * A CommandLine implementation using the Preferences API, useful when @@ -129,11 +130,15 @@ else if("false".equals(value)){ } } - public String getProperty(final String property, final String defaultValue) { + public String getProperty(final String property) { + return getProperty(new PropertyOption(), property); + } + + public String getProperty(final Option option, final String property, final String defaultValue) { return preferences.get(property, defaultValue); } - public Set getProperties() { + public Set getProperties(final Option option) { try { return new HashSet(Arrays.asList(preferences.keys())); } catch (BackingStoreException e) { @@ -141,6 +146,10 @@ public Set getProperties() { } } + public Set getProperties() { + return getProperties(new PropertyOption()); + } + public List getOptions() { try { final List options = new ArrayList(); diff --git a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java b/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java index f019d1ac9..139eecf66 100644 --- a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java +++ b/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java @@ -26,6 +26,7 @@ import java.util.StringTokenizer; import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.option.PropertyOption; /** * A CommandLine implementation using a java Properties instance, useful for @@ -122,14 +123,22 @@ else if("false".equals(value)){ } } - public String getProperty(final String property, final String defaultValue) { + public String getProperty(final String property) { + return getProperty(new PropertyOption(), property); + } + + public String getProperty(final Option option, final String property, final String defaultValue) { return properties.getProperty(property,defaultValue); } - public Set getProperties() { + public Set getProperties(final Option option) { return properties.keySet(); } + public Set getProperties() { + return getProperties(new PropertyOption()); + } + public List getOptions() { final List options = new ArrayList(); final Iterator keys = properties.keySet().iterator(); diff --git a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java index 97a5d1124..75b206d5d 100644 --- a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java @@ -28,6 +28,7 @@ import org.apache.commons.cli2.Argument; import org.apache.commons.cli2.Option; import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.option.PropertyOption; import org.apache.commons.cli2.resource.ResourceConstants; import org.apache.commons.cli2.resource.ResourceHelper; @@ -37,7 +38,8 @@ */ public class WriteableCommandLineImpl extends CommandLineImpl implements WriteableCommandLine { - private final Properties properties = new Properties(); + private final Map optionToProperties = new HashMap(); +// private final Properties properties = new Properties(); private final List options = new ArrayList(); private final Map nameToOption = new HashMap(); private final Map values = new HashMap(); @@ -159,20 +161,47 @@ public Boolean getSwitch(final Option option, return bool; } - public void addProperty(final String property, + public String getProperty(final String property) { + return getProperty(new PropertyOption(), property); + } + + public void addProperty(final Option option, + final String property, final String value) { + Properties properties = (Properties) optionToProperties.get(option); + if (properties == null) { + properties = new Properties(); + optionToProperties.put(option, properties); + } properties.setProperty(property, value); } - public String getProperty(final String property, + public void addProperty(final String property, final String value) { + addProperty(new PropertyOption(), property, value); + } + + public String getProperty(final Option option, + final String property, final String defaultValue) { + Properties properties = (Properties) optionToProperties.get(option); + if (properties == null) { + return defaultValue; + } return properties.getProperty(property, defaultValue); } - public Set getProperties() { + public Set getProperties(final Option option) { + Properties properties = (Properties) optionToProperties.get(option); + if (properties == null) { + return Collections.EMPTY_SET; + } return Collections.unmodifiableSet(properties.keySet()); } + public Set getProperties() { + return getProperties(new PropertyOption()); + } + public boolean looksLikeOption(final String trigger) { for (final Iterator i = prefixes.iterator(); i.hasNext();) { final String prefix = (String) i.next(); diff --git a/src/java/org/apache/commons/cli2/option/PropertyOption.java b/src/java/org/apache/commons/cli2/option/PropertyOption.java index 6c418eca0..ccd340915 100644 --- a/src/java/org/apache/commons/cli2/option/PropertyOption.java +++ b/src/java/org/apache/commons/cli2/option/PropertyOption.java @@ -100,7 +100,7 @@ public void process(final WriteableCommandLine commandLine, value = arg.substring(equalsIndex + 1); } - commandLine.addProperty(property, value); + commandLine.addProperty(this, property, value); } public Set getTriggers() { diff --git a/src/test/org/apache/commons/cli2/CommandLineTestCase.java b/src/test/org/apache/commons/cli2/CommandLineTestCase.java index 07b2009b2..f4cf9477d 100644 --- a/src/test/org/apache/commons/cli2/CommandLineTestCase.java +++ b/src/test/org/apache/commons/cli2/CommandLineTestCase.java @@ -234,8 +234,8 @@ public final void testGetPropertyString() { * Class to test for String getProperty(String, String) */ public final void testGetPropertyStringString() { - assertEquals("present property", commandLine.getProperty("present", "default property")); - assertEquals("default property", commandLine.getProperty("missing", "default property")); + assertEquals("present property", commandLine.getProperty(new PropertyOption(), "present", "default property")); + assertEquals("default property", commandLine.getProperty(new PropertyOption(), "missing", "default property")); } public final void testGetProperties() { @@ -272,23 +272,23 @@ public final void testGetOptionTriggers() { // OLD TESTS FOLLOW public final void testProperties() { - final Option option = new PropertyOption(); + final PropertyOption option = new PropertyOption(); final List args = CLITestCase.list(); final WriteableCommandLine writeable = OptionTestCase.commandLine(option, args); - assertTrue(writeable.getProperties().isEmpty()); + assertTrue(writeable.getProperties(option).isEmpty()); - writeable.addProperty("myprop", "myval"); - assertEquals(1, writeable.getProperties().size()); - assertEquals("myval", writeable.getProperty("myprop")); + writeable.addProperty(option, "myprop", "myval"); + assertEquals(1, writeable.getProperties(option).size()); + assertEquals("myval", writeable.getProperty(option, "myprop")); - writeable.addProperty("myprop", "myval2"); - assertEquals(1, writeable.getProperties().size()); - assertEquals("myval2", writeable.getProperty("myprop")); + writeable.addProperty(option, "myprop", "myval2"); + assertEquals(1, writeable.getProperties(option).size()); + assertEquals("myval2", writeable.getProperty(option, "myprop")); - writeable.addProperty("myprop2", "myval3"); - assertEquals(2, writeable.getProperties().size()); - assertEquals("myval3", writeable.getProperty("myprop2")); + writeable.addProperty(option, "myprop2", "myval3"); + assertEquals(2, writeable.getProperties(option).size()); + assertEquals("myval3", writeable.getProperty(option, "myprop2")); } public final void testOptions() { diff --git a/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java b/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java index df6b4e3ea..a19661ebd 100644 --- a/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java +++ b/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java @@ -17,6 +17,7 @@ package org.apache.commons.cli2; import org.apache.commons.cli2.option.ArgumentTest; +import org.apache.commons.cli2.option.PropertyOption; /** * @author Rob Oxspring @@ -33,7 +34,7 @@ public abstract class WriteableCommandLineTestCase extends CommandLineTestCase { protected final CommandLine createCommandLine() { final WriteableCommandLine cl = createWriteableCommandLine(); cl.addOption(present); - cl.addProperty("present","present property"); + cl.addProperty(new PropertyOption(), "present","present property"); cl.addSwitch(bool,true); cl.addValue(present,"present value"); cl.addOption(multiple); @@ -82,9 +83,9 @@ public final void testAddSwitch() { assertTrue(writeable.hasOption(present)); } public final void testAddProperty() { - assertNull(writeable.getProperty("present")); - writeable.addProperty("present","present value"); - assertEquals("present value",writeable.getProperty("present")); + assertNull(writeable.getProperty(new PropertyOption(), "present")); + writeable.addProperty(new PropertyOption(), "present","present value"); + assertEquals("present value",writeable.getProperty(new PropertyOption(), "present")); } public final void testLooksLikeOption() { //TODO Implement looksLikeOption(). diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI126Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI126Test.java new file mode 100644 index 000000000..9aefeb4c1 --- /dev/null +++ b/src/test/org/apache/commons/cli2/bug/BugCLI126Test.java @@ -0,0 +1,32 @@ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; +import org.apache.commons.cli2.option.PropertyOption; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.builder.GroupBuilder; + +/** + * @author brianegge + */ +public class BugCLI126Test extends TestCase { + public void testMultiplePropertyArgs() throws OptionException { + PropertyOption conf = new PropertyOption("-P", "Properties for this process", 1); + PropertyOption env = new PropertyOption("-C", "Properties for child processes", 2); + GroupBuilder builder = new GroupBuilder(); + Group options = builder.withOption(conf).withOption(env).create(); + + Parser parser = new Parser(); + parser.setGroup(options); + CommandLine line = + parser.parseAndHelp( + new String[] { + "-Phome=.", + "-Chome=/" + }); + assertEquals(".", line.getProperty(conf, "home")); + assertEquals("/", line.getProperty(env, "home")); + } +} diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java index fa1a09a16..25f02aeb0 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI12Test.java @@ -35,7 +35,7 @@ public class BugCLI12Test extends TestCase { public void testBug() { Argument arg = new ArgumentBuilder().withName("file").create(); - Option option = new PropertyOption(); + PropertyOption option = new PropertyOption(); Group group = new GroupBuilder().withOption(option).withOption(arg).create(); @@ -47,8 +47,8 @@ public void testBug() { assertTrue("Couldn't parse valid commandLine", false); } - assertEquals( "myval1", cl.getProperty("myprop1")); - assertEquals( "myval2", cl.getProperty("myprop2")); + assertEquals( "myval1", cl.getProperty(option, "myprop1")); + assertEquals( "myval2", cl.getProperty(option, "myprop2")); String extraArgs = (String) cl.getValue(arg); assertEquals( "myfile", extraArgs); diff --git a/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java b/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java index f1fdaed9a..6e1dc6244 100644 --- a/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java +++ b/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java @@ -25,6 +25,7 @@ import org.apache.commons.cli2.CommandLineTestCase; import org.apache.commons.cli2.Option; import org.apache.commons.cli2.WriteableCommandLine; +import org.apache.commons.cli2.option.PropertyOption; import org.apache.commons.cli2.builder.DefaultOptionBuilder; /** @@ -44,7 +45,7 @@ public class DefaultingCommandLineTest protected final CommandLine createCommandLine() { final WriteableCommandLine writeable = new WriteableCommandLineImpl(root, new ArrayList()); writeable.addOption(present); - writeable.addProperty("present", "present property"); + writeable.addProperty(new PropertyOption(), "present", "present property"); writeable.addSwitch(bool, true); writeable.addValue(present, "present value"); writeable.addOption(multiple); diff --git a/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java b/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java index 1bd46111a..24e4b2f68 100644 --- a/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java +++ b/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java @@ -75,15 +75,15 @@ public void testPrefixes() { * @see org.apache.commons.cli2.OptionTestCase#testProcess() */ public void testProcess() throws OptionException { - final Option option = new PropertyOption(); + final PropertyOption option = new PropertyOption(); final List args = list("-Dmyprop=myvalue"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); - assertEquals("myvalue", commandLine.getProperty("myprop")); + assertEquals("myvalue", commandLine.getProperty(option, "myprop")); assertFalse(iterator.hasNext()); - assertEquals(1, commandLine.getProperties().size()); + assertEquals(1, commandLine.getProperties(option).size()); } public void testProcess_UnexpectedOptionException() { @@ -105,26 +105,26 @@ public void testProcess_UnexpectedOptionException() { } public void testProcess_BadPropertyException() throws OptionException { - final Option option = new PropertyOption(); + final PropertyOption option = new PropertyOption(); final List args = list("-Dmyprop"); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); - assertEquals("true", commandLine.getProperty("myprop")); + assertEquals("true", commandLine.getProperty(option, "myprop")); } public void testProcess_SetToEmpty() throws OptionException { - final Option option = new PropertyOption(); + final PropertyOption option = new PropertyOption(); final List args = list("-Dmyprop="); final WriteableCommandLine commandLine = commandLine(option, args); final ListIterator iterator = args.listIterator(); option.process(commandLine, iterator); - assertEquals("", commandLine.getProperty("myprop")); + assertEquals("", commandLine.getProperty(option, "myprop")); assertFalse(iterator.hasNext()); - assertEquals(1, commandLine.getProperties().size()); + assertEquals(1, commandLine.getProperties(option).size()); } /* From b7b2069f9d846c6aea5fee98508ec1491fdf1123 Mon Sep 17 00:00:00 2001 From: Oliver Heger Date: Tue, 22 Jul 2008 20:30:55 +0000 Subject: [PATCH 0097/1663] Added missing license header. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@678887 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli2/bug/BugCLI126Test.java | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI126Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI126Test.java index 9aefeb4c1..986c1fe42 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI126Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI126Test.java @@ -1,12 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.commons.cli2.bug; import junit.framework.TestCase; -import org.apache.commons.cli2.option.PropertyOption; -import org.apache.commons.cli2.Group; + import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; import org.apache.commons.cli2.OptionException; -import org.apache.commons.cli2.commandline.Parser; import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.option.PropertyOption; /** * @author brianegge From c338c8aca40d43efda580057f6d41ba228e26ec1 Mon Sep 17 00:00:00 2001 From: Oliver Heger Date: Wed, 23 Jul 2008 20:09:05 +0000 Subject: [PATCH 0098/1663] CLI-144: validate() is now called only once for an option that belongs to a group. Thanks to David dot Biesack at sas dot com for the unit test and dioktos at gmail dot com for a proposed fix. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@679179 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli2/option/GroupImpl.java | 13 ++-- .../commons/cli2/bug/BugCLI144Test.java | 66 +++++++++++++++++++ 2 files changed, 71 insertions(+), 8 deletions(-) create mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI144Test.java diff --git a/src/java/org/apache/commons/cli2/option/GroupImpl.java b/src/java/org/apache/commons/cli2/option/GroupImpl.java index 2a042fa17..e3b69f80c 100644 --- a/src/java/org/apache/commons/cli2/option/GroupImpl.java +++ b/src/java/org/apache/commons/cli2/option/GroupImpl.java @@ -245,14 +245,8 @@ public void validate(final WriteableCommandLine commandLine) for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); - // if the child option is required then validate it - if (option.isRequired()) { - option.validate(commandLine); - } - - if (option instanceof Group) { - option.validate(commandLine); - } + // needs validation? + boolean validate = option.isRequired() || option instanceof Group; // if the child option is present then validate it if (commandLine.hasOption(option)) { @@ -261,7 +255,10 @@ public void validate(final WriteableCommandLine commandLine) break; } + validate = true; + } + if (validate) { option.validate(commandLine); } } diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI144Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI144Test.java new file mode 100644 index 000000000..547033824 --- /dev/null +++ b/src/test/org/apache/commons/cli2/bug/BugCLI144Test.java @@ -0,0 +1,66 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import java.io.File; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.option.DefaultOption; +import org.apache.commons.cli2.validation.FileValidator; + +/** + * Test case for http://issues.apache.org/jira/browse/CLI-144 CLI 2 throws + * + *

        + * Exception in thread "main" java.lang.ClassCastException: java.io.File cannot be cast to java.lang.String
        + * 
        + * + * when there should be no such exception + * + * @author David Biesack + */ +public class BugCLI144Test extends TestCase { + public void testFileValidator() { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + DefaultOption fileNameOption = obuilder.withShortName("f") + .withLongName("file-name").withRequired(true).withDescription( + "name of an existing file").withArgument( + abuilder.withName("file-name").withValidator( + FileValidator.getExistingFileInstance()) + .create()).create(); + Group options = gbuilder.withName("options").withOption(fileNameOption) + .create(); + Parser parser = new Parser(); + parser.setHelpTrigger("--help"); + parser.setGroup(options); + + final String fileName = "src/test/org/apache/commons/cli2/bug/BugCLI144Test.java"; + CommandLine cl = parser + .parseAndHelp(new String[] { "--file-name", fileName }); + assertNotNull(cl); + assertEquals("Wrong file", new File(fileName), cl.getValue(fileNameOption)); + } +} From a93139165b160af1c908c85a06b0af6b3dda3387 Mon Sep 17 00:00:00 2001 From: Oliver Heger Date: Thu, 24 Jul 2008 19:38:04 +0000 Subject: [PATCH 0099/1663] CLI-158: Default arguments are now applied even if arguments are passed. The default values for missing arguments will be set. Thanks to tobias dot bocanegra at day dot com for the patch. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@679511 13f79535-47bb-0310-9956-ffa450edef68 --- .../commandline/WriteableCommandLineImpl.java | 37 +++--- .../commons/cli2/bug/BugCLI158Test.java | 114 ++++++++++++++++++ 2 files changed, 136 insertions(+), 15 deletions(-) create mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI158Test.java diff --git a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java index 75b206d5d..319f8c219 100644 --- a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java @@ -109,26 +109,33 @@ public Option getOption(final String trigger) { } public List getValues(final Option option, - final List defaultValues) { - // First grab the command line values + List defaultValues) { + // initialize the return list List valueList = (List) values.get(option); - // Secondly try the defaults supplied to the method - if ((valueList == null) || valueList.isEmpty()) { - valueList = defaultValues; - } - - // Thirdly try the option's default values - if ((valueList == null) || valueList.isEmpty()) { - valueList = (List) this.defaultValues.get(option); + // grab the correct default values + if (defaultValues == null || defaultValues.isEmpty()) { + defaultValues = (List) this.defaultValues.get(option); } - // Finally use an empty list - if (valueList == null) { - valueList = Collections.EMPTY_LIST; + // augment the list with the default values + if (defaultValues != null && !defaultValues.isEmpty()) { + if (valueList == null || valueList.isEmpty()) { + valueList = defaultValues; + } else { + // if there are more default values as specified, add them to + // the list. + if (defaultValues.size() > valueList.size()) { + // copy the list first + valueList = new ArrayList(valueList); + for (int i=valueList.size(); i Date: Thu, 24 Jul 2008 19:46:30 +0000 Subject: [PATCH 0100/1663] CLI-6: Added an additional test case to verify that unknown short options cause an exception. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@679516 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli2/commandline/ParserTest.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/test/org/apache/commons/cli2/commandline/ParserTest.java b/src/test/org/apache/commons/cli2/commandline/ParserTest.java index e6e46eb3e..6326c3db8 100644 --- a/src/test/org/apache/commons/cli2/commandline/ParserTest.java +++ b/src/test/org/apache/commons/cli2/commandline/ParserTest.java @@ -82,6 +82,17 @@ public void testParse_WithUnexpectedOption() { } } + public void testParse_WithUnexpectedShortOption() { + try { + parser.parse(new String[]{"-vx"}); + fail("OptionException"); + } + catch(OptionException e) { + assertEquals(options,e.getOption()); + assertEquals("Unexpected -x while processing --help|--verbose",e.getMessage()); + } + } + public void testParseAndHelp_Successful() throws IOException { final CommandLine cl = parser.parseAndHelp(new String[]{"-v"}); From f104dd060c6c88450ac9ee9eb818b26374512440 Mon Sep 17 00:00:00 2001 From: Oliver Heger Date: Thu, 24 Jul 2008 20:28:16 +0000 Subject: [PATCH 0101/1663] CLI-123: Groups are now added to the command line if any of their child options are found. This makes it possible to test for the presence of a group and also validate minimum and maximum constraints when child groups are involved. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@679530 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli2/Option.java | 21 +++ .../commandline/WriteableCommandLineImpl.java | 7 + .../apache/commons/cli2/option/GroupImpl.java | 1 + .../commons/cli2/option/OptionImpl.java | 13 +- .../commons/cli2/CommandLineTestCase.java | 1 + .../commons/cli2/bug/BugCLI123Test.java | 126 ++++++++++++++++++ 6 files changed, 168 insertions(+), 1 deletion(-) create mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI123Test.java diff --git a/src/java/org/apache/commons/cli2/Option.java b/src/java/org/apache/commons/cli2/Option.java index 96c50c601..0102573aa 100644 --- a/src/java/org/apache/commons/cli2/Option.java +++ b/src/java/org/apache/commons/cli2/Option.java @@ -194,4 +194,25 @@ void appendUsage( * @return true iff the CommandLine will be invalid without this Option */ boolean isRequired(); + + /** + * Returns the parent of this option. Options can be organized in a + * hierarchical manner if they are added to groups. This method can be used + * for obtaining the parent option of this option. The result may be + * null if this option does not have a parent. + * + * @return the parent of this option + */ + Option getParent(); + + /** + * Sets the parent of this option. This method is called when the option is + * added to a group. Storing the parent of an option makes it possible to + * keep track of hierarchical relations between options. For instance, if an + * option is identified while parsing a command line, the group this option + * belongs to can also be added to the command line. + * + * @param parent the parent option + */ + void setParent(Option parent); } diff --git a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java index 319f8c219..ec97eab90 100644 --- a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java @@ -69,6 +69,13 @@ public void addOption(Option option) { for (Iterator i = option.getTriggers().iterator(); i.hasNext();) { nameToOption.put(i.next(), option); } + + // ensure that all parent options are also added + Option parent = option.getParent(); + while (parent != null && !options.contains(parent)) { + options.add(parent); + parent = parent.getParent(); + } } public void addValue(final Option option, diff --git a/src/java/org/apache/commons/cli2/option/GroupImpl.java b/src/java/org/apache/commons/cli2/option/GroupImpl.java index e3b69f80c..38fc6c286 100644 --- a/src/java/org/apache/commons/cli2/option/GroupImpl.java +++ b/src/java/org/apache/commons/cli2/option/GroupImpl.java @@ -89,6 +89,7 @@ public GroupImpl(final List options, // process the options for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); + option.setParent(this); if (option instanceof Argument) { i.remove(); diff --git a/src/java/org/apache/commons/cli2/option/OptionImpl.java b/src/java/org/apache/commons/cli2/option/OptionImpl.java index eab47a9bd..f74313d05 100644 --- a/src/java/org/apache/commons/cli2/option/OptionImpl.java +++ b/src/java/org/apache/commons/cli2/option/OptionImpl.java @@ -33,6 +33,7 @@ public abstract class OptionImpl implements Option { private final int id; private final boolean required; + private Option parent; /** * Creates an OptionImpl with the specified id @@ -95,7 +96,9 @@ private boolean equals(Object left, public int hashCode() { int hashCode = getId(); - hashCode = (hashCode * 37) + getPreferredName().hashCode(); + if (getPreferredName() != null) { + hashCode = (hashCode * 37) + getPreferredName().hashCode(); + } if (getDescription() != null) { hashCode = (hashCode * 37) + getDescription().hashCode(); @@ -123,6 +126,14 @@ public void defaults(final WriteableCommandLine commandLine) { // nothing to do normally } + public Option getParent() { + return parent; + } + + public void setParent(Option parent) { + this.parent = parent; + } + protected void checkPrefixes(final Set prefixes) { // nothing to do if empty prefix list if (prefixes.isEmpty()) { diff --git a/src/test/org/apache/commons/cli2/CommandLineTestCase.java b/src/test/org/apache/commons/cli2/CommandLineTestCase.java index f4cf9477d..6be03c72c 100644 --- a/src/test/org/apache/commons/cli2/CommandLineTestCase.java +++ b/src/test/org/apache/commons/cli2/CommandLineTestCase.java @@ -433,6 +433,7 @@ public final void testGetOptions_Order() final Iterator i = cl.getOptions().iterator(); assertSame(login, i.next()); + assertSame(group, i.next()); assertSame(help, i.next()); assertSame(targets, i.next()); assertSame(targets, i.next()); diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI123Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI123Test.java new file mode 100644 index 000000000..af418333d --- /dev/null +++ b/src/test/org/apache/commons/cli2/bug/BugCLI123Test.java @@ -0,0 +1,126 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; + +/** + * Group options are not added to the command line when child elements are + * detected. This causes the validation of maximum and minimum to fail. + * + * @author Oliver Heger + * @version $Id$ + */ +public class BugCLI123Test extends TestCase { + /** An option of the parent group. */ + private Option parentOption; + + /** An option of the child group. */ + private Option childOption1; + + /** Another option of the child group. */ + private Option childOption2; + + /** The parent group. */ + private Group parentGroup; + + /** The child group. */ + private Group childGroup; + + /** The parser. */ + private Parser parser; + + protected void setUp() throws Exception { + super.setUp(); + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final ArgumentBuilder abuilder = new ArgumentBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + parentOption = obuilder.withLongName("parent").withShortName("p") + .withArgument(abuilder.withName("name").create()).create(); + childOption1 = obuilder.withLongName("child").withShortName("c") + .withArgument(abuilder.withName("c").create()).create(); + childOption2 = obuilder.withLongName("sub").withShortName("s") + .withArgument(abuilder.withName("s").create()).create(); + childGroup = gbuilder.withName("childOptions").withMinimum(0) + .withMaximum(2).withOption(childOption1).withOption( + childOption2).create(); + parentGroup = gbuilder.withName("parentOptions").withMinimum(1) + .withMaximum(1).withOption(parentOption).withOption(childGroup) + .create(); + parser = new Parser(); + parser.setGroup(parentGroup); + } + + /** + * A single option of the child group is specified. + */ + public void testSingleChildOption() throws OptionException { + CommandLine cl = parser.parse(new String[] { "--child", "test" }); + assertTrue("Child option not found", cl.hasOption(childOption1)); + assertEquals("Wrong value for option", "test", cl + .getValue(childOption1)); + assertTrue("Child group not found", cl.hasOption(childGroup)); + } + + /** + * Two options of the child group are specified. + */ + public void testMultipleChildOptions() throws OptionException { + CommandLine cl = parser.parse(new String[] { "--child", "test", + "--sub", "anotherTest" }); + assertTrue("Child option not found", cl.hasOption(childOption1)); + assertEquals("Wrong value for option", "test", cl + .getValue(childOption1)); + assertTrue("Sub option not found", cl.hasOption(childOption2)); + assertEquals("Wrong value for sub option", "anotherTest", cl + .getValue(childOption2)); + assertTrue("Child group not found", cl.hasOption(childGroup)); + } + + /** + * The option defined for the parent group is specified. + */ + public void testSingleParentOption() throws OptionException { + CommandLine cl = parser.parse(new String[] { "--parent", "yes" }); + assertTrue("Parent option not found", cl.hasOption(parentOption)); + assertEquals("Wrong value for option", "yes", cl.getValue(parentOption)); + assertFalse("Found child group", cl.hasOption(childGroup)); + } + + /** + * The parent option and an option of the child group is specified. This + * should cause an exception. + */ + public void testParentOptionAndChildOption() throws OptionException { + try { + parser.parse(new String[] { "--parent", "error", "--child", + "exception" }); + fail("Maximum restriction for parent not verified!"); + } catch (OptionException oex) { + // ok + } + } +} From cf06f677daf09348e0595b50dc19f7e32f1521b9 Mon Sep 17 00:00:00 2001 From: Oliver Heger Date: Sun, 27 Jul 2008 20:32:14 +0000 Subject: [PATCH 0102/1663] CLI-159: It is now possible to set a required flag on a group explicitly. If this group is then added as child to another group, it is only validated if options of this group are found on the command line or its required flag is true. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@680178 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli2/builder/GroupBuilder.java | 16 +- .../apache/commons/cli2/option/GroupImpl.java | 20 ++- .../commons/cli2/bug/BugCLI159Test.java | 169 ++++++++++++++++++ .../apache/commons/cli2/option/GroupTest.java | 78 +++++++- 4 files changed, 274 insertions(+), 9 deletions(-) create mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI159Test.java diff --git a/src/java/org/apache/commons/cli2/builder/GroupBuilder.java b/src/java/org/apache/commons/cli2/builder/GroupBuilder.java index 9d098464b..ceb94451d 100644 --- a/src/java/org/apache/commons/cli2/builder/GroupBuilder.java +++ b/src/java/org/apache/commons/cli2/builder/GroupBuilder.java @@ -33,6 +33,7 @@ public class GroupBuilder { private List options; private int minimum; private int maximum; + private boolean required; /** * Creates a new GroupBuilder @@ -47,7 +48,7 @@ public GroupBuilder() { */ public Group create() { final GroupImpl group = - new GroupImpl(options, name, description, minimum, maximum); + new GroupImpl(options, name, description, minimum, maximum, required); reset(); @@ -63,6 +64,7 @@ public GroupBuilder reset() { options = new ArrayList(); minimum = 0; maximum = Integer.MAX_VALUE; + required = true; return this; } @@ -115,4 +117,16 @@ public GroupBuilder withOption(final Option option) { this.options.add(option); return this; } + + /** + * Sets the required flag. This flag is evaluated for groups that are + * added to other groups as child groups. If set to true the + * minimum and maximum constraints of the child group are always evaluated. + * @param newRequired the required flag + * @return this builder + */ + public GroupBuilder withRequired(final boolean newRequired) { + this.required = newRequired; + return this; + } } diff --git a/src/java/org/apache/commons/cli2/option/GroupImpl.java b/src/java/org/apache/commons/cli2/option/GroupImpl.java index 38fc6c286..56f295727 100644 --- a/src/java/org/apache/commons/cli2/option/GroupImpl.java +++ b/src/java/org/apache/commons/cli2/option/GroupImpl.java @@ -60,13 +60,15 @@ public class GroupImpl * @param description a description of this Group * @param minimum the minimum number of Options for a valid CommandLine * @param maximum the maximum number of Options for a valid CommandLine + * @param required a flag whether this group is required */ public GroupImpl(final List options, final String name, final String description, final int minimum, - final int maximum) { - super(0, false); + final int maximum, + final boolean required) { + super(0, required); this.name = name; this.description = description; @@ -247,7 +249,7 @@ public void validate(final WriteableCommandLine commandLine) final Option option = (Option) i.next(); // needs validation? - boolean validate = option.isRequired() || option instanceof Group; + boolean validate = option.isRequired(); // if the child option is present then validate it if (commandLine.hasOption(option)) { @@ -470,8 +472,16 @@ public int getMaximum() { return maximum; } - public boolean isRequired() { - return getMinimum() > 0; + /** + * Tests whether this option is required. For groups we evaluate the + * required flag common to all options, but also take the + * minimum constraints into account. + * + * @return a flag whether this option is required + */ + public boolean isRequired() + { + return (getParent() == null || super.isRequired()) && getMinimum() > 0; } public void defaults(final WriteableCommandLine commandLine) { diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI159Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI159Test.java new file mode 100644 index 000000000..7e38a9d5c --- /dev/null +++ b/src/test/org/apache/commons/cli2/bug/BugCLI159Test.java @@ -0,0 +1,169 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; + +/** + * Inconsistent handling of minimum and maximum constraints for groups and their + * child groups. + * + * @author Oliver Heger + * @version $Id$ + */ +public class BugCLI159Test extends TestCase +{ + /** The parent group. */ + private Group parent; + + /** The child group. */ + private Group child; + + /** The parser. */ + private Parser parser; + + /** + * Creates some test options, including a group with a child group. + * + * @param childGroupRequired a flag whether the child group is required + */ + private void setUpOptions(boolean childGroupRequired) + { + final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); + final GroupBuilder gbuilder = new GroupBuilder(); + Option parentOpt = obuilder.withLongName("parent").withShortName("p") + .create(); + Option childOpt1 = obuilder.withLongName("child").withShortName("c") + .create(); + Option childOpt2 = obuilder.withLongName("sub").withShortName("s") + .create(); + Option childOpt3 = obuilder.withLongName("test").withShortName("t") + .create(); + child = gbuilder.withName("childOptions").withOption(childOpt1) + .withOption(childOpt2).withOption(childOpt3).withMinimum(2) + .withRequired(childGroupRequired).create(); + parent = gbuilder.withName("options").withOption(parentOpt).withOption( + child).withMinimum(0).create(); + parser = new Parser(); + parser.setGroup(parent); + } + + /** + * Tests whether the child group can be omitted. + */ + public void testNoChildGroup() throws OptionException + { + setUpOptions(false); + CommandLine cl = parser.parse(new String[] { + "--parent" + }); + assertNotNull("No command line parsed", cl); + assertFalse("Child group found", cl.hasOption(child)); + } + + /** + * Tests whether a required child groupd can be omitted. + */ + public void testNoChildGroupRequired() + { + setUpOptions(true); + try + { + parser.parse(new String[] { + "--parent" + }); + fail("Missing child group not detected!"); + } + catch (OptionException oex) + { + // ok + } + } + + /** + * Tests parsing an empty command line. Because the parent group is optional + * this should be possible. + */ + public void testNoOptions() throws OptionException + { + setUpOptions(false); + CommandLine cl = parser.parse(new String[0]); + assertFalse("Found parent option", cl.hasOption("--parent")); + assertFalse("Found child option", cl.hasOption("--child")); + } + + /** + * Tests parsing a command line with options of the child group. + */ + public void testWithChildOptions() throws OptionException + { + setUpOptions(false); + CommandLine cl = parser.parse(new String[] { + "-ct" + }); + assertTrue("child option not found", cl.hasOption("--child")); + assertTrue("test option not found", cl.hasOption("--test")); + } + + /** + * Tests a command line containing options of the child group, but the + * minimum constraint is violated. + */ + public void testWithChildOptionsMissing() + { + setUpOptions(false); + try + { + parser.parse(new String[] { + "--parent", "--sub" + }); + fail("Missing options of child group not detected!"); + } + catch (OptionException oex) + { + // ok + } + } + + /** + * Tests whether the root group is always validated. + */ + public void testRequiredRootGroup() + { + setUpOptions(false); + parser.setGroup(child); + try + { + parser.parse(new String[] { + "--test" + }); + fail("Missing options not detected!"); + } + catch (OptionException oex) + { + // ok + } + } +} diff --git a/src/test/org/apache/commons/cli2/option/GroupTest.java b/src/test/org/apache/commons/cli2/option/GroupTest.java index 32cc36f48..0f9fbbdcb 100644 --- a/src/test/org/apache/commons/cli2/option/GroupTest.java +++ b/src/test/org/apache/commons/cli2/option/GroupTest.java @@ -55,7 +55,7 @@ public static Group buildApacheCommandGroup() { options.add(COMMAND_START); options.add(COMMAND_STOP); - return new GroupImpl(options, "httpd-cmds", "The command to pass to the server", 1, 1); + return new GroupImpl(options, "httpd-cmds", "The command to pass to the server", 1, 1, true); } public static Group buildApachectlGroup() { @@ -64,7 +64,7 @@ public static Group buildApachectlGroup() { options.add(ParentTest.buildKParent()); return new GroupImpl(options, "apachectl", "Controls the apache http deamon", 0, - Integer.MAX_VALUE); + Integer.MAX_VALUE, true); } public static Group buildAntGroup() { @@ -72,7 +72,18 @@ public static Group buildAntGroup() { options.add(DefaultOptionTest.buildHelpOption()); options.add(ArgumentTest.buildTargetsArgument()); - return new GroupImpl(options, "ant", "The options for ant", 0, Integer.MAX_VALUE); + return new GroupImpl(options, "ant", "The options for ant", 0, Integer.MAX_VALUE, true); + } + + private static Group buildRequiredTestGroup(final boolean required, + final int minimum) + { + final Group group = new GroupImpl(new ArrayList(), "test", null, + minimum, Integer.MAX_VALUE, required); + final List options = new ArrayList(1); + options.add(group); + new GroupImpl(options, "parent", null, 0, Integer.MAX_VALUE, false); + return group; } /* @@ -437,4 +448,65 @@ public void testHelpLines_NoName() { assertFalse(i.hasNext()); } + + /** + * Tests isRequired() for a child group if neither the required flag nor a + * minimum constraint is set. + */ + public void testIsRequired_ChildNoFlagNoMinimum() + { + final Group group = buildRequiredTestGroup(false, 0); + assertFalse("Group is required", group.isRequired()); + } + + /** + * Tests isRequired() for a child group that has a minimum constraint, but + * the required flag is not set. + */ + public void testIsRequired_ChildNoFlagMinimum() + { + final Group group = buildRequiredTestGroup(false, 10); + assertFalse("Group is required", group.isRequired()); + } + + /** + * Tests isRequired() for a child group that has the required flag set, but + * no minimum constraint. In this constellation the group is de facto not + * required. + */ + public void testIsRequired_ChildFlagNoMinimum() + { + final Group group = buildRequiredTestGroup(true, 0); + assertFalse("Group is required", group.isRequired()); + } + + /** + * Tests isRequired() for a child group that has both the required flag and + * a minimum constraint set. This is indeed a required group. + */ + public void testIsRequired_ChildFlagMinimum() + { + final Group group = buildRequiredTestGroup(true, 10); + assertTrue("Group is not required", group.isRequired()); + } + + /** + * Tests isRequired() for the root group when no minimum constraint is set. + */ + public void testIsRequired_ParentNoMinimum() + { + final Group parent = (Group) buildRequiredTestGroup(false, 0) + .getParent(); + assertFalse("Group is required", parent.isRequired()); + } + + /** + * Tests isRequired() for the root group with a minimum constraint. + */ + public void testIsRequired_ParentMiminum() + { + final Group parent = new GroupImpl(new ArrayList(), "test", null, 10, + Integer.MAX_VALUE, false); + assertTrue("Group not required", parent.isRequired()); + } } From e179f1f1ce8bf5f5315acc85df48bac131d8d269 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Mon, 28 Jul 2008 16:28:23 +0000 Subject: [PATCH 0103/1663] Updated the download link and the revision history git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@680391 13f79535-47bb-0310-9956-ffa450edef68 --- doap_cli.rdf | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/doap_cli.rdf b/doap_cli.rdf index 5fa977356..9a448a829 100644 --- a/doap_cli.rdf +++ b/doap_cli.rdf @@ -23,7 +23,7 @@ limitations under the License. - + Commons CLI @@ -37,6 +37,11 @@ limitations under the License. + + commons-cli + 2007-07-08 + 1.1 + commons-cli 2002-12-27 From c0a339af3d496b611cc9a5ba2a11d5a0addb9689 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Tue, 29 Jul 2008 16:35:43 +0000 Subject: [PATCH 0104/1663] Updated the changes for CLI 1.2 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@680761 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/changes.xml | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/xdocs/changes.xml b/xdocs/changes.xml index f9d877460..55ac8f5cd 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -23,6 +23,28 @@ + + The number of arguments defined for an option specifies the arguments per occurence of the option + and not for all occurences. This was a major regression in CLI 1.1 which prevented the use of repeated options. + + + Added a getOptionProperties() method in the CommandLine class to retrieve easily the key/value pairs + specified with options like -Dkey1=value1 -Dkey2=value2. + + + GnuParser now supports long options with an '=' sign (ie. --foo=bar and -foo=bar) + + + PosixParser no longer ignores unrecognized short options. + + + PosixParser no longer stops the bursting process of a token if stopAtNonOption is enabled and a non option + character is encountered. + + + PosixParser no longer keeps processing the tokens after an unrecognized long option + when stopAtNonOption is enabled. + Required options are properly checked if an Options instance is used twice to parse a command line. @@ -35,8 +57,11 @@ The message of MissingOptionException has been improved. + + The exceptions have been enhanced with methods to retrieve easily the related options. + - Option.toString() now reports arguments properly. + Option.toString() now reports arguments properly. The Parser class has been changed to be more easily extendable. @@ -44,6 +69,9 @@ The following classes are now serializable: Option, OptionGroup, CommandLine and Options. + + OptionValidator is no longer public, its methods were all private. + From 416844c1e8adfe657ffb77a5c0a928a21b124af3 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 30 Jul 2008 14:53:29 +0000 Subject: [PATCH 0105/1663] Updated the site for CLI 1.2 Changed the main page to include a more detailed presentation of the component Removed the redundant pages (navigation.xml and cvs-usage.xml) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@681071 13f79535-47bb-0310-9956-ffa450edef68 --- src/site/site.xml | 11 +- xdocs/changes.xml | 4 +- xdocs/download_cli.xml | 24 ++-- xdocs/index.xml | 278 ++++++++++++++++++++++------------------- xdocs/introduction.xml | 8 +- xdocs/navigation.xml | 60 --------- xdocs/properties.xml | 4 +- xdocs/release_1_0.xml | 4 +- xdocs/release_1_2.xml | 101 +++++++++++++++ xdocs/usage.xml | 20 +-- 10 files changed, 290 insertions(+), 224 deletions(-) delete mode 100644 xdocs/navigation.xml create mode 100644 xdocs/release_1_2.xml diff --git a/src/site/site.xml b/src/site/site.xml index 5663d9925..74c682697 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -15,7 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. --> - + Commons CLI /images/logo.png @@ -23,7 +23,7 @@ - + @@ -32,15 +32,14 @@ - + - - + - + diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 55ac8f5cd..9c106a0cf 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -24,8 +24,8 @@ - The number of arguments defined for an option specifies the arguments per occurence of the option - and not for all occurences. This was a major regression in CLI 1.1 which prevented the use of repeated options. + The number of arguments defined for an option specifies the arguments per occurrence of the option + and not for all occurrences. This was a major regression in CLI 1.1 which prevented the use of repeated options. Added a getOptionProperties() method in the CommandLine class to retrieve easily the key/value pairs diff --git a/xdocs/download_cli.xml b/xdocs/download_cli.xml index 169a0753c..6008e9155 100644 --- a/xdocs/download_cli.xml +++ b/xdocs/download_cli.xml @@ -102,17 +102,17 @@ limitations under the License.
          • -
          • 1.1.tar.gz +
          • 1.2.tar.gz
          • -
          • 1.1.zip +
          • 1.2.zip
          • @@ -120,17 +120,17 @@ limitations under the License.
            • -
            • 1.1.tar.gz +
            • 1.2.tar.gz
            • -
            • 1.1.zip +
            • 1.2.zip
            • diff --git a/xdocs/index.xml b/xdocs/index.xml index a32b4f44b..f7b5b4bd1 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -19,147 +19,173 @@ --> - + Home commons-dev - + - -
              -

              -The Apache Commons CLI library provides an API for processing command line interfaces. -

              -
              - -
              -

              -Commons CLI 1.0 was formed from the merger of ideas and code from three different libraries - -Werken, Avalon and Optz. In dealing with the bugs and the feature requests a freshly designed and not backwards compatible -CLI 2.0 was created, but never finished or released. Since then a CLI 1.1 bugfix release has been made. -

              -

              -There are currently no plans to continue the 1.x line beyond bugfixes. The 2.x design is generally preferred and is in use, -however there is no current activity to make a 2.0 release. To this end, the 1.1 release is recommended to most users -while the 2.x line is recommended for anyone interested in helping to get this better API released. -

              -
              - -
              -

              -A full User's Guide is available -as are various project reports. -

              -

              -The JavaDoc API documents are available online: -

              - -

              -The subversion repository can be -browsed. -

              -
              - -
              -

              -The latest version is v1.1. - -Download now!
              -The release notes are also available. -

              -

              -For previous releases, see the Apache Archive -

              -
              - -
              -

              -The commons mailing lists act as the main support forum. -The user list is suitable for most library usage queries. -The dev list is intended for the development discussion. -Please remember that the lists are shared between all commons components, -so prefix your email by [cli]. -

              -

              -Issues may be reported via the ASF JIRA. -

              -
              - - - + +
              +

              + The latest version is v1.2. - + Download now! +
              + The release notes are also available. +

              +

              + For previous releases, see the Apache Archive. +

              +
              + +
              +

              The commons mailing lists act as the main support forum. The user list + is suitable for most library usage queries. The dev list is intended for the development discussion. Please + remember that the lists are shared between all commons components, so prefix your email subject by + [cli].

              + +

              Issues may be reported via the ASF JIRA.

              +
              + + +
              diff --git a/xdocs/introduction.xml b/xdocs/introduction.xml index 58808be9a..0557d37a1 100644 --- a/xdocs/introduction.xml +++ b/xdocs/introduction.xml @@ -39,9 +39,9 @@ to define the interface to the application.

              - CLI uses the + CLI uses the Options class, as a container for - + Option instances. There are two ways to create Options in CLI. One of them is via the constructors, the other way is via the factory methods defined in @@ -66,11 +66,11 @@

              The parse method defined on - + CommandLineParser takes an Options instance and a String[] of arguments and returns a - + CommandLine.

              diff --git a/xdocs/navigation.xml b/xdocs/navigation.xml deleted file mode 100644 index 29eb9269c..000000000 --- a/xdocs/navigation.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - Commons CLI - - - - - - -

              - - - - - - - - - - - - - - - - - - - - - - - - - &commons; - - - diff --git a/xdocs/properties.xml b/xdocs/properties.xml index 7a47d0902..2976747ac 100644 --- a/xdocs/properties.xml +++ b/xdocs/properties.xml @@ -28,10 +28,10 @@

              The following are the properties that each - Option has. All of these + Option has. All of these can be set using the accessors or using the methods defined in the - OptionBuilder. + OptionBuilder.

      diff --git a/xdocs/release_1_0.xml b/xdocs/release_1_0.xml index 284223c61..0ac1aa11d 100644 --- a/xdocs/release_1_0.xml +++ b/xdocs/release_1_0.xml @@ -17,14 +17,14 @@ limitations under the License. --> - Release notes for 1.0 + Release notes for CLI 1.0 Commons Documentation Team

      -These are the release notes for Commons-CLI version 1.0. +These are the release notes for Commons CLI 1.0. INTRODUCTION: diff --git a/xdocs/release_1_2.xml b/xdocs/release_1_2.xml new file mode 100644 index 000000000..24777c736 --- /dev/null +++ b/xdocs/release_1_2.xml @@ -0,0 +1,101 @@ + + + + + Release notes for CLI 1.2 + Commons Documentation Team + + + +

      + +

      These are the release notes for Commons CLI 1.2.

      + + +INTRODUCTION: + +This document contains the release notes for this version of the Commons CLI +package. Commons CLI provides a simple API for working with the command line +arguments and options. + +Commons CLI 1.2 is a bugfix release. The following notable changes were made: + + * A major regression introduced in CLI 1.1 that prevented the usage of repeated options has been fixed. + * Several parser issues have been fixed, especially with the PosixParser. + * HelpFormatter now wraps the lines properly + * The ordering of the option in the help message can now be defined. + * Various API enhancements (improved exceptions, serializable classes) + +Commons CLI 1.2 is binary compatible with the previous versions, except for +the OptionValidator class that is no longer public. + +More information can be found on the project site at http://commons.apache.org/cli + + +NEW FEATURES: + + * The method getOptionProperties() in the CommandLine class was added + to retrieve easily the key/value pairs specified with options like + -Dkey1=value1 -Dkey2=value2. + + * GnuParser now supports long options with an '=' sign + (ie. --foo=bar and -foo=bar) (CLI-157) + + * The ordering of options can be defined in help messages. (CLI-155) + + +BUG FIXES: + + * The number of arguments defined for an option specifies the arguments + per occurrence of the option and not for all occurrences. (CLI-137) + + * PosixParser no longer ignores unrecognized short options. (CLI-164) + + * PosixParser no longer stops the bursting process of a token if stopAtNonOption + is enabled and a non option character is encountered. (CLI-163) + + * PosixParser no longer keeps processing the tokens after an unrecognized + long option when stopAtNonOption is enabled. (CLI-165) + + * Required options are properly checked if an Options instance is used twice + to parse a command line. (CLI-156) + + * The line wrapping in HelpFormatter now works properly. (CLI-151) + + +CHANGES: + + * The message of MissingOptionException has been improved. (CLI-149) + + * The exceptions have been enhanced with methods to retrieve easily + the related options. (CLI-86) + + * Option.toString() now reports arguments properly. (CLI-141) + + * The Parser class has been changed to be more easily extendable. (CLI-142) + + * The following classes are now serializable: Option, OptionGroup, + CommandLine and Options. (CLI-140) + + * OptionValidator is no longer public, its methods were all private. + + +
      + + + diff --git a/xdocs/usage.xml b/xdocs/usage.xml index 6a6139549..dc50873c0 100644 --- a/xdocs/usage.xml +++ b/xdocs/usage.xml @@ -45,7 +45,7 @@

      - An + An Options object must be created and the Option must be added to it.

      @@ -78,7 +78,7 @@ CommandLine cmd = parser.parse( options, args);

      Now we need to check if the t option is present. To do this we will interrogate the - CommandLine + CommandLine object. The hasOption method takes a java.lang.String parameter and returns true if the option represented by the java.lang.String is present, otherwise @@ -212,11 +212,11 @@ Option find = OptionBuilder.withArgName( "file" )

      Now that we have created each - Option we need + Option we need to create the - Options + Options instance. This is achieved using the - addOption + addOption method of Options.

      Options options = new Options(); @@ -243,8 +243,8 @@ options.addOption( property );

      We now need to create a Parser. This will parse the command line arguments, using the rules specified by the Options and - return an instance of CommandLine. - This time we will use a GnuParser + return an instance of CommandLine. + This time we will use a GnuParser which is able to handle options that are more than one character long.

      public static void main( String[] args ) { @@ -276,7 +276,7 @@ if( line.hasOption( "buildfile" ) ) {

      CLI also provides the means to automatically generate usage and help information. This is achieved with the - HelpFormatter + HelpFormatter class.

      // automatically generate the help statement @@ -311,7 +311,7 @@ formatter.printHelp( "ant", options );

      One of the most widely used command line applications in the *nix world is ls. To parse a command line for an application like this - we will use the PosixParser. + we will use the PosixParser. Due to the large number of options required for ls this example will only cover a small proportion of the options. The following is a section of the help output. @@ -332,7 +332,7 @@ Sort entries alphabetically if none of -cftuSUX nor --sort. -C list entries by columns

      The following is the code that is used to create the - Options for this example. + Options for this example.

      // create the command line parser CommandLineParser parser = new PosixParser(); From 3a5905c0efdae788adb01f73ebf07b743e4e8e39 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 30 Jul 2008 15:02:35 +0000 Subject: [PATCH 0106/1663] Removed cvs-usage.xml git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@681075 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/cvs-usage.xml | 45 --------------------------------------------- 1 file changed, 45 deletions(-) delete mode 100644 xdocs/cvs-usage.xml diff --git a/xdocs/cvs-usage.xml b/xdocs/cvs-usage.xml deleted file mode 100644 index 2b06de3ff..000000000 --- a/xdocs/cvs-usage.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - Source repository - Commons Documentation Team - - - -
      -

      - Apache Commons CLI is hosted on the Apache - subversion repository. -

      -

      - The project URL is:
      - http://svn.apache.org/repos/asf/commons/proper/cli/trunk -

      -

      - The best way to view the repository is via the - subversion viewer. -

      -

      - The alternative is to use the - native subversion display. -

      -
      - - -
      From 34d2ee961a748fecc501bc312317963e14b5f76d Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 30 Jul 2008 15:07:18 +0000 Subject: [PATCH 0107/1663] Minor improvement to the ls example git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@681077 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/usage.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xdocs/usage.xml b/xdocs/usage.xml index dc50873c0..f27d65607 100644 --- a/xdocs/usage.xml +++ b/xdocs/usage.xml @@ -345,8 +345,8 @@ options.addOption( "b", "escape", false, "print octal escapes for nongraphic " + "characters" ); options.addOption( OptionBuilder.withLongOpt( "block-size" ) .withDescription( "use SIZE-byte blocks" ) - .withValueSeparator( '=' ) .hasArg() + .withArgName("SIZE") .create() ); options.addOption( "B", "ignore-backups", false, "do not list implied entried " + "ending with ~"); From 028893dad71e4823f67a427903699999d6eedd4b Mon Sep 17 00:00:00 2001 From: Oliver Heger Date: Wed, 30 Jul 2008 19:55:21 +0000 Subject: [PATCH 0108/1663] CLI-124: Provide better support for displaying usage information for optional child groups. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@681185 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli2/DisplaySetting.java | 11 ++- .../apache/commons/cli2/option/GroupImpl.java | 5 +- .../commons/cli2/util/HelpFormatter.java | 2 +- .../apache/commons/cli2/option/GroupTest.java | 28 ++++++++ .../commons/cli2/option/NestedGroupTest.java | 72 ++++++++++++------- 5 files changed, 86 insertions(+), 32 deletions(-) diff --git a/src/java/org/apache/commons/cli2/DisplaySetting.java b/src/java/org/apache/commons/cli2/DisplaySetting.java index a8bd71e54..32273b495 100644 --- a/src/java/org/apache/commons/cli2/DisplaySetting.java +++ b/src/java/org/apache/commons/cli2/DisplaySetting.java @@ -31,12 +31,12 @@ public class DisplaySetting { private static final Set all = new HashSet(); /** - * A Set guarenteed to contain all possible DisplaySetting values + * A Set guaranteed to contain all possible DisplaySetting values */ public static final Set ALL = Collections.unmodifiableSet(all); /** - * A Set guarenteed to contain no DisplaySetting values + * A Set guaranteed to contain no DisplaySetting values */ public static final Set NONE = Collections.EMPTY_SET; @@ -52,6 +52,13 @@ public class DisplaySetting { public static final DisplaySetting DISPLAY_OPTIONAL = new DisplaySetting("DISPLAY_OPTIONAL"); + /** + * Indicates that optional child groups should be displayed in square + * brackets. + */ + public static final DisplaySetting DISPLAY_OPTIONAL_CHILD_GROUP = + new DisplaySetting("DISPLAY_OPTIONAL_CHILD_GROUP"); + /** * Indicates that property options should be included */ diff --git a/src/java/org/apache/commons/cli2/option/GroupImpl.java b/src/java/org/apache/commons/cli2/option/GroupImpl.java index 56f295727..a0e2df9bb 100644 --- a/src/java/org/apache/commons/cli2/option/GroupImpl.java +++ b/src/java/org/apache/commons/cli2/option/GroupImpl.java @@ -304,8 +304,9 @@ public void appendUsage(final StringBuffer buffer, final String separator) { final Set helpSettingsCopy = new HashSet(helpSettings); - final boolean optional = - (minimum == 0) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_OPTIONAL); + final boolean optional = !isRequired() + && (helpSettingsCopy.contains(DisplaySetting.DISPLAY_OPTIONAL) || + helpSettingsCopy.contains(DisplaySetting.DISPLAY_OPTIONAL_CHILD_GROUP)); final boolean expanded = (name == null) || helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED); diff --git a/src/java/org/apache/commons/cli2/util/HelpFormatter.java b/src/java/org/apache/commons/cli2/util/HelpFormatter.java index ff24e8c73..11b51c19f 100644 --- a/src/java/org/apache/commons/cli2/util/HelpFormatter.java +++ b/src/java/org/apache/commons/cli2/util/HelpFormatter.java @@ -17,7 +17,6 @@ package org.apache.commons.cli2.util; import java.io.PrintWriter; - import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -84,6 +83,7 @@ public class HelpFormatter { final Set fullUsage = new HashSet(DisplaySetting.ALL); fullUsage.remove(DisplaySetting.DISPLAY_ALIASES); fullUsage.remove(DisplaySetting.DISPLAY_GROUP_NAME); + fullUsage.remove(DisplaySetting.DISPLAY_OPTIONAL_CHILD_GROUP); DEFAULT_FULL_USAGE_SETTINGS = Collections.unmodifiableSet(fullUsage); final Set lineUsage = new HashSet(); diff --git a/src/test/org/apache/commons/cli2/option/GroupTest.java b/src/test/org/apache/commons/cli2/option/GroupTest.java index 0f9fbbdcb..3e5c1b025 100644 --- a/src/test/org/apache/commons/cli2/option/GroupTest.java +++ b/src/test/org/apache/commons/cli2/option/GroupTest.java @@ -344,6 +344,34 @@ public void testAppendUsage_WithArgs() { assertEquals("[ant (--help (-?,-h)) [ [ ...]]]", buffer.toString()); } + public void testAppendUsage_OptionalChildGroup() { + final Option option = buildRequiredTestGroup(false, 2).getParent(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + option.appendUsage(buffer, settings, null); + + assertEquals("[parent ([test ()])]", buffer.toString()); + } + + public void testAppendUsage_OptionalChildGroupNoSetting() { + final Option option = buildRequiredTestGroup(false, 2).getParent(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + settings.remove(DisplaySetting.DISPLAY_OPTIONAL_CHILD_GROUP); + option.appendUsage(buffer, settings, null); + + assertEquals("[parent (test ())]", buffer.toString()); + } + + public void testAppendUsage_RequiredChildGroup() { + final Option option = buildRequiredTestGroup(true, 2).getParent(); + final StringBuffer buffer = new StringBuffer(); + final Set settings = new HashSet(DisplaySetting.ALL); + option.appendUsage(buffer, settings, null); + + assertEquals("[parent (test ())]", buffer.toString()); + } + /* * (non-Javadoc) * diff --git a/src/test/org/apache/commons/cli2/option/NestedGroupTest.java b/src/test/org/apache/commons/cli2/option/NestedGroupTest.java index 5fd8219bb..663d560b7 100644 --- a/src/test/org/apache/commons/cli2/option/NestedGroupTest.java +++ b/src/test/org/apache/commons/cli2/option/NestedGroupTest.java @@ -16,8 +16,20 @@ */ package org.apache.commons.cli2.option; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import org.apache.commons.cli2.CLITestCase; import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.DisplaySetting; import org.apache.commons.cli2.Group; import org.apache.commons.cli2.OptionException; import org.apache.commons.cli2.builder.ArgumentBuilder; @@ -26,20 +38,28 @@ import org.apache.commons.cli2.commandline.Parser; import org.apache.commons.cli2.util.HelpFormatter; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringReader; -import java.io.StringWriter; - -import java.util.ArrayList; -import java.util.List; - /** * Test to exercise nested groups developed to demonstrate bug 32533 */ public class NestedGroupTest extends CLITestCase { + private static final String[] EXPECTED_USAGE = new String[] { + "Usage: ", + " [-h -k -e|-d -b|-3 -f |-s ] ", + "encryptionService ", + " -h (--help) Print this message ", + " -k (--key) Encryption key ", + " Action Action ", + " -e (--encrypt) Encrypt input ", + " -d (--decrypt) Decrypt input ", + " Algorithm Encryption Algorithm ", + " -b (--blowfish) Blowfish ", + " -3 (--3DES) Triple DES ", + " Input Input ", + " -f (--file) file Input file ", + " -s (--string) string Input string " + }; + final static DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final static ArgumentBuilder abuilder = new ArgumentBuilder(); final static GroupBuilder gbuilder = new GroupBuilder(); @@ -127,13 +147,27 @@ public void testNestedGroup() } public void testNestedGroupHelp() { + checkNestedGroupHelp(new HelpFormatter(), EXPECTED_USAGE); + } + + public void testNestedGroupHelpOptional() + { + HelpFormatter helpFormatter = new HelpFormatter(); + Set dispOptions = new HashSet(helpFormatter.getFullUsageSettings()); + dispOptions.add(DisplaySetting.DISPLAY_OPTIONAL_CHILD_GROUP); + List expLines = new ArrayList(Arrays.asList(EXPECTED_USAGE)); + expLines.set(1," [-h -k -e|-d [-b|-3] -f |-s ] "); + helpFormatter.setFullUsageSettings(dispOptions); + checkNestedGroupHelp(helpFormatter, (String[]) expLines + .toArray(new String[expLines.size()])); + } + + private void checkNestedGroupHelp(HelpFormatter helpFormatter, String[] expected) { Group[] nestedGroups = { buildActionGroup(), buildAlgorithmGroup(), buildInputGroup() }; - - HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setGroup(buildEncryptionServiceGroup(nestedGroups)); final StringWriter out = new StringWriter(); @@ -144,22 +178,6 @@ public void testNestedGroupHelp() { final BufferedReader bufferedReader = new BufferedReader(new StringReader( out.toString())); - final String[] expected = new String[] { - "Usage: ", - " [-h -k -e|-d -b|-3 -f |-s ] ", - "encryptionService ", - " -h (--help) Print this message ", - " -k (--key) Encryption key ", - " Action Action ", - " -e (--encrypt) Encrypt input ", - " -d (--decrypt) Decrypt input ", - " Algorithm Encryption Algorithm ", - " -b (--blowfish) Blowfish ", - " -3 (--3DES) Triple DES ", - " Input Input ", - " -f (--file) file Input file ", - " -s (--string) string Input string " - }; List actual = new ArrayList(expected.length); String input; From 9cd78b4c83df53ba302baadac4c976ca84f428f9 Mon Sep 17 00:00:00 2001 From: Oliver Heger Date: Wed, 30 Jul 2008 20:16:51 +0000 Subject: [PATCH 0109/1663] CLI-150: Make WriteableCommandLineImpl.looksLikeOption() more intelligent, so that it does not misinterpret negative numbers passed to arguments as options. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@681191 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli2/WriteableCommandLine.java | 16 +++++ .../commandline/WriteableCommandLineImpl.java | 59 +++++++++++++++--- .../apache/commons/cli2/option/GroupImpl.java | 24 ++++++- .../commons/cli2/bug/BugCLI150Test.java | 62 +++++++++++++++++++ 4 files changed, 151 insertions(+), 10 deletions(-) create mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI150Test.java diff --git a/src/java/org/apache/commons/cli2/WriteableCommandLine.java b/src/java/org/apache/commons/cli2/WriteableCommandLine.java index a4e45d610..8bd6752af 100644 --- a/src/java/org/apache/commons/cli2/WriteableCommandLine.java +++ b/src/java/org/apache/commons/cli2/WriteableCommandLine.java @@ -93,4 +93,20 @@ public interface WriteableCommandLine extends CommandLine { * @return true if the argument looks like an Option trigger */ boolean looksLikeOption(final String argument); + + /** + * Returns the option that is currently processed. + * + * @return the current option + */ + Option getCurrentOption(); + + /** + * Sets the current option. This method is called by concrete option + * implementations during command line processing. It enables the command + * line to keep track about the option that is currently processed. + * + * @param currentOption the new current option + */ + void setCurrentOption(Option currentOption); } diff --git a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java index ec97eab90..8c5e29bd1 100644 --- a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java +++ b/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java @@ -48,6 +48,8 @@ public class WriteableCommandLineImpl private final Map defaultSwitches = new HashMap(); private final List normalised; private final Set prefixes; + private Option currentOption; + private String checkForOption; /** * Creates a new WriteableCommandLineImpl rooted on the specified Option, to @@ -60,6 +62,15 @@ public WriteableCommandLineImpl(final Option rootOption, final List arguments) { this.prefixes = rootOption.getPrefixes(); this.normalised = arguments; + setCurrentOption(rootOption); + } + + public Option getCurrentOption() { + return currentOption; + } + + public void setCurrentOption(Option currentOption) { + this.currentOption = currentOption; } public void addOption(Option option) { @@ -141,7 +152,7 @@ public List getValues(final Option option, } } } - + return valueList == null ? Collections.EMPTY_LIST : valueList; } @@ -216,16 +227,48 @@ public Set getProperties() { return getProperties(new PropertyOption()); } - public boolean looksLikeOption(final String trigger) { - for (final Iterator i = prefixes.iterator(); i.hasNext();) { - final String prefix = (String) i.next(); + /** + * Tests whether the passed in trigger looks like an option. This + * implementation first checks whether the passed in string starts with a + * prefix that indicates an option. If this is the case, it is also checked + * whether an option of this name is known for the current option. (This can + * lead to reentrant invocations of this method, so care has to be taken + * about this.) + * + * @param trigger the command line element to test + * @return a flag whether this element seems to be an option + */ + public boolean looksLikeOption(final String trigger) + { + if (checkForOption != null) + { + // this is a reentrant call + return !checkForOption.equals(trigger); + } - if (trigger.startsWith(prefix)) { - return true; + checkForOption = trigger; + try + { + for (final Iterator i = prefixes.iterator(); i.hasNext();) + { + final String prefix = (String) i.next(); + + if (trigger.startsWith(prefix)) + { + if (getCurrentOption().canProcess(this, trigger) + || getCurrentOption().findOption(trigger) != null) + { + return true; + } + } } - } - return false; + return false; + } + finally + { + checkForOption = null; + } } public String toString() { diff --git a/src/java/org/apache/commons/cli2/option/GroupImpl.java b/src/java/org/apache/commons/cli2/option/GroupImpl.java index a0e2df9bb..fc5a82d9d 100644 --- a/src/java/org/apache/commons/cli2/option/GroupImpl.java +++ b/src/java/org/apache/commons/cli2/option/GroupImpl.java @@ -136,7 +136,7 @@ public boolean canProcess(final WriteableCommandLine commandLine, } } - if (commandLine.looksLikeOption(arg)) { + if (looksLikeOption(commandLine, arg)) { return false; } @@ -188,7 +188,7 @@ public void process(final WriteableCommandLine commandLine, else { // it might be an anonymous argument continue search // [START argument may be anonymous - if (commandLine.looksLikeOption(arg)) { + if (looksLikeOption(commandLine, arg)) { // narrow the search final Collection values = optionMap.tailMap(arg).values(); @@ -498,6 +498,26 @@ public void defaults(final WriteableCommandLine commandLine) { option.defaults(commandLine); } } + + /** + * Helper method for testing whether an element of the command line looks + * like an option. This method queries the command line, but sets the + * current option first. + * + * @param commandLine the command line + * @param trigger the trigger to be checked + * @return a flag whether this element looks like an option + */ + private boolean looksLikeOption(final WriteableCommandLine commandLine, + final String trigger) { + Option oldOption = commandLine.getCurrentOption(); + try { + commandLine.setCurrentOption(this); + return commandLine.looksLikeOption(trigger); + } finally { + commandLine.setCurrentOption(oldOption); + } + } } diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI150Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI150Test.java new file mode 100644 index 000000000..cb56c17a9 --- /dev/null +++ b/src/test/org/apache/commons/cli2/bug/BugCLI150Test.java @@ -0,0 +1,62 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.cli2.bug; + +import junit.framework.TestCase; + +import org.apache.commons.cli2.Argument; +import org.apache.commons.cli2.CommandLine; +import org.apache.commons.cli2.Group; +import org.apache.commons.cli2.Option; +import org.apache.commons.cli2.OptionException; +import org.apache.commons.cli2.builder.ArgumentBuilder; +import org.apache.commons.cli2.builder.DefaultOptionBuilder; +import org.apache.commons.cli2.builder.GroupBuilder; +import org.apache.commons.cli2.commandline.Parser; +import org.apache.commons.cli2.validation.NumberValidator; + +/** + * An argument whose value is a negative number is mistaken as an option. + * + * @author Oliver Heger + * @version $Id$ + */ +public class BugCLI150Test extends TestCase +{ + public void testNegativeNumber() throws OptionException + { + final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder(); + final ArgumentBuilder aBuilder = new ArgumentBuilder(); + final GroupBuilder gBuilder = new GroupBuilder(); + + final Argument numArg = aBuilder.withValidator( + NumberValidator.getNumberInstance()).withMinimum(1) + .withMaximum(1).create(); + final Option numOpt = oBuilder.withLongName("num").withArgument(numArg) + .create(); + final Group options = gBuilder.withOption(numOpt).create(); + + final Parser parser = new Parser(); + parser.setGroup(options); + + CommandLine cl = parser.parse(new String[] { + "--num", "-42" + }); + Number num = (Number) cl.getValue(numOpt); + assertEquals("Wrong option value", -42, num.intValue()); + } +} From 6183eaa93eac3a365ba7630755c4664a8ea88633 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Tue, 14 Oct 2008 12:10:08 +0000 Subject: [PATCH 0110/1663] Fixed several typos spotted by Hendrik Maryns (CLI-171) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@704507 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/examples/ant.xml | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/xdocs/examples/ant.xml b/xdocs/examples/ant.xml index fb9cf0e6e..440837153 100644 --- a/xdocs/examples/ant.xml +++ b/xdocs/examples/ant.xml @@ -48,53 +48,53 @@ final GroupBuilder gbuilder = new GroupBuilder();

      Option help = obuilder - .withShortName("help") + .withLongName("help") .withShortName("h") .withDescription("print this message") .create(); Option projecthelp = obuilder - .withShortName("projecthelp") + .withLongName("projecthelp") .withShortName("p") .withDescription("print project help information") .create(); Option version = obuilder - .withShortName("version") + .withLongName("version") .withDescription("print the version information and exit") .create(); Option diagnostics = obuilder - .withShortName("diagnostics") + .withLongName("diagnostics") .withDescription("print information that might be helpful to diagnose or report problems.") .create(); Option quiet = obuilder - .withShortName("quiet") + .withLongName("quiet") .withShortName("q") .withDescription("be extra quiet") .create(); Option verbose = obuilder - .withShortName("verbose") + .withLongName("verbose") .withShortName("v") .withDescription("be extra verbose") .create(); Option debug = obuilder - .withShortName("debug") + .withLongName("debug") .withShortName("d") .withDescription("print debugging information") .create(); Option emacs = obuilder - .withShortName("emacs") + .withLongName("emacs") .withShortName("e") .withDescription("produce logging information without adornments") .create(); Option lib = obuilder - .withShortName("lib") + .withLongName("lib") .withDescription("specifies a path to search for jars and classes") .withArgument( abuilder @@ -105,7 +105,7 @@ Option lib = .create(); Option logfile = obuilder - .withShortName("logfile") + .withLongName("logfile") .withShortName("l") .withDescription("use given file for log") .withArgument( @@ -117,7 +117,7 @@ Option logfile = .create(); Option logger = obuilder - .withShortName("logger") + .withLongName("logger") .withDescription("the class which is to perform logging") .withArgument( abuilder @@ -128,7 +128,7 @@ Option logger = .create(); Option listener = obuilder - .withShortName("listener") + .withLongName("listener") .withDescription("add an instance of class as a project listener") .withArgument( abuilder @@ -139,13 +139,13 @@ Option listener = .create(); Option noinput = obuilder - .withShortName("noinput") + .withLongName("noinput") .withDescription("do not allow interactive input") .create(); Option buildfile = obuilder - .withShortName("buildfile") - .withShortName("file") + .withLongName("buildfile") + .withLongName("file") .withShortName("f") .withDescription("use given buildfile") .withArgument( @@ -158,7 +158,7 @@ Option buildfile = Option property = new PropertyOption(); Option propertyfile = obuilder - .withShortName("propertyfile") + .withLongName("propertyfile") .withDescription("load all properties from file with -D properties taking precedence") .withArgument( abuilder @@ -169,7 +169,7 @@ Option propertyfile = .create(); Option inputhandler = obuilder - .withShortName("inputhandler") + .withLongName("inputhandler") .withDescription("the class which will handle input requests") .withArgument( abuilder @@ -180,7 +180,7 @@ Option inputhandler = .create(); Option find = obuilder - .withShortName("find") + .withLongName("find") .withShortName("s") .withDescription("search for buildfile towards the root of the filesystem and use it") .withArgument( @@ -260,7 +260,7 @@ for (Iterator i = targetList.iterator(); i.hasNext();) {

      To generate a help page for ant we first need to create a HelpFormatter and set some basic properties. The shell command is - the command that the used would have typed to invoke the application, + the command that the user would have typed to invoke the application, and the group is the group of options that compose the model.

      HelpFormatter hf = new HelpFormatter(); From f564e7800a9a26e47a655391dda37a0f26e67a28 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Tue, 14 Oct 2008 14:34:05 +0000 Subject: [PATCH 0111/1663] Reverted the replacement of withShortName with withLongName (CLI-171) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@704549 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/examples/ant.xml | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/xdocs/examples/ant.xml b/xdocs/examples/ant.xml index 440837153..8be3bf5c5 100644 --- a/xdocs/examples/ant.xml +++ b/xdocs/examples/ant.xml @@ -48,53 +48,53 @@ final GroupBuilder gbuilder = new GroupBuilder();

      Option help = obuilder - .withLongName("help") + .withShortName("help") .withShortName("h") .withDescription("print this message") .create(); Option projecthelp = obuilder - .withLongName("projecthelp") + .withShortName("projecthelp") .withShortName("p") .withDescription("print project help information") .create(); Option version = obuilder - .withLongName("version") + .withShortName("version") .withDescription("print the version information and exit") .create(); Option diagnostics = obuilder - .withLongName("diagnostics") + .withShortName("diagnostics") .withDescription("print information that might be helpful to diagnose or report problems.") .create(); Option quiet = obuilder - .withLongName("quiet") + .withShortName("quiet") .withShortName("q") .withDescription("be extra quiet") .create(); Option verbose = obuilder - .withLongName("verbose") + .withShortName("verbose") .withShortName("v") .withDescription("be extra verbose") .create(); Option debug = obuilder - .withLongName("debug") + .withShortName("debug") .withShortName("d") .withDescription("print debugging information") .create(); Option emacs = obuilder - .withLongName("emacs") + .withShortName("emacs") .withShortName("e") .withDescription("produce logging information without adornments") .create(); Option lib = obuilder - .withLongName("lib") + .withShortName("lib") .withDescription("specifies a path to search for jars and classes") .withArgument( abuilder @@ -105,7 +105,7 @@ Option lib = .create(); Option logfile = obuilder - .withLongName("logfile") + .withShortName("logfile") .withShortName("l") .withDescription("use given file for log") .withArgument( @@ -117,7 +117,7 @@ Option logfile = .create(); Option logger = obuilder - .withLongName("logger") + .withShortName("logger") .withDescription("the class which is to perform logging") .withArgument( abuilder @@ -128,7 +128,7 @@ Option logger = .create(); Option listener = obuilder - .withLongName("listener") + .withShortName("listener") .withDescription("add an instance of class as a project listener") .withArgument( abuilder @@ -139,13 +139,13 @@ Option listener = .create(); Option noinput = obuilder - .withLongName("noinput") + .withShortName("noinput") .withDescription("do not allow interactive input") .create(); Option buildfile = obuilder - .withLongName("buildfile") - .withLongName("file") + .withShortName("buildfile") + .withShortName("file") .withShortName("f") .withDescription("use given buildfile") .withArgument( @@ -158,7 +158,7 @@ Option buildfile = Option property = new PropertyOption(); Option propertyfile = obuilder - .withLongName("propertyfile") + .withShortName("propertyfile") .withDescription("load all properties from file with -D properties taking precedence") .withArgument( abuilder @@ -169,7 +169,7 @@ Option propertyfile = .create(); Option inputhandler = obuilder - .withLongName("inputhandler") + .withShortName("inputhandler") .withDescription("the class which will handle input requests") .withArgument( abuilder @@ -180,7 +180,7 @@ Option inputhandler = .create(); Option find = obuilder - .withLongName("find") + .withShortName("find") .withShortName("s") .withDescription("search for buildfile towards the root of the filesystem and use it") .withArgument( From 06aa39c58ae8c758c80396e1c3c6c607281e35a9 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Fri, 17 Oct 2008 16:50:01 +0000 Subject: [PATCH 0112/1663] Fixed the test resources for Maven 2 Updated the pom to reflect the changes on the 1.x branch git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@705669 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 46 ++++++++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/pom.xml b/pom.xml index 5e2cdffc4..fe0a2cc5c 100644 --- a/pom.xml +++ b/pom.xml @@ -15,10 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. --> - + org.apache.commons commons-parent @@ -32,8 +29,7 @@ 2002 - Commons CLI provides a simple API for presenting, processing and - validating a command line interface. + Commons CLI provides a simple API for presenting, processing and validating a command line interface. http://commons.apache.org/cli/ @@ -102,6 +98,12 @@ contributed ideas and code from Avalon Excalibur's cli package + + Brian Egge + + made the 1.1 release happen + + Berin Loritsch bloritsch@apache.org @@ -117,10 +119,15 @@ supplied patch + + Andrew Shirley + + lots of fixes for 1.1 + + - junit @@ -128,21 +135,13 @@ 3.8.1 test - - - - jdepend - jdepend - 2.5 - test - - cli + commons-cli-${commons.release.version} org.apache.commons.cli2 - 1.1 + 1.2 CLI 12310463 @@ -169,13 +168,12 @@ - - src/test/org/apache/commons/cli2/resource - org/apache/commons/cli2/resource - - **/*.properties - - + + src/test + + **/*.properties + + From 4e4db7b36b883405058a25575a0f7cf5c24ac243 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Fri, 17 Oct 2008 17:06:43 +0000 Subject: [PATCH 0113/1663] Removed the Maven 1 build and the old Gump descriptor git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@705674 13f79535-47bb-0310-9956-ffa450edef68 --- README.txt | 18 +- build-gump.xml | 36 --- maven.xml | 49 ---- project.xml | 217 ------------------ .../cli2/validation/FileValidatorTest.java | 14 +- xdocs/index.xml | 2 +- 6 files changed, 16 insertions(+), 320 deletions(-) delete mode 100644 build-gump.xml delete mode 100644 maven.xml delete mode 100644 project.xml diff --git a/README.txt b/README.txt index edf5fb339..914bd6d6c 100644 --- a/README.txt +++ b/README.txt @@ -7,36 +7,36 @@ The information in this file is relevant if you have downloaded a CLI source distribution. For testing the project, you will need JUnit (if you use -maven this will be automatically installed and configured +Maven this will be automatically installed and configured for you): - http://www.junit.org/ + http://www.junit.org -There are two ways to build CLI, either with ant or maven. +There are two ways to build CLI, either with Ant or Maven 2. Ant can be found here : - http://ant.apache.org/ + http://ant.apache.org and to build and test the system use: ant dist -Maven can be found here : +Maven 2 can be found here : - http://maven.apache.org/ + http://maven.apache.org and to build and test the system use: - maven jar:jar + mvn clean package The system will build and test itself. For complete documentation and to create a local copy of the CLI project website, type: - maven site + mvn site Good luck! --The CLI Team +- The Apache Commons Team diff --git a/build-gump.xml b/build-gump.xml deleted file mode 100644 index b5d7d58a4..000000000 --- a/build-gump.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/maven.xml b/maven.xml deleted file mode 100644 index 14c612c00..000000000 --- a/maven.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - Moving test bundle. - - - - - - - - - - - - diff --git a/project.xml b/project.xml deleted file mode 100644 index 6f5448df8..000000000 --- a/project.xml +++ /dev/null @@ -1,217 +0,0 @@ - - - - commons-cli - commons-cli - CLI - 2.0-SNAPSHOT - 2002 - Commons CLI - - Commons CLI provides a simple API for presenting, processing and - validating a command line interface. - - /images/logo.png - - http://commons.apache.org/cli/ - org.apache.commons - - - Apache Software Foundation - http://commons.apache.org/ - http://commons.apache.org/images/logo.png - - - - - The Apache Software License, Version 2.0 - /LICENSE.txt - repo - - - - commons - http://issues.apache.org/jira/ - people.apache.org - /www/commons.apache.org/cli/ - /www/people.apache.org/builds/commons/cli/ - - - scm:svn:http://svn.apache.org/repos/asf/commons/proper/cli/trunk - http://svn.apache.org/repos/asf/commons/proper/cli/trunk - - - - - Commons Dev List - dev-subscribe@commons.apache.org - dev-unsubscribe@commons.apache.org - http://mail-archives.apache.org/mod_mbox/commons-dev/ - - - Commons User List - user-subscribe@commons.apache.org - user-unsubscribe@commons.apache.org - http://mail-archives.apache.org/mod_mbox/commons-user/ - - - - - - James Strachan - jstrachan - jstrachan@apache.org - SpiritSoft, Inc. - - - Bob McWhirter - bob - bob@werken.com - Werken - - contributed ideas and code from werken.opt - - - - John Keyes - jkeyes - jbjk@mac.com - integral Source - - contributed ideas and code from Optz - - - - Rob Oxspring - roxspring - roxspring@imapmail.org - Indigo Stone - - designed CLI2 - - - - Oliver Heger - oheger - oheger@apache.org - Agfa HealthCare - +1 - - Java Developer - - - - - - - Peter Donald - - contributed ideas and code from Avalon Excalibur's cli package - - - - Brian Egge - - made the 1.1 release happen - - - - Berin Loritsch - bloritsch@apache.org - - helped in the Avalon CLI merge - - - - Peter Maddocks - peter_maddocks@hp.com - Hewlett-Packard - - supplied patch - - - - - - - - - junit - junit - 3.8.1 - - test - - Required only for testing. - - - - - - - jdepend - jdepend - 2.5 - - test - - Required only for testing. - - - - - - - - dev@commons.apache.org - src/java - src/test - - - - - src/java/org/apache/commons/cli2 - org/apache/commons/cli2 - - **/*.properties - - - - - - - - **/Test*.java - **/*Test.java - - - - - - maven-changes-plugin - maven-jdepend-plugin - maven-checkstyle-plugin - maven-javadoc-plugin - maven-jdepend-plugin - maven-junit-report-plugin - maven-jxr-plugin - maven-license-plugin - maven-pmd-plugin - maven-findbugs-plugin - - diff --git a/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java b/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java index 8ced24047..88e688767 100644 --- a/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java +++ b/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java @@ -33,8 +33,7 @@ public class FileValidatorTest extends TestCase { public void testValidate() throws InvalidArgumentException { - final Object[] array = new Object[] { "src", "project.xml", - "veryunlikelyfilename" }; + final Object[] array = new Object[] { "src", "pom.xml", "veryunlikelyfilename" }; final List list = Arrays.asList(array); final FileValidator validator = new FileValidator(); @@ -42,13 +41,13 @@ public void testValidate() throws InvalidArgumentException { final Iterator i = list.iterator(); assertEquals(new File("src"), i.next()); - assertEquals(new File("project.xml"), i.next()); + assertEquals(new File("pom.xml"), i.next()); assertEquals(new File("veryunlikelyfilename"), i.next()); assertFalse(i.hasNext()); } public void testValidate_Directory() { - final Object[] array = new Object[] { "src", "project.xml" }; + final Object[] array = new Object[] { "src", "pom.xml" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator .getExistingDirectoryInstance(); @@ -62,7 +61,7 @@ public void testValidate_Directory() { validator.validate(list); fail("InvalidArgumentException"); } catch (InvalidArgumentException e) { - assertEquals("project.xml", e.getMessage()); + assertEquals("pom.xml", e.getMessage()); } } @@ -163,8 +162,7 @@ private void attribute(String attr) { } public void testValidate_Existing() { - final Object[] array = new Object[] { "project.xml", - "veryunlikelyfilename" }; + final Object[] array = new Object[] { "pom.xml", "veryunlikelyfilename" }; final List list = Arrays.asList(array); final FileValidator validator = FileValidator.getExistingInstance(); @@ -182,7 +180,7 @@ public void testValidate_Existing() { } public void testValidate_File() { - final Object[] array = new Object[] { "project.xml", "src" }; + final Object[] array = new Object[] { "pom.xml", "src" }; final List list = Arrays.asList(array); final Validator validator = FileValidator.getExistingFileInstance(); diff --git a/xdocs/index.xml b/xdocs/index.xml index f7b5b4bd1..215bc31d2 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -76,7 +76,7 @@ usage: ls

      A full User's Guide is available - as are variousproject reports. + as are various project reports.

      The Javadoc API documents are available online: From dcb1ec428fc6b34bbbf1531812dbc1f54ce83325 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Fri, 17 Oct 2008 17:10:40 +0000 Subject: [PATCH 0114/1663] Fixed the compilation error on the jdepend test git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@705675 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pom.xml b/pom.xml index fe0a2cc5c..a2c0bf919 100644 --- a/pom.xml +++ b/pom.xml @@ -135,6 +135,12 @@ 3.8.1 test + + jdepend + jdepend + 2.5 + test + From c906602a331e91625aa95d42673acbc9962fcd43 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Sat, 18 Oct 2008 15:43:55 +0000 Subject: [PATCH 0115/1663] Added the gump profile git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@705891 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/pom.xml b/pom.xml index a2c0bf919..9852eadcd 100644 --- a/pom.xml +++ b/pom.xml @@ -251,4 +251,27 @@ + + + + + gump + + + maven.final.name + + + + + + maven-jar-plugin + + ${maven.final.name} + + + + + + + From f1e3d9db8fe9efd30ecadc466a2009524fc1710a Mon Sep 17 00:00:00 2001 From: Siegfried Goeschl Date: Mon, 12 Jan 2009 14:52:23 +0000 Subject: [PATCH 0116/1663] Fixed three javadoc warnings found during the M2 build. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@733774 13f79535-47bb-0310-9956-ffa450edef68 --- src/test/org/apache/commons/cli2/bug/BugCLI144Test.java | 4 +++- .../org/apache/commons/cli2/resource/ResourceHelperTest.java | 2 -- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/org/apache/commons/cli2/bug/BugCLI144Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI144Test.java index 547033824..f92df8951 100644 --- a/src/test/org/apache/commons/cli2/bug/BugCLI144Test.java +++ b/src/test/org/apache/commons/cli2/bug/BugCLI144Test.java @@ -30,7 +30,9 @@ import org.apache.commons.cli2.validation.FileValidator; /** - * Test case for http://issues.apache.org/jira/browse/CLI-144 CLI 2 throws + * Test case for http://issues.apache.org/jira/browse/CLI-144. + * + * CLI 2 throws * *

        * Exception in thread "main" java.lang.ClassCastException: java.io.File cannot be cast to java.lang.String
      diff --git a/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java b/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java
      index 1bc28873d..a5888a3f1 100644
      --- a/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java
      +++ b/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java
      @@ -49,8 +49,6 @@ public void tearDown() {
           
           /**
            * Create a new ResourceHelper for the specified class.
      -     *
      -     * @param clazz the Class that requires some resources
            */
           public ResourceHelperTest() {
           	super("ResourceHelperTest");
      
      From 0a7160dae4a0c9c8d1d59cdc2ce31301e67194c2 Mon Sep 17 00:00:00 2001
      From: Siegfried Goeschl 
      Date: Mon, 12 Jan 2009 16:53:15 +0000
      Subject: [PATCH 0117/1663] Some cosmetic javadoc fixes to make reviewers happy
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@733838 13f79535-47bb-0310-9956-ffa450edef68
      ---
       src/java/org/apache/commons/cli2/Option.java                 | 4 ++++
       .../org/apache/commons/cli2/builder/ArgumentBuilder.java     | 1 +
       src/java/org/apache/commons/cli2/builder/CommandBuilder.java | 1 +
       .../apache/commons/cli2/builder/DefaultOptionBuilder.java    | 3 ++-
       src/java/org/apache/commons/cli2/builder/GroupBuilder.java   | 5 +++--
       src/java/org/apache/commons/cli2/builder/PatternBuilder.java | 3 ++-
       src/java/org/apache/commons/cli2/builder/SwitchBuilder.java  | 3 ++-
       src/java/org/apache/commons/cli2/commandline/Parser.java     | 1 -
       .../org/apache/commons/cli2/validation/ClassValidator.java   | 2 ++
       .../org/apache/commons/cli2/validation/UrlValidator.java     | 1 +
       10 files changed, 18 insertions(+), 6 deletions(-)
      
      diff --git a/src/java/org/apache/commons/cli2/Option.java b/src/java/org/apache/commons/cli2/Option.java
      index 0102573aa..029b137bd 100644
      --- a/src/java/org/apache/commons/cli2/Option.java
      +++ b/src/java/org/apache/commons/cli2/Option.java
      @@ -62,6 +62,8 @@ void process(
            * Indicates whether this Option will be able to process the particular
            * argument.
            *
      +     * @param commandLine
      +     *            The CommandLine to check
            * @param argument
            *            The argument to be tested
            * @return true if the argument can be processed by this Option
      @@ -74,6 +76,8 @@ void process(
            * returning the boolean.
            *
            * @see #canProcess(WriteableCommandLine,String)
      +     * @param commandLine
      +     *            the CommandLine to check
            * @param arguments
            *            the ListIterator over String arguments
            * @return true if the argument can be processed by this Option
      diff --git a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java b/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java
      index c0f28fd27..9148e953e 100644
      --- a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java
      +++ b/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java
      @@ -99,6 +99,7 @@ public final Argument create() {
           /**
            * Resets the ArgumentBuilder to the defaults for a new Argument. The
            * method is called automatically at the end of a create() call.
      +     * @return this ArgumentBuilder
            */
           public final ArgumentBuilder reset() {
               name = "arg";
      diff --git a/src/java/org/apache/commons/cli2/builder/CommandBuilder.java b/src/java/org/apache/commons/cli2/builder/CommandBuilder.java
      index 56c7eb21d..ed9484b1a 100644
      --- a/src/java/org/apache/commons/cli2/builder/CommandBuilder.java
      +++ b/src/java/org/apache/commons/cli2/builder/CommandBuilder.java
      @@ -84,6 +84,7 @@ public Command create() {
            *
            * This method is called automatically at the end of the
            * {@link #create() create} method.
      +     * @return this CommandBuilder
            */
           public CommandBuilder reset() {
               preferredName = null;
      diff --git a/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java b/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java
      index cecfcf54c..71a40b967 100644
      --- a/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java
      +++ b/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java
      @@ -99,7 +99,8 @@ public DefaultOption create()
           }
       
           /**
      -     * Resets the builder
      +     * Resets the builder.
      +     * @return this builder
            */
           public DefaultOptionBuilder reset() {
               preferredName = null;
      diff --git a/src/java/org/apache/commons/cli2/builder/GroupBuilder.java b/src/java/org/apache/commons/cli2/builder/GroupBuilder.java
      index ceb94451d..7c912acc8 100644
      --- a/src/java/org/apache/commons/cli2/builder/GroupBuilder.java
      +++ b/src/java/org/apache/commons/cli2/builder/GroupBuilder.java
      @@ -56,7 +56,8 @@ public Group create() {
           }
       
           /**
      -     * Resets the builder
      +     * Resets the builder.
      +     * @return this builder     
            */
           public GroupBuilder reset() {
               name = null;
      @@ -69,7 +70,7 @@ public GroupBuilder reset() {
           }
       
           /**
      -     * Use this option description
      +     * Use this option description.
            * @param newDescription the description to use
            * @return this builder
            */
      diff --git a/src/java/org/apache/commons/cli2/builder/PatternBuilder.java b/src/java/org/apache/commons/cli2/builder/PatternBuilder.java
      index 2b4c1b54d..2f41f97ae 100644
      --- a/src/java/org/apache/commons/cli2/builder/PatternBuilder.java
      +++ b/src/java/org/apache/commons/cli2/builder/PatternBuilder.java
      @@ -90,7 +90,8 @@ public Option create() {
           }
       
           /**
      -     * Resets this builder
      +     * Resets this builder.
      +     * @return this builder
            */
           public PatternBuilder reset() {
               options.clear();
      diff --git a/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java b/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java
      index fa88df359..54526a023 100644
      --- a/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java
      +++ b/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java
      @@ -91,7 +91,8 @@ public Switch create() {
           }
       
           /**
      -     * Resets the builder
      +     * Resets the builder.
      +     * @return this builder
            */
           public SwitchBuilder reset() {
               description = null;
      diff --git a/src/java/org/apache/commons/cli2/commandline/Parser.java b/src/java/org/apache/commons/cli2/commandline/Parser.java
      index 07ecdbabe..1225baaf9 100644
      --- a/src/java/org/apache/commons/cli2/commandline/Parser.java
      +++ b/src/java/org/apache/commons/cli2/commandline/Parser.java
      @@ -114,7 +114,6 @@ public CommandLine parse(final String[] arguments)
            *
            * @param arguments the command line arguments
            * @return a valid CommandLine or null if the parse was unsuccessful
      -     * @throws IOException if an error occurs while formatting help
            */
           public CommandLine parseAndHelp(final String[] arguments) {
               helpFormatter.setGroup(group);
      diff --git a/src/java/org/apache/commons/cli2/validation/ClassValidator.java b/src/java/org/apache/commons/cli2/validation/ClassValidator.java
      index a4770f2b6..b65519e70 100644
      --- a/src/java/org/apache/commons/cli2/validation/ClassValidator.java
      +++ b/src/java/org/apache/commons/cli2/validation/ClassValidator.java
      @@ -172,6 +172,8 @@ public void setInstance(boolean instance) {
           /**
            * Returns whether the specified name is allowed as
            * a Java class name.
      +     * @param name the name to be checked
      +     * @return true if allowed as Java class name
            */
           protected boolean isPotentialClassName(final String name) {
               final char[] chars = name.toCharArray();
      diff --git a/src/java/org/apache/commons/cli2/validation/UrlValidator.java b/src/java/org/apache/commons/cli2/validation/UrlValidator.java
      index 4ce1d37f2..2f74cf42d 100644
      --- a/src/java/org/apache/commons/cli2/validation/UrlValidator.java
      +++ b/src/java/org/apache/commons/cli2/validation/UrlValidator.java
      @@ -61,6 +61,7 @@ public UrlValidator() {
       
           /**
            * Creates a UrlValidator for the specified protocol.
      +     * @param protocol the protocol to be used
            */
           public UrlValidator(final String protocol) {
               setProtocol(protocol);
      
      From 0a531dbc4d52a5a22374b38003e3728371469dc4 Mon Sep 17 00:00:00 2001
      From: Siegfried Goeschl 
      Date: Mon, 12 Jan 2009 17:01:45 +0000
      Subject: [PATCH 0118/1663] Fixed some minor javadoc issues to make reviewers
       happy.
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@733840 13f79535-47bb-0310-9956-ffa450edef68
      ---
       xdocs/changes.xml | 3 +++
       1 file changed, 3 insertions(+)
      
      diff --git a/xdocs/changes.xml b/xdocs/changes.xml
      index 9c106a0cf..6ef3e88bc 100644
      --- a/xdocs/changes.xml
      +++ b/xdocs/changes.xml
      @@ -23,6 +23,9 @@
         
       
           
      +      
      +        Fixing some minor javadoc issues.
      +      
             
               The number of arguments defined for an option specifies the arguments per occurrence of the option
               and not for all occurrences. This was a major regression in CLI 1.1 which prevented the use of repeated options.
      
      From 043c62bffd422755c68475b8d66d280dac6c2a97 Mon Sep 17 00:00:00 2001
      From: Henri Yandell 
      Date: Fri, 6 Feb 2009 05:03:30 +0000
      Subject: [PATCH 0119/1663] Moving the CLI1->2 converter into CLI2 as it would
       require dependency on both and 1 doesn't care about 2's existence.
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@741413 13f79535-47bb-0310-9956-ffa450edef68
      ---
       CLI2Converter.java     | 191 +++++++++++++++++++++++++++++++++++++++++
       CLI2ConverterTest.java | 133 ++++++++++++++++++++++++++++
       2 files changed, 324 insertions(+)
       create mode 100644 CLI2Converter.java
       create mode 100644 CLI2ConverterTest.java
      
      diff --git a/CLI2Converter.java b/CLI2Converter.java
      new file mode 100644
      index 000000000..76ddcf3d5
      --- /dev/null
      +++ b/CLI2Converter.java
      @@ -0,0 +1,191 @@
      +/**
      + * Licensed to the Apache Software Foundation (ASF) under one or more
      + * contributor license agreements.  See the NOTICE file distributed with
      + * this work for additional information regarding copyright ownership.
      + * The ASF licenses this file to You under the Apache License, Version 2.0
      + * (the "License"); you may not use this file except in compliance with
      + * the License.  You may obtain a copy of the License at
      + *
      + *     http://www.apache.org/licenses/LICENSE-2.0
      + *
      + * Unless required by applicable law or agreed to in writing, software
      + * distributed under the License is distributed on an "AS IS" BASIS,
      + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      + * See the License for the specific language governing permissions and
      + * limitations under the License.
      + */
      +package org.apache.commons.cli;
      +
      +import java.util.HashSet;
      +import java.util.Iterator;
      +import java.util.List;
      +import java.util.ListIterator;
      +import java.util.Set;
      +
      +import org.apache.commons.cli2.Group;
      +import org.apache.commons.cli2.Option;
      +import org.apache.commons.cli2.builder.ArgumentBuilder;
      +import org.apache.commons.cli2.builder.DefaultOptionBuilder;
      +import org.apache.commons.cli2.builder.GroupBuilder;
      +import org.apache.commons.cli2.validation.InvalidArgumentException;
      +import org.apache.commons.cli2.validation.Validator;
      +
      +/**
      + * A utility class for converting data structures version 1 to 
      + * version 2 Option instances.
      + */
      +public class CLI2Converter {
      +	
      +	private CLI2Converter(){
      +		// prevent creation of static utility class 
      +	}
      +	
      +	/**
      +	 * Creates a version 2 Option instance from a version 1 Option instance.
      +	 * 
      +	 * @param option1 the version 1 Option to convert
      +	 * @return a version 2 Option  
      +	 */
      +	public static Option option(final org.apache.commons.cli.Option option1){
      +		
      +		final DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
      +		obuilder.withRequired(option1.isRequired());
      +		
      +		final String shortName = option1.getOpt();
      +		if(shortName!=null && !" ".equals(shortName)){
      +			obuilder.withShortName(shortName);
      +		}
      +		
      +		final String longName = option1.getLongOpt();
      +		if(longName!=null){
      +			obuilder.withLongName(longName);
      +		}
      +		obuilder.withId(option1.getId());
      +		
      +		final String description = option1.getDescription();
      +		if(description!=null){
      +			obuilder.withDescription(description);
      +		}
      +		
      +		if(option1.hasArg()){
      +			final ArgumentBuilder abuilder = new ArgumentBuilder();
      +			final String argName = option1.getArgName();
      +			abuilder.withName(argName);
      +			abuilder.withMaximum(option1.getArgs());
      +			if(option1.hasValueSeparator()){
      +				abuilder.withSubsequentSeparator(option1.getValueSeparator());
      +			}
      +			if(option1.hasOptionalArg()){
      +				abuilder.withMinimum(0);
      +			}
      +			else{
      +				//TODO check what non-optional arg means
      +				abuilder.withMinimum(option1.getArgs());
      +			}
      +			
      +			final Object type = option1.getType();
      +			if(type!=null){
      +				abuilder.withValidator(new TypeHandlerValidator(type));
      +			}
      +			
      +			obuilder.withArgument(abuilder.create());
      +		}
      +		
      +		return obuilder.create();
      +	}
      +	
      +	/**
      +	 * Creates a version 2 Group instance from a version 1 OptionGroup instance.
      +	 * 
      +	 * @param optionGroup1 the version 1 OptionGroup to convert
      +	 * @return a version 2 Group
      +	 */
      +	public static Group group(final OptionGroup optionGroup1){
      +		
      +		final GroupBuilder gbuilder = new GroupBuilder();
      +		
      +		for(final Iterator i = optionGroup1.getOptions().iterator();i.hasNext();){
      +			final org.apache.commons.cli.Option option1 = (org.apache.commons.cli.Option)i.next();
      +			final Option option2 = option(option1);
      +			gbuilder.withOption(option2);
      +		}
      +		
      +		gbuilder.withMaximum(1);
      +		
      +		if(optionGroup1.isRequired()){
      +			gbuilder.withMinimum(1);
      +		}
      +		
      +		return gbuilder.create();
      +	}
      +	
      +	/**
      +	 * Creates a version 2 Group instance from a version 1 Options instance.
      +	 * 
      +	 * @param options1 the version 1 Options to convert
      +	 * @return a version 2 Group
      +	 */
      +	public static Group group(final Options options1){
      +		
      +		final GroupBuilder gbuilder = new GroupBuilder();
      +		
      +		final Set optionGroups = new HashSet();
      +		
      +		for(final Iterator i = options1.getOptionGroups().iterator();i.hasNext();){
      +			final OptionGroup optionGroup1 = (OptionGroup)i.next();
      +			Group group = group(optionGroup1);
      +			gbuilder.withOption(group);
      +			optionGroups.add(optionGroup1);
      +		}
      +		
      +		for(final Iterator i = options1.getOptions().iterator();i.hasNext();){
      +			final org.apache.commons.cli.Option option1 = (org.apache.commons.cli.Option)i.next();
      +			if(!optionInAGroup(option1,optionGroups)){
      +				final Option option2 = option(option1);
      +				gbuilder.withOption(option2);
      +			}
      +		}
      +		
      +		return gbuilder.create();
      +	}
      +
      +	private static boolean optionInAGroup(final org.apache.commons.cli.Option option1, final Set optionGroups) {
      +		for (Iterator i = optionGroups.iterator(); i.hasNext();) {
      +			OptionGroup group = (OptionGroup) i.next();
      +			if(group.getOptions().contains(option1)){
      +				return true;
      +			}
      +		}
      +		return false;
      +	}
      +}
      +
      +class TypeHandlerValidator implements Validator{
      +	
      +	private final Object type;
      +	
      +	/**
      +     * Creates a new Validator using the TypeHandler class.
      +     * 
      +     * @see TypeHandler
      +	 * @param type The required type for valid elements
      +	 */
      +	public TypeHandlerValidator(final Object type){
      +		this.type = type;
      +	}
      +	
      +	/* (non-Javadoc)
      +	 * @see org.apache.commons.cli2.validation.Validator#validate(java.util.List)
      +	 */
      +	public void validate(final List values) throws InvalidArgumentException {
      +		final ListIterator i = values.listIterator();
      +		while(i.hasNext()){
      +			final String value = (String)i.next();
      +			final Object converted = TypeHandler.createValue(value,type);
      +			if(converted==null){
      +				throw new InvalidArgumentException("Unable to understand value: " + value);
      +			}
      +			i.set(converted);
      +		}
      +	}
      +}
      \ No newline at end of file
      diff --git a/CLI2ConverterTest.java b/CLI2ConverterTest.java
      new file mode 100644
      index 000000000..04810a0bc
      --- /dev/null
      +++ b/CLI2ConverterTest.java
      @@ -0,0 +1,133 @@
      +/**
      + * Licensed to the Apache Software Foundation (ASF) under one or more
      + * contributor license agreements.  See the NOTICE file distributed with
      + * this work for additional information regarding copyright ownership.
      + * The ASF licenses this file to You under the Apache License, Version 2.0
      + * (the "License"); you may not use this file except in compliance with
      + * the License.  You may obtain a copy of the License at
      + *
      + *     http://www.apache.org/licenses/LICENSE-2.0
      + *
      + * Unless required by applicable law or agreed to in writing, software
      + * distributed under the License is distributed on an "AS IS" BASIS,
      + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      + * See the License for the specific language governing permissions and
      + * limitations under the License.
      + */
      +package org.apache.commons.cli;
      +
      +import org.apache.commons.cli2.Group;
      +import org.apache.commons.cli2.builder.PatternBuilder;
      +import org.apache.commons.cli2.option.GroupImpl;
      +
      +import junit.framework.TestCase;
      +
      +public class CLI2ConverterTest extends TestCase {
      +	
      +	private Options aceOptions;
      +	private OptionGroup aceOptionGroup;
      +	private Options abcdeOptions;
      +	private Options pattern;
      +	
      +	private Option a;
      +	private Option bbb;
      +	private Option c;
      +	private Option ddd;
      +	private Option e;
      +	private Option f;
      +	private Option g;
      +	private Option h;
      +	private Option i;
      +	
      +	public void setUp(){
      +		a = OptionBuilder.withDescription("A description").create('a');
      +		bbb = OptionBuilder.create("bbb");
      +		c = OptionBuilder.withLongOpt("ccc").create('c');
      +		ddd = OptionBuilder.withLongOpt("ddd").create();
      +		e = OptionBuilder.isRequired(true).create("e");
      +		f = OptionBuilder.hasArg().withArgName("argument").create('f');
      +		g = OptionBuilder.hasArgs(5).create('g');
      +		h = OptionBuilder.hasOptionalArg().create('h');
      +		i = OptionBuilder.hasOptionalArgs(5).create('i');
      +
      +		aceOptions = new Options();
      +		aceOptions.addOption(OptionBuilder.create('a'));
      +		aceOptions.addOption(OptionBuilder.create('c'));
      +		aceOptions.addOption(OptionBuilder.create('e'));
      +		
      +		aceOptionGroup = new OptionGroup();
      +		aceOptionGroup.addOption(OptionBuilder.create('a'));
      +		aceOptionGroup.addOption(OptionBuilder.create('c'));
      +		aceOptionGroup.addOption(OptionBuilder.create('e'));
      +		
      +		abcdeOptions = new Options();
      +		abcdeOptions.addOption(OptionBuilder.create('d'));
      +		OptionGroup og = new OptionGroup();
      +		og.addOption(OptionBuilder.create('a'));
      +		og.addOption(OptionBuilder.create('c'));
      +		og.addOption(OptionBuilder.create('e'));
      +		abcdeOptions.addOptionGroup(og);
      +		abcdeOptions.addOption(OptionBuilder.create('b'));
      +		
      +		pattern = PatternOptionBuilder.parsePattern("a%ce:");
      +	}
      +	
      +	/*
      +	 * Class to test for Option option(Option)
      +	 */
      +	public void testOption() {
      +		assertTrue(e.isRequired());
      +		
      +		assertEquals("A description",a.getDescription());
      +		assertEquals('a',a.getId());
      +		assertEquals("[-a]",CLI2Converter.option(a).toString());
      +		assertEquals("[-bbb]",CLI2Converter.option(bbb).toString());
      +		assertEquals("[-c (--ccc)]",CLI2Converter.option(c).toString());
      +		assertEquals("[--ddd]",CLI2Converter.option(ddd).toString());
      +		assertEquals("-e",CLI2Converter.option(e).toString());
      +		assertEquals("[-f ]",CLI2Converter.option(f).toString());
      +		assertEquals("[-g     ]",CLI2Converter.option(g).toString());
      +		assertEquals("[-h []]",CLI2Converter.option(h).toString());
      +		assertEquals("[-i [ [ [ [ []]]]]]",CLI2Converter.option(i).toString());
      +	}
      +	/*
      +	 * Class to test for Group group(OptionGroup)
      +	 */
      +	public void testGroupOptionGroup() {
      +		GroupImpl group;
      +		
      +		group = (GroupImpl)CLI2Converter.group(aceOptionGroup);
      +		assertEquals("[-a|-c|-e]",group.toString());
      +		assertEquals(0,group.getMinimum());
      +		assertEquals(1,group.getMaximum());
      +		
      +		aceOptionGroup.setRequired(true);
      +		group = (GroupImpl)CLI2Converter.group(aceOptionGroup);
      +		assertEquals("-a|-c|-e",group.toString());
      +		assertEquals(1,group.getMinimum());
      +		assertEquals(1,group.getMaximum());
      +	}
      +	/*
      +	 * Class to test for Group group(Options)
      +	 */
      +	public void testGroupOptions() {
      +		
      +		GroupImpl group;
      +		
      +		group = (GroupImpl)CLI2Converter.group(aceOptions);
      +		assertEquals("[-a|-c|-e]",group.toString());
      +		assertEquals(0,group.getMinimum());
      +		assertEquals(Integer.MAX_VALUE,group.getMaximum());
      +		
      +		group = (GroupImpl)CLI2Converter.group(abcdeOptions);
      +		
      +		assertEquals("[-a|-c|-e|-d|-b]",group.toString());
      +		assertEquals(0,group.getMinimum());
      +		assertEquals(Integer.MAX_VALUE,group.getMaximum());
      +		
      +		group = (GroupImpl)CLI2Converter.group(pattern);
      +		assertEquals("[-a |-c|-e ]",group.toString());
      +		assertEquals(0,group.getMinimum());
      +		assertEquals(Integer.MAX_VALUE,group.getMaximum());
      +	}
      +}
      
      From 70d9beec262c36db9b358e23ff66f6118f61069c Mon Sep 17 00:00:00 2001
      From: Henri Yandell 
      Date: Fri, 6 Feb 2009 06:53:40 +0000
      Subject: [PATCH 0120/1663] Updating with latest changes
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@741436 13f79535-47bb-0310-9956-ffa450edef68
      ---
       xdocs/changes.xml | 12 ++++++++++++
       1 file changed, 12 insertions(+)
      
      diff --git a/xdocs/changes.xml b/xdocs/changes.xml
      index 6ef3e88bc..1715bdb38 100644
      --- a/xdocs/changes.xml
      +++ b/xdocs/changes.xml
      @@ -23,6 +23,18 @@
         
       
           
      +      
      +        Incomplete usage documentation about Java property option.
      +      
      +      
      +        TypeHandler prints messages to stderr.
      +      
      +      
      +        TypeHandler prints messages to stderr.
      +      
      +      
      +        Infinite loop in the wrapping code of HelpFormatter.
      +      
             
               Fixing some minor javadoc issues.
             
      
      From daed6dcaea7b9aabd9d815cb58583459bc5202e6 Mon Sep 17 00:00:00 2001
      From: Henri Yandell 
      Date: Fri, 6 Feb 2009 06:54:18 +0000
      Subject: [PATCH 0121/1663] Updating with latest changes
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@741437 13f79535-47bb-0310-9956-ffa450edef68
      ---
       xdocs/changes.xml | 3 +++
       1 file changed, 3 insertions(+)
      
      diff --git a/xdocs/changes.xml b/xdocs/changes.xml
      index 1715bdb38..a3aae48bb 100644
      --- a/xdocs/changes.xml
      +++ b/xdocs/changes.xml
      @@ -23,6 +23,9 @@
         
       
           
      +      
      +        Ant build system removed. 
      +      
             
               Incomplete usage documentation about Java property option.
             
      
      From 60144879b0b43658ca645fadb32b109e3d71a2e0 Mon Sep 17 00:00:00 2001
      From: Henri Yandell 
      Date: Fri, 20 Feb 2009 05:07:46 +0000
      Subject: [PATCH 0122/1663] Updating the text for CLI-151
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@746140 13f79535-47bb-0310-9956-ffa450edef68
      ---
       xdocs/changes.xml | 5 ++++-
       1 file changed, 4 insertions(+), 1 deletion(-)
      
      diff --git a/xdocs/changes.xml b/xdocs/changes.xml
      index a3aae48bb..0abce61a8 100644
      --- a/xdocs/changes.xml
      +++ b/xdocs/changes.xml
      @@ -70,7 +70,10 @@
               The ordering of options can be defined in help messages.
             
             
      -        The line wrapping in HelpFormatter now works properly.
      +        The line wrapping in HelpFormatter now works properly. This caused CLI-162, and thus there was a feature change 
      +        for the HelpFormatter in that it is strict on width now rather than what seemed to be lenience before. Text without 
      +        whitespace will be cut off to fit in the spacing, and an IllegalStateException will be thrown if it is impossible 
      +        to output the information due to spacing constraints. 
             
             
               The message of MissingOptionException has been improved.
      
      From f0fba7bff7de067e12a78169d1371f3773f3f5a7 Mon Sep 17 00:00:00 2001
      From: Henri Yandell 
      Date: Mon, 16 Mar 2009 07:29:19 +0000
      Subject: [PATCH 0123/1663] Adding CLI-177
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@754832 13f79535-47bb-0310-9956-ffa450edef68
      ---
       xdocs/changes.xml | 3 +++
       1 file changed, 3 insertions(+)
      
      diff --git a/xdocs/changes.xml b/xdocs/changes.xml
      index 0abce61a8..bd8647567 100644
      --- a/xdocs/changes.xml
      +++ b/xdocs/changes.xml
      @@ -23,6 +23,9 @@
         
       
           
      +      
      +        OptionBuilder is not reseted in case of an IAE at create.
      +      
             
               Ant build system removed. 
             
      
      From 38e49dd28d6015c53fdbbec5b5d8360d37e2b33a Mon Sep 17 00:00:00 2001
      From: Henri Yandell 
      Date: Thu, 19 Mar 2009 22:46:00 +0000
      Subject: [PATCH 0124/1663] Adding last minute changes and date
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@756244 13f79535-47bb-0310-9956-ffa450edef68
      ---
       xdocs/changes.xml | 5 ++++-
       1 file changed, 4 insertions(+), 1 deletion(-)
      
      diff --git a/xdocs/changes.xml b/xdocs/changes.xml
      index bd8647567..07662d291 100644
      --- a/xdocs/changes.xml
      +++ b/xdocs/changes.xml
      @@ -22,7 +22,10 @@
         
         
       
      -    
      +    
      +      
      +        Test class BugCLI162Test fails under Windows
      +      
             
               OptionBuilder is not reseted in case of an IAE at create.
             
      
      From 6da34a7a6a1baf740190f29a3571a1b29afce838 Mon Sep 17 00:00:00 2001
      From: Henri Yandell 
      Date: Sat, 21 Mar 2009 22:41:54 +0000
      Subject: [PATCH 0125/1663] Making the cli website CLI2 specific
      
      git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@757041 13f79535-47bb-0310-9956-ffa450edef68
      ---
       src/site/site.xml              |  13 +-
       xdocs/index.xml                | 136 +-----------
       xdocs/introduction.xml         | 101 ---------
       xdocs/properties.xml           | 115 ----------
       xdocs/release_1_0.xml          |  45 ----
       xdocs/release_1_2.xml          | 101 ---------
       xdocs/upgrading-1.0-to-1.1.xml |  48 -----
       xdocs/usage.xml                | 376 ---------------------------------
       8 files changed, 12 insertions(+), 923 deletions(-)
       delete mode 100644 xdocs/introduction.xml
       delete mode 100644 xdocs/properties.xml
       delete mode 100644 xdocs/release_1_0.xml
       delete mode 100644 xdocs/release_1_2.xml
       delete mode 100644 xdocs/upgrading-1.0-to-1.1.xml
       delete mode 100644 xdocs/usage.xml
      
      diff --git a/src/site/site.xml b/src/site/site.xml
      index 74c682697..cb7a0ded9 100644
      --- a/src/site/site.xml
      +++ b/src/site/site.xml
      @@ -23,23 +23,14 @@
           
       
           
      -        
      +        
                   
      -            
      -            
                   
                   
                   
               
       
      -        
      -            
      -            
      -            
      -            
      -        
      -
      -        
      +        
                   
                   
                   
      diff --git a/xdocs/index.xml b/xdocs/index.xml
      index 215bc31d2..c3908818c 100644
      --- a/xdocs/index.xml
      +++ b/xdocs/index.xml
      @@ -25,54 +25,19 @@
         
       
         
      -    
      +

      - The Apache Commons CLI library provides an API for parsing command line options passed to programs. - It's also able to print help messages detailing the options available for a command line tool. + CLI2 has been developed with the goals of clearer responsibilities and + being more flexible than Commons CLI. The intention is that CLI2 should + be able to model a far greater selection of interfaces and do so more + completely, validating as much as possible.

      - Commons CLI supports different types of options: -

      -
        -
      • POSIX like options (ie. tar -zxvf foo.tar.gz)
      • -
      • GNU like long options (ie. du --human-readable --max-depth=1)
      • -
      • Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
      • -
      • Short options with value attached (ie. gcc -O2 foo.c)
      • -
      • long options with single hyphen (ie. ant -projecthelp)
      • -
      -

      - A typical help message displayed by Commons CLI looks like this: -

      - -usage: ls - -A,--almost-all do not list implied . and .. - -a,--all do not hide entries starting with . - -B,--ignore-backups do not list implied entried ending with ~ - -b,--escape print octal escapes for nongraphic characters - --block-size <SIZE> use SIZE-byte blocks - -c with -lt: sort by, and show, ctime (time of last - modification of file status information) with - -l:show ctime and sort by name otherwise: sort - by ctime - -C list entries by columns - -

      - Check out the introduction page for a detailed presentation. + The redesigned CLI2 is rooted in the org.apache.commons.cli2 + package.

      -
      -

      Commons CLI 1.0 was formed from the merger of ideas and code from three different libraries - - Werken, Avalon and Optz. In dealing with the bugs and the feature requests a freshly designed and not - backwards compatible CLI 2 was created, but never finished or released. Since then bugfix releases - have been made for CLI 1.

      - -

      The current plan is to maintain the 1.x line until CLI 2 is officially released. The 2.x design is generally - preferred and is in use, however there is no current activity to make a 2.0 release. To this end, the 1.2 - release is recommended to most users while the 2.x line is recommended for anyone interested in helping to get - this better API released.

      -
      -

      A full User's Guide is available @@ -82,26 +47,17 @@ usage: ls The Javadoc API documents are available online:

      The Subversion repository can be - browsed. + browsed.

      - The latest version is v1.2. - - Download now! -
      - The release notes are also available. -

      -

      - For previous releases, see the Apache Archive. + CLI2 is a component in the Commons Sandbox and therefore has not had a release.

      @@ -109,83 +65,11 @@ usage: ls

      The commons mailing lists act as the main support forum. The user list is suitable for most library usage queries. The dev list is intended for the development discussion. Please remember that the lists are shared between all commons components, so prefix your email subject by - [cli].

      + [cli2].

      Issues may be reported via the ASF JIRA.

      - - diff --git a/xdocs/introduction.xml b/xdocs/introduction.xml deleted file mode 100644 index 0557d37a1..000000000 --- a/xdocs/introduction.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - commons-dev - Introduction - - - -
      -

      - There are three stages to command line processing. They are the - definition, parsing and interrogation stages. The following - sections will discuss each of these stages in turn, and discuss how - to implement them with CLI. -

      -
      -
      -

      - Each command line must define the set of options that will be used - to define the interface to the application. -

      -

      - CLI uses the - Options class, as a container for - - Option instances. There are two ways to create - Options in CLI. One of them is via the constructors, - the other way is via the factory methods defined in - Options. -

      -

      - The Usage Scenarios document provides - examples how to create an Options object and also - provides some real world examples. -

      -

      - The result of the definition stage is an Options - instance. -

      -
      -
      -

      - The parsing stage is where the text passed into the - application via the command line is processed. The text is - processed according to the rules defined by the parser - implementation. -

      -

      - The parse method defined on - - CommandLineParser takes an Options - instance and a String[] of arguments and - returns a - - CommandLine. -

      -

      - The result of the parsing stage is a CommandLine - instance. -

      -
      -
      -

      - The interrogation stage is where the application querys the - CommandLine to decide what execution branch to - take depending on boolean options and uses the option values - to provide the application data. -

      -

      - This stage is implemented in the user code. The accessor methods - on CommandLine provide the interrogation capability - to the user code. -

      -

      - The result of the interrogation stage is that the user code - is fully informed of all the text that was supplied on the command - line and processed according to the parser and Options - rules. -

      -
      - -
      diff --git a/xdocs/properties.xml b/xdocs/properties.xml deleted file mode 100644 index 2976747ac..000000000 --- a/xdocs/properties.xml +++ /dev/null @@ -1,115 +0,0 @@ - - - - - - commons-dev - Option Properties - - - -
      -

      - The following are the properties that each - Option has. All of these - can be set using the accessors or using the methods - defined in the - OptionBuilder. -

      -
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      NameTypeDescription
      optjava.lang.Stringthe identification string of the Option.
      longOptjava.lang.Stringan alias and more descriptive identification string
      descriptionjava.lang.Stringa description of the function of the option
      requiredbooleana flag to say whether the option must appear on - the command line.
      multipleArgsbooleana flag to say whether the option takes multiple argument - values
      argbooleana flag to say whether the option takes an argument
      argsbooleana flag to say whether the option takes more than one argument
      optionalArgbooleana flag to say whether the option's argument is optional
      argNamejava.lang.Stringthe name of the argument value for the usage statement
      valueSeparatorcharthe character value used to split the argument string, that - is used in conjunction with multipleArgs e.g. - if the separator is ',' and the argument string is 'a,b,c' then - there are three argument values, 'a', 'b' and 'c'.
      typejava.lang.Objectthe type of the argument
      valuejava.lang.Stringthe value of the option
      valuesjava.lang.String[]the values of the option
      -
      - - diff --git a/xdocs/release_1_0.xml b/xdocs/release_1_0.xml deleted file mode 100644 index 0ac1aa11d..000000000 --- a/xdocs/release_1_0.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - Release notes for CLI 1.0 - Commons Documentation Team - - - -
      -

      -These are the release notes for Commons CLI 1.0. - -INTRODUCTION: - -This document contains the release notes for this version of the Commons -CLI package. Commons CLI provides a simple API for working with the -command line arguments and options. - -This is the first release of the CLI component, therefore all features are new, -there are no bug-fixes, nothing is deprecated and there are no changes. - -For more information, read the documentation on the project site at -http://commons.apache.org/cli/ - -

      -
      - - -
      diff --git a/xdocs/release_1_2.xml b/xdocs/release_1_2.xml deleted file mode 100644 index 24777c736..000000000 --- a/xdocs/release_1_2.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - - - Release notes for CLI 1.2 - Commons Documentation Team - - - -
      - -

      These are the release notes for Commons CLI 1.2.

      - - -INTRODUCTION: - -This document contains the release notes for this version of the Commons CLI -package. Commons CLI provides a simple API for working with the command line -arguments and options. - -Commons CLI 1.2 is a bugfix release. The following notable changes were made: - - * A major regression introduced in CLI 1.1 that prevented the usage of repeated options has been fixed. - * Several parser issues have been fixed, especially with the PosixParser. - * HelpFormatter now wraps the lines properly - * The ordering of the option in the help message can now be defined. - * Various API enhancements (improved exceptions, serializable classes) - -Commons CLI 1.2 is binary compatible with the previous versions, except for -the OptionValidator class that is no longer public. - -More information can be found on the project site at http://commons.apache.org/cli - - -NEW FEATURES: - - * The method getOptionProperties() in the CommandLine class was added - to retrieve easily the key/value pairs specified with options like - -Dkey1=value1 -Dkey2=value2. - - * GnuParser now supports long options with an '=' sign - (ie. --foo=bar and -foo=bar) (CLI-157) - - * The ordering of options can be defined in help messages. (CLI-155) - - -BUG FIXES: - - * The number of arguments defined for an option specifies the arguments - per occurrence of the option and not for all occurrences. (CLI-137) - - * PosixParser no longer ignores unrecognized short options. (CLI-164) - - * PosixParser no longer stops the bursting process of a token if stopAtNonOption - is enabled and a non option character is encountered. (CLI-163) - - * PosixParser no longer keeps processing the tokens after an unrecognized - long option when stopAtNonOption is enabled. (CLI-165) - - * Required options are properly checked if an Options instance is used twice - to parse a command line. (CLI-156) - - * The line wrapping in HelpFormatter now works properly. (CLI-151) - - -CHANGES: - - * The message of MissingOptionException has been improved. (CLI-149) - - * The exceptions have been enhanced with methods to retrieve easily - the related options. (CLI-86) - - * Option.toString() now reports arguments properly. (CLI-141) - - * The Parser class has been changed to be more easily extendable. (CLI-142) - - * The following classes are now serializable: Option, OptionGroup, - CommandLine and Options. (CLI-140) - - * OptionValidator is no longer public, its methods were all private. - - -
      - - -
      diff --git a/xdocs/upgrading-1.0-to-1.1.xml b/xdocs/upgrading-1.0-to-1.1.xml deleted file mode 100644 index 866477fb0..000000000 --- a/xdocs/upgrading-1.0-to-1.1.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - Upgrading from 1.0 to 1.1 - Commons Documentation Team - - - -
      -

      CLI 1.1 is a bugfix release of CLI. The following changes notable API changes were made:

      - -
        -
      • The Parser abstract class has two additional parse methods that take a Properties parameter.
      • -
      • The HelpFormatter class had publicly accessible fields. These should now be accessed via - get/set methods and the public fields are deprecated.
      • -
      • The Option class addValue(String) method now throws UnsupportedOperationException.
      • -
      • OptionValidator is a newly added class.
      • -
      • Option's now have equals(Object) and hashCode() methods.
      • -
      • The Option class also received two new methods, setDescription(String) and hasValueSeparator();boolean.
      • -
      - -

      The jar should be API backwards compatible, though if you were calling addValue(String) then you won't be happy. Please - let us know your use case if that is so.

      - -
      -
      -

      The list of bugs fixed in 1.1 may be seen via the - changes report.

      -
      - - -
      diff --git a/xdocs/usage.xml b/xdocs/usage.xml deleted file mode 100644 index f27d65607..000000000 --- a/xdocs/usage.xml +++ /dev/null @@ -1,376 +0,0 @@ - - - - - - commons-dev - Usage Scenarios - - - -
      -

      - The following sections describe some example scenarios on how to - use CLI in applications. -

      - - -

      - A boolean option is represented on a command line by the presence - of the option, i.e. if the option is found then the option value - is true, otherwise the value is false. -

      -

      - The DateApp utility prints the current date to standard - output. If the -t option is present the current time is - also printed. -

      -
      - -

      - An - Options object must be created and the Option must be - added to it. -

      - -// create Options object -Options options = new Options(); - -// add t option -options.addOption("t", false, "display current time"); -

      - The addOption method has three parameters. The first - parameter is a java.lang.String that represents the option. - The second parameter is a boolean that specifies whether the - option requires an argument or not. In the case of a boolean option - (sometimes referred to as a flag) an argument value is not present so - false is passed. The third parameter is the description - of the option. This description will be used in the usage text of the - application. -

      -
      - -

      - The parse methods of CommandLineParser are used - to parse the command line arguments. The PosixPaser is - great when you need to handle options that are one character long, - like the t option in this example. -

      - CommandLineParser parser = new PosixParser(); -CommandLine cmd = parser.parse( options, args); -

      - Now we need to check if the t option is present. To do - this we will interrogate the - CommandLine - object. The hasOption method takes a - java.lang.String parameter and returns true if the option - represented by the java.lang.String is present, otherwise - it returns false. -

      - if(cmd.hasOption("t")) { - // print the date and time -} -else { - // print the date -} -
      - -

      - The InternationalDateApp utility extends the - DateApp utility by providing the ability to print the - date and time in any country in the world. To facilitate this a new - command line option, c, has been introduced. -

      - // add c option -options.addOption("c", true, "country code"); -

      - The second parameter is true this time. This specifies that the - c option requires an argument value. If the required option - argument value is specified on the command line it is returned, - otherwise null is returned. -

      -
      - -

      - The getOptionValue methods of CommandLine are - used to retrieve the argument values of options. -

      - // get c option value -String countryCode = cmd.getOptionValue("c"); - -if(countryCode == null) { - // print default date -} -else { - // print date for country specified by countryCode -} -
      -
      - -
      -

      - One of the most ubiquitous Java applications - Ant will be used - here to illustrate how to create the Options required. The following - is the help output for Ant. -

      - ant [options] [target [target2 [target3] ...]] - Options: - -help print this message - -projecthelp print project help information - -version print the version information and exit - -quiet be extra quiet - -verbose be extra verbose - -debug print debugging information - -emacs produce logging information without adornments - -logfile <file> use given file for log - -logger <classname> the class which is to perform logging - -listener <classname> add an instance of class as a project listener - -buildfile <file> use given buildfile - -D<property>=<value> use value for given property - -find <file> search for buildfile towards the root of the - filesystem and use it - -

      - Lets create the boolean options for the application as they - are the easiest to create. For clarity the constructors for - Option are used here. -

      - Option help = new Option( "help", "print this message" ); -Option projecthelp = new Option( "projecthelp", "print project help information" ); -Option version = new Option( "version", "print the version information and exit" ); -Option quiet = new Option( "quiet", "be extra quiet" ); -Option verbose = new Option( "verbose", "be extra verbose" ); -Option debug = new Option( "debug", "print debugging information" ); -Option emacs = new Option( "emacs", - "produce logging information without adornments" ); -
      - -

      - The argument options are created using the OptionBuilder. -

      - Option logfile = OptionBuilder.withArgName( "file" ) - .hasArg() - .withDescription( "use given file for log" ) - .create( "logfile" ); - -Option logger = OptionBuilder.withArgName( "classname" ) - .hasArg() - .withDescription( "the class which it to perform " - + "logging" ) - .create( "logger" ); - -Option listener = OptionBuilder.withArgName( "classname" ) - .hasArg() - .withDescription( "add an instance of class as " - + "a project listener" ) - .create( "listener"); - -Option buildfile = OptionBuilder.withArgName( "file" ) - .hasArg() - .withDescription( "use given buildfile" ) - .create( "buildfile"); - -Option find = OptionBuilder.withArgName( "file" ) - .hasArg() - .withDescription( "search for buildfile towards the " - + "root of the filesystem and use it" ) - .create( "find" ); -
      - -

      - The last option to create is the Java property and it is also created - using the OptionBuilder. -

      - Option property = OptionBuilder.withArgName( "property=value" ) - .hasArgs(2) - .withValueSeparator() - .withDescription( "use value for given property" ) - .create( "D" ); - - The map of properties specified by this option can later be retrieved by - calling getOptionProperties("D") on the CommandLine. - -
      - -

      - Now that we have created each - Option we need - to create the - Options - instance. This is achieved using the - addOption - method of Options. -

      - Options options = new Options(); - -options.addOption( help ); -options.addOption( projecthelp ); -options.addOption( version ); -options.addOption( quiet ); -options.addOption( verbose ); -options.addOption( debug ); -options.addOption( emacs ); -options.addOption( logfile ); -options.addOption( logger ); -options.addOption( listener ); -options.addOption( buildfile ); -options.addOption( find ); -options.addOption( property ); -

      - All the preperation is now complete and we are now ready to - parse the command line arguments. -

      -
      - -

      - We now need to create a Parser. This will parse the command - line arguments, using the rules specified by the Options and - return an instance of CommandLine. - This time we will use a GnuParser - which is able to handle options that are more than one character long. -

      - public static void main( String[] args ) { - // create the parser - CommandLineParser parser = new GnuParser(); - try { - // parse the command line arguments - CommandLine line = parser.parse( options, args ); - } - catch( ParseException exp ) { - // oops, something went wrong - System.err.println( "Parsing failed. Reason: " + exp.getMessage() ); - } -} -
      - -

      - To see if an option has been passed the hasOption - method is used. The argument value can be retrieved using - the getOptionValue method. -

      - // has the buildfile argument been passed? -if( line.hasOption( "buildfile" ) ) { - // initialise the member variable - this.buildfile = line.getOptionValue( "buildfile" ); -} -
      - -

      - CLI also provides the means to automatically generate usage - and help information. This is achieved with the - HelpFormatter - class. -

      - // automatically generate the help statement -HelpFormatter formatter = new HelpFormatter(); -formatter.printHelp( "ant", options ); -

      - When executed the following output is produced: -

      - usage: ant --D <property=value> use value for given property --buildfile <file> use given buildfile --debug print debugging information --emacs produce logging information without adornments --file <file> search for buildfile towards the root of the - filesystem and use it --help print this message --listener <classname> add an instance of class as a project listener --logger <classname> the class which it to perform logging --projecthelp print project help information --quiet be extra quiet --verbose be extra verbose --version print the version information and exit -

      - If you also require to have a usage statement printed - then calling formatter.printHelp( "ant", options, true ) - will generate a usage statment as well as the help information. -

      -
      -
      - -
      -

      - One of the most widely used command line applications in the *nix world - is ls. To parse a command line for an application like this - we will use the PosixParser. - Due to the large number of options required for ls this - example will only cover a small proportion of the options. The following - is a section of the help output. -

      - Usage: ls [OPTION]... [FILE]... -List information about the FILEs (the current directory by default). -Sort entries alphabetically if none of -cftuSUX nor --sort. - --a, --all do not hide entries starting with . --A, --almost-all do not list implied . and .. --b, --escape print octal escapes for nongraphic characters - --block-size=SIZE use SIZE-byte blocks --B, --ignore-backups do not list implied entries ending with ~ --c with -lt: sort by, and show, ctime (time of last - modification of file status information) - with -l: show ctime and sort by name - otherwise: sort by ctime --C list entries by columns -

      - The following is the code that is used to create the - Options for this example. -

      - // create the command line parser -CommandLineParser parser = new PosixParser(); - -// create the Options -Options options = new Options(); -options.addOption( "a", "all", false, "do not hide entries starting with ." ); -options.addOption( "A", "almost-all", false, "do not list implied . and .." ); -options.addOption( "b", "escape", false, "print octal escapes for nongraphic " - + "characters" ); -options.addOption( OptionBuilder.withLongOpt( "block-size" ) - .withDescription( "use SIZE-byte blocks" ) - .hasArg() - .withArgName("SIZE") - .create() ); -options.addOption( "B", "ignore-backups", false, "do not list implied entried " - + "ending with ~"); -options.addOption( "c", false, "with -lt: sort by, and show, ctime (time of last " - + "modification of file status information) with " - + "-l:show ctime and sort by name otherwise: sort " - + "by ctime" ); -options.addOption( "C", false, "list entries by columns" ); - -String[] args = new String[]{ "--block-size=10" }; - -try { - // parse the command line arguments - CommandLine line = parser.parse( options, args ); - - // validate that block-size has been set - if( line.hasOption( "block-size" ) ) { - // print the value of block-size - System.out.println( line.getOptionValue( "block-size" ) ); - } -} -catch( ParseException exp ) { - System.out.println( "Unexpected exception:" + exp.getMessage() ); -} -
      - -
      From 72c6ec5331fec536edb92120cbc2e870a8668a8e Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 21 Mar 2009 22:43:51 +0000 Subject: [PATCH 0126/1663] Dumping Ant build git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@757042 13f79535-47bb-0310-9956-ffa450edef68 --- build.xml | 245 --------------------------------------------- project.properties | 52 ---------- 2 files changed, 297 deletions(-) delete mode 100644 build.xml delete mode 100644 project.properties diff --git a/build.xml b/build.xml deleted file mode 100644 index 00ccfcee3..000000000 --- a/build.xml +++ /dev/null @@ -1,245 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ================================= WARNING ================================ - Junit isn't present in your ${ANT_HOME}/lib directory. Tests not executed. - ========================================================================== - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Proxy used : - Proxy host [${proxy.host}] - Proxy port [${proxy.port}] - Proxy user [${proxy.username}] - - - - - Proxy not used. - - - - - - - - \ No newline at end of file diff --git a/project.properties b/project.properties deleted file mode 100644 index 0dbaa684a..000000000 --- a/project.properties +++ /dev/null @@ -1,52 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# ------------------------------------------------------------------- -# P R O J E C T P R O P E R T I E S -# ------------------------------------------------------------------- -maven.repo.remote=http://repo1.maven.org/maven - -maven.checkstyle.properties=checkstyle.xml - -maven.changelog.factory=org.apache.maven.svnlib.SvnChangeLogFactory - -maven.changes.issue.template=http://issues.apache.org/jira/browse/%ISSUE% - -compile.debug = on -compile.optimize = off -compile.deprecation = off - -maven.compile.source=1.3 -maven.compile.target=1.3 - -maven.jarResources.basedir=${basedir}/src/java - -# Reset the checkstyle properties to use the default sun settings -maven.checkstyle.properties= -maven.checkstyle.format=sun - -maven.xdoc.date=left -maven.xdoc.version=${pom.currentVersion} -maven.xdoc.developmentProcessUrl=http://commons.apache.org/charter.html -maven.xdoc.poweredby.image=maven-feather.png - -maven.javadoc.links=http://java.sun.com/j2se/1.4/docs/api/ - -# Jar Manifest and Additional Attributes -maven.jar.manifest=${basedir}/src/conf/MANIFEST.MF -maven.jar.manifest.attributes.list=Implementation-Vendor-Id,X-Compile-Source-JDK,X-Compile-Target-JDK -maven.jar.manifest.attribute.Implementation-Vendor-Id=org.apache -maven.jar.manifest.attribute.X-Compile-Source-JDK=${maven.compile.source} -maven.jar.manifest.attribute.X-Compile-Target-JDK=${maven.compile.target} From 4a552a9f2496f82244d018ce26e3f0e81d858854 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 21 Mar 2009 22:47:24 +0000 Subject: [PATCH 0127/1663] Moving to cli2 in the sandbox git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@757047 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index 9852eadcd..659ed18d1 100644 --- a/pom.xml +++ b/pom.xml @@ -32,7 +32,7 @@ Commons CLI provides a simple API for presenting, processing and validating a command line interface. - http://commons.apache.org/cli/ + http://commons.apache.org/sandbox/cli2/ jira @@ -40,9 +40,9 @@ - scm:svn:http://svn.apache.org/repos/asf/commons/proper/cli/trunk - scm:svn:https://svn.apache.org/repos/asf/commons/proper/cli/trunk - http://svn.apache.org/viewvc/commons/proper/cli/trunk + scm:svn:http://svn.apache.org/repos/asf/commons/sandbox/cli2/trunk + scm:svn:https://svn.apache.org/repos/asf/commons/sandbox/cli2/trunk + http://svn.apache.org/viewvc/commons/sandbox/cli2/trunk @@ -147,7 +147,7 @@ cli commons-cli-${commons.release.version} org.apache.commons.cli2 - 1.2 + 2.0 CLI 12310463 @@ -232,7 +232,6 @@ false - org.codehaus.mojo cobertura-maven-plugin From 2db2ae9ad3e6fab735392114dde233d0d64c1741 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sat, 21 Mar 2009 23:12:40 +0000 Subject: [PATCH 0128/1663] Fixing svn info git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@757064 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index e0a14cbe0..4ac88f4ff 100644 --- a/pom.xml +++ b/pom.xml @@ -40,9 +40,9 @@ - scm:svn:http://svn.apache.org/repos/asf/commons/proper/cli/branches/cli-1.x/ - scm:svn:https://svn.apache.org/repos/asf/commons/proper/cli/branches/cli-1.x/ - http://svn.apache.org/viewvc/commons/proper/cli/branches/cli-1.x/ + scm:svn:http://svn.apache.org/repos/asf/commons/proper/cli/trunk/ + scm:svn:https://svn.apache.org/repos/asf/commons/proper/cli/trunk/ + http://svn.apache.org/viewvc/commons/proper/cli/trunk/ From 530fe675d35303e271dd798d0f14929772120edb Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 23 Mar 2009 16:08:26 +0000 Subject: [PATCH 0129/1663] Moving the CLI DOAP back into trunk git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@757430 13f79535-47bb-0310-9956-ffa450edef68 --- doap_cli.rdf | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 doap_cli.rdf diff --git a/doap_cli.rdf b/doap_cli.rdf new file mode 100644 index 000000000..9a448a829 --- /dev/null +++ b/doap_cli.rdf @@ -0,0 +1,53 @@ + + + + + Apache Commons CLI + + Java + + + + + + Commons CLI + + Commons CLI provides a simple API for presenting, proecessing and + validating a command line interface. + + + + + + + + + + commons-cli + 2007-07-08 + 1.1 + + + commons-cli + 2002-12-27 + 1.0 + + + + + From 8161311f8bc8fa0604abc98f37226aca0ce3f748 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Fri, 27 Mar 2009 23:37:56 +0000 Subject: [PATCH 0130/1663] JUnit 3.8.2 is best for Java 1.4 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@759392 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 4ac88f4ff..c623051e4 100644 --- a/pom.xml +++ b/pom.xml @@ -122,7 +122,7 @@ junit junit - 3.8.1 + 3.8.2 test From e366a69318c97c70bd3278ffd8c61fad3c4a4456 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Tue, 26 May 2009 11:48:44 +0000 Subject: [PATCH 0131/1663] Implemented the partial matching for long options in the PosixParser (CLI-160) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@778664 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli/AmbiguousOptionException.java | 53 +++++++++++ src/java/org/apache/commons/cli/Options.java | 26 ++++++ src/java/org/apache/commons/cli/Parser.java | 2 +- .../org/apache/commons/cli/PosixParser.java | 40 ++++++--- .../apache/commons/cli/BasicParserTest.java | 25 ++++++ .../org/apache/commons/cli/GnuParserTest.java | 25 ++++++ .../org/apache/commons/cli/OptionsTest.java | 11 +++ .../apache/commons/cli/ParserTestCase.java | 90 +++++++++++++++++++ xdocs/changes.xml | 9 +- 9 files changed, 267 insertions(+), 14 deletions(-) create mode 100644 src/java/org/apache/commons/cli/AmbiguousOptionException.java diff --git a/src/java/org/apache/commons/cli/AmbiguousOptionException.java b/src/java/org/apache/commons/cli/AmbiguousOptionException.java new file mode 100644 index 000000000..4b292c7ea --- /dev/null +++ b/src/java/org/apache/commons/cli/AmbiguousOptionException.java @@ -0,0 +1,53 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.cli; + +import java.util.Collection; + +/** + * Exception thrown when an option can't be identified from a partial name. + * + * @author Emmanuel Bourg + * @version $Revision$, $Date$ + * @since 1.3 + */ +public class AmbiguousOptionException extends UnrecognizedOptionException +{ + /** The list of options matching the partial name specified */ + private Collection matchingOptions; + + /** + * Constructs a new AmbiguousOptionException. + * + * @param option the partial option name + * @param matchingOptions the options matching the name + */ + public AmbiguousOptionException(String option, Collection matchingOptions) + { + super("Ambiguous option: " + option, option); + this.matchingOptions = matchingOptions; + } + + /** + * Returns the options matching the partial name. + */ + public Collection getMatchingOptions() + { + return matchingOptions; + } +} diff --git a/src/java/org/apache/commons/cli/Options.java b/src/java/org/apache/commons/cli/Options.java index 9e56f2eb2..9d20fdaf0 100644 --- a/src/java/org/apache/commons/cli/Options.java +++ b/src/java/org/apache/commons/cli/Options.java @@ -213,6 +213,32 @@ public Option getOption(String opt) return (Option) longOpts.get(opt); } + /** + * Returns the options with a long name starting with the name specified. + * + * @param opt the partial name of the option + * @return the options matching the partial name specified, or an empty list if none matches + * @since 1.3 + */ + public List getMatchingOptions(String opt) + { + opt = Util.stripLeadingHyphens(opt); + + List matchingOpts = new ArrayList(); + + Iterator it = longOpts.keySet().iterator(); + while (it.hasNext()) + { + String longOpt = (String) it.next(); + if (longOpt.startsWith(opt)) + { + matchingOpts.add(longOpt); + } + } + + return matchingOpts; + } + /** * Returns whether the named {@link Option} is a member of this {@link Options}. * diff --git a/src/java/org/apache/commons/cli/Parser.java b/src/java/org/apache/commons/cli/Parser.java index b8306b6d6..2a597196b 100644 --- a/src/java/org/apache/commons/cli/Parser.java +++ b/src/java/org/apache/commons/cli/Parser.java @@ -68,7 +68,7 @@ protected List getRequiredOptions() * flattening when a non option has been encountered * @return a String array of the flattened arguments */ - protected abstract String[] flatten(Options opts, String[] arguments, boolean stopAtNonOption); + protected abstract String[] flatten(Options opts, String[] arguments, boolean stopAtNonOption) throws ParseException; /** * Parses the specified arguments based diff --git a/src/java/org/apache/commons/cli/PosixParser.java b/src/java/org/apache/commons/cli/PosixParser.java index ca8b6c633..e6add97ed 100644 --- a/src/java/org/apache/commons/cli/PosixParser.java +++ b/src/java/org/apache/commons/cli/PosixParser.java @@ -92,7 +92,7 @@ private void init() * when an non option is found. * @return The flattened arguments String array. */ - protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) + protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException { init(); this.options = options; @@ -106,21 +106,33 @@ protected String[] flatten(Options options, String[] arguments, boolean stopAtNo // get the next command line token String token = (String) iter.next(); + // single or double hyphen + if ("-".equals(token) || "--".equals(token)) + { + tokens.add(token); + } + // handle long option --foo or --foo=bar - if (token.startsWith("--")) + else if (token.startsWith("--")) { int pos = token.indexOf('='); String opt = pos == -1 ? token : token.substring(0, pos); // --foo + + List matchingOpts = options.getMatchingOptions(opt); - if (!options.hasOption(opt)) + if (matchingOpts.isEmpty()) { processNonOptionToken(token, stopAtNonOption); } + else if (matchingOpts.size() > 1) + { + throw new AmbiguousOptionException(opt, matchingOpts); + } else { - currentOption = options.getOption(opt); + currentOption = options.getOption((String) matchingOpts.get(0)); - tokens.add(opt); + tokens.add("--" + currentOption.getLongOpt()); if (pos != -1) { tokens.add(token.substring(pos + 1)); @@ -128,17 +140,25 @@ protected String[] flatten(Options options, String[] arguments, boolean stopAtNo } } - // single hyphen - else if ("-".equals(token)) - { - tokens.add(token); - } else if (token.startsWith("-")) { if (token.length() == 2 || options.hasOption(token)) { processOptionToken(token, stopAtNonOption); } + else if (!options.getMatchingOptions(token).isEmpty()) + { + List matchingOpts = options.getMatchingOptions(token); + if (matchingOpts.size() > 1) + { + throw new AmbiguousOptionException(token, matchingOpts); + } + else + { + Option opt = options.getOption((String) matchingOpts.get(0)); + processOptionToken("-" + opt.getLongOpt(), stopAtNonOption); + } + } // requires bursting else { diff --git a/src/test/org/apache/commons/cli/BasicParserTest.java b/src/test/org/apache/commons/cli/BasicParserTest.java index 2f8145a25..a4c42555f 100644 --- a/src/test/org/apache/commons/cli/BasicParserTest.java +++ b/src/test/org/apache/commons/cli/BasicParserTest.java @@ -53,4 +53,29 @@ public void testLongWithEqualSingleDash() throws Exception { // not supported by the BasicParser } + + public void testUnambiguousPartialLongOption1() throws Exception + { + // not supported by the BasicParser + } + + public void testUnambiguousPartialLongOption2() throws Exception + { + // not supported by the BasicParser + } + + public void testAmbiguousPartialLongOption1() throws Exception + { + // not supported by the BasicParser + } + + public void testAmbiguousPartialLongOption2() throws Exception + { + // not supported by the BasicParser + } + + public void testPartialLongOptionWithShort() throws Exception + { + // not supported by the BasicParser + } } diff --git a/src/test/org/apache/commons/cli/GnuParserTest.java b/src/test/org/apache/commons/cli/GnuParserTest.java index 43f80fa70..439953dc7 100644 --- a/src/test/org/apache/commons/cli/GnuParserTest.java +++ b/src/test/org/apache/commons/cli/GnuParserTest.java @@ -24,4 +24,29 @@ public void setUp() super.setUp(); parser = new GnuParser(); } + + public void testUnambiguousPartialLongOption1() throws Exception + { + // not supported by the GnuParser + } + + public void testUnambiguousPartialLongOption2() throws Exception + { + // not supported by the GnuParser + } + + public void testAmbiguousPartialLongOption1() throws Exception + { + // not supported by the GnuParser + } + + public void testAmbiguousPartialLongOption2() throws Exception + { + // not supported by the GnuParser + } + + public void testPartialLongOptionWithShort() throws Exception + { + // not supported by the GnuParser + } } diff --git a/src/test/org/apache/commons/cli/OptionsTest.java b/src/test/org/apache/commons/cli/OptionsTest.java index 6282824e0..07b9888ea 100644 --- a/src/test/org/apache/commons/cli/OptionsTest.java +++ b/src/test/org/apache/commons/cli/OptionsTest.java @@ -159,4 +159,15 @@ public void testGetOptionsGroups() assertNotNull(options.getOptionGroups()); assertEquals(2, options.getOptionGroups().size()); } + + public void testGetMatchingOpts() + { + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("version").create()); + options.addOption(OptionBuilder.withLongOpt("verbose").create()); + + assertTrue(options.getMatchingOptions("foo").isEmpty()); + assertEquals(1, options.getMatchingOptions("version").size()); + assertEquals(2, options.getMatchingOptions("ver").size()); + } } diff --git a/src/test/org/apache/commons/cli/ParserTestCase.java b/src/test/org/apache/commons/cli/ParserTestCase.java index 53781a3b3..7bfdefc47 100644 --- a/src/test/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/org/apache/commons/cli/ParserTestCase.java @@ -303,4 +303,94 @@ public void testPropertiesOption() throws Exception assertEquals("Should be 1 arg left",1,argsleft.size()); assertEquals("Expecting foo","foo",argsleft.get(0)); } + + public void testUnambiguousPartialLongOption1() throws Exception + { + String[] args = new String[] { "--ver" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("version").create()); + options.addOption(OptionBuilder.withLongOpt("help").create()); + + CommandLine cl = parser.parse(options, args); + + assertTrue("Confirm --version is set", cl.hasOption("version")); + } + + public void testUnambiguousPartialLongOption2() throws Exception + { + String[] args = new String[] { "-ver" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("version").create()); + options.addOption(OptionBuilder.withLongOpt("help").create()); + + CommandLine cl = parser.parse(options, args); + + assertTrue("Confirm --version is set", cl.hasOption("version")); + } + + public void testAmbiguousPartialLongOption1() throws Exception + { + String[] args = new String[] { "--ver" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("version").create()); + options.addOption(OptionBuilder.withLongOpt("verbose").create()); + + boolean caught = false; + + try + { + parser.parse(options, args); + } + catch (AmbiguousOptionException e) + { + caught = true; + assertEquals("Partial option", "--ver", e.getOption()); + assertNotNull("Matching options null", e.getMatchingOptions()); + assertEquals("Matching options size", 2, e.getMatchingOptions().size()); + } + + assertTrue( "Confirm MissingArgumentException caught", caught ); + } + + public void testAmbiguousPartialLongOption2() throws Exception + { + String[] args = new String[] { "-ver" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("version").create()); + options.addOption(OptionBuilder.withLongOpt("verbose").create()); + + boolean caught = false; + + try + { + parser.parse(options, args); + } + catch (AmbiguousOptionException e) + { + caught = true; + assertEquals("Partial option", "-ver", e.getOption()); + assertNotNull("Matching options null", e.getMatchingOptions()); + assertEquals("Matching options size", 2, e.getMatchingOptions().size()); + } + + assertTrue( "Confirm MissingArgumentException caught", caught ); + } + + public void testPartialLongOptionWithShort() throws Exception + { + String[] args = new String[] { "-ver" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("version").create()); + options.addOption(OptionBuilder.hasArg().create('v')); + + CommandLine cl = parser.parse(options, args); + + assertTrue("Confirm --version is set", cl.hasOption("version")); + assertTrue("Confirm -v is not set", !cl.hasOption("v")); + } } diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 07662d291..ad1b6bf47 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -21,6 +21,12 @@ Commons CLI Release Notes + + + + PosixParser now supports partial long options (--ver instead of --version) + + @@ -38,9 +44,6 @@ TypeHandler prints messages to stderr. - - TypeHandler prints messages to stderr. - Infinite loop in the wrapping code of HelpFormatter. From 58d89c0a5b5eb446cae4c494eeb6180b9ac965ae Mon Sep 17 00:00:00 2001 From: Jim Jagielski Date: Tue, 26 May 2009 21:39:52 +0000 Subject: [PATCH 0132/1663] Allow for auto-detection of terminal width... Only viable under Unix for now. Include "test" which shows the operation. CLI-166 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@778895 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/HelpFormatter.java | 83 +++++++++++++++++++ .../apache/commons/cli/HelpFormatterTest.java | 18 ++++ 2 files changed, 101 insertions(+) diff --git a/src/java/org/apache/commons/cli/HelpFormatter.java b/src/java/org/apache/commons/cli/HelpFormatter.java index c82852403..4acead29e 100644 --- a/src/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/java/org/apache/commons/cli/HelpFormatter.java @@ -24,6 +24,9 @@ import java.util.Comparator; import java.util.Iterator; import java.util.List; +import java.util.StringTokenizer; +import java.io.InputStream; +import java.io.ByteArrayOutputStream; /** * A formatter of help messages for the current command line options @@ -134,6 +137,11 @@ public class HelpFormatter */ protected Comparator optionComparator = new OptionComparator(); + /** + * Flag to determine if we try to determine terminal width + */ + public boolean autoWidth = false; + /** * Sets the 'width'. * @@ -321,6 +329,28 @@ public void setOptionComparator(Comparator comparator) } } + /** + * Sets the 'autoWidth'. + * + * @param flag the new value of 'autoWidth' + */ + public void setAutoWidth(boolean flag) + { + this.autoWidth = flag; + int newWidth = (flag ? getTerminalWidth() : DEFAULT_WIDTH); + setWidth(newWidth); + } + + /** + * Returns the 'autoWidth'. + * + * @return the 'autoWidth' + */ + public boolean getAutoWidth() + { + return autoWidth; + } + /** * Print the help for options with the specified * command line syntax. This method prints help information to @@ -631,6 +661,58 @@ private static void appendOption(final StringBuffer buff, final Option option, f } } + /** + * Returns the auto-detected Terminal width as reported by stty -a + * + */ + + private static int getTerminalWidth() + { + int ret = DEFAULT_WIDTH; + if (System.getProperty("os.name").toLowerCase().indexOf("windows") == -1) { + String sttya = unixCmdOut("stty -a < /dev/tty"); + StringTokenizer stok = new StringTokenizer(sttya, ";"); + while (stok.hasMoreTokens()) { + String out = stok.nextToken().trim(); + if (out.startsWith("columns")) { + int index = out.lastIndexOf(" "); + ret = Integer.parseInt(out.substring(index).trim()); + break; + } else if (out.endsWith("columns")) { + int index = out.indexOf(" "); + ret = Integer.parseInt(out.substring(0, index).trim()); + break; + } + } + } + return ret; + } + + /** + * Runs the provided Unix command line and returns stdout + * + * @param program the program to run + */ + private static String unixCmdOut(String program) + { + int c; + InputStream in; + String rstr; + ByteArrayOutputStream sout = new ByteArrayOutputStream(); + try { + Process p = Runtime.getRuntime().exec(new String[] {"sh","-c",program}); + in = p.getInputStream(); + while ((c = in.read()) != -1) { + sout.write(c); + } + p.waitFor(); + rstr = new String(sout.toString()); + } catch (Exception e) { + rstr = new String(DEFAULT_WIDTH + " columns;"); + } + return rstr; + } + /** * Print the cmdLineSyntax to the specified writer, using the * specified width. @@ -981,4 +1063,5 @@ public int compare(Object o1, Object o2) return opt1.getKey().compareToIgnoreCase(opt2.getKey()); } } + } diff --git a/src/test/org/apache/commons/cli/HelpFormatterTest.java b/src/test/org/apache/commons/cli/HelpFormatterTest.java index 10ecab336..e1c9509ea 100644 --- a/src/test/org/apache/commons/cli/HelpFormatterTest.java +++ b/src/test/org/apache/commons/cli/HelpFormatterTest.java @@ -450,4 +450,22 @@ public void testOptionWithoutShortFormat2() "footer"+EOL ,out.toString()); } + + public void testAutoWidth() + { + // related to Bugzilla #19383 (CLI-67) + Options options = new Options(); + options.addOption(new Option("a", "aaa", false, "aaaaaaa aaaa aaaaa aaaaaaaa aaaaaa aa aaaaa aaaaaaaaaaaaa")); + options.addOption(new Option(null, "bbb", false, "bbbbbbb bbbb bbbbbb bbbbb bbbbbb bbbb bbbbbbbb bbbbbbbb bbbbbbbbbb")); + options.addOption(new Option("c", null, false, "ccccccc ccccccccccc ccccccccccccc ccc ccccc cccccccc cccccccccccc ccccc ccc ccc ccccccccccccccccc cc")); + + HelpFormatter formatter = new HelpFormatter(); + formatter.setAutoWidth(true); + StringWriter out = new StringWriter(); + formatter.printHelp("foobar", options); + assertEquals("1", "1"); + } + + + } From 0e45f911c8269f0888596fe62be35a18e6e3fb82 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Tue, 26 May 2009 22:58:48 +0000 Subject: [PATCH 0133/1663] Merged ParseRequiredTest into ParserTestCase git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@778920 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli/ParseRequiredTest.java | 138 ------------------ .../apache/commons/cli/ParserTestCase.java | 104 ++++++++++++- 2 files changed, 103 insertions(+), 139 deletions(-) delete mode 100644 src/test/org/apache/commons/cli/ParseRequiredTest.java diff --git a/src/test/org/apache/commons/cli/ParseRequiredTest.java b/src/test/org/apache/commons/cli/ParseRequiredTest.java deleted file mode 100644 index 481027ed2..000000000 --- a/src/test/org/apache/commons/cli/ParseRequiredTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.cli; - -import junit.framework.TestCase; - -/** - * @author John Keyes (john at integralsource.com) - * @version $Revision$ - */ -public class ParseRequiredTest extends TestCase -{ - private Options _options = null; - private CommandLineParser parser = new PosixParser(); - - public void setUp() - { - _options = new Options() - .addOption("a", - "enable-a", - false, - "turn [a] on or off") - .addOption( OptionBuilder.withLongOpt( "bfile" ) - .hasArg() - .isRequired() - .withDescription( "set the value of [b]" ) - .create( 'b' ) ); - } - - public void testWithRequiredOption() throws Exception - { - String[] args = new String[] { "-b", "file" }; - - CommandLine cl = parser.parse(_options,args); - - assertTrue( "Confirm -a is NOT set", !cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("file") ); - assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0); - } - - public void testOptionAndRequiredOption() throws Exception - { - String[] args = new String[] { "-a", "-b", "file" }; - - CommandLine cl = parser.parse(_options,args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("file") ); - assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0); - } - - public void testMissingRequiredOption() - { - String[] args = new String[] { "-a" }; - - try - { - CommandLine cl = parser.parse(_options,args); - fail( "exception should have been thrown" ); - } - catch (MissingOptionException e) - { - assertEquals( "Incorrect exception message", "Missing required option: b", e.getMessage() ); - assertTrue(e.getMissingOptions().contains("b")); - } - catch (ParseException e) - { - fail( "expected to catch MissingOptionException" ); - } - } - - public void testMissingRequiredOptions() - { - String[] args = new String[] { "-a" }; - - _options.addOption( OptionBuilder.withLongOpt( "cfile" ) - .hasArg() - .isRequired() - .withDescription( "set the value of [c]" ) - .create( 'c' ) ); - - try - { - CommandLine cl = parser.parse(_options,args); - fail( "exception should have been thrown" ); - } - catch (MissingOptionException e) - { - assertEquals( "Incorrect exception message", "Missing required options: b, c", e.getMessage() ); - assertTrue(e.getMissingOptions().contains("b")); - assertTrue(e.getMissingOptions().contains("c")); - } - catch (ParseException e) - { - fail( "expected to catch MissingOptionException" ); - } - } - - public void testReuseOptionsTwice() throws Exception - { - Options opts = new Options(); - opts.addOption(OptionBuilder.isRequired().create('v')); - - GnuParser parser = new GnuParser(); - - // first parsing - parser.parse(opts, new String[] { "-v" }); - - try - { - // second parsing, with the same Options instance and an invalid command line - parser.parse(opts, new String[0]); - fail("MissingOptionException not thrown"); - } - catch (MissingOptionException e) - { - // expected - } - } - -} diff --git a/src/test/org/apache/commons/cli/ParserTestCase.java b/src/test/org/apache/commons/cli/ParserTestCase.java index 7bfdefc47..412defe4e 100644 --- a/src/test/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/org/apache/commons/cli/ParserTestCase.java @@ -30,7 +30,7 @@ */ public abstract class ParserTestCase extends TestCase { - protected Parser parser; + protected CommandLineParser parser; protected Options options; @@ -393,4 +393,106 @@ public void testPartialLongOptionWithShort() throws Exception assertTrue("Confirm --version is set", cl.hasOption("version")); assertTrue("Confirm -v is not set", !cl.hasOption("v")); } + + public void testWithRequiredOption() throws Exception + { + String[] args = new String[] { "-b", "file" }; + + Options options = new Options(); + options.addOption("a", "enable-a", false, null); + options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b')); + + CommandLine cl = parser.parse(options,args); + + assertTrue("Confirm -a is NOT set", !cl.hasOption("a")); + assertTrue("Confirm -b is set", cl.hasOption("b")); + assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("file")); + assertTrue("Confirm NO of extra args", cl.getArgList().size() == 0); + } + + public void testOptionAndRequiredOption() throws Exception + { + String[] args = new String[] { "-a", "-b", "file" }; + + Options options = new Options(); + options.addOption("a", "enable-a", false, null); + options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b')); + + CommandLine cl = parser.parse(options,args); + + assertTrue("Confirm -a is set", cl.hasOption("a")); + assertTrue("Confirm -b is set", cl.hasOption("b")); + assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("file")); + assertTrue("Confirm NO of extra args", cl.getArgList().size() == 0); + } + + public void testMissingRequiredOption() + { + String[] args = new String[] { "-a" }; + + Options options = new Options(); + options.addOption("a", "enable-a", false, null); + options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b')); + + try + { + parser.parse(options,args); + fail("exception should have been thrown"); + } + catch (MissingOptionException e) + { + assertEquals( "Incorrect exception message", "Missing required option: b", e.getMessage() ); + assertTrue(e.getMissingOptions().contains("b")); + } + catch (ParseException e) + { + fail("expected to catch MissingOptionException"); + } + } + + public void testMissingRequiredOptions() + { + String[] args = new String[] { "-a" }; + + Options options = new Options(); + options.addOption("a", "enable-a", false, null); + options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b')); + options.addOption(OptionBuilder.withLongOpt("cfile").hasArg().isRequired().create('c')); + + try + { + parser.parse(options,args); + fail("exception should have been thrown"); + } + catch (MissingOptionException e) + { + assertEquals("Incorrect exception message", "Missing required options: b, c", e.getMessage()); + assertTrue(e.getMissingOptions().contains("b")); + assertTrue(e.getMissingOptions().contains("c")); + } + catch (ParseException e) + { + fail("expected to catch MissingOptionException"); + } + } + + public void testReuseOptionsTwice() throws Exception + { + Options opts = new Options(); + opts.addOption(OptionBuilder.isRequired().create('v')); + + // first parsing + parser.parse(opts, new String[] { "-v" }); + + try + { + // second parsing, with the same Options instance and an invalid command line + parser.parse(opts, new String[0]); + fail("MissingOptionException not thrown"); + } + catch (MissingOptionException e) + { + // expected + } + } } From ace122cc24c7e7b396b7071654702d857bbd23ab Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 27 May 2009 08:37:57 +0000 Subject: [PATCH 0134/1663] Code style git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779054 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/CommandLine.java | 3 +-- .../org/apache/commons/cli/TypeHandler.java | 27 +++++++------------ 2 files changed, 10 insertions(+), 20 deletions(-) diff --git a/src/java/org/apache/commons/cli/CommandLine.java b/src/java/org/apache/commons/cli/CommandLine.java index 0d2d64d13..c0967d1bb 100644 --- a/src/java/org/apache/commons/cli/CommandLine.java +++ b/src/java/org/apache/commons/cli/CommandLine.java @@ -106,8 +106,7 @@ public Object getOptionObject(String opt) * @throws ParseException if there are problems turning the option value into the desired type * @see PatternOptionBuilder */ - public Object getParsedOptionValue(String opt) - throws ParseException + public Object getParsedOptionValue(String opt) throws ParseException { String res = getOptionValue(opt); diff --git a/src/java/org/apache/commons/cli/TypeHandler.java b/src/java/org/apache/commons/cli/TypeHandler.java index 86de7b2c5..f78229b5a 100644 --- a/src/java/org/apache/commons/cli/TypeHandler.java +++ b/src/java/org/apache/commons/cli/TypeHandler.java @@ -43,8 +43,7 @@ public class TypeHandler * @return The instance of obj initialised with * the value of str. */ - public static Object createValue(String str, Object obj) - throws ParseException + public static Object createValue(String str, Object obj) throws ParseException { return createValue(str, (Class) obj); } @@ -58,8 +57,7 @@ public static Object createValue(String str, Object obj) * @return The instance of clazz initialised with * the value of str. */ - public static Object createValue(String str, Class clazz) - throws ParseException + public static Object createValue(String str, Class clazz) throws ParseException { if (PatternOptionBuilder.STRING_VALUE == clazz) { @@ -110,8 +108,7 @@ else if (PatternOptionBuilder.URL_VALUE == clazz) * @return the initialised object, or null if it couldn't create * the Object. */ - public static Object createObject(String classname) - throws ParseException + public static Object createObject(String classname) throws ParseException { Class cl = null; @@ -146,8 +143,7 @@ public static Object createObject(String classname) * @return the number represented by str, if str * is not a number, null is returned. */ - public static Number createNumber(String str) - throws ParseException + public static Number createNumber(String str) throws ParseException { try { @@ -172,8 +168,7 @@ public static Number createNumber(String str) * @param classname the class name * @return The class if it is found, otherwise return null */ - public static Class createClass(String classname) - throws ParseException + public static Class createClass(String classname) throws ParseException { try { @@ -192,8 +187,7 @@ public static Class createClass(String classname) * @return The date if str is a valid date string, * otherwise return null. */ - public static Date createDate(String str) - throws ParseException + public static Date createDate(String str) throws ParseException { throw new UnsupportedOperationException("Not yet implemented"); } @@ -205,8 +199,7 @@ public static Date createDate(String str) * @return The URL is str is well-formed, otherwise * return null. */ - public static URL createURL(String str) - throws ParseException + public static URL createURL(String str) throws ParseException { try { @@ -224,8 +217,7 @@ public static URL createURL(String str) * @param str the File location * @return The file represented by str. */ - public static File createFile(String str) - throws ParseException + public static File createFile(String str) throws ParseException { return new File(str); } @@ -236,8 +228,7 @@ public static File createFile(String str) * @param str the paths to the files * @return The File[] represented by str. */ - public static File[] createFiles(String str) - throws ParseException + public static File[] createFiles(String str) throws ParseException { // to implement/port: // return FileW.findFiles(str); From b4b0fb12338b7b3e240b4d8d9663bdea3bed06a4 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 27 May 2009 10:13:36 +0000 Subject: [PATCH 0135/1663] Added missing @since tags git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779077 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli/CommandLine.java | 3 ++- src/java/org/apache/commons/cli/HelpFormatter.java | 10 ++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/java/org/apache/commons/cli/CommandLine.java b/src/java/org/apache/commons/cli/CommandLine.java index c0967d1bb..891797725 100644 --- a/src/java/org/apache/commons/cli/CommandLine.java +++ b/src/java/org/apache/commons/cli/CommandLine.java @@ -105,6 +105,7 @@ public Object getOptionObject(String opt) * @return the value parsed into a particluar object * @throws ParseException if there are problems turning the option value into the desired type * @see PatternOptionBuilder + * @since 1.2 */ public Object getParsedOptionValue(String opt) throws ParseException { @@ -118,7 +119,7 @@ public Object getParsedOptionValue(String opt) throws ParseException Object type = option.getType(); - return (res == null) ? null : TypeHandler.createValue(res, type); + return (res == null) ? null : TypeHandler.createValue(res, type); } /** diff --git a/src/java/org/apache/commons/cli/HelpFormatter.java b/src/java/org/apache/commons/cli/HelpFormatter.java index 4acead29e..e687a46fa 100644 --- a/src/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/java/org/apache/commons/cli/HelpFormatter.java @@ -303,9 +303,10 @@ public String getArgName() } /** - * Comparator used to sort the options when they output in help text + * Comparator used to sort the options when they output in help text. + * Defaults to case-insensitive alphabetical sorting by option key. * - * Defaults to case-insensitive alphabetical sorting by option key + * @since 1.2 */ public Comparator getOptionComparator() { @@ -313,9 +314,10 @@ public Comparator getOptionComparator() } /** - * Set the comparator used to sort the options when they output in help text + * Set the comparator used to sort the options when they output in help text. + * Passing in a null parameter will set the ordering to the default mode. * - * Passing in a null parameter will set the ordering to the default mode + * @since 1.2 */ public void setOptionComparator(Comparator comparator) { From 837a209e950b8bc7a4978def5cd8eb519c11169d Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 27 May 2009 10:17:49 +0000 Subject: [PATCH 0136/1663] Added myself to the list of developers git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779080 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pom.xml b/pom.xml index c623051e4..daf7e7082 100644 --- a/pom.xml +++ b/pom.xml @@ -79,6 +79,12 @@ designed CLI2 + + Emmanuel Bourg + ebourg + ebourg@apache.org + Ariane Software + @@ -115,6 +121,7 @@ lots of fixes for 1.1 + From 0bb2aa0ccaf15575855decac89eca17b1bedaa97 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 27 May 2009 11:26:01 +0000 Subject: [PATCH 0137/1663] Added CLI 1.0 in the release history git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779115 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/changes.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xdocs/changes.xml b/xdocs/changes.xml index ad1b6bf47..3d62ab227 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -105,7 +105,6 @@ - Wrong usage summary. Dependecy on commons-lang-2.0 but commons-lang-1.0 is obtained. Line separator as first char for helpformatter (footer) throws exception. @@ -134,8 +133,9 @@ NullPointerException in Util.stripLeadingHyphens when passed a null argument. 1.1 is not backwards compatible because it adds methods to the CommandLineParser interface. Backwards compatibility between 1.1 and 1.0 broken due to Option.addValue removal. + - + From d189f816ffaa68f7699c194aa0ebb851ea10b5d5 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 27 May 2009 11:44:49 +0000 Subject: [PATCH 0138/1663] Removed a change invisible to the users git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779118 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/changes.xml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 3d62ab227..f4f248330 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -29,11 +29,8 @@ - - Test class BugCLI162Test fails under Windows - - OptionBuilder is not reseted in case of an IAE at create. + OptionBuilder is now reseted if an IllegalArgumentException occurs in create(). Ant build system removed. From 5bdcb9fc1e524beafabea56c6758bc3cf64e75c5 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 27 May 2009 12:13:57 +0000 Subject: [PATCH 0139/1663] Added the 1.2 release to the doap file git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779135 13f79535-47bb-0310-9956-ffa450edef68 --- doap_cli.rdf | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/doap_cli.rdf b/doap_cli.rdf index 9a448a829..c384d1f34 100644 --- a/doap_cli.rdf +++ b/doap_cli.rdf @@ -37,6 +37,11 @@ limitations under the License. + + commons-cli + 2009-03-19 + 1.2 + commons-cli 2007-07-08 @@ -44,7 +49,7 @@ limitations under the License. commons-cli - 2002-12-27 + 2002-11-06 1.0 From 7a0a2107127733c77a579e8e341558c6f6a0408b Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 27 May 2009 12:27:29 +0000 Subject: [PATCH 0140/1663] Fixed the syntax of the revisions in the doap file git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779142 13f79535-47bb-0310-9956-ffa450edef68 --- doap_cli.rdf | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/doap_cli.rdf b/doap_cli.rdf index c384d1f34..d04241f52 100644 --- a/doap_cli.rdf +++ b/doap_cli.rdf @@ -37,21 +37,21 @@ limitations under the License. - + commons-cli 2009-03-19 - 1.2 - - + 1.2 + + commons-cli 2007-07-08 - 1.1 - - + 1.1 + + commons-cli 2002-11-06 - 1.0 - + 1.0 + From 1b2be924006d3ac8ead0960145cbcb140b0ceafc Mon Sep 17 00:00:00 2001 From: Jim Jagielski Date: Wed, 27 May 2009 13:25:09 +0000 Subject: [PATCH 0141/1663] docco cli-166 change git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779163 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/changes.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/xdocs/changes.xml b/xdocs/changes.xml index f4f248330..7ae94e30f 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -23,6 +23,9 @@ + + HelpFormatter can now autodetect (if desired) terminal width under Unix. + PosixParser now supports partial long options (--ver instead of --version) From 32c9109d429f01e299ded69756644501191d33ac Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Thu, 28 May 2009 11:06:57 +0000 Subject: [PATCH 0142/1663] Improved the message of AmbiguousOptionException git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779562 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli/AmbiguousOptionException.java | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/java/org/apache/commons/cli/AmbiguousOptionException.java b/src/java/org/apache/commons/cli/AmbiguousOptionException.java index 4b292c7ea..1092d8630 100644 --- a/src/java/org/apache/commons/cli/AmbiguousOptionException.java +++ b/src/java/org/apache/commons/cli/AmbiguousOptionException.java @@ -18,6 +18,7 @@ package org.apache.commons.cli; import java.util.Collection; +import java.util.Iterator; /** * Exception thrown when an option can't be identified from a partial name. @@ -39,7 +40,7 @@ public class AmbiguousOptionException extends UnrecognizedOptionException */ public AmbiguousOptionException(String option, Collection matchingOptions) { - super("Ambiguous option: " + option, option); + super(createMessage(option, matchingOptions), option); this.matchingOptions = matchingOptions; } @@ -50,4 +51,33 @@ public Collection getMatchingOptions() { return matchingOptions; } + + /** + * Build the exception message from the specified list of options. + * + * @param option + * @param matchingOptions + * @return + */ + private static String createMessage(String option, Collection matchingOptions) + { + StringBuffer buff = new StringBuffer("Ambiguous option: '"); + buff.append(option); + buff.append("' (could be: "); + + Iterator it = matchingOptions.iterator(); + while (it.hasNext()) + { + buff.append("'"); + buff.append(it.next()); + buff.append("'"); + if (it.hasNext()) + { + buff.append(", "); + } + } + buff.append(")"); + + return buff.toString(); + } } From aa9f4de4650ac323fa6b0bb7c9d1a58affe07858 Mon Sep 17 00:00:00 2001 From: Jim Jagielski Date: Thu, 28 May 2009 12:50:54 +0000 Subject: [PATCH 0143/1663] tune up the autoWidth impl and docco how it's impl so people can determine if it is worth it. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779586 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli/HelpFormatter.java | 4 ++-- xdocs/changes.xml | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/java/org/apache/commons/cli/HelpFormatter.java b/src/java/org/apache/commons/cli/HelpFormatter.java index e687a46fa..7cfe181dc 100644 --- a/src/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/java/org/apache/commons/cli/HelpFormatter.java @@ -140,7 +140,7 @@ public class HelpFormatter /** * Flag to determine if we try to determine terminal width */ - public boolean autoWidth = false; + private boolean autoWidth = false; /** * Sets the 'width'. @@ -702,7 +702,7 @@ private static String unixCmdOut(String program) String rstr; ByteArrayOutputStream sout = new ByteArrayOutputStream(); try { - Process p = Runtime.getRuntime().exec(new String[] {"sh","-c",program}); + Process p = Runtime.getRuntime().exec(new String[] {"/bin/sh","-c",program}); in = p.getInputStream(); while ((c = in.read()) != -1) { sout.write(c); diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 7ae94e30f..773cf0189 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -25,6 +25,9 @@ HelpFormatter can now autodetect (if desired) terminal width under Unix. + This is done via setAutoWidth(true) and the actual terminal width determination + is done internally by calling "/bin/sh -c stty -a < /dev/null". If anything + fails, the defaultWidth is used. PosixParser now supports partial long options (--ver instead of --version) From 94f50c098ff5bede66ab67d56176c2329f21e758 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Thu, 28 May 2009 13:50:19 +0000 Subject: [PATCH 0144/1663] More tests for the partial option matching git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779605 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli/BasicParserTest.java | 24 +++++- .../org/apache/commons/cli/GnuParserTest.java | 22 ++++- .../apache/commons/cli/ParserTestCase.java | 84 ++++++++++++++++++- .../apache/commons/cli/PosixParserTest.java | 10 +++ 4 files changed, 134 insertions(+), 6 deletions(-) diff --git a/src/test/org/apache/commons/cli/BasicParserTest.java b/src/test/org/apache/commons/cli/BasicParserTest.java index a4c42555f..27cad46cf 100644 --- a/src/test/org/apache/commons/cli/BasicParserTest.java +++ b/src/test/org/apache/commons/cli/BasicParserTest.java @@ -44,7 +44,7 @@ public void testShortWithoutEqual() throws Exception // not supported by the BasicParser } - public void testLongWithEqual() throws Exception + public void testLongWithEqualDoubleDash() throws Exception { // not supported by the BasicParser } @@ -64,6 +64,16 @@ public void testUnambiguousPartialLongOption2() throws Exception // not supported by the BasicParser } + public void testUnambiguousPartialLongOption3() throws Exception + { + // not supported by the BasicParser + } + + public void testUnambiguousPartialLongOption4() throws Exception + { + // not supported by the BasicParser + } + public void testAmbiguousPartialLongOption1() throws Exception { // not supported by the BasicParser @@ -74,7 +84,17 @@ public void testAmbiguousPartialLongOption2() throws Exception // not supported by the BasicParser } - public void testPartialLongOptionWithShort() throws Exception + public void testAmbiguousPartialLongOption3() throws Exception + { + // not supported by the BasicParser + } + + public void testAmbiguousPartialLongOption4() throws Exception + { + // not supported by the BasicParser + } + + public void testPartialLongOptionSingleDash() throws Exception { // not supported by the BasicParser } diff --git a/src/test/org/apache/commons/cli/GnuParserTest.java b/src/test/org/apache/commons/cli/GnuParserTest.java index 439953dc7..4f797d8bc 100644 --- a/src/test/org/apache/commons/cli/GnuParserTest.java +++ b/src/test/org/apache/commons/cli/GnuParserTest.java @@ -35,6 +35,16 @@ public void testUnambiguousPartialLongOption2() throws Exception // not supported by the GnuParser } + public void testUnambiguousPartialLongOption3() throws Exception + { + // not supported by the GnuParser + } + + public void testUnambiguousPartialLongOption4() throws Exception + { + // not supported by the GnuParser + } + public void testAmbiguousPartialLongOption1() throws Exception { // not supported by the GnuParser @@ -45,7 +55,17 @@ public void testAmbiguousPartialLongOption2() throws Exception // not supported by the GnuParser } - public void testPartialLongOptionWithShort() throws Exception + public void testAmbiguousPartialLongOption3() throws Exception + { + // not supported by the GnuParser + } + + public void testAmbiguousPartialLongOption4() throws Exception + { + // not supported by the GnuParser + } + + public void testPartialLongOptionSingleDash() throws Exception { // not supported by the GnuParser } diff --git a/src/test/org/apache/commons/cli/ParserTestCase.java b/src/test/org/apache/commons/cli/ParserTestCase.java index 412defe4e..5038ec800 100644 --- a/src/test/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/org/apache/commons/cli/ParserTestCase.java @@ -122,7 +122,7 @@ public void testUnrecognizedOption() throws Exception { assertEquals("-d", e.getOption()); } - } + } public void testMissingArg() throws Exception { @@ -259,7 +259,7 @@ public void testShortWithoutEqual() throws Exception assertEquals("bar", cl.getOptionValue("foo")); } - public void testLongWithEqual() throws Exception + public void testLongWithEqualDoubleDash() throws Exception { String[] args = new String[] { "--foo=bar" }; @@ -330,6 +330,34 @@ public void testUnambiguousPartialLongOption2() throws Exception assertTrue("Confirm --version is set", cl.hasOption("version")); } + public void testUnambiguousPartialLongOption3() throws Exception + { + String[] args = new String[] { "--ver=1" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create()); + options.addOption(OptionBuilder.withLongOpt("help").create()); + + CommandLine cl = parser.parse(options, args); + + assertTrue("Confirm --verbose is set", cl.hasOption("verbose")); + assertEquals("1", cl.getOptionValue("verbose")); + } + + public void testUnambiguousPartialLongOption4() throws Exception + { + String[] args = new String[] { "-ver=1" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create()); + options.addOption(OptionBuilder.withLongOpt("help").create()); + + CommandLine cl = parser.parse(options, args); + + assertTrue("Confirm --verbose is set", cl.hasOption("verbose")); + assertEquals("1", cl.getOptionValue("verbose")); + } + public void testAmbiguousPartialLongOption1() throws Exception { String[] args = new String[] { "--ver" }; @@ -379,8 +407,58 @@ public void testAmbiguousPartialLongOption2() throws Exception assertTrue( "Confirm MissingArgumentException caught", caught ); } + + public void testAmbiguousPartialLongOption3() throws Exception + { + String[] args = new String[] { "--ver=1" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("version").create()); + options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create()); + + boolean caught = false; + + try + { + parser.parse(options, args); + } + catch (AmbiguousOptionException e) + { + caught = true; + assertEquals("Partial option", "--ver", e.getOption()); + assertNotNull("Matching options null", e.getMatchingOptions()); + assertEquals("Matching options size", 2, e.getMatchingOptions().size()); + } + + assertTrue( "Confirm MissingArgumentException caught", caught ); + } + + public void testAmbiguousPartialLongOption4() throws Exception + { + String[] args = new String[] { "-ver=1" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("version").create()); + options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create()); + + boolean caught = false; + + try + { + parser.parse(options, args); + } + catch (AmbiguousOptionException e) + { + caught = true; + assertEquals("Partial option", "-ver", e.getOption()); + assertNotNull("Matching options null", e.getMatchingOptions()); + assertEquals("Matching options size", 2, e.getMatchingOptions().size()); + } + + assertTrue( "Confirm MissingArgumentException caught", caught ); + } - public void testPartialLongOptionWithShort() throws Exception + public void testPartialLongOptionSingleDash() throws Exception { String[] args = new String[] { "-ver" }; diff --git a/src/test/org/apache/commons/cli/PosixParserTest.java b/src/test/org/apache/commons/cli/PosixParserTest.java index d94daed42..3dd7f3e3d 100644 --- a/src/test/org/apache/commons/cli/PosixParserTest.java +++ b/src/test/org/apache/commons/cli/PosixParserTest.java @@ -185,4 +185,14 @@ public void testShortWithEqual() throws Exception { // not supported by the PosixParser } + + public void testUnambiguousPartialLongOption4() throws Exception + { + // not supported by the PosixParser + } + + public void testAmbiguousPartialLongOption4() throws Exception + { + // not supported by the PosixParser + } } From ce3a962527c403b7a2ee285830df47caaef56359 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Thu, 28 May 2009 13:56:42 +0000 Subject: [PATCH 0145/1663] Moved the bursting tests from PosixParserTest to ParserTestCase git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779606 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli/BasicParserTest.java | 25 ++++++ .../org/apache/commons/cli/GnuParserTest.java | 25 ++++++ .../apache/commons/cli/ParserTestCase.java | 76 ++++++++++++++++++ .../apache/commons/cli/PosixParserTest.java | 79 ------------------- 4 files changed, 126 insertions(+), 79 deletions(-) diff --git a/src/test/org/apache/commons/cli/BasicParserTest.java b/src/test/org/apache/commons/cli/BasicParserTest.java index 27cad46cf..f6c582ded 100644 --- a/src/test/org/apache/commons/cli/BasicParserTest.java +++ b/src/test/org/apache/commons/cli/BasicParserTest.java @@ -98,4 +98,29 @@ public void testPartialLongOptionSingleDash() throws Exception { // not supported by the BasicParser } + + public void testBursting() throws Exception + { + // not supported by the BasicParser + } + + public void testUnrecognizedOptionWithBursting() throws Exception + { + // not supported by the BasicParser + } + + public void testMissingArgWithBursting() throws Exception + { + // not supported by the BasicParser + } + + public void testStopBursting() throws Exception + { + // not supported by the BasicParser + } + + public void testStopBursting2() throws Exception + { + // not supported by the BasicParser + } } diff --git a/src/test/org/apache/commons/cli/GnuParserTest.java b/src/test/org/apache/commons/cli/GnuParserTest.java index 4f797d8bc..10e9e209e 100644 --- a/src/test/org/apache/commons/cli/GnuParserTest.java +++ b/src/test/org/apache/commons/cli/GnuParserTest.java @@ -69,4 +69,29 @@ public void testPartialLongOptionSingleDash() throws Exception { // not supported by the GnuParser } + + public void testBursting() throws Exception + { + // not supported by the GnuParser + } + + public void testUnrecognizedOptionWithBursting() throws Exception + { + // not supported by the GnuParser + } + + public void testMissingArgWithBursting() throws Exception + { + // not supported by the GnuParser + } + + public void testStopBursting() throws Exception + { + // not supported by the GnuParser + } + + public void testStopBursting2() throws Exception + { + // not supported by the GnuParser + } } diff --git a/src/test/org/apache/commons/cli/ParserTestCase.java b/src/test/org/apache/commons/cli/ParserTestCase.java index 5038ec800..ed6ae09a4 100644 --- a/src/test/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/org/apache/commons/cli/ParserTestCase.java @@ -573,4 +573,80 @@ public void testReuseOptionsTwice() throws Exception // expected } } + + public void testBursting() throws Exception + { + String[] args = new String[] { "-acbtoast", "foo", "bar" }; + + CommandLine cl = parser.parse(options, args); + + assertTrue( "Confirm -a is set", cl.hasOption("a") ); + assertTrue( "Confirm -b is set", cl.hasOption("b") ); + assertTrue( "Confirm -c is set", cl.hasOption("c") ); + assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); + assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); + } + + public void testUnrecognizedOptionWithBursting() throws Exception + { + String[] args = new String[] { "-adbtoast", "foo", "bar" }; + + try + { + parser.parse(options, args); + fail("UnrecognizedOptionException wasn't thrown"); + } + catch (UnrecognizedOptionException e) + { + assertEquals("-adbtoast", e.getOption()); + } + } + + public void testMissingArgWithBursting() throws Exception + { + String[] args = new String[] { "-acb" }; + + boolean caught = false; + + try + { + parser.parse(options, args); + } + catch (MissingArgumentException e) + { + caught = true; + assertEquals("option missing an argument", "b", e.getOption().getOpt()); + } + + assertTrue( "Confirm MissingArgumentException caught", caught ); + } + + public void testStopBursting() throws Exception + { + String[] args = new String[] { "-azc" }; + + CommandLine cl = parser.parse(options, args, true); + assertTrue( "Confirm -a is set", cl.hasOption("a") ); + assertFalse( "Confirm -c is not set", cl.hasOption("c") ); + + assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); + assertTrue(cl.getArgList().contains("zc")); + } + + public void testStopBursting2() throws Exception + { + String[] args = new String[] { "-c", "foobar", "-btoast" }; + + CommandLine cl = parser.parse(options, args, true); + assertTrue("Confirm -c is set", cl.hasOption("c")); + assertTrue("Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); + + cl = parser.parse(options, cl.getArgs()); + + assertTrue("Confirm -c is not set", !cl.hasOption("c")); + assertTrue("Confirm -b is set", cl.hasOption("b")); + assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast")); + assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); + assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar")); + } } diff --git a/src/test/org/apache/commons/cli/PosixParserTest.java b/src/test/org/apache/commons/cli/PosixParserTest.java index 3dd7f3e3d..0418f3b53 100644 --- a/src/test/org/apache/commons/cli/PosixParserTest.java +++ b/src/test/org/apache/commons/cli/PosixParserTest.java @@ -30,85 +30,6 @@ public void setUp() parser = new PosixParser(); } - public void testBursting() throws Exception - { - String[] args = new String[] { "-acbtoast", - "foo", "bar" }; - - CommandLine cl = parser.parse(options, args); - - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertTrue( "Confirm -b is set", cl.hasOption("b") ); - assertTrue( "Confirm -c is set", cl.hasOption("c") ); - assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); - assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); - } - - public void testUnrecognizedOptionWithBursting() throws Exception - { - String[] args = new String[] { "-adbtoast", "foo", "bar" }; - - try - { - parser.parse(options, args); - fail("UnrecognizedOptionException wasn't thrown"); - } - catch (UnrecognizedOptionException e) - { - assertEquals("-adbtoast", e.getOption()); - } - } - - public void testMissingArgWithBursting() throws Exception - { - String[] args = new String[] { "-acb" }; - - boolean caught = false; - - try - { - parser.parse(options, args); - } - catch (MissingArgumentException e) - { - caught = true; - assertEquals("option missing an argument", "b", e.getOption().getOpt()); - } - - assertTrue( "Confirm MissingArgumentException caught", caught ); - } - - public void testStopBursting() throws Exception - { - String[] args = new String[] { "-azc" }; - - CommandLine cl = parser.parse(options, args, true); - assertTrue( "Confirm -a is set", cl.hasOption("a") ); - assertFalse( "Confirm -c is not set", cl.hasOption("c") ); - - assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); - assertTrue(cl.getArgList().contains("zc")); - } - - public void testStopBursting2() throws Exception - { - String[] args = new String[] { "-c", - "foobar", - "-btoast" }; - - CommandLine cl = parser.parse(options, args, true); - assertTrue("Confirm -c is set", cl.hasOption("c")); - assertTrue("Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); - - cl = parser.parse(options, cl.getArgs()); - - assertTrue("Confirm -c is not set", !cl.hasOption("c")); - assertTrue("Confirm -b is set", cl.hasOption("b")); - assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast")); - assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); - assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar")); - } - /** * Real world test with long and short options. */ From 3972aca26c57a2301c9fcb67c11d526c0e0fd084 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Thu, 28 May 2009 15:07:51 +0000 Subject: [PATCH 0146/1663] Moved the real world test from PosixParserTest to ApplicationTest git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779616 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli/ApplicationTest.java | 67 +++++++++++++++++++ .../apache/commons/cli/PosixParserTest.java | 67 ------------------- 2 files changed, 67 insertions(+), 67 deletions(-) diff --git a/src/test/org/apache/commons/cli/ApplicationTest.java b/src/test/org/apache/commons/cli/ApplicationTest.java index 673c2a656..7ab8ad216 100644 --- a/src/test/org/apache/commons/cli/ApplicationTest.java +++ b/src/test/org/apache/commons/cli/ApplicationTest.java @@ -218,4 +218,71 @@ public void testMan() hf.printHelp(60, cmdLine, null, options, null); } + + /** + * Real world test with long and short options. + */ + public void testNLT() throws Exception { + Option help = new Option("h", "help", false, "print this message"); + Option version = new Option("v", "version", false, "print version information"); + Option newRun = new Option("n", "new", false, "Create NLT cache entries only for new items"); + Option trackerRun = new Option("t", "tracker", false, "Create NLT cache entries only for tracker items"); + + Option timeLimit = OptionBuilder.withLongOpt("limit").hasArg() + .withValueSeparator() + .withDescription("Set time limit for execution, in minutes") + .create("l"); + + Option age = OptionBuilder.withLongOpt("age").hasArg() + .withValueSeparator() + .withDescription("Age (in days) of cache item before being recomputed") + .create("a"); + + Option server = OptionBuilder.withLongOpt("server").hasArg() + .withValueSeparator() + .withDescription("The NLT server address") + .create("s"); + + Option numResults = OptionBuilder.withLongOpt("results").hasArg() + .withValueSeparator() + .withDescription("Number of results per item") + .create("r"); + + Option configFile = OptionBuilder.withLongOpt("file").hasArg() + .withValueSeparator() + .withDescription("Use the specified configuration file") + .create(); + + Options options = new Options(); + options.addOption(help); + options.addOption(version); + options.addOption(newRun); + options.addOption(trackerRun); + options.addOption(timeLimit); + options.addOption(age); + options.addOption(server); + options.addOption(numResults); + options.addOption(configFile); + + // create the command line parser + CommandLineParser parser = new PosixParser(); + + String[] args = new String[] { + "-v", + "-l", + "10", + "-age", + "5", + "-file", + "filename" + }; + + CommandLine line = parser.parse(options, args); + assertTrue(line.hasOption("v")); + assertEquals(line.getOptionValue("l"), "10"); + assertEquals(line.getOptionValue("limit"), "10"); + assertEquals(line.getOptionValue("a"), "5"); + assertEquals(line.getOptionValue("age"), "5"); + assertEquals(line.getOptionValue("file"), "filename"); + } } diff --git a/src/test/org/apache/commons/cli/PosixParserTest.java b/src/test/org/apache/commons/cli/PosixParserTest.java index 0418f3b53..fd88a5ffe 100644 --- a/src/test/org/apache/commons/cli/PosixParserTest.java +++ b/src/test/org/apache/commons/cli/PosixParserTest.java @@ -30,73 +30,6 @@ public void setUp() parser = new PosixParser(); } - /** - * Real world test with long and short options. - */ - public void testLongOptionWithShort() throws Exception { - Option help = new Option("h", "help", false, "print this message"); - Option version = new Option("v", "version", false, "print version information"); - Option newRun = new Option("n", "new", false, "Create NLT cache entries only for new items"); - Option trackerRun = new Option("t", "tracker", false, "Create NLT cache entries only for tracker items"); - - Option timeLimit = OptionBuilder.withLongOpt("limit").hasArg() - .withValueSeparator() - .withDescription("Set time limit for execution, in minutes") - .create("l"); - - Option age = OptionBuilder.withLongOpt("age").hasArg() - .withValueSeparator() - .withDescription("Age (in days) of cache item before being recomputed") - .create("a"); - - Option server = OptionBuilder.withLongOpt("server").hasArg() - .withValueSeparator() - .withDescription("The NLT server address") - .create("s"); - - Option numResults = OptionBuilder.withLongOpt("results").hasArg() - .withValueSeparator() - .withDescription("Number of results per item") - .create("r"); - - Option configFile = OptionBuilder.withLongOpt("file").hasArg() - .withValueSeparator() - .withDescription("Use the specified configuration file") - .create(); - - Options options = new Options(); - options.addOption(help); - options.addOption(version); - options.addOption(newRun); - options.addOption(trackerRun); - options.addOption(timeLimit); - options.addOption(age); - options.addOption(server); - options.addOption(numResults); - options.addOption(configFile); - - // create the command line parser - CommandLineParser parser = new PosixParser(); - - String[] args = new String[] { - "-v", - "-l", - "10", - "-age", - "5", - "-file", - "filename" - }; - - CommandLine line = parser.parse(options, args); - assertTrue(line.hasOption("v")); - assertEquals(line.getOptionValue("l"), "10"); - assertEquals(line.getOptionValue("limit"), "10"); - assertEquals(line.getOptionValue("a"), "5"); - assertEquals(line.getOptionValue("age"), "5"); - assertEquals(line.getOptionValue("file"), "filename"); - } - public void testLongWithEqualSingleDash() throws Exception { // not supported by the PosixParser From 0cebfb4cdd85a968f76bca830bcfab8c094d8949 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Thu, 28 May 2009 15:57:58 +0000 Subject: [PATCH 0147/1663] Added a test for the -Dflag case git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779636 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli/BasicParserTest.java | 7 ++++- .../apache/commons/cli/ParserTestCase.java | 29 ++++++++++++++++--- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/test/org/apache/commons/cli/BasicParserTest.java b/src/test/org/apache/commons/cli/BasicParserTest.java index f6c582ded..7ac0c6287 100644 --- a/src/test/org/apache/commons/cli/BasicParserTest.java +++ b/src/test/org/apache/commons/cli/BasicParserTest.java @@ -29,11 +29,16 @@ public void setUp() parser = new BasicParser(); } - public void testPropertiesOption() throws Exception + public void testPropertiesOption1() throws Exception { // not supported by the BasicParser } + public void testPropertiesOption2() throws Exception + { + // not supported by the BasicParser + } + public void testShortWithEqual() throws Exception { // not supported by the BasicParser diff --git a/src/test/org/apache/commons/cli/ParserTestCase.java b/src/test/org/apache/commons/cli/ParserTestCase.java index ed6ae09a4..0aef0c6e1 100644 --- a/src/test/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/org/apache/commons/cli/ParserTestCase.java @@ -19,6 +19,7 @@ import java.util.Arrays; import java.util.List; +import java.util.Properties; import junit.framework.TestCase; @@ -283,7 +284,7 @@ public void testLongWithEqualSingleDash() throws Exception assertEquals("bar", cl.getOptionValue("foo")); } - public void testPropertiesOption() throws Exception + public void testPropertiesOption1() throws Exception { String[] args = new String[] { "-Jsource=1.5", "-J", "target", "1.5", "foo" }; @@ -299,11 +300,31 @@ public void testPropertiesOption() throws Exception assertEquals("value 2", "1.5", values.get(1)); assertEquals("value 3", "target", values.get(2)); assertEquals("value 4", "1.5", values.get(3)); + List argsleft = cl.getArgList(); - assertEquals("Should be 1 arg left",1,argsleft.size()); - assertEquals("Expecting foo","foo",argsleft.get(0)); + assertEquals("Should be 1 arg left", 1, argsleft.size()); + assertEquals("Expecting foo", "foo", argsleft.get(0)); } - + + public void testPropertiesOption2() throws Exception + { + String[] args = new String[] { "-Dparam1", "-Dparam2=value2", "-D"}; + + Options options = new Options(); + options.addOption(OptionBuilder.withValueSeparator().hasOptionalArgs(2).create('D')); + + CommandLine cl = parser.parse(options, args); + + Properties props = cl.getOptionProperties("D"); + assertNotNull("null properties", props); + assertEquals("number of properties in " + props, 2, props.size()); + assertEquals("property 1", "true", props.getProperty("param1")); + assertEquals("property 2", "value2", props.getProperty("param2")); + + List argsleft = cl.getArgList(); + assertEquals("Should be no arg left", 0, argsleft.size()); + } + public void testUnambiguousPartialLongOption1() throws Exception { String[] args = new String[] { "--ver" }; From 6a999186695d404ccb6c1528df68fe2eb42863c2 Mon Sep 17 00:00:00 2001 From: Jim Jagielski Date: Thu, 28 May 2009 16:22:05 +0000 Subject: [PATCH 0148/1663] revert CLI-166 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@779646 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/HelpFormatter.java | 79 ------------------- .../apache/commons/cli/HelpFormatterTest.java | 17 ---- xdocs/changes.xml | 6 -- 3 files changed, 102 deletions(-) diff --git a/src/java/org/apache/commons/cli/HelpFormatter.java b/src/java/org/apache/commons/cli/HelpFormatter.java index 7cfe181dc..d4068d076 100644 --- a/src/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/java/org/apache/commons/cli/HelpFormatter.java @@ -136,11 +136,6 @@ public class HelpFormatter * Defaults to case-insensitive alphabetical sorting by option key */ protected Comparator optionComparator = new OptionComparator(); - - /** - * Flag to determine if we try to determine terminal width - */ - private boolean autoWidth = false; /** * Sets the 'width'. @@ -331,28 +326,6 @@ public void setOptionComparator(Comparator comparator) } } - /** - * Sets the 'autoWidth'. - * - * @param flag the new value of 'autoWidth' - */ - public void setAutoWidth(boolean flag) - { - this.autoWidth = flag; - int newWidth = (flag ? getTerminalWidth() : DEFAULT_WIDTH); - setWidth(newWidth); - } - - /** - * Returns the 'autoWidth'. - * - * @return the 'autoWidth' - */ - public boolean getAutoWidth() - { - return autoWidth; - } - /** * Print the help for options with the specified * command line syntax. This method prints help information to @@ -662,58 +635,6 @@ private static void appendOption(final StringBuffer buff, final Option option, f buff.append("]"); } } - - /** - * Returns the auto-detected Terminal width as reported by stty -a - * - */ - - private static int getTerminalWidth() - { - int ret = DEFAULT_WIDTH; - if (System.getProperty("os.name").toLowerCase().indexOf("windows") == -1) { - String sttya = unixCmdOut("stty -a < /dev/tty"); - StringTokenizer stok = new StringTokenizer(sttya, ";"); - while (stok.hasMoreTokens()) { - String out = stok.nextToken().trim(); - if (out.startsWith("columns")) { - int index = out.lastIndexOf(" "); - ret = Integer.parseInt(out.substring(index).trim()); - break; - } else if (out.endsWith("columns")) { - int index = out.indexOf(" "); - ret = Integer.parseInt(out.substring(0, index).trim()); - break; - } - } - } - return ret; - } - - /** - * Runs the provided Unix command line and returns stdout - * - * @param program the program to run - */ - private static String unixCmdOut(String program) - { - int c; - InputStream in; - String rstr; - ByteArrayOutputStream sout = new ByteArrayOutputStream(); - try { - Process p = Runtime.getRuntime().exec(new String[] {"/bin/sh","-c",program}); - in = p.getInputStream(); - while ((c = in.read()) != -1) { - sout.write(c); - } - p.waitFor(); - rstr = new String(sout.toString()); - } catch (Exception e) { - rstr = new String(DEFAULT_WIDTH + " columns;"); - } - return rstr; - } /** * Print the cmdLineSyntax to the specified writer, using the diff --git a/src/test/org/apache/commons/cli/HelpFormatterTest.java b/src/test/org/apache/commons/cli/HelpFormatterTest.java index e1c9509ea..211b9bd5c 100644 --- a/src/test/org/apache/commons/cli/HelpFormatterTest.java +++ b/src/test/org/apache/commons/cli/HelpFormatterTest.java @@ -450,22 +450,5 @@ public void testOptionWithoutShortFormat2() "footer"+EOL ,out.toString()); } - - public void testAutoWidth() - { - // related to Bugzilla #19383 (CLI-67) - Options options = new Options(); - options.addOption(new Option("a", "aaa", false, "aaaaaaa aaaa aaaaa aaaaaaaa aaaaaa aa aaaaa aaaaaaaaaaaaa")); - options.addOption(new Option(null, "bbb", false, "bbbbbbb bbbb bbbbbb bbbbb bbbbbb bbbb bbbbbbbb bbbbbbbb bbbbbbbbbb")); - options.addOption(new Option("c", null, false, "ccccccc ccccccccccc ccccccccccccc ccc ccccc cccccccc cccccccccccc ccccc ccc ccc ccccccccccccccccc cc")); - - HelpFormatter formatter = new HelpFormatter(); - formatter.setAutoWidth(true); - StringWriter out = new StringWriter(); - formatter.printHelp("foobar", options); - assertEquals("1", "1"); - } - - } diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 773cf0189..f4f248330 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -23,12 +23,6 @@ - - HelpFormatter can now autodetect (if desired) terminal width under Unix. - This is done via setAutoWidth(true) and the actual terminal width determination - is done internally by calling "/bin/sh -c stty -a < /dev/null". If anything - fails, the defaultWidth is used. - PosixParser now supports partial long options (--ver instead of --version) From 4c971f08861e8cefb8ca9ac20799bfdad4e973a4 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Sat, 30 May 2009 02:31:22 +0000 Subject: [PATCH 0149/1663] OptionGroup now selects properly an option with no short name (CLI-182) OptionGroups no longer throw an AlreadySelectedException when reused for several parsings (CLI-183) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@780163 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/OptionGroup.java | 11 +++- src/java/org/apache/commons/cli/Parser.java | 7 +++ .../apache/commons/cli/ParserTestCase.java | 58 ++++++++++++++++++- xdocs/changes.xml | 8 ++- 4 files changed, 80 insertions(+), 4 deletions(-) diff --git a/src/java/org/apache/commons/cli/OptionGroup.java b/src/java/org/apache/commons/cli/OptionGroup.java index 863612983..67cd5e21e 100644 --- a/src/java/org/apache/commons/cli/OptionGroup.java +++ b/src/java/org/apache/commons/cli/OptionGroup.java @@ -85,12 +85,19 @@ public Collection getOptions() */ public void setSelected(Option option) throws AlreadySelectedException { + if (option == null) + { + // reset the option previously selected + selected = null; + return; + } + // if no option has already been selected or the // same option is being reselected then set the // selected member variable - if (selected == null || selected.equals(option.getOpt())) + if (selected == null || selected.equals(option.getKey())) { - selected = option.getOpt(); + selected = option.getKey(); } else { diff --git a/src/java/org/apache/commons/cli/Parser.java b/src/java/org/apache/commons/cli/Parser.java index 2a597196b..2b99dd8bb 100644 --- a/src/java/org/apache/commons/cli/Parser.java +++ b/src/java/org/apache/commons/cli/Parser.java @@ -145,6 +145,13 @@ public CommandLine parse(Options options, String[] arguments, Properties propert Option opt = (Option) it.next(); opt.clearValues(); } + + // clear the data from the groups + for (Iterator it = options.getOptionGroups().iterator(); it.hasNext();) + { + OptionGroup group = (OptionGroup) it.next(); + group.setSelected(null); + } // initialise members setOptions(options); diff --git a/src/test/org/apache/commons/cli/ParserTestCase.java b/src/test/org/apache/commons/cli/ParserTestCase.java index 0aef0c6e1..e62375bcb 100644 --- a/src/test/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/org/apache/commons/cli/ParserTestCase.java @@ -144,7 +144,7 @@ public void testMissingArg() throws Exception assertTrue( "Confirm MissingArgumentException caught", caught ); } - public void testDoubleDash() throws Exception + public void testDoubleDash1() throws Exception { String[] args = new String[] { "--copt", "--", @@ -574,7 +574,63 @@ public void testMissingRequiredOptions() fail("expected to catch MissingOptionException"); } } + + public void testMissingRequiredGroup() throws Exception + { + OptionGroup group = new OptionGroup(); + group.addOption(OptionBuilder.create("a")); + group.addOption(OptionBuilder.create("b")); + group.setRequired(true); + + Options options = new Options(); + options.addOptionGroup(group); + options.addOption(OptionBuilder.isRequired().create("c")); + + try + { + parser.parse(options, new String[] { "-c" }); + fail("MissingOptionException not thrown"); + } + catch (MissingOptionException e) + { + assertEquals(1, e.getMissingOptions().size()); + assertTrue(e.getMissingOptions().get(0) instanceof OptionGroup); + } + catch (ParseException e) + { + fail("Expected to catch MissingOptionException"); + } + } + + public void testOptionGroup() throws Exception + { + OptionGroup group = new OptionGroup(); + group.addOption(OptionBuilder.create("a")); + group.addOption(OptionBuilder.create("b")); + + Options options = new Options(); + options.addOptionGroup(group); + + parser.parse(options, new String[] { "-b" }); + + assertEquals("selected option", "b", group.getSelected()); + } + public void testOptionGroupLong() throws Exception + { + OptionGroup group = new OptionGroup(); + group.addOption(OptionBuilder.withLongOpt("foo").create()); + group.addOption(OptionBuilder.withLongOpt("bar").create()); + + Options options = new Options(); + options.addOptionGroup(group); + + CommandLine cl = parser.parse(options, new String[] { "--bar" }); + + assertTrue(cl.hasOption("bar")); + assertEquals("selected option", "bar", group.getSelected()); + } + public void testReuseOptionsTwice() throws Exception { Options opts = new Options(); diff --git a/xdocs/changes.xml b/xdocs/changes.xml index f4f248330..43df2b08e 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -23,8 +23,14 @@ + + OptionGroups no longer throw an AlreadySelectedException when reused for several parsings. + + + OptionGroup now selects properly an option with no short name. + - PosixParser now supports partial long options (--ver instead of --version) + PosixParser now supports partial long options (--ver instead of --version). From 560487a936449c458f768c92f7eb2be27b9216f1 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Sat, 30 May 2009 09:12:02 +0000 Subject: [PATCH 0150/1663] Updated the comparison version for the clirr plugin git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@780212 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index daf7e7082..7bab13288 100644 --- a/pom.xml +++ b/pom.xml @@ -238,7 +238,7 @@ clirr-maven-plugin 2.2.1 - 1.1 + 1.2 From 135281e95ce1616ba42a18691282be9d8d4af73b Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Sat, 30 May 2009 09:29:50 +0000 Subject: [PATCH 0151/1663] Fixed the definition of the h option in ValuesTest (1 argument instead of 2) Code simplification git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@780217 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 16 +++ .../org/apache/commons/cli/ValuesTest.java | 97 +++++++------------ 2 files changed, 53 insertions(+), 60 deletions(-) diff --git a/pom.xml b/pom.xml index 7bab13288..4a9674dfd 100644 --- a/pom.xml +++ b/pom.xml @@ -132,6 +132,22 @@ 3.8.2 test + + junit-addons + junit-addons + 1.4 + test + + + xerces + xercesImpl + + + xerces + xmlParserAPIs + + + diff --git a/src/test/org/apache/commons/cli/ValuesTest.java b/src/test/org/apache/commons/cli/ValuesTest.java index 83eeb984b..7c5d8e418 100644 --- a/src/test/org/apache/commons/cli/ValuesTest.java +++ b/src/test/org/apache/commons/cli/ValuesTest.java @@ -17,14 +17,12 @@ package org.apache.commons.cli; -import java.util.Arrays; - import junit.framework.TestCase; +import junitx.framework.ArrayAssert; public class ValuesTest extends TestCase { - /** CommandLine instance */ - private CommandLine _cmdline = null; + private CommandLine cmd; public void setUp() throws Exception { @@ -38,7 +36,7 @@ public void setUp() throws Exception options.addOption(OptionBuilder.withLongOpt("e").hasArgs().withDescription("set -e ").create('e')); options.addOption("f", "f", false, "jk"); options.addOption(OptionBuilder.withLongOpt("g").hasArgs(2).withDescription("set -g").create('g')); - options.addOption(OptionBuilder.withLongOpt("h").hasArgs(2).withDescription("set -h").create('h')); + options.addOption(OptionBuilder.withLongOpt("h").hasArg().withDescription("set -h").create('h')); options.addOption(OptionBuilder.withLongOpt("i").withDescription("set -i").create('i')); options.addOption(OptionBuilder.withLongOpt("j").hasArgs().withDescription("set -j").withValueSeparator('=').create('j')); options.addOption(OptionBuilder.withLongOpt("k").hasArgs().withDescription("set -k").withValueSeparator('=').create('k')); @@ -62,91 +60,70 @@ public void setUp() throws Exception CommandLineParser parser = new PosixParser(); - _cmdline = parser.parse(options,args); + cmd = parser.parse(options,args); } public void testShortArgs() { - assertTrue( _cmdline.hasOption("a") ); - assertTrue( _cmdline.hasOption("c") ); + assertTrue("Option a is not set", cmd.hasOption("a")); + assertTrue("Option c is not set", cmd.hasOption("c")); - assertNull( _cmdline.getOptionValues("a") ); - assertNull( _cmdline.getOptionValues("c") ); + assertNull(cmd.getOptionValues("a")); + assertNull(cmd.getOptionValues("c")); } public void testShortArgsWithValue() { - assertTrue( _cmdline.hasOption("b") ); - assertTrue( _cmdline.getOptionValue("b").equals("foo")); - assertEquals(1, _cmdline.getOptionValues("b").length); + assertTrue("Option b is not set", cmd.hasOption("b")); + assertTrue(cmd.getOptionValue("b").equals("foo")); + assertEquals(1, cmd.getOptionValues("b").length); - assertTrue( _cmdline.hasOption("d") ); - assertTrue( _cmdline.getOptionValue("d").equals("bar")); - assertEquals(1, _cmdline.getOptionValues("d").length); + assertTrue("Option d is not set", cmd.hasOption("d")); + assertTrue(cmd.getOptionValue("d").equals("bar")); + assertEquals(1, cmd.getOptionValues("d").length); } public void testMultipleArgValues() { - String[] result = _cmdline.getOptionValues("e"); - String[] values = new String[] { "one", "two" }; - assertTrue( _cmdline.hasOption("e") ); - assertEquals(2, _cmdline.getOptionValues("e").length); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues("e") ) ); + assertTrue("Option e is not set", cmd.hasOption("e")); + ArrayAssert.assertEquals(new String[] { "one", "two" }, cmd.getOptionValues("e")); } public void testTwoArgValues() { - String[] result = _cmdline.getOptionValues("g"); - String[] values = new String[] { "val1", "val2" }; - assertTrue( _cmdline.hasOption("g") ); - assertEquals(2, _cmdline.getOptionValues("g").length); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues("g") ) ); + assertTrue("Option g is not set", cmd.hasOption("g")); + ArrayAssert.assertEquals(new String[] { "val1", "val2" }, cmd.getOptionValues("g")); } public void testComplexValues() { - String[] result = _cmdline.getOptionValues("h"); - String[] values = new String[] { "val1", "val2" }; - assertTrue( _cmdline.hasOption("i") ); - assertTrue( _cmdline.hasOption("h") ); - assertEquals(2, _cmdline.getOptionValues("h").length); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues("h") ) ); + assertTrue("Option i is not set", cmd.hasOption("i")); + assertTrue("Option h is not set", cmd.hasOption("h")); + ArrayAssert.assertEquals(new String[] { "val1", "val2" }, cmd.getOptionValues("h")); } public void testExtraArgs() { - String[] args = new String[] { "arg1", "arg2", "arg3" }; - assertEquals(3, _cmdline.getArgs().length); - assertTrue( Arrays.equals( args, _cmdline.getArgs() ) ); + ArrayAssert.assertEquals("Extra args", new String[] { "arg1", "arg2", "arg3" }, cmd.getArgs()); } public void testCharSeparator() { - // tests the char methods of CommandLine that delegate to - // the String methods - String[] values = new String[] { "key", "value", "key", "value" }; - assertTrue( _cmdline.hasOption( "j" ) ); - assertTrue( _cmdline.hasOption( 'j' ) ); - assertEquals( 4, _cmdline.getOptionValues( "j" ).length ); - assertEquals( 4, _cmdline.getOptionValues( 'j' ).length ); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( "j" ) ) ); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( 'j' ) ) ); - - values = new String[] { "key1", "value1", "key2", "value2" }; - assertTrue( _cmdline.hasOption( "k" ) ); - assertTrue( _cmdline.hasOption( 'k' ) ); - assertEquals(4, _cmdline.getOptionValues( "k" ).length); - assertEquals(4, _cmdline.getOptionValues( 'k' ).length); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( "k" ) ) ); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( 'k' ) ) ); - - values = new String[] { "key", "value" }; - assertTrue( _cmdline.hasOption( "m" ) ); - assertTrue( _cmdline.hasOption( 'm' ) ); - assertEquals(2, _cmdline.getOptionValues( "m" ).length); - assertEquals(2, _cmdline.getOptionValues( 'm' ).length); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( "m" ) ) ); - assertTrue( Arrays.equals( values, _cmdline.getOptionValues( 'm' ) ) ); + // tests the char methods of CommandLine that delegate to the String methods + assertTrue("Option j is not set", cmd.hasOption("j")); + assertTrue("Option j is not set", cmd.hasOption('j')); + ArrayAssert.assertEquals(new String[] { "key", "value", "key", "value" }, cmd.getOptionValues("j")); + ArrayAssert.assertEquals(new String[] { "key", "value", "key", "value" }, cmd.getOptionValues('j')); + + assertTrue("Option k is not set", cmd.hasOption("k")); + assertTrue("Option k is not set", cmd.hasOption('k')); + ArrayAssert.assertEquals(new String[] { "key1", "value1", "key2", "value2" }, cmd.getOptionValues("k")); + ArrayAssert.assertEquals(new String[] { "key1", "value1", "key2", "value2" }, cmd.getOptionValues('k')); + + assertTrue("Option m is not set", cmd.hasOption("m")); + assertTrue("Option m is not set", cmd.hasOption('m')); + ArrayAssert.assertEquals(new String[] { "key", "value" }, cmd.getOptionValues("m")); + ArrayAssert.assertEquals(new String[] { "key", "value" }, cmd.getOptionValues('m')); } /** From f43698527ef2b5ba15fe85d46d2d505418f68243 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Sat, 30 May 2009 13:43:44 +0000 Subject: [PATCH 0152/1663] New unified parser (CLI-181, also fixes CLI-160, CLI-161, CLI-167, CLI-184) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@780264 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/DefaultParser.java | 590 ++++++++++++++++++ src/java/org/apache/commons/cli/Option.java | 34 +- src/java/org/apache/commons/cli/Options.java | 31 +- .../apache/commons/cli/BasicParserTest.java | 20 + .../apache/commons/cli/DefaultParserTest.java | 30 + .../org/apache/commons/cli/GnuParserTest.java | 35 ++ .../apache/commons/cli/ParserTestCase.java | 143 +++++ .../apache/commons/cli/PosixParserTest.java | 25 + xdocs/changes.xml | 5 + 9 files changed, 910 insertions(+), 3 deletions(-) create mode 100644 src/java/org/apache/commons/cli/DefaultParser.java create mode 100644 src/test/org/apache/commons/cli/DefaultParserTest.java diff --git a/src/java/org/apache/commons/cli/DefaultParser.java b/src/java/org/apache/commons/cli/DefaultParser.java new file mode 100644 index 000000000..d3e6bf7a6 --- /dev/null +++ b/src/java/org/apache/commons/cli/DefaultParser.java @@ -0,0 +1,590 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.cli; + +import java.util.ArrayList; +import java.util.List; +import java.util.Iterator; + +/** + * Default parser. + * + * @author Emmanuel Bourg + * @version $Revision$, $Date$ + * @since 1.3 + */ +public class DefaultParser implements CommandLineParser +{ + protected CommandLine cmd; + protected Options options; + protected boolean stopAtNonOption; + + /** The token currently processed. */ + protected String currentToken; + + /** The last option parsed. */ + protected Option currentOption; + + /** Flag indicating if tokens should no longer be analysed and simply added as arguments of the command line. */ + protected boolean skipParsing; + + /** The required options expected to be found when parsing the command line. */ + protected List expectedOpts; + + public CommandLine parse(Options options, String[] arguments) throws ParseException + { + return parse(options, arguments, false); + } + + public CommandLine parse(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException + { + this.options = options; + this.stopAtNonOption = stopAtNonOption; + skipParsing = false; + currentOption = null; + expectedOpts = new ArrayList(options.getRequiredOptions()); + + // clear the data from the groups + for (Iterator it = options.getOptionGroups().iterator(); it.hasNext();) + { + OptionGroup group = (OptionGroup) it.next(); + group.setSelected(null); + } + + cmd = new CommandLine(); + + if (arguments != null) + { + for (int i = 0; i < arguments.length; i++) + { + handleToken(arguments[i]); + } + } + + // check the arguments of the last option + checkRequiredArgs(); + + checkRequiredOptions(); + + return cmd; + } + + /** + * Throws a {@link MissingOptionException} if all of the required options + * are not present. + * + * @throws MissingOptionException if any of the required Options + * are not present. + */ + private void checkRequiredOptions() throws MissingOptionException + { + // if there are required options that have not been processsed + if (!expectedOpts.isEmpty()) + { + throw new MissingOptionException(expectedOpts); + } + } + + /** + * Throw a {@link MissingArgumentException} if the current option + * didn't receive the number of arguments expected. + */ + private void checkRequiredArgs() throws ParseException + { + if (currentOption != null && currentOption.requiresArg()) + { + throw new MissingArgumentException(currentOption); + } + } + + /** + * Handle any command line token. + * + * @param token the command line token to handle + * @throws ParseException + */ + private void handleToken(String token) throws ParseException + { + currentToken = token; + + if (skipParsing) + { + cmd.addArg(token); + } + else if ("--".equals(token)) + { + skipParsing = true; + } + else if (currentOption != null && currentOption.acceptsArg() && isArgument(token)) + { + currentOption.addValueForProcessing(Util.stripLeadingAndTrailingQuotes(token)); + } + else if (token.startsWith("--")) + { + handleLongOption(token); + } + else if (token.startsWith("-") && !"-".equals(token)) + { + handleShortAndLongOption(token); + } + else + { + handleUnknownToken(token); + } + + if (currentOption != null && !currentOption.acceptsArg()) + { + currentOption = null; + } + } + + /** + * Returns true is the token is a valid argument. + * + * @param token + */ + private boolean isArgument(String token) + { + return !isOption(token) || isNegativeNumber(token); + } + + /** + * Check if the token is a negative number. + * + * @param token + */ + private boolean isNegativeNumber(String token) + { + try + { + Double.parseDouble(token); + return true; + } + catch (NumberFormatException e) + { + return false; + } + } + + /** + * Tells if the token looks like an option. + * + * @param token + */ + private boolean isOption(String token) + { + return isLongOption(token) || isShortOption(token); + } + + /** + * Tells if the token looks like a short option. + * + * @param token + */ + private boolean isShortOption(String token) + { + // short options (-S, -SV, -S=V, -SV1=V2, -S1S2) + return token.startsWith("-") && token.length() >= 2 && options.hasShortOption(token.substring(1, 2)); + } + + /** + * Tells if the token looks like a long option. + * + * @param token + */ + private boolean isLongOption(String token) + { + if (!token.startsWith("-") || token.length() == 1) + { + return false; + } + + int pos = token.indexOf("="); + String t = pos == -1 ? token : token.substring(0, pos); + + if (!options.getMatchingOptions(t).isEmpty()) + { + // long or partial long options (--L, -L, --L=V, -L=V, --l, --l=V) + return true; + } + else if (getLongPrefix(token) != null && !token.startsWith("--")) + { + // -LV + return true; + } + + return false; + } + + /** + * Handles an unknown token. If the token starts with a dash an + * UnrecognizedOptionException is thrown. Otherwise the token is added + * to the arguments of the command line. If the stopAtNonOption flag + * is set, this stops the parsing and the remaining tokens are added + * as-is in the arguments of the command line. + * + * @param token the command line token to handle + */ + private void handleUnknownToken(String token) throws ParseException + { + if (token.startsWith("-") && token.length() > 1 && !stopAtNonOption) + { + throw new UnrecognizedOptionException("Unrecognized option: " + token, token); + } + + cmd.addArg(token); + if (stopAtNonOption) + { + skipParsing = true; + } + } + + /** + * Handles the following tokens: + * + * --L + * --L=V + * --L V + * --l + * + * @param token the command line token to handle + */ + private void handleLongOption(String token) throws ParseException + { + if (token.indexOf('=') == -1) + { + handleLongOptionWithoutEqual(token); + } + else + { + handleLongOptionWithEqual(token); + } + } + + /** + * Handles the following tokens: + * + * --L + * -L + * --l + * -l + * + * @param token the command line token to handle + */ + private void handleLongOptionWithoutEqual(String token) throws ParseException + { + List matchingOpts = options.getMatchingOptions(token); + if (matchingOpts.isEmpty()) + { + handleUnknownToken(currentToken); + } + else if (matchingOpts.size() > 1) + { + throw new AmbiguousOptionException(token, matchingOpts); + } + else + { + handleOption(options.getOption((String) matchingOpts.get(0))); + } + } + + /** + * Handles the following tokens: + * + * --L=V + * -L=V + * --l=V + * -l=V + * + * @param token the command line token to handle + */ + private void handleLongOptionWithEqual(String token) throws ParseException + { + int pos = token.indexOf('='); + + String value = token.substring(pos + 1); + + String opt = token.substring(0, pos); + + List matchingOpts = options.getMatchingOptions(opt); + if (matchingOpts.isEmpty()) + { + handleUnknownToken(currentToken); + } + else if (matchingOpts.size() > 1) + { + throw new AmbiguousOptionException(opt, matchingOpts); + } + else + { + Option option = options.getOption((String) matchingOpts.get(0)); + + if (option.acceptsArg()) + { + handleOption(option); + currentOption.addValueForProcessing(value); + currentOption = null; + } + else + { + handleUnknownToken(currentToken); + } + } + } + + /** + * Handles the following tokens: + * + * -S + * -SV + * -S V + * -S=V + * -S1S2 + * -S1S2 V + * -SV1=V2 + * + * -L + * -LV + * -L V + * -L=V + * -l + * + * @param token the command line token to handle + */ + private void handleShortAndLongOption(String token) throws ParseException + { + String t = Util.stripLeadingHyphens(token); + + int pos = t.indexOf('='); + + if (t.length() == 1) + { + // -S + if (options.hasShortOption(t)) + { + handleOption(options.getOption(t)); + } + else + { + handleUnknownToken(token); + } + } + else if (pos == -1) + { + if (options.hasShortOption(t)) + { + handleOption(options.getOption(t)); + } + else if (!options.getMatchingOptions(t).isEmpty()) + { + // -L or -l + handleLongOptionWithoutEqual(token); + } + else + { + // look for a long prefix (-Xmx512m) + String opt = getLongPrefix(t); + + if (opt != null && options.getOption(opt).acceptsArg()) + { + handleOption(options.getOption(opt)); + currentOption.addValueForProcessing(t.substring(opt.length())); + currentOption = null; + } + else if (isJavaProperty(t)) + { + // -SV1 (-Dflag) + handleOption(options.getOption(t.substring(0, 1))); + currentOption.addValueForProcessing(t.substring(1)); + currentOption = null; + } + else + { + // -S1S2S3 or -S1S2V + handleConcatenatedOptions(token); + } + } + } + else + { + String opt = t.substring(0, pos); + String value = t.substring(pos + 1); + + if (opt.length() == 1) + { + // -S=V + Option option = options.getOption(opt); + if (option != null && option.acceptsArg()) + { + handleOption(option); + currentOption.addValueForProcessing(value); + currentOption = null; + } + else + { + handleUnknownToken(token); + } + } + else if (isJavaProperty(opt)) + { + // -SV1=V2 (-Dkey=value) + handleOption(options.getOption(opt.substring(0, 1))); + currentOption.addValueForProcessing(opt.substring(1)); + currentOption.addValueForProcessing(value); + currentOption = null; + } + else + { + // -L=V or -l=V + handleLongOptionWithEqual(token); + } + } + } + + /** + * Search for a prefix that is the long name of an option (-Xmx512m) + * + * @param token + */ + private String getLongPrefix(String token) + { + String t = Util.stripLeadingHyphens(token); + + int i; + String opt = null; + for (i = t.length() - 2; i > 1; i--) + { + String prefix = t.substring(0, i); + if (options.hasLongOption(prefix)) + { + opt = prefix; + break; + } + } + + return opt; + } + + /** + * Check if the specified token is a Java-like property (-Dkey=value). + */ + private boolean isJavaProperty(String token) + { + String opt = token.substring(0, 1); + Option option = options.getOption(opt); + + return option != null && (option.getArgs() >= 2 || option.getArgs() == Option.UNLIMITED_VALUES); + } + + private void handleOption(Option option) throws ParseException + { + // check the previous option before handling the next one + checkRequiredArgs(); + + option = (Option) option.clone(); + + updateRequiredOptions(option); + + cmd.addOption(option); + + if (option.hasArg()) + { + currentOption = option; + } + else + { + currentOption = null; + } + } + + /** + * Removes the option or its group from the list of expected elements. + * + * @param option + */ + private void updateRequiredOptions(Option option) throws AlreadySelectedException + { + if (option.isRequired()) + { + expectedOpts.remove(option.getKey()); + } + + // if the option is in an OptionGroup make that option the selected option of the group + if (options.getOptionGroup(option) != null) + { + OptionGroup group = options.getOptionGroup(option); + + if (group.isRequired()) + { + expectedOpts.remove(group); + } + + group.setSelected(option); + } + } + + /** + * Breaks token into its constituent parts + * using the following algorithm. + * + *
        + *
      • ignore the first character ("-")
      • + *
      • foreach remaining character check if an {@link Option} + * exists with that id.
      • + *
      • if an {@link Option} does exist then add that character + * prepended with "-" to the list of processed tokens.
      • + *
      • if the {@link Option} can have an argument value and there + * are remaining characters in the token then add the remaining + * characters as a token to the list of processed tokens.
      • + *
      • if an {@link Option} does NOT exist AND + * stopAtNonOption IS set then add the special token + * "--" followed by the remaining characters and also + * the remaining tokens directly to the processed tokens list.
      • + *
      • if an {@link Option} does NOT exist AND + * stopAtNonOption IS NOT set then add that + * character prepended with "-".
      • + *
      + * + * @param token The current token to be burst + * at the first non-Option encountered. + */ + protected void handleConcatenatedOptions(String token) throws ParseException + { + for (int i = 1; i < token.length(); i++) + { + String ch = String.valueOf(token.charAt(i)); + + if (options.hasOption(ch)) + { + handleOption(options.getOption(ch)); + + if (currentOption != null && (token.length() != (i + 1))) + { + // add the trail as an argument of the option + currentOption.addValueForProcessing(token.substring(i + 1)); + break; + } + } + else + { + handleUnknownToken(stopAtNonOption && i > 1 ? token.substring(i) : token); + break; + } + } + } +} diff --git a/src/java/org/apache/commons/cli/Option.java b/src/java/org/apache/commons/cli/Option.java index 79caf454e..80839baf2 100644 --- a/src/java/org/apache/commons/cli/Option.java +++ b/src/java/org/apache/commons/cli/Option.java @@ -465,7 +465,7 @@ private void processValue(String value) */ private void add(String value) { - if ((numberOfArgs > 0) && (values.size() > (numberOfArgs - 1))) + if (!acceptsArg()) { throw new RuntimeException("Cannot add value, list full."); } @@ -671,4 +671,36 @@ public boolean addValue(String value) + "Subclasses should use the addValueForProcessing method instead. "); } + /** + * Tells if the option can accept more arguments. + * + * @return false if the maximum number of arguments is reached + * @since 1.3 + */ + boolean acceptsArg() + { + return (hasArg() || hasArgs() || hasOptionalArg()) && (numberOfArgs <= 0 || values.size() < numberOfArgs); + } + + /** + * Tells if the option requires more arguments to be valid. + * + * @return false if the option doesn't require more arguments + * @since 1.3 + */ + boolean requiresArg() + { + if (optionalArg) + { + return false; + } + if (numberOfArgs == UNLIMITED_VALUES) + { + return values.size() < 1; + } + else + { + return acceptsArg(); + } + } } diff --git a/src/java/org/apache/commons/cli/Options.java b/src/java/org/apache/commons/cli/Options.java index 9d20fdaf0..0f3a9811d 100644 --- a/src/java/org/apache/commons/cli/Options.java +++ b/src/java/org/apache/commons/cli/Options.java @@ -243,8 +243,7 @@ public List getMatchingOptions(String opt) * Returns whether the named {@link Option} is a member of this {@link Options}. * * @param opt short or long name of the {@link Option} - * @return true if the named {@link Option} is a member - * of this {@link Options} + * @return true if the named {@link Option} is a member of this {@link Options} */ public boolean hasOption(String opt) { @@ -253,6 +252,34 @@ public boolean hasOption(String opt) return shortOpts.containsKey(opt) || longOpts.containsKey(opt); } + /** + * Returns whether the named {@link Option} is a member of this {@link Options}. + * + * @param opt long name of the {@link Option} + * @return true if the named {@link Option} is a member of this {@link Options} + * @since 1.3 + */ + public boolean hasLongOption(String opt) + { + opt = Util.stripLeadingHyphens(opt); + + return longOpts.containsKey(opt); + } + + /** + * Returns whether the named {@link Option} is a member of this {@link Options}. + * + * @param opt short name of the {@link Option} + * @return true if the named {@link Option} is a member of this {@link Options} + * @since 1.3 + */ + public boolean hasShortOption(String opt) + { + opt = Util.stripLeadingHyphens(opt); + + return shortOpts.containsKey(opt); + } + /** * Returns the OptionGroup the opt belongs to. * @param opt the option whose OptionGroup is being queried. diff --git a/src/test/org/apache/commons/cli/BasicParserTest.java b/src/test/org/apache/commons/cli/BasicParserTest.java index 7ac0c6287..58ed510b5 100644 --- a/src/test/org/apache/commons/cli/BasicParserTest.java +++ b/src/test/org/apache/commons/cli/BasicParserTest.java @@ -29,6 +29,26 @@ public void setUp() parser = new BasicParser(); } + public void testDoubleDash2() throws Exception + { + // not supported by the BasicParser + } + + public void testLongWithoutEqualSingleDash() throws Exception + { + // not supported by the BasicParser + } + + public void testAmbiguousLongWithoutEqualSingleDash() throws Exception + { + // not supported by the basicParser + } + + public void testNegativeOption() throws Exception + { + // not supported by the BasicParser (CLI-184) + } + public void testPropertiesOption1() throws Exception { // not supported by the BasicParser diff --git a/src/test/org/apache/commons/cli/DefaultParserTest.java b/src/test/org/apache/commons/cli/DefaultParserTest.java new file mode 100644 index 000000000..abc628c59 --- /dev/null +++ b/src/test/org/apache/commons/cli/DefaultParserTest.java @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.cli; + +/** + * @author Emmanuel Bourg + * @version $Revision$, $Date$ + */ +public class DefaultParserTest extends ParserTestCase { + + public void setUp() { + super.setUp(); + parser = new DefaultParser(); + } +} diff --git a/src/test/org/apache/commons/cli/GnuParserTest.java b/src/test/org/apache/commons/cli/GnuParserTest.java index 10e9e209e..7093a9dc0 100644 --- a/src/test/org/apache/commons/cli/GnuParserTest.java +++ b/src/test/org/apache/commons/cli/GnuParserTest.java @@ -25,6 +25,41 @@ public void setUp() parser = new GnuParser(); } + public void testDoubleDash2() throws Exception + { + // not supported by the GnuParser + } + + public void testLongWithoutEqualSingleDash() throws Exception + { + // not supported by the GnuParser + } + + public void testAmbiguousLongWithoutEqualSingleDash() throws Exception + { + // not supported by the GnuParser + } + + public void testNegativeOption() throws Exception + { + // not supported by the GnuParser (CLI-184) + } + + public void testLongWithUnexpectedArgument1() throws Exception + { + // not supported by the GnuParser + } + + public void testLongWithUnexpectedArgument2() throws Exception + { + // not supported by the GnuParser + } + + public void testShortWithUnexpectedArgument() throws Exception + { + // not supported by the GnuParser + } + public void testUnambiguousPartialLongOption1() throws Exception { // not supported by the GnuParser diff --git a/src/test/org/apache/commons/cli/ParserTestCase.java b/src/test/org/apache/commons/cli/ParserTestCase.java index e62375bcb..3f5beba0c 100644 --- a/src/test/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/org/apache/commons/cli/ParserTestCase.java @@ -157,6 +157,24 @@ public void testDoubleDash1() throws Exception assertTrue("Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); } + public void testDoubleDash2() throws Exception + { + Options options = new Options(); + options.addOption(OptionBuilder.hasArg().create('n')); + options.addOption(OptionBuilder.create('m')); + + try + { + parser.parse(options, new String[]{"-n", "--", "-m"}); + fail("MissingArgumentException not thrown for option -n"); + } + catch (MissingArgumentException e) + { + assertNotNull("option null", e.getOption()); + assertEquals("n", e.getOption().getOpt()); + } + } + public void testSingleDash() throws Exception { String[] args = new String[] { "--copt", @@ -228,6 +246,16 @@ public void testNegativeArgument() throws Exception assertEquals("-1", cl.getOptionValue("b")); } + public void testNegativeOption() throws Exception + { + String[] args = new String[] { "-b", "-1"} ; + + options.addOption("1", false, null); + + CommandLine cl = parser.parse(options, args); + assertEquals("-1", cl.getOptionValue("b")); + } + public void testArgumentStartingWithHyphen() throws Exception { String[] args = new String[]{"-b", "-foo"}; @@ -284,6 +312,105 @@ public void testLongWithEqualSingleDash() throws Exception assertEquals("bar", cl.getOptionValue("foo")); } + public void testLongWithoutEqualSingleDash() throws Exception + { + String[] args = new String[] { "-foobar" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f')); + + CommandLine cl = parser.parse(options, args); + + assertEquals("bar", cl.getOptionValue("foo")); + } + + public void testAmbiguousLongWithoutEqualSingleDash() throws Exception + { + String[] args = new String[] { "-b", "-foobar" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("foo").hasOptionalArg().create('f')); + options.addOption(OptionBuilder.withLongOpt("bar").hasOptionalArg().create('b')); + + CommandLine cl = parser.parse(options, args); + + assertTrue(cl.hasOption("b")); + assertTrue(cl.hasOption("f")); + assertEquals("bar", cl.getOptionValue("foo")); + } + + public void testLongWithoutEqualDoubleDash() throws Exception + { + String[] args = new String[] { "--foobar" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f')); + + CommandLine cl = parser.parse(options, args, true); + + assertFalse(cl.hasOption("foo")); // foo isn't expected to be recognized with a double dash + } + + public void testLongWithUnexpectedArgument1() throws Exception + { + String[] args = new String[] { "--foo=bar" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("foo").create('f')); + + try + { + parser.parse(options, args); + } + catch (UnrecognizedOptionException e) + { + assertEquals("--foo=bar", e.getOption()); + return; + } + + fail("UnrecognizedOptionException not thrown"); + } + + public void testLongWithUnexpectedArgument2() throws Exception + { + String[] args = new String[] { "-foobar" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("foo").create('f')); + + try + { + parser.parse(options, args); + } + catch (UnrecognizedOptionException e) + { + assertEquals("-foobar", e.getOption()); + return; + } + + fail("UnrecognizedOptionException not thrown"); + } + + public void testShortWithUnexpectedArgument() throws Exception + { + String[] args = new String[] { "-f=bar" }; + + Options options = new Options(); + options.addOption(OptionBuilder.withLongOpt("foo").create('f')); + + try + { + parser.parse(options, args); + } + catch (UnrecognizedOptionException e) + { + assertEquals("-f=bar", e.getOption()); + return; + } + + fail("UnrecognizedOptionException not thrown"); + } + public void testPropertiesOption1() throws Exception { String[] args = new String[] { "-Jsource=1.5", "-J", "target", "1.5", "foo" }; @@ -726,4 +853,20 @@ public void testStopBursting2() throws Exception assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar")); } + + public void testUnlimitedArgs() throws Exception + { + String[] args = new String[]{"-e", "one", "two", "-f", "alpha"}; + + Options options = new Options(); + options.addOption(OptionBuilder.hasArgs().create("e")); + options.addOption(OptionBuilder.hasArgs().create("f")); + + CommandLine cl = parser.parse(options, args); + + assertTrue("Confirm -e is set", cl.hasOption("e")); + assertEquals("number of arg for -e", 2, cl.getOptionValues("e").length); + assertTrue("Confirm -f is set", cl.hasOption("f")); + assertEquals("number of arg for -f", 1, cl.getOptionValues("f").length); + } } diff --git a/src/test/org/apache/commons/cli/PosixParserTest.java b/src/test/org/apache/commons/cli/PosixParserTest.java index fd88a5ffe..8f881857b 100644 --- a/src/test/org/apache/commons/cli/PosixParserTest.java +++ b/src/test/org/apache/commons/cli/PosixParserTest.java @@ -30,6 +30,31 @@ public void setUp() parser = new PosixParser(); } + public void testDoubleDash2() throws Exception + { + // not supported by the PosixParser + } + + public void testLongWithoutEqualSingleDash() throws Exception + { + // not supported by the PosixParser + } + + public void testAmbiguousLongWithoutEqualSingleDash() throws Exception + { + // not supported by the PosixParser + } + + public void testNegativeOption() throws Exception + { + // not supported by the PosixParser (CLI-184) + } + + public void testLongWithUnexpectedArgument1() throws Exception + { + // not supported by the PosixParser + } + public void testLongWithEqualSingleDash() throws Exception { // not supported by the PosixParser diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 43df2b08e..1aaf933ba 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -23,6 +23,11 @@ + + A new parser is available: DefaultParser. It combines the features of the GnuParser and the PosixParser. + It also provides additional features like partial matching for the long options, and long options without + separator (i.e like the JVM memory settings: -Xmx512m). This new parser deprecates the previous ones. + OptionGroups no longer throw an AlreadySelectedException when reused for several parsings. From 8fd05b58d8fea56b61c15f3a9c0b67fd5f095188 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Mon, 15 Jun 2009 15:34:34 +0000 Subject: [PATCH 0153/1663] Minor refactoring of BugCLI148Test git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@784813 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli/bug/BugCLI148Test.java | 42 ++++++++----------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/src/test/org/apache/commons/cli/bug/BugCLI148Test.java b/src/test/org/apache/commons/cli/bug/BugCLI148Test.java index 466846851..28e2d1878 100644 --- a/src/test/org/apache/commons/cli/bug/BugCLI148Test.java +++ b/src/test/org/apache/commons/cli/bug/BugCLI148Test.java @@ -17,50 +17,44 @@ package org.apache.commons.cli.bug; +import junit.framework.TestCase; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; -import junit.framework.TestCase; - /** * http://issues.apache.org/jira/browse/CLI-148 * * @author brianegge */ -public class BugCLI148Test extends TestCase { +public class BugCLI148Test extends TestCase +{ + private Options options; + + protected void setUp() throws Exception + { + options = new Options(); + options.addOption(OptionBuilder.hasArg().create('t')); + options.addOption(OptionBuilder.hasArg().create('s')); + } public void testWorkaround1() throws Exception { - Options options = buildCommandLineOptions(); CommandLineParser parser = new PosixParser(); - String[] args = new String[] {"-t-something" }; - CommandLine commandLine; - commandLine = parser.parse( options, args ); - assertEquals("-something", commandLine.getOptionValue( 't')); + String[] args = new String[]{ "-t-something" }; + + CommandLine commandLine = parser.parse(options, args); + assertEquals("-something", commandLine.getOptionValue('t')); } public void testWorkaround2() throws Exception { - Options options = buildCommandLineOptions(); CommandLineParser parser = new PosixParser(); - String[] args = new String[] {"-t", "\"-something\"" }; - CommandLine commandLine; - commandLine = parser.parse( options, args ); - assertEquals("-something", commandLine.getOptionValue( 't')); - } + String[] args = new String[]{ "-t", "\"-something\"" }; - private Options buildCommandLineOptions() - { - Option t = OptionBuilder.withArgName( "t").hasArg().create('t'); - Option s = OptionBuilder.withArgName( "s").hasArg().create('s'); - Options options = new Options(); - options.addOption( t); - options.addOption( s); - return options; + CommandLine commandLine = parser.parse(options, args); + assertEquals("-something", commandLine.getOptionValue('t')); } - } From 389d0b71d8046f0a4e93050b327b04ddad74b2ed Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Tue, 20 Oct 2009 23:00:29 +0000 Subject: [PATCH 0154/1663] Update to commons-parent-12 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@827830 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 4a9674dfd..0015e7e2f 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ org.apache.commons commons-parent - 11 + 12 4.0.0 commons-cli From 9e9414f1ad46e019857eaf726f42bbb546a09776 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Mon, 8 Mar 2010 00:05:47 +0000 Subject: [PATCH 0155/1663] Upgrade to version 13 of commons-parent git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@920154 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0015e7e2f..0458e2d52 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ org.apache.commons commons-parent - 12 + 13 4.0.0 commons-cli From 8ae1cd18f82905fa84d2a097d1e6b5111c922f38 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Mon, 8 Mar 2010 00:11:50 +0000 Subject: [PATCH 0156/1663] Re-generate the download pages using the new commons-build-plugin .12 (via commons-parent version 13) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@920156 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/download_cli.xml | 87 +++++++++++++++++++----------------------- 1 file changed, 40 insertions(+), 47 deletions(-) diff --git a/xdocs/download_cli.xml b/xdocs/download_cli.xml index 6008e9155..194d6c2c3 100644 --- a/xdocs/download_cli.xml +++ b/xdocs/download_cli.xml @@ -50,6 +50,7 @@ limitations under the License.
      +

      We recommend you use a mirror to download our release builds, but you must verify the integrity of @@ -87,59 +88,51 @@ limitations under the License.

      - The KEYS link links to the code signing keys used to sign the product. + The KEYS + link links to the code signing keys used to sign the product. The PGP link downloads the OpenPGP compatible signature from our main site. The MD5 link downloads the checksum from the main site.

      - -

      - For more information concerning Commons CLI, see the - Commons CLI web site. -

      - -

      -

      -
      +
      + + + + + + + + + + + + +
      commons-cli-1.2.tar.gzmd5pgp
      commons-cli-1.2.zipmd5pgp
      +
      + + + + + + + + + + + + +
      commons-cli-1.2-src.tar.gzmd5pgp
      commons-cli-1.2-src.zipmd5pgp
      +
      +
      +
      +

      + Older releases can be obtained from the archives. +

      + -

      From 5253c11e72dc115325478a487bf1356fe71b3247 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Mon, 8 Mar 2010 20:35:56 +0000 Subject: [PATCH 0157/1663] Fix CLI download page - remove and re-generate git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@920496 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 1 - xdocs/download_cli.xml | 12 ++++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index 0458e2d52..d3ca56d63 100644 --- a/pom.xml +++ b/pom.xml @@ -157,7 +157,6 @@ 1.2 commons-cli-${commons.release.version} org.apache.commons.cli - CLI 12310463 diff --git a/xdocs/download_cli.xml b/xdocs/download_cli.xml index 194d6c2c3..1eb96590e 100644 --- a/xdocs/download_cli.xml +++ b/xdocs/download_cli.xml @@ -99,14 +99,14 @@ limitations under the License. - - - + + + - - - + + +
      commons-cli-1.2.tar.gzmd5pgpcommons-cli-1.2-bin.tar.gzmd5pgp
      commons-cli-1.2.zipmd5pgpcommons-cli-1.2-bin.zipmd5pgp
      From 682f8c6b1c502a9b27e5a22aeb04ff4f26dcf637 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Tue, 9 Mar 2010 11:59:53 +0000 Subject: [PATCH 0158/1663] Fix cli for multi-module profile git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@920816 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 3 ++- src/conf/checkstyle.xml | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d3ca56d63..b9d51d915 100644 --- a/pom.xml +++ b/pom.xml @@ -230,8 +230,9 @@ maven-checkstyle-plugin 2.1 - src/conf/checkstyle.xml + ${basedir}/src/conf/checkstyle.xml false + ${basedir}/src/conf/HEADER.txt
      diff --git a/src/conf/checkstyle.xml b/src/conf/checkstyle.xml index b027be698..00a4e2914 100644 --- a/src/conf/checkstyle.xml +++ b/src/conf/checkstyle.xml @@ -77,7 +77,7 @@ limitations under the License. - + From b7d1c757e3fdc1e8f138608b62a32767e8c4ffc7 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Mon, 15 Mar 2010 17:04:53 +0000 Subject: [PATCH 0159/1663] Update components to point to the new download pages git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@923339 13f79535-47bb-0310-9956-ffa450edef68 --- src/site/site.xml | 2 +- xdocs/index.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/site/site.xml b/src/site/site.xml index 1eef9294c..47a7f882e 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -25,7 +25,7 @@ - + diff --git a/xdocs/index.xml b/xdocs/index.xml index da69a0499..0ac117f3a 100644 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -92,7 +92,7 @@ usage: ls

      The latest version is v1.2. - - Download now! + Download now!
      The release notes are also available.

      From f2c06c0fca5276eb5acbd4e0fef629d4b4be4ad2 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Mon, 15 Mar 2010 23:10:18 +0000 Subject: [PATCH 0160/1663] Upgrade to commons-parent-14 (and maven-javadoc-plugin 2.5 when specified) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@923495 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b9d51d915..1e2529018 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ org.apache.commons commons-parent - 13 + 14 4.0.0 commons-cli From 9a1ff9c5dafa0bc0cf667a2ca0684ec2e46d836a Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Fri, 9 Apr 2010 17:09:11 +0000 Subject: [PATCH 0161/1663] Move/rename "xdocs" directory to standard m2 "src/site/xdoc" git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@932513 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- src/assembly/src.xml | 3 - {xdocs => src/changes}/changes.xml | 0 {xdocs => src/site/xdoc}/download_cli.xml | 0 {xdocs => src/site/xdoc}/index.xml | 0 {xdocs => src/site/xdoc}/introduction.xml | 0 {xdocs => src/site/xdoc}/issue-tracking.xml | 0 {xdocs => src/site/xdoc}/properties.xml | 0 {xdocs => src/site/xdoc}/release_1_0.xml | 0 {xdocs => src/site/xdoc}/release_1_2.xml | 0 .../site/xdoc}/upgrading-1.0-to-1.1.xml | 0 {xdocs => src/site/xdoc}/usage.xml | 0 xdocs/images/1x1.gif | Bin 43 -> 0 bytes xdocs/images/logo.jpg | Bin 5776 -> 0 bytes xdocs/images/logo.png | Bin 10153 -> 0 bytes xdocs/images/options.png | Bin 27463 -> 0 bytes xdocs/images/svg/commandlines.svg | 57 --- xdocs/images/svg/diagrams-cli2.js | 291 -------------- xdocs/images/svg/diagrams.css | 65 ---- xdocs/images/svg/diagrams.js | 368 ------------------ xdocs/images/svg/options.svg | 66 ---- xdocs/images/svg/util.svg | 47 --- xdocs/style/project.css | 1 - 23 files changed, 1 insertion(+), 899 deletions(-) rename {xdocs => src/changes}/changes.xml (100%) rename {xdocs => src/site/xdoc}/download_cli.xml (100%) rename {xdocs => src/site/xdoc}/index.xml (100%) rename {xdocs => src/site/xdoc}/introduction.xml (100%) rename {xdocs => src/site/xdoc}/issue-tracking.xml (100%) rename {xdocs => src/site/xdoc}/properties.xml (100%) rename {xdocs => src/site/xdoc}/release_1_0.xml (100%) rename {xdocs => src/site/xdoc}/release_1_2.xml (100%) rename {xdocs => src/site/xdoc}/upgrading-1.0-to-1.1.xml (100%) rename {xdocs => src/site/xdoc}/usage.xml (100%) delete mode 100755 xdocs/images/1x1.gif delete mode 100644 xdocs/images/logo.jpg delete mode 100644 xdocs/images/logo.png delete mode 100644 xdocs/images/options.png delete mode 100644 xdocs/images/svg/commandlines.svg delete mode 100644 xdocs/images/svg/diagrams-cli2.js delete mode 100644 xdocs/images/svg/diagrams.css delete mode 100644 xdocs/images/svg/diagrams.js delete mode 100644 xdocs/images/svg/options.svg delete mode 100644 xdocs/images/svg/util.svg delete mode 100644 xdocs/style/project.css diff --git a/pom.xml b/pom.xml index 1e2529018..d849234ab 100644 --- a/pom.xml +++ b/pom.xml @@ -214,7 +214,7 @@ maven-changes-plugin 2.0 - ${basedir}/xdocs/changes.xml + ${basedir}/src/changes/changes.xml %URL%/%ISSUE% diff --git a/src/assembly/src.xml b/src/assembly/src.xml index f3c0bdad2..fc31b07f2 100644 --- a/src/assembly/src.xml +++ b/src/assembly/src.xml @@ -38,8 +38,5 @@ src - - xdocs - diff --git a/xdocs/changes.xml b/src/changes/changes.xml similarity index 100% rename from xdocs/changes.xml rename to src/changes/changes.xml diff --git a/xdocs/download_cli.xml b/src/site/xdoc/download_cli.xml similarity index 100% rename from xdocs/download_cli.xml rename to src/site/xdoc/download_cli.xml diff --git a/xdocs/index.xml b/src/site/xdoc/index.xml similarity index 100% rename from xdocs/index.xml rename to src/site/xdoc/index.xml diff --git a/xdocs/introduction.xml b/src/site/xdoc/introduction.xml similarity index 100% rename from xdocs/introduction.xml rename to src/site/xdoc/introduction.xml diff --git a/xdocs/issue-tracking.xml b/src/site/xdoc/issue-tracking.xml similarity index 100% rename from xdocs/issue-tracking.xml rename to src/site/xdoc/issue-tracking.xml diff --git a/xdocs/properties.xml b/src/site/xdoc/properties.xml similarity index 100% rename from xdocs/properties.xml rename to src/site/xdoc/properties.xml diff --git a/xdocs/release_1_0.xml b/src/site/xdoc/release_1_0.xml similarity index 100% rename from xdocs/release_1_0.xml rename to src/site/xdoc/release_1_0.xml diff --git a/xdocs/release_1_2.xml b/src/site/xdoc/release_1_2.xml similarity index 100% rename from xdocs/release_1_2.xml rename to src/site/xdoc/release_1_2.xml diff --git a/xdocs/upgrading-1.0-to-1.1.xml b/src/site/xdoc/upgrading-1.0-to-1.1.xml similarity index 100% rename from xdocs/upgrading-1.0-to-1.1.xml rename to src/site/xdoc/upgrading-1.0-to-1.1.xml diff --git a/xdocs/usage.xml b/src/site/xdoc/usage.xml similarity index 100% rename from xdocs/usage.xml rename to src/site/xdoc/usage.xml diff --git a/xdocs/images/1x1.gif b/xdocs/images/1x1.gif deleted file mode 100755 index 35d42e808f0a8017b8d52a06be2f8fec0b466a66..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 43 scmZ?wbhEHbWMp7uXkcLY|NlP&1B2pE7Dgb&paUX6G7L;iE{qJ;0LZEa`2YX_ diff --git a/xdocs/images/logo.jpg b/xdocs/images/logo.jpg deleted file mode 100644 index bcb742221707b247a0231d132867f702cc005368..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5776 zcmb7HcT^MKww{m#P)ZWIp;tq10V$!E&=CR%A|-$d2uLpi(t8a>kPgzMNKpi=bWo)C z-lYgiQBV+g_`BD;?qBb%x6iCub7p^guXSdx{mr+}C(joFxR$!6IsgKJ0F8?UoSy;o zD(<)Op11ATd>lOO*^KOOvtc!Lub6qxLX^^xC1Oqz*l9`#6m6e*FgNuWOi;0Dm}0omU!UQP~iz4mcuz9qhBY;&&|ZHh^_Ky>hSqa zBUPr%PM_!gGI$Z4EYWZp2jbOZKibE0c9*p}C;(^2n*Ec;3Dv67*uhm-GS!<7oA-^c zb##8}OX|wWT-xR^)9GT@fWgXAT|B9{EhU&<(mYnf@x~y@vV4f}5yLH!fgKw30fpu@O$NiF)c}zE>l8%9DL3khMo$!Yki}MG0iE z^2s!*>t|pyyZJc~M87wF4!FX)LypK-epNBPaN~Tr{I)E{>bc+RB_UP<9YTnJ_o8zSPr3E%w|<@)MBT4f6}h4g zvAu<8va62Xp=5w_RYk99SZ~VIb2MA4d52jssR=ODjQRqgOBNJ{0-{($ieh^_M96*! z?JKHLw-^lL_QZ0Th7r+;^p;}pA;)+0t@soucqxHe)$yLK-xHkq#nQ9&i+Eam4*cmC8pMB**gp;9`cGF}u$ux1 z`o92({sPqC01@b-$wVOW%4usD0w{ zRhJT1-@~j4tbEniB78bmcgocAr}|>s!)%(WdR~h8WWTc%7D#RCZS?z+j1rQ&E~xHV zw-0$f$&R*%BhyZwzY1cdzljcFow+3EsTD-`u@;nD5kg$b6{I$M5%*S&$}~GkWpeIlwUXb}dYk z#r)%EbOz=sf0|obsAL;V!K~6hj>il4u~mNPbJ;6G9g?TspYL8j{6j-R9ql_m>76f6 z>KbFG@$;B_WhC2AT7ABnMJkJXta`-8x_P;_X_AUQ-w#Z868`KRt}f}?R@D2PNl(T`0 zw2~0aAmd?_@y_fz2c~IXZ=3`CH+eBLx|l6&f|9VH*`#le-`Pj)*O~rV!{QYv{eYb{ zq-Mcxv|m)3Ou6Z9+!1=u{h?1P!78PR{~&Z*a=6Af*n3!+F_mGyyLhO{?0RQ|o~4gZ zfywB{Pz8RItt=0Y=;AD0!Q7b-ozA6M=p^Pn$7GGIS5M|rXLKp2B;$J{`j0hU#=RhS zZ(cCj6)3l(vMZPE+G;c+X!BXef1`CGXeAm@R$rB>e$^XufWS}&jH*oz7cizy!y!mbL@!hMNbCzTzuW9ODAjE1OTqeIf;NJSR)4jUj zYE>7%0~3OuGC4FxvX&0Beuw{-Ygbg25Pz%S>12^j3^nHX25sb(s!kgF2V-t#MSaef zZ2Pq?3o?m5m2DLCJV>+sL8j}**Nr@Qj=KtRwL8k3 ztI8$2S+c0+bvoBFQ2!)S)}dpEO}U=jVL@G6iY=3GwNjcqVDwR~tEbw+Gp*mNs;ozL zgbx24b-RsmSJd?EuBS|0vI#C!E}iL!Zcv3f!E~Bx@-Wa{*3L%ohlA4STfz0>#t>!o zFn|)}tByK*z)Nq5!RMg{wj0}5)qYEz^qH(2Y40A-eW{U(sM{{HU2fAjOiIa%3y@c} zx**jtl1i(n@%6@Yz+LR!kP_GG)+gt@uyf!&w;bJ1w-=6E7P4z3zUA+uSp6zsChuX- zBui2zsYWLJ$}JM zIxuBPPk&%A^Rqlg3F3aWtBR1jzH>k3 z4T+hH>XW;o>fAajOgTNqd$Z>5!CuoY?gg>cK*Hu?rx=p|)|U1uTY|o+)mZ)oq4UBo zgeVb+i1Gwjt?Oe?$))6C=OlUWBV(P6xc7s(G_70d3+%cVVBfN!uai? zHwCG$7?amsr~Mg$fHsH;cltq}W(@L1tUQCQc9%bCf3;0NGXjwf_;o*f=ep!$ zj{WHgiifo+i+-?oKqa5^NilWj zv0%trCNKU_jbuD(rC6E!zSld%cOQvYP0S4ksO_R6(+ar*52rPyd#mO}c*~M0O!P^+ zc-q>R-qeq5X2W0ejcFNcVO&B6bV=*AtC!}FZEyrL3urdA@VvGxeXjgm$=tS5XL?%& z#a$Y3#6pYWgGsQXWvRUFkcgLo7ve}jC^TYxIt6{PWtQoX70TVipzD( zuvWMa>Mi|va1N+yv-*S|KgjnV5VI9=fK|)u3x9H+0HZe+zwP}dXc=;@hO8+~KZA>o z1!Y_Al`IJEzDdPTV3a<&G}3>2T~@_=bpveXxt9ri{)BwB^_G6S zFsE)e^G5FR_vm(6ir_}4Mswm^5xpEjHJu<)oN=|$)U^t%CuWU6v!s5cl%}jg)GRlg zn@xs@tlj*?!#Z`HZ_qjPQk}i{EO=LcE*>;bb?4#t-NrHG_jGwkr-S>G?iH(`#Td=9 zLpNjZP5UP4qldVkrlYsYcgcM*Z#Hs#1CCu{3ejgh3Z@N9%1g*sPM9QXtgDt*2P=ZY zFjd-crc&xXNq*pvgu;t^lv$3>R{Mdo9dU%aeb=DHOJ18ecIvhpHGMi%ma^W`_@L+F z(9RMup^7S=wyd#YmfXgp0rU4kTv7MjbM8qAVP}Py@P&{ve}?!|@bamR$lB-8%=m zFSz2L`Szcg3x1Gl(o9lVU&@uKz`u{*kWm|4X|51K@*SOn(<#2myh? z|CX)@;13nz-9iX(5ye8b>lbu5wDeb>UgSL+RC`q=7cOOS7$38$-(v4&MOn0adKc~I zu^s!6=NyoZuM!q&5|OcmlyxelR;z{eWa-F+T|X@nqEIbD>nnt4E(%g{%OY3}+IxIv ztN5%3vqWHgiyIQGy-)K)meAHL#@(C}o-kSZUEL6aV83?l6pDSS2dl1b$la$&OMzA5 zmQZ@3b^sYJYA~Vv<2Z(eZM5tww3tn;iK`^^*4l`%V`8biPeZiMMuTovlG7!&=;(sP z58jS(U0EGmTi-GfkGSAYisdRyWg|JhssgRtFy*Yr)hKr>Bh6xv zP-whZfzmKCZi=8-X%}-4SkV-GF?Cz9ukUI{Hm2a(+t=gvY_0Et?~H`?*Kuk^F)B%e z)&{L_7#?Rw(|k^o!qUv8R`}b)Ez)i%-C9FbTxX&fV}8}jBCpaS;qWC`+E8hK`b$bW z?@0a1u8g0HyrGTUff`)XZo^HAT=Wglb(T%nVs-6KbC9ml51aIi9{S7{=_$f8>T+Kd z?2WE96r^nVR$qS7vy~N({UWGbQ_J}~P>5H|V2O^keP!gD-!=FOan2c)TdZhW`bI#>zo4pGBoqCT+ReIs%h+(Wgp9k#&k*yDGcQM@GUyWQA zYFp%T+=b(w!O+O%>>)-tX}BqO`8ArJc(|5D$jIfw^mQzh_6z8yP_&7S1S&8&SBb2v zc7H30#W}wp?5xms-r;_?Lj-UabNg@B9)P_!0h*c+k?!6xG-z!)Vry)=ISb@ z{#@#N->j;QB7t#j@{T3*4R8hrUtxXowsp z5%G?RHW^)+QI`o6v3TlbZ%6dF-IE&j4(vGg5jj?{uDWwC?)W}sqVzL+X20QC4PzFM z^6{VsGNUL+s*3I+#TB}tLbO)64XimU_!whcVk_Te@%k~^qj0(D#0fK)zL^?g32F~d zCIFH1!K@73yz^4=%4xWDW*&m-PPrkHDkw<`X8hTy55MB{ih(^>KW(S}>|<*q zYZf=}?VPN>Sp6geo}Ua-YkqoT)0K&vu7)zuyX5rAp4kQAv~EOp=YUoAuYsI9x4tlU zAB!-B8@m~vt?em-X@JAV6$s_G$c$6t)QEmQYS2)QCUPHqH)?$mvVw$aZRNO!Agnta*1U`a#vmP0jMSPXO?()5cYiPe*o#- B3YGu> diff --git a/xdocs/images/logo.png b/xdocs/images/logo.png deleted file mode 100644 index 7c689339b56e61ec5c04ffff32653aad0cee3165..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10153 zcmb7Kg| zE)Vg{aL=6Bd+oi}x>4$?3fLIr7zhXm*f7Nxng|Gp9N=#YGzj?FWS*4{exaJZRCs~# z_up4RcXITk)jI?POoD&kh_mbd58%ZoZZH+OC-aEtCBpL=XSmqJhF1W! z{?=6ceU8u6ZEp9p@cl8pV)CHd{>&G5E;n~XxBcIRvdo1zltx&&p(1W>+-?MiGhc>g zU=^|or2qdn2Il?o*Mza8@kErgMN7jb=t|C4mDb2C_q#eymZBX4Gv9Ylx?t5+`3DlDD#KBPm&yhZaWb(9U^6>DqDa$Icv$3(UuoUPZUS3^YHR4)W zSU4xkMu#m@;yh96<7{?V{7e@4hR0x!jztgV&xtdj?(} ziKl$2s;Z08x_UzT+_>xg6%*Q%v3_`QRt9_Ez?RqJuSM?qv@{Y9S*}J*QceduyCQd; zSFhSF#t0Tx)S1586oYM8s4tuRc`-t5jvk_O4E8jg<5h52M6{!m)1SlY`n>nw$rhMa z+uvDhX%RZ|ED&s4508wL|92sElbIhJ9B_rp7_TrMQ?+3ekPs7_`fwO`{qFty_}0(Q z&&X)~M}B~W;|kvjbhY(ueSQ5~J3EZ8=9ib3>hnc%F%=ab*!8ZD788`l$Hr`JY}BtM zBL*5hP7HRb=mZ59e_SmrEn*MI%T6+b_}-`znu`2eDM&6{5Tj0}?E ziVB;tWJWmE+10JD#6}n3pH@TU@%e7 zQwJNH^IKo=FH4^s4P|5?#6o^|ZZ=F#&ST@_*~0J2KFYYhdv|nrC~>z>uRh-2;JEs! zqoZSZc=-EwtA(!-1Yj2eF2|VT;^Jn0f>DHAcNNXd=-`#r)nFDY8>`}Yoak4VmkqYy zT=uVS>x?>e4Gn#6FD>gAk1o9A6R1=Sw@+F(dcb1+{JKA)F4h^vjCmX{Y3S*VM7egZ zr!cFP&6cU=dOzN|v#AgbF}_Tj$Pp$~rr|ugymZ}n7RYwo`W)8Y-oE)mB!vd;hAM{-FgwP(_Og z9hJ(S)P3_N;AEvGD~mi~M9av?h;aw3w&)rD)2D_yIy#1i;|ny=X0dzUzZ-XZFC6{S z6haEa8|E2!*Y{mlQ#n-14KC3Q4)X3q4Z?6*B*Q&Zmw z^mKK-yT5gGh}69ip}?`&j3wi(d((^aW>TkSd~c=Ag?=Ox95eK_lqX_VcDD6IM!ycJ zuYs*?<>FDd@9oEt9hdgkZvq~Fb>Dn@sbyttEt;!p<5z{-_~*pqKJKYtLFmH5f>Z12 z&V^UEas8stW*?%W)~i z%_mH_pmFlWU!bI!$JkHSTQ&_m~QNi&Sa3oqA2FF zJ-FWKdG9Ns7yzPD^sMXM`DQ-^(RZLiqgc1@b=0eXiy_jT;kebV_wO7WY8YUBguNRZ zD=Xy0#5#Iu7O0SClk@SQ!l6 zrzUYbc;X?ueRy~nLFJ8hgu$N1E#S7V9x;G82JU)Bf~k+4%zz#oNNmpq4aXvL1+$$i zSCicaXAg%fLHTWlWK8!JZhd?B?Z1lsn%DaB<%{~2x}pZr6C8?+{QLw~FoUH=^TvZX zdHTpnI2=O7#KfeU!G)-VmT%6JSr7`6FhAhWEx@Nd|2x}#C{qf0z)2cAU*Qe9^<)-G zfY{^DIdPwB2M3424qoy&l9(a87K7Taou?f!*{%<}%#r{grG^+`v!E(mEHdYL6*V^E zTj3P3$nXX>qmkvD{7mnCC@m}uQWeNpsT)4u8qllJM;wQ8tp>&0@MKO{@mlZWP)qnO zROzUz9=GU2MdVClg(>38%9yI6w}gKxX1QK$519|g1|5+2OGNT#PtNS%zf9+R9D45m zWoZfRpzw$3dOSHlhE~VA6AJZvIX0uw|qw(jx%8sK* zU}Ho*u#9bOZ4twYYYcz0ROnEIfxudJP*qkg(Up~xL-EI1Fwq}PP9}KJNoK%fHtG*goN2gU(H1ymaj9Pl&NDNZ<6c!e?nW;Busj{BVb91k*sE9NOF&~L{bZ`h| z5`WQ}qIdSvzHFp19AquJ?pwku8N;zc>3s z^ieIwJKT@B`a{tP&)*?S_f4s=3((O8XFK;iT#m0rj#-d9Q-^(G)Ke8%|K%kH3bmVf zrg;m<>SkL)UkD!_mYTW&^k&kkY0ToVZY6;Z866V?!GS>7A?r?D|Gz1GX(wY7b(CIxN2BaEa{qewMD;OH&z7Kr|)l+{7)4`_4k@o^e#--|+9Dl5MF0wc(caHr?jNR*-*M% zH8(gK1!ZXd)98nmXyWk&gehp{SYONcDxGSp>AZhXNAV>?%wgSg!;j`Vq5!u=QL$E` z09zHQt(_;{Vm|HYOR)k7j0HRXOl5$i+C2M&IaRE3g?;y@oeAuqhaxj*pXqyjwb|J~ z9z@>9BHK;3`^^>$nK|>&!!90`9SP^88LJ-}V_CrZAxe%+9kqN87Es#69~TV~-3-^1?<0B-!bw#9y-4BCz@r--$0L3@h) z=NXIuC(#X?kkEu0LU6tRg#SK-^+W_RpUGPdhgx;U+rXC9sXfhFF? zEp@5HPiqpWDxQTK=C!wz(rZf5&h>t2S^XKpS4W|ccug8z zhf%~jM@D4hTKz_|vv1vg_t$&=wN+K#TVbT9?LYGBd+so_MUJk&t#0KryLGNpIBKWR zI?BYGIy&uSWI(5;ZsW&h_SP_8g$w9$&|6tNeOZPsBG1gsOfBjE0Pfdfde{CM;L&=M zHSVdio4o0tzncQzJ0ox?i~MEDSwD~z%;I0{e<|)S!_Hwj9h)hXeZ_q9;fz%12TzT@ zi2XtXDc~2>HR|priA}o50CF}XAjYCad^zWa?gMjHgaYGFa#H+@{ z3BZQ(`Rz$4wS<-O#eGQRY&}U2xe%zLUMt)NX(cuBh*2es?BJsZcPp}c3`XMn-Tgdp zK%L4H7iDM1+N zlyo|a|0w_O1M>+61v)6+5n}Vu-8PkmC)B>`G%;uEK6@g{3`|U}lgRw_-5x`bBagK< z7qD%b>)>AVqzWT)O3KG#>PMU5Sh56(I~FF7&h$-r=G{-a;#AXz3)SrG z>|X*jmxufMKvNnTihOADAtPhdQGi0+n}~EUq&7;+GjZe3b*pnEqUWqT0nae9w0?sL zqTeOxID+)zhUMeu4hFG@mzI_ysQvY6zCo(8&rTv3V7Iro^BKY7&o*f*1}7$z?=XHz zV}FJ9oXyY`(xAnVJloF6j;9djv7X8SNe7puDEeAwl%11v>@4JQx`r;=J5MVlD3~6- z((U8v?#}NGt%`rQ??O&W`h?wfUjSt_K?Jujb0421VWi1?1jk8`Uw?>acypevR$r$z zFJ1_L0}-L!bbil*??7FoRi;~g;x zNfAAYcbw;F;A6Lw-f!QK{=}3NS+$%R!`7)i*Dab+R@q1_NI>teuZ9f_NJ^E(V%mIY zDY?0ilY$%Sd*PFIjrw->_S}rnu{DVCjVzjq4Hp#f=uZyIMGq}iRd%570+hjLzcAwa zRBor!x(JQ3s_N8W6ye1@*=cKVWlB;KA}s*|n7QBgOzVp0EI6z0-@li#&7S-On$&OI zJ};9)f0XxOBgor3eH-O_FNaGZg(%Y#eC{Q-HBm1U{4&-O?Fm&vgb&1B)TA#ESMnk8 z(iv2EoQM!|dW499Acf{nPU~4|Y2m83>aCl~&(VU%_b_@*=Est_zyI>ScpIOnT7Gr= zBmaq{j);5+Te$v{*hX|hCb7#=`V}0VbtGD49B9$(++6!rOV$2j{l@CsUUB~iFR@Ez zl#X`kXVw-LU7(71q5cFNT4iM=U>gdg-+(lcnwq-YWX(H#>~RmGYN=d}Iw=Q^L{K!s zYP4q_ODXJ%>>cQuuAI!k**LNz?ERDF51f{rJ%&lb=ekCd=b=Apy~UmszKc3akfPn$I|H|`#+i}2srsd@1xP~bu{e2H+OCRrV zJcTF#t-QZJA!JfU@Gp{%EY7Aud)sv(pFurDSsv{AQR+^Ess~Iyg-InChAp1k<*>{% z>UKC^`BcC`%KG9|{4XxPr*^X148MSYahKOc6mwqR5*~#=fHKMJC38HDU=%9h;?rW5 z+MXW&e{|rJO&1&zck;4v{zj0@}g5Cy6iIsoUas;UYOhH$!KnR75PSuHh~0z%yL z_s{(kTq=hagO@K~0_{hKkaw8M_q-pL!h}sBk4`@zsc2|uST(gbG@OI@g8#uV8;N_Go{^D}l_g>` zLlZMpl;j0Id1oYnn#)AW&h8Mje_MmO3@{+QsHmu5V`BpW#<0;0Y-5<+(2B#S@_c_0 zUS2{q-quf_f}`+>iHY&?HFR}#H8q3F;y&j5)-bMb1#(hBL7=E=*q$<2g_;^QkA>ok z7olSoS-jQ&R*qL&>o)+Ge!L+w2aEw79sOrR_N0~1VP!d$&oOr-@{gPQNh@BC)fX>b zY+lGLsNLt$@u3Gr08I#J5nxK`oJMS{tio>lcsA`|DfsmAvDA`OBWx7i=PZI*g31yp z7?Zg74W*@}V0r+F5Or+%$N}sB#}>D@O>7ad*ffZ+QITT5(p)X}{^2LlOij4mx_Avm z`97VWpOpnjiJ-$$;1m*9f58X}&702k9l+jU~uGzhju~>Nr{PEjw{Vyzv@EY8yXlu z&Ao(hdYZ3vV>>Vk>7C7QAXM8u*e9o>)M5j0ZajtOY}jmB^7sApcIscG5O&eU^I}xD zX3qN#@9w3a#-JwF0tjW42F7L#9L* zO&71#(2gbk6dqU(Gs#30AsY=HjOA90H7g|G;wFMZf=$fW$YK!11{M2@d=2vJ+7L_& zyj@%faL=S)N)O2h)7rBzpEk@T1W!i<5%XvCn=}~Is#iM~so){^Zs6vJe1PeNWE|%v z*q6%}c3iTK#<$x9Ykr!EE}lJq))9v&`#d*NcA=Ux zTIO^g7vV9AI~*RDMBe~GrwgwMr=^H4OoB3)o6U=HVQs}IQz;dAr9MRn>6fB>Me{~6 z)?6%-f7CR-?HPY67E$TFEEkasd19<}aD$nxA#@jN4J|+(M}X*z!XOt7VzUdC9MkwLVRMuy! zBbQF4<(iVZX_CQjb)m(IkDs3mt9w2tFL#IXw8Pm2cW=hh4K9VF?8JK~LKMYDmT1Bt zg-I9`WqT{EQmq`Dtii}*W>u_e5;}m!hf=AZ1sxAGdQIQRjn|xA#Q2=xhNwp0pp`;4 z6??LMou$btsOfc_!O);~(A*#A>Nm+Nn=9S-Th~sOG9l8*i*s_@648SLI3-5*1h4Ey znEHD@L)@887_}h+l2035AsQVPic!*Xue}l9V#6lP~^NdYrX2 zqsAInd8;2vRKXGTQH>BFp({B`cdF*{f(~iQN}7gGL3Xjo=P(ACYB{f@WG~PXMA2kSo0dW81wtGPb5m0j zU^%Z~$y{)lzkkp8-uCB+YRKoY{sk$wk>Jx7#pKYxvz~>0K*m(E{uw`6AwI)j7(bK9 zP}$Zd#LoWmy#WNq2-AeY&^@(ht(q8_m^xl_I!8`VPKL#+62An^@a5k4hfGj0a&jn~ z1xF%Map%QZa%!^x>UqmrSzF8t>}RPfpb1gLm%dEbyjyno^z+~4w%;~SD3x6D`SWL> zZVjB!tCpwC5sx977zQ`qBoAG|0eLz9P_e9XxX_k3$p!3s+z zd2Y-BoBe1x-j)xPptaVwZ-oA={E1ybFd{shkuf%=%Bhp*Fle>`5>d_^u7cd~5*WwW z_d@Q};SV7EZL20y1KK(|kH^-M#nXfY1lMO9&r$B!Xt`(7<3w;#wY27!3xH5s*Lk|l zbGI3STQR=tXgN>IFb{U8AOmoSasbkM#i7^Jl(3rTmuviVhsoIg5uJ$!r|hza7Jr>|F{_$M^bFs0OdLM&O5k1T_p!7XVSx%YR~Gx6gr zCU@tS$jMsD!#@DqZifVn28VB(O+3?YpkZPv)9HadrDxk@P}0mH{yrF8B;>T#288LT z7e|SZMcNOHgkMm%6-kR&7qAG7|0I2Y zakZPGW+vFpiWICqYe<)xB0C=uOf!)!h)bn(nZ<@36%N(G|G1Yo{IrvYMDjXgmWGiW@~UUy{_lONWMs>5wk$kXHCnggMAl;snzL|7fS#p{16^ zhc0l_hcPrnkn|!l1(J?ui@<_VrQ&pt;~rVX)1T{|lYq{Uh6^w3NQG-mvS)lHhN*K% z<30FG%C}){(h28t5T@rQ;+~;G)h+(c;^t%l*(cL@wo4mE1Qm;( zQ>56_wk@kg*R>s zk=U-GOU`h4Sj7XsvIKH=!0c;=kN4#h)w~{unc#Mgwr6mtJ^G7x?|7@ELnts)c@l>Y z`4jOHMy1xq`WypI*2QzErVkjgDHl}#gyw5JEdcXvRoCHJyA(GT8r#Kok=~lFRFY98 z`y3r}eeJ18<;u&q7uqnn37>mUh6udi-y|yxCB{?1$2)Y1io0u}Gm58ZT%*hv&KG4Z zEyNF>gB@G!If6nf8H6?9%eg$yPsdKI=B@S_9tvfB_9!DGu#gRj_@K!cQ3_;=u*fbT zV2GC-&|)PGx+p*)#Ub>YivnB>6sT-te<{^9K*|mWpS{r2(UDV7n0v}d%wD*kEZ8h|M&~)n(^=AtfH2DQv{jXn#o4U>9=O zhN(@Gy-#`Eh}~2wLb#VdYqJdi5dv*}gh6hQv?Rs#`>?oaP*#d}Ymn1}YOgM~(dfH> z#fz4kJIUvA**ZT;x=0V1{wZcp>a?xu+L$_{ltLpNMM9=?vO5*n%r=x#rk~#3Kc@53 ziP9;$wP+B*(*bP%o&{hlv=hX@;F6Jpk4@bcy#2DrHx~}hw{-@%aX{TT-2%J>Bfy0D z>;5FUqzeb}XjD1QVko=_b%)k(R)=E&RzZ&dytv&wA`+6XU%$HI3cs;CnUoK$$|R2s zbwo&`Wn|m~w6Az@PIt$sn&BVnNXf{225MG&#Qn{go~E28(x1V{3!~3l&P2q-{d>G? z(2KuwbYS3+5n%tdGoN+e7=voKN1MyY_E((^21^E_!`;ouC=$M*%Y|Io}iT)+~ZdVK6~r{(B)!d~B{2}+FE;FOBz)sU28 z@~)f6S?}LJpvL~6otug)g^rCvtgKdL@VSUZBzFp^ooU=@Nl8IS$m0CFF#8(?TxFlj@)_MC-4#S{RdN=BjI!^H^Ta;f>r z6n&y4!P`uk6vEQ;z$N3gnt--NI0LncAWAcYdp*^3U5pABv&ErUd8Tpq*jo*S(g;Ty z$0D4HYjZR?EzM(E{D$LA&%;{#yNrKc1R%qp=TTBo@!Je~^1wjH<r5p`}GsHPSHD zPA)MaViDIg3@u?4=A&A)4OY>btKr45*nm+L?&!lD!*TAu;M zrn;)?d=Z#iocaxYR!yezdx?ZJr;QGm8&C6HaNoEbcV+3xcmG;do8z+Z2Wa;$Oj zihg%5kQgJ%T|Ab;JkZkV-@9?(cDmk4%0n*f3S7tOKn@&ol3We z2;S@7(Bhv3Skly=sqvguQq6~ff!nZFqgyS93U%n85Bu0_`qczo3mfZJ2G40Yv6Py4j|OA_&1UL+b7?hN|<6xj;RWpG8celInzXx38Y$b}oX(&9DHIw*U)h4z0hQ z+^Jw;eUH(=IzSCqRK?{{X;MihRXkveoW06sDw_`rW7Oyo!}Bk_XIz_&f$nPuE|cx* z3vmc_o_~nf3{eIMjeO#ZDjb;g!UOV!iEos4+g43Zf`*ZSz#yD;?Tygir?AQ5FnU^* z1l?-s9==7X&pEDkiH2Jxe8aKlToE59niDAve<1t=2KuBbR&;+ePom_SmJj&{1nYU+Hp; zPJEL6SJj?LNrv8oc+!`auDqn=1= zRdGi=W>ku{r>(AoJIC>2*-wFHD^_>~QyNQq;l~zu@G1VS^at83kJp>%#|1xCWqwCx z6S}5w=1^;DRAtRb$)Fc|eAdw=*Gyu?(zg7nZK;8c#cMo;75*A(&P7%h6x&|p!SNsB zm*5##CNq$YJt|cc*g!S4JxA%VwNj`mo&+T#*dPc;7om01CwCDcPk*?uO=T)_EmOb@ zL_)0TpV>C$45m;fPJb_4+%ZsX1a_XPIa?Ez?tR6F$SY3HOg!iS-BQ3Snybtj|AP)3 zLDPY@sCk0);d$q+XP}}1HGzF%`4C=m0r}2f1x@Z;L234SdbHbElEnEGay&?7&;G%!4n-7 zZEDTZ{`MxDGftZZ{Jb4awpNuV%2!XmS)jc|X(C{~*-yq&iK0eZnLfLb<@{Y&KvKS> z=+u6o|6h}jAw;DV)JbYGO1AgZNc(2HLRITyd@*vXSIA+!L6^29=3rLoVJeDn)wE^A qn-RyOxmM?uG44dIF3RA)Nao^-OnX7^KY@qp5MXkuFY07Wg8v854`avx diff --git a/xdocs/images/options.png b/xdocs/images/options.png deleted file mode 100644 index b0f9d8febf66b837cbeb3ec6e5e62cf9f8fdd21c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 27463 zcma&O1z258o27m52ol^SxH}<%V8PuXxVyVc0zrez!QC~u9^Bmt?(XjJZ{F|g>7Jhc z=bGfohGV+m$qL**cglp86P!2aWXmC}wk43>l@p z`)M(+$t07m>ONF4p#LJrdfs_j^KdRwOx<4`J-BmC8M*Nox$zvm@x1qLIXT%mfAS0l z`tg7LQ&b>A5q}lUqfXM#KU`@TQ7Q%x8gto>dlRoG#yCa-D-B`}@ugu>gNF|nF8ZNP z|NT$t)H57NcNa>Lh<<1E=3CJZ%Ab@VUu`x)G@v08UFiR{F_#a+V-)i@&q>z5e>&|P zovPS?t^Bh~mo}Q-`qLj8l&u?1?z``PPAGPN^-;k~cW_%JjK7LkGx(w>**p?ejyI#M-Vz8tp+n|M9%~-PdoUSU&eX7e@Tx_a# zyZG4XekIGwR{YUhFowe0`y&YC!@+=0_&NAfT z+)B==;k>0-8lP$Y&l*`0ms8EH^n{6mBHLc73-oT?ihW;ud;GU=j|Cn#wX`q1-O+g% z?4#)`v_4+9wkGZ;5Q;t{kS@lQ3dKV|RVL|ai8_a{O5-iI*ZrQzorlW_Rv&aYZYnQC zVCW(jHVmILhmaduh`F-Xy1+5DrKP>v^Ul!y_B7~of^1r|MDz3cAd{TEedBF&snw+Z zit>!fcU@ha;gl~wuaC8;p~L-Q1{)l}yXRX=qzQ<4n@rm2+%E6K2<8G+%F`qu9xn73 zXhD@T8rn(hmfv--G%I((I?f?6!AvcGrT6y0MiGDX7c%zkx4cv#?lpV!HTab=abexO zZ2Dc$^9^kLSZ^W*W_VJ0Z*`4wy>*1oFHQ!3Iyr2z0;gOF1J_Lo7JGYdF1e$#72FDr zi<8!Bs>RA>H=7fWS;o5P41kE6jA|=2$}om;eW}5o)GWH&0$b?c_Y$+2?aGOs-Hm5! zb>Gw8BQCV^CH91SNydI<()=r5Le6d2H+f~(AL{pcgSIH-ZZJ-B*af9CDQzrl+;+L&{|GU1Xv z)bq_sxso6UnUISnuVH^;vg%NhqkjLixcoZUtnBz;sxWS1D>`~a{$!c3Z@4t{(AQgi znW%?Q37P0CV_s)x#6U6W-~-~uEGcOVwv}(GIz)BN29IMPu1vFmF%N~{vkW66TP&mM zj5}Qn<-C-S_-q-moW6e2n@Xk@QwATMR7 zvM$gLfjEun{mts8b|sl8BPnq@l;h2@*IA>!jU*Os1Aj@(0)GQ11DF<9^{U2VHaY+~ zmFj2d`faU|R{(<=tM;XTsq$co^U=G4Q%*RzyCCgKO^(6bJg0+a3SDtY`n94_4M%yan9w7T%sdB8>Luv6m2aXUDv>?xSHkDqHxI$>b-tnwj%K+QfZO!aG-)RfB&j;@i{Ug8fXw#G=+y{sp&`M zV#8#bFMUu2p_5ezAm6eA2Hk;P@J3oCFmm@~l(2LZqcd-{D=dNIfG2RijS1xw1HZsZ z{r_w>48qAlp#GWC!0ysB&{U!Dd;Ifrd%-sPVO$RcUjg{R(#<0X;#(*@eX93K+Un0E zuCdHe{7;pYm79||oE$m$r|(;k?xOW#Uv@@DD!bP`-ucD* z%w*1!z7>zXT-4YoyEu^uZ7GKx>&$~$hpk-kZiQTSt>wn~>a(n_E_Qoc9NFPy4+Zsk z3UXecDc`l*%@{eBcf&=>iUkfkKI8f6*0HTO{~9d0j{c(Z*VamRdnlMGs1;T=J53j> zCYNb737Cvn=J+9iCo%+{#XMh+Stly4+i#KZL$W*`9uGy=+ne(n??;xH0Awd}wko_z zg}mbLwM7RK;tl+r0bhchAkXfSuM^6@`%v%okoHD@sG}q0-FxDJl_sATC=T-}eyQZ- z*_@w05tOyTmw2zUEly4V(!n4TIt{J6kkkJ6zLjFN$=|?W8oCGE@C9}oJ4MZm{B5ux zX4BU}GY~lyV-gkBZgcO>#e@g}L4(Wnv_1hDg^#w}x>TzveqzGd?Ew0<_kP!NCg@#8 zq>EK?3%G9D(a9d*`5Fsx!N3u8Lg$<_CpTQ9RObN=Y#aooA{gI(^NFqyXy_hluak*f zzP{yW%=so4y^7g<*_#h2!BYmc%}#NL%AppV@*O}|@HDU9`2y!m?ng%l4mtEcqCp93 zo*60wr)AE@(~}krdW!VpT8V3TL`44G#g4^QlSVZ)ITI5n&@;Jmi`lX`F5oI=vZV|P zWGtXFCDn!Y9V<~|yK~fC{Z9S{hrNtOPfcx(S`XUS*!E9s*%w&mfQ&-M-Afoi-2v_X zj~iW2M|U-Gd3n^_ygUVWcdo6?O*wCG-e)qBsY1m-OH0eX<>fR20)oCp0#*LKm{JXt z;;Z{lz5}M?9U`SsbEou;R&?W74m zt^IQAZdl1-cT;Np@>F298?O%bF17|~=-3pW=jkfZ{7Xw<$H(TA_BkzsctHLg9yhzr zGRQ`Gc_E^kX*}!gxg);5pd?nKcWC0G7?SY@FfdUh8OjS-^wc%Pc*<=<0|TT?Iyw?T zVQ~okP`tcTk}B$d%*LTTK(PlZ&Yvjyer~lR;qThJb4jOi#gUSdQq$A_wzRT};^*pU zpO75%GlQXqm(G5lkS~*-S9gDtuc>DCLozC+<@V=&IIbYaI3*mdyS7RZ0V$pQxgX5V zJT4nG4NWkY%dyn>`1n+*1}8Zh$TUU7qu>6Iqq7}qdvvi@T?)6TwYK(~csU~(A|ic0 zbF%l*Zf26<|T*+8Qm9)Y8&I>I&QuN^OX0RRPf( z8^Xz3(S8W1^a2I~4r-3o1r4j8hOZ80$>c$8w$PO6TjjUsk}Si7o=Mb;u~_^|_3krF zFF~VDt7Zzd@J2+!_o#o{3f-js4)&toV88ajmph)k4TUkvFBpa-@(A-_7Ip6Qb0u zu)SZXNF!1EVpn6?zjlF4%qvx8GK#e^@zZSek*rX;=~IpAWB~8{pC5-@E;Iet)Z11- zi?)d47ru!}Ni>XPYx^vUgzY;6cNf+BohW89-xK;0zLqSk%V$%c^1Yz$DMW>uj1J^i zWEY2XKUYV?b-u5>+=hC}ZAWySUs=(KWpp|G`w@D3B$Yc#m+~763L&4Z@62$Lu+9K< zG~<7?CeK%+(w~>FgEd-9>50|qHBO4hz|AjdQjvm1wlkD@YUG2W!n2+W-ZdA2XCUH9 zsvSy|Y?v*_<|bpj8#=dM%t#dws5ZWLe0O${&CO{OG7B*@88!%#8S(}hYw%*nReSCp^P;+r{&ef{Iyqry=j`1>E^Ti_Wv%F(onR8|b>Gj<9yXJ%&&AJv@bX=8bd-tLNQMtuU`DOo#Ri9J zDQDlrFAkKY8g(+c8h&T|_!@QA%J*qtFm{crih=&nV0UjXA5Z=E7F~{HZ9TX6*;bm$ z-PX<)?odm+mB-nNCmFna6viS%(%9IzdhK%0{^GlvTf848!smlLY2ml=y`NJn&6NwU zW+Qnd-MHzQBg2WmirL5}2~o8^gg4eVDDU6O&s-~Q-L?Z4i+tPTUOv6wpxD0i$+cA_ z^|-gOwVnV9CZo%0?c3f=L19Y!xYUmUQpuF8I&R^@A`^#U_}z{+vaSrdD)%S@yRugtIrAc>-}jD@0j*t8EL2ZJv>?E zSq9u$xm8P}#i;n}`mc0%C6#{`oSN3)g#dbUOGZMYmW+!YITc zshS-ZA&IN)PY+WW@?mdFaOk|S;fwRsKBcq7!<)*g5$_WS zmCuo>>t`oo_JZ$ujp^x3BK+$^r7nj>%|EY2oB0*oL3@c^8&BFMvF0#oh z7szjz&)67IC}OLb$yUG?4V-1u_I@DXn-VNd^*%h(VM!>$lRkTgm{SgB#GEGhjX&1V z?j2iFO}577VBHzX3S&a_*2PEFx%PJZkDlZCSZ2P-a3x|lE>cL-tz~OfT^%;mN6q-! zP%MTlTsGq%w4FT@D`n6?EVy@IpsFleWcfs$fLWGX+c59S~%=i6rYV`sTcb937${6`ZnKP zTwLrO9MHkhh|#&l$;tR=?_+8IIXqrJf9^)ow>p&K-6*A2SZg&LfX}Zj2)Tkb1i3|f zC5ZV37Knhcyf`3a@XUvdnc3E|a6d76nXuspsq;x5ifS2o#NK37hs3JB{?$UAF_PC8 zCt5dG*D>Id@`EjeE{om@=f~V~_~)mAQSL`3%p#vC6Um3YuDAF5*%79thq%3w19P+s zJGILCe9C|eUC*2k?74`Y!rIIJ6hT((yZXE>D;m`Ctn0RqsZL z*@L`?2ePyw?&IXY-nT)45J`0_|NH@HLoF6KVTh0wRsem9h#q_3x;Qq691#6k0FWqR zhb02}F2hN+AcrF~*H%|!XeB-o5X$qsH*cT*!)Ej_Sy4cZO76y2RaGSjC<8rssp}qm z8#ztQl;)f-Wm??hsBa)9nML(}qnpTtyNCTTS%!%T3Dm7|*dSj@vu5N_zwJWB{4T3_ z*OCDW;D!<@!&%)Rvu3p_x*3L@wj1tZQOnqr6s_l^-}oe179iY@2Kr5@%UYJU6}_D& zo!s?n+_S$QP&Hi}${rppL+C3>!M)tDx;{%yR6PM(YscOyIOb7Iglo%x7TXc5;u~v9 zQ<}1Too%fM)8(`uwy;^wBWM=Y<-rfBDiNPIdLyuTOmB`BM5CgjFfcKNv5nd<)~gf* z#V@vpv$qDplRR_n=u+4^v>k%;Ztm_OnaA~71df3ShN5Frd}h7jiHF{%u~3ShnI%eX zo#3-6H=z3} z?tWvBq4ls!x(q1eLQ)1gc)V(64o{K(K_p&5I>gvLma{XIRn z809u&>$UV-y`LhVG0Kw@a?ATs(a^q4=1HTQNFB_SqNfG`o~mB%B#)_RF{yW!o>(OOS0 zFX2%!5J<55N2JZv@DEl%d7h^u?RRikDYSXsEV*_c9?%&6qG7eijkOzQ zvA-l(_+56g-3uarTS@Kes;>ELS!(@neq3H|d=7JrtD^O9v@vwMI{-p&e#&q0HnM7KywS2x3Txv(QFzxCmmyFw7!*IPnTGCLt5 zL4kr%u=6OAhK6Qc-L8cw+M~fxJe+$)^d6W^{{uzqD^w#)2%(9y(?~8gM^3=vr zT@-T$)`abEHMRLxEpot27jS%UY-|``(x}@kxBGLM#77(qV~&zEZyb<=0CHM2|I1sc z>n4gte^=|})%#l@%U50iFsn7Nk~bd(h5DoYj83D-F4v38N%h(aG9<7-Q)u)yJDYMb z#>1vYngrH}D6gy_BnO#SvvO0nfr|yT9qpA4NWe=L`k^3*$I?SVp@TAD%L3vg;uVr9 zep0-eP3q4+yrBeykgba&_p2;236Y%%ZTt|V#7xb1;{xyfMFidjwbDe6xz9fM4h6MhJVTLbJ*D=d&WsmuOnUeHq=^qLc9r4m3CSPG^k~B^XKZ31aAm6nyb68}LVn@3J^1 z^A&^AiI*DOsydwhG&M9}pc2sYcBXILMIV4AIwq>>AUyx5-0ht+qs0KZ@dsz;%boJp z0ltlFxsYx2U%@ub0$vRCT{pR1J+ur~@ff^JoGi0blJK`IN~ww0G&?aPXJkJ;^*5R+a(S=%?q;wX zO&94O?9@tj?~ii^B4uwNpiC^pP>%PXv}7|{TTA#Q>C-eW_(EN_?wZ=CGyjn3?vlF^ z@Y_5=c(|Vkq*GP!prWcs9c+e}_5ONKo3EzU3MB`S1oY^;jfl<9jsD?@d;YUMiVhAn`bez)BjgR8eU?Y=I?m<^SC*OwRZFA}P^$ zgqssZKasF5M`;HK_YB)f<23MMla~h3;t&J+zseJ>oeI7D?}FkZ=Sn1CjN+b=UO^4KRE1LBA(zzg*<7U-cM_*# z!LG2z%oZIw@5Aq`Z-T;@G%ho1Zpt%j=omtQpKP$ElNLRkdm5dL%2s^FNYw2v3lerL zWE-riQ?s)NTH|1D%CQ;84k&o5NLUptx$BaV3HY>Q10>fS*G|f3GoXeSAj#I6O)7i; zJ|0Sic~2V?6!Jyt^)5CI={4pPLYI-HLtHp@R_-H7%4@Z5eG)N`a`Z^8^DU5OD<#Zk z%j#&|zwO<^U&$BPSS74r(uIWjB%-2uMj0(=PB?wHGr;tqUBa?=(}7O0)vi<2nvFlu z0OI%@B)@x9H0TtI;eE&Y`~?74000F>&;N1bi`s5P0g|KeVveZk=-vlIalMQGHF_=hI<`H$&e$NrklFsatVxvrdFTJV)&E-1 z`_Ize|MuHIAK^Dzg`Y5&Q&JKtEG&#oOOyHXMH;C zc2Cq6FsDnXsj1x}_{mh8%8O}hTfa#Nz#zZzdSDO^2vnT%d6B$>gA>D`=5w7XlRiE^ zW*_SGgGV8v|5>O9KiK(-m0#q>zE~kh!w%7YZ?z_5czJXfQ2N|i>$8Pv|EGrHAONXQ z@9AEQ{KGLOmcq!aS+}2LDijnHyU_rK--9#&3D5T`ei)p|!k5n1>S`1| zeSlJALcvhmJlGPhc>DI8WRFc3gmgR|s@{j}3)<>$aSFZeyG}(yKvB5g8f16cR|*LV z%6L`1ajBNLc*ybE7m(8kxKuc4SScQ-`zf0Jml=)Nm}EMMC>^OJA%pvCii;$UsLvT_ z$vf%!G=c#^2nZv%7PATp3TRHpi-}p;*@b}n2MV7&0os+c@RHajCaClc^H+=U44Yfq z0lIIMx7Rkwud{)|qMWui(HAbRiT)U>C}!XW4hSvQYcT9jb=Tx}%Icaf{s*F!&@*&D zZ!SZcc70bsh>AKimPR(X= z-lD;=2NatKK0bCi%E^7e#KIz#f87%dibUJ2+IcS7B0d)XWIfr36PvlYxoVpgUh+3U zwMuUl)e}d@BzXBx1_L?*l6&Keum~y3@2Qwx*-LjXxlfvbg|Mo<=e91t5h$3AzH$w7 zLqR!Sjq(ZCT)L!tiImq_2B!-7SNVg zw9lSX5|hM}d6$H=5FB$qDh4RsJ#3_PMcIhz%*Qqs{`D|HADOt1m{r`4NHkn%kLT4q z`#5(~t!f4dIf!Y2`M_L*O|GEWZA7lgV?021o1)l(mXMOn4o9a9y2E#K z!>D$klGdpTc>MNlcRQ8)+{mIHgRc|3t%Jw%leJ7ccRUn(a*;t}*WJ2IJin=WMf~BT zsYtO*DYdQ%h{4k(Goclz1CahCqwZqzpOMlb+s;*3NLPI!Prv3p=jT2P3!a+IVv^qd z{6j%sae%%%o}>Ks{#tm!top?il|Hf5k0C6DExH5zYY>ckHu0u0$u15HsLW_=TW2mF zG)TLj1j^20^Ce}KYCI3bPh5Y9X*x?sBX zq8PsM2>p$Rw)YyGL_Ay|Ar#d4sO9smL5#G^0X$L{+X}4=q3bD93nBOw!I_R{{j~^L z-`GeeGQBv*`my_)^t&zW!;caY{)gg=lZZ)isSFZn#vJBBcYOxErW=QI`twyT zHutB4Omv6|e8$ETa-yOY;p1gx?9wW%99zEqE}VKVH$E@<@mF@bvF8zv>xH-K;)R8Y z@6vhbHDvDiXA|EI;`-GGeNL)1PD(gFb4F3;wQG2jkPAJYD0jzR#|Bto^_rHOnxwZ?Yso&djtAkLHqF9#17v znH&5M*@whSB+vYz5Wni4Geq8Ij5oVE*g2OBqisi#i56^FlJUA$kX@B_eckdNaz1VP#c1{k8jofVs4U z9y7iw3UaKh-%v`bt4>RAQc(XCUd)}_h8c&gyk=7W?s{0yX2KyXJ$pt=BeY1?=<{x2 z)0rB~O@)Ct7a zVi~qdVAC|Fep+nEahS?( zzl*smti$xAt`sLBkiz}=JBdxA1rfX*LHv~wC2z4uZRVbwU`m$AJqf#^ajtt3?!{4& zT5lgXVgnKqo-sPs*=*C2lD894fCgaiThVa@t^2yz?oHU2cRpHnz`g^@c7J0r#&LJ6 zOduw>KJl~D8QMH{g#$JCoLvVEE+-1yb6kM~+8ZY+<=y)(UY(qYGEa9V3Hjvmu3I7t2cUJj?M8GE(`$*o*dn}|_F2Ivi z=aIInsW{<3N*QFNLg2-9Xdxex=INLL6kA!{&EbzW8hJ%B>i%b3zDrz+oO>mxvYl5Y^t!*=!yfX?{p_bxA z*MP)jq_UA#>(SiB^>|1w5qRkkCq5v zy^bhna$U1O${zHz5*My}bAcTtzQ2hdAqzQBT$CxM zRLKgo6yEc-;8YHzonuAxz#``)<|3b8=XWrlE&3(oYAon@Ir(Jsm${}ihWi#49^SlW zgP;IgwFw$JZyE2aD>H}1jFi&g@mG7;w^;(eSXjhh8N;Y81(h0Z((n}y7PFJu)h2C{nbDC^8Eb5%z1ZmIUbOC1>tb~ZS3@#zqSq!=^4pS z_)NmS+x4>X!gDB+n97H5R{@pM@L83m91xRe`JFL zD!af@yM15Buh`h=Zz?J()pi>q@=cjC69v2!fgLaaHKm$DI=cs)ETdzDGBh@V~qaT z23yQ_nexvd;p0tRuRI(uv3#OOap@(y6}z24Jw_TN^c+IE{A9l{P#^l%6eR-HgYF@| z-r!vX?9^Ce=J<=T*0BqKxtP5lUB~^LSAeQFE-p|zmyc!SCdt!j4(b}uFfcQNhdg-} z1_5OKm2F0O)@v;?%Mw_9V84=^uV9b4hlD(QgwAWh9yZE_MnOS2qo$?JnwnCQkd@6p zJhY^xrx$`Q+&$aqUAGTh@p;i&q)y2XL?MRj&-~A0O&zGwps6r6u9ct!6j*U_alivHY44!bJMz1} z0?I86P32$~8II86GuJU_#yFDFC_WGrx}$5r5N;Ym5g2*o>EQvol%8NCt}71cQ1 zl$?hjG>H%3%#?!5%bAXrAsX7h$k(b&_I@Y+^7kjH0Nugd!9bz^#y7FFHdtGBTO8>~ zT$q_rY3_ww-A3bZ)>ba)KM!xKatlJt|)d5cTu2qG~Yxlp);G-S^FvM9$Xo{0$B zJA*cEpPh(Vu4WOQWszslRb+qx5PJ}LJNe;fZgMf*Qlp3JGaka=9nKvr`v>-E0d%sb zSTLXFlIGrVY3l_7f@Jw!A92QWMxj+bu`z`$M~p@~uj9c8p&fTQi`N6-STN2-iR*YB zcV-AH&GZDldP#hI?F8CNy4rPvnwqH9?Eid4BakX@xg|w|za&yUvVW@>J8NJ5OSbFfy7F_tzp zT9hz14}FB{L9j}|jO4nteZ`*Z`_ozeZ$UmTr)$v^2!qqX#lk>N3ThG-1zrJx7&%(A zQs@utEw_&tq335Y`+l@n>?!?0l}(&NvTzu9w0iRRF^)d>lO(JpFaiqfjHWX=k2{q+ zADQk%k>$oKngG1Bv!7V4@^OtJ-Db9!kZ?|o%V)RffDh<4mawoeX0j?4J!ag`urU9Yn|-S_tkH+Oca zCLnok(uaSk_3#2?-(&BF1*7+8+34(l)`RZO%TcoMLfW6sK4@szgjnKwHS57F^$iwZ zf6~6+Krtud#x=cK_J~bM(>}U7`@}Hck{U3QESk^CTBIeN>T$yeCn^-FBlZTcS|US! zYa3|O|29byD}2>kk#F9Na(I_b94M%$H~lw1HT{HNbOD(#Y3SOYTa39+xXBE*k;+Mz zc_jCdb+0wo7hZyQ%-&_dIV6Od47!C!m^|-~*;|Vut3=!ojZrNvnz>hRePku%a*O`t z^T>jIQo|Vn+b>ygi*DjH}GI^1j7VAlZ%gq6uclH?_PeSHsfp4k(=x7g^dWvdV zs<4?RY)wp9i{#QVE?d+zPd!G9H*{@6M`kv!dcRRufr?qtqzd^fQA2Zb2CB(%1 z-QHha`8zeQF6A&?&*fcJIB_Y)x9@oUSIv9@QhE>VC`6#f>D5SV*B`f2W3MmQe{!@r z9}HO0uFkS5LMw@-9LFy*$<+pCe+!*ptrDhl{swRLSNYu!bGw+TTGC_kxC?D_SVUL( z3D(Tqtd_U-Ra$G^9l)UwDS6BM^6`PX;?Zq&GdGDpl#8fMBH%> z5UXgc%(~{f{&V^O5Z)cv8;`Z4^}8-xmgEif zimg4fpSQ(>g3c3g&&t{CR8Hw!_Kd;fyCHD0T1w)Liu+t#)e>-ZFd26+TX@I!ED(|Y z74>3zNyHl4>${Q=*7mmf-SDGEF1kP99_TPv2kwX6C>T$mImWZ-pal{t;fJ z<1xY2@z{^WM#s#A$^1g;i|uK3ow`p}yB2D}aTJ3yJoD2v^9y|oSZ7Z+vEFx;ySIv3 zX_XVJ;R!e_!_yGt+S+OL73w*g%@|nc)muCJL>3tC__wyU&KYbg>GBKrnxYL8S9G#B zWY)x~YgwsJ1(hog0<$R83@p-`4rWhT99v7S^A+VPN9vaut0#E5Q@2V{BED#O<3XB# ze7_mxW|tgV;_=yLP}?c@o~3)E&3c4uHO6Yk$FX9EZO$nvRZRc7cOc z^6>JM-dBCNi4oN$8OGslo`TQ!vXs-s4TVU>p0}rKP6H-~#li?$S{8nH}^^ z!N5<%Xv#SavkqoGjjcCiWvrzVdlii<#Y5FV(zm+{(~;#U%k%+po|s%a{d5lYoOn}~ zF1*auy~C44&G8WmRw{dqluqkhFuKCaqh`isr|G2Y;**b0jTPCADdhHQ)?7m;8y<-o zKofVKPP4-Y$yK}ISbGD@Kw#V2J-OP%}I*5;&4BEXQ+D% z8nvp2kM>T<})W0uxq+TOs?v6>{j*TF9RYjplm%IIGoPy{{@a$#$7HpYIO zXfF0xcV}QC0!%@`vKMraqg1-cJ=AM$0%9aa_Vm9k`*=myYn9RVYw-%cPi2<-^~zYj zACCaFC~@j!@g^xl_94^T3XJrVa(CK0$hS~%B8Yl70HqNzejhJUR6XK;W{2{@BJdH4 zYl!$?;2QES3Don!bDC!YPF;AfUcXIu|@VT#eM;jbS zLY_>^v3)0^v^g=l4g5J`#tmdyRoa12=}Vw>8MO##D!7Rzb zej%zAJNp9z1M#vENCcritfteoa0?Pgfo~GrgNienJt5Q|KM4?#BitfpX#06YNx#P@ z{{TcouNfr%#_%I>666f-fz9@(3NcVo1@!dv3@t2*D^8|?X_kNFQr`D^-Vt|SUCk7M_Wr5o^RK^ex&iTK8Bi8t!{Bvne zg|IBY5^muY#;nHp|Cw-0^d)_e2$uy2wJEtC1pFgz_dI7~V$`}Ttvb4se ztgI}df0Ci~UToy#{#?$71?ODAT@z99a2J@qr!+)!f3crFHC0P<<fe>fNJVL_EO>2pvkN{Q(!r}2wuli-o9u= zk=Ec2n~~BG%ryD7XML>2RecxvS)*J}MG!H6CPUsYpCav(cGl(q1+BLAUVHB5 zR%oG(m&3k>ybD7cU36@FxBze(`e2LA4eyi3Y%9$eS)}=FsdUw+5%+nRc@NyBRu`Sa z6$Txf!gKqrEjA;!K)%ieC*3Eg0U+fsau?ANnVN_5nii~f5Ab}vJnL zxG|43?`oWlqcQCh+4?3rPdjX?tr2QCnNv2F8O)#|!e%mp;fGv+MtyTQCs<`XtZ=Vw zYs(De&w|W|BC|L7;m^*_*1s^FoGeV9fo45jqSps=Lv|j&ZZw501^ZE%UiZv(YkREa zV()GY6Nm1N$$l#|I0IOk3&HNChDT`;>@q&dI+-`_H#nwm4riqpKUfWKr7j zTAh(c{YvhDsqi@~T~70*8V;`yk3SxH7{5r|NySka`vCqGUWwMUpj7y>E(TbzLM9FiI|WR7)`5T@X1HmbqL^wX#lC{=nrTvr?R zqa}T|%aTanQZRI*kP5Cu=GW}loF_o|mG{Qz27eRH_*;iswq@n&#LCm-LoPhc8o#-G z@6Y3<7Aij6O)szx_^bD2z0x1$nNIELE!qK-fpZye>lV+4TkdD~Q*74QLRhJ{2$EJR z{q`pBkQ0PaScDQ;H90P~|8NQ~Ab}|xl8TyPH43cG<_rTE^QLYy~ho>wZ|%GF`$*lpy_XVL*h?AGz3=U ztoz7O^5zl@-7lx$uL8gJ19FTHBonwNVb+n@|JbGJGh?%T$5p);};%5m+<=WW^%guMcT{<`=z2laK}}B&in$otZ+lmvy`@ z<4ma@Rd;-%0G4V`bWFd(>9!&pERCAF;Hpi0p6Ks!bo^r8y8DCMv&VMa4{ItPh?&|g zN$X}Drn9tmaF=iwTW!>b1aVXLwR}IAje>BWYlZwJ{ODe27XURD;AL?=4pwZ%0BXA} zcOu1iyC+)%qdS@ugM>eBR}Yof&OrQ-TQuThtMYyCqJ8_KEJE-JuOf@Ic$QvWQe*i0Dx}Fh$X$}4d zkRMG82J)l-0fs#h368zDyd%IIgs+~pk(fdP(WXHp3Y~= z`;>G=ceOtqN-3S>F9hgG_OGv+!^(<*ktLDakntyF0nc|vg33sRXoW5gFg~Ys*Y^sb z#em?ZHBnK~nB3glU5VqJ-N1b{x%XuOse7Me!i5RZ1)^`*xVf)ZzJ*yx)CbaApTPP0 z7TVb~pTT!`clS#sZOn(E6aE=5N+%H?92|VE;byj;6TyVr&XE9` z_G?U+fR!fF>t0yU`2ETOC@@;+Q{ZnAKX4}YtisEomL-0!-ASl-^!MmwwXWJU|1J&W z%>aIEa*LQMnUws=3Ju%!f`SSVL6{M$M>?3Da%ZK9uFc|dD2&|>8Ef1e)t0l-cW$^Iu^aBfLszWXO)=QhGSoBri|C+~umEJ^I z!qlzSDGu~ioA!^1dzZs42*gr@lb`bP^A(+)KfPA$e<)qvo*BqP-#^`~bbArF0SkuL zrizs5&Yt%s^Y?)D3Ryxk4Gt#b;g+TX(RGQvRNEDLVQcpTudEgQg${tA(tqfc+z-CM zO2NEMTkPpakwY?Z^zrer%ZiGLQ9OirKiy}F<}V{iKl()SInroz_PQS?Wr%xP(2hI; z3xY5RHF7*Sj13LtEGg2IdBxBb*~ZQzmrbvYNOO6{OkWzh5biT5#${rsNjf zmKya7rd$5ur?V5z1nML1BYu;hTU~#@d%D&co039bCcYI;&uP8*Vbt>zeb}%4%}sLm zU*^S})YMcpE}2X3?|?jjfFzJeHM==pI;SOno6aL?GDJ^K4jY^+ngckBf8G%G*}wt+ z{msaRGuFsrZEfv3&v9ulc*qtLEkcgXc9s8Z$m;q)`OSZ10T}+>5xKnTYW9%eU>YY8 zGt>H13JMBgO~HX#4@?Yn3^sh{{?7*+A# z%oM<=Ee7`hMvdfa6C%-7S=U|V?b1s5a?wt5E5;1D-47MR0d1l%qZUM$cD1iMk64)l zy1MkYMlikzaCQM3M;*<@e45BcjHp6Y*3%9`451Xg7kCB=Es?~CImn2fAKDVxa7d-Y zF8v;%-XxF!1lMt!zNUXw7v%f;M8@jl-9zQs70(lLdfrh;bODSg)K6}L3^ zoLg_of7iufAc7=#|9*%PfpAH*gv+ix$L5u%%7p1yYVLF2HLa7bce%irvdPAB@U7>f zI&y3j{RP(zEs@IH=6HENWF4{F?0y~i94B9*URUBtTB_>a^558I+?QAO$^Xhe2NsG; zS8S%cLK=~FMaDIlSGl3{P$P@N28wtaW1WMqeQMI+R6VJEnErAmP%@=U zi4qZgZ2iEe&fym43R$&=N=!@~517R7`s$Kr`nUcg+~J!K?G2euf_Gf;1m9n6v*X20 za&AjnQysE0oLZ{i8^AW^e(unbe*Z;`C z2HB(PJBL!X4?FEe(_IrVw`9DE>(C)L4Ui+vMX%I2QSU?LfvIYRO_hHi?EcZ5#{bvY zSBFK}b?*)$BBG#@l1j%A0*-V@NlOUQAl==KAUz;Rr$|V5mk5GLN_Te(3^mkm&+Gfu zIp1}Dhd-W+YvS3@?3rinweEG__ihAaxV&*e9aTX_rvs7)lB2-HfGhs7n@(ayXP?s4 zu2n%*)8xfvW06_sVCmsHWRiX4%}kbbZomYoi86BE(JpQ}(+V5aYu73B5pQ%^TO|*j zA&`j-r3g93!Zg7=Tf?7XcI9yh%e}4#h4V%UrcYjFQTz}aN>&GLPVd)o)BJjBW}lV5 z>23=|$)>}?&5?ko_lZI1xvsbWn+Bbox96^IXJQXxR}Ui@BLY%-ed77O_>rBo~S2r2bt(CH1V z9DgS&#jZBAst{d7>Ox!V+lA?jBopQ1ufNUAv(ob!CcOL3S@+sJ7d!W)c7iXU812#L zwfSdR-fc*H6g>hq0-(^e^!)n2CMHFk9D945*Oy6MJ2meI2fYh!ygw~pyd#_!vHMs$ zHP=9%sG#_D`wqu>^CW#v%n7|RAV8@g<*!(;Q`eagov+1p+^^xO}!3c}z%X@bHBXK(#p|cqm^^S>m_LipYSO%zHA@0B4 zUeM4HMCGgd+CB6?ByTdX`q6nOzvLWc#7#iqomhdb#QEh-v>xBg4^A9{D0ffMc^TFp zV-1&-k5oqEu#&fnmV+dI@W?K?^W0&MXvkCe6)al%bq!j0B#5YaP;39-+J{fl=MJYR z&bV~hdaO>dPgtQ#-AjU}QWQLIypm zih;++CvTUK1MHIB2VZasP;`%&OmBefWIfq6)sva`5+IKMqS>0>13LI{vcKU~0=+Cs z$dPa?6ubrin!k^twZ64G#h_rzS2$)_l-{>cs)hgV(GcV3hYk6!XOd2Ue5Jnloq++$ zf^0db`6K=1#{;p1EO(5~D@egGU*fq2ag`-Uwt=-n*ObSjhlGyuQzCc(8)Z^|+xrJv zyovTt#w;ELL4xY4>b$%?pgu4Rb3_6w3KTf}=P*E0segl*CmaC?5LghVuV8{V{g~AM zT=o0|x7vV^4{j&~HiK;NrO?G)qzre=%3_qvnn{oUOx0gss~1!))p$>sjFGFQC0LJO8%Bdz@*3s4?hmmJW={E-RAXc9W{;w`=Mb=~u7IAL6?A$xkcR^l@l94|3Yg+12J-*Tl> zaI#F>5#8^jg?!gI=^A1*7&EjoXEOBdeX+3?ZU1W8q8;PT!z(Oa-)?D$Y?Na+oA@7u zg-ut#&eHC0e8n?xMYdPdU@lXj;CSHh+A~dO>o-Z0~tF`tz3I(B+!--Q0;e@h>qmZkjhUy$Q(Y0T2Y`*p_u%yCS zQyat@*!FS&fZGKUYjLfRukdg%;Ym5J-6he$Vu&D)@1Nwo#H5gP1$^3{=PrB7h&a=F zuS1xd>|qATJn+$;@84_f(w;gg`^ULAIh-Y#7m){5|;}Aws>)ahkKj}x|U;Dr!rx0 z(gmcm%0n57=p;Kr8nQx6?ld=+)Hqu*=c!wVyQ=Uonuus-`5rj=8(SwxZ5bEgb*I94 zix zz$>Kj@svBt&SN$DBrf>m^cf~SX6VENYJd8c{%p~-Jy@w`onMI#Skn=u!96UtrlXQ5 zlZaPRd$Qg^C`jwhE`IP91Fn@Ijelm=-1#K~D;3uCbi2&dXud1d-Rdi{L~7zt1+5V;zIJU|kK%OuZg_S+ZMLR0$YXEo4ASXZ2iF zu8@I=OG8vCMD(uVN9!{09sjItvR6JgmPtI9L#OVy>pB+a&FN19Nlf zO3KQN^z^yo9+$`?QKT}ezXQHqVabDo12J2Ew*wl$75@;_IV3X9$-%(@gT?jq_I6E7 zB-T4^Nmxx))2gYdDJI>VK?R%vDj-MvY>o5rAIuw{rHJRtXooW{bF|FN%;i9o{QUeD zDhzyP6R{Vz94$;tScCnzx;$4_RQxrBURrpwOT-R1b#PgZm$u;cl#k8K%zW?#(H7DX zR-lFpEEl@Ey6`C}6`VGQKLI=<7%2bblenayYXAqdwzf7jGYb(z%^5p6aHIH_#!o3E z`Y+xMs%I5WiYaLQZh5v~8mFtZ{}1U#9UB{4oWP<)r^$5wtKVYc6xCn4HCZz=GkiQe z<@|Od(^_&4TH3(!ii+GmklmR_O5)=vrX)sE{M_Jr<6Y{zB zABsH*Ny#wG_4n0)Ujst>2$08`e&s`7J}hx^jc{+ALB~Qje{!!gAvQJw{Ah@sOC6mY zvKwl4f9fvjZ9JR9{-f7>Kjneut6}@h@;{g{2=RXx?CoY6cC~W+v&ds-`Vx%+q5>K{6V}a#Y~=eOODP%A_uB z6?Z!hwP>J9I;g!PBCfw?YXlD8=2tT3(RRATM7^`=K7mu_cw@O<-fdb1cEZ}in-He# zjCnuT)d!v(w*WKcDZM35-Rrlf9PuQq(z(osbY4_0O$fkB26<*QDB3hr=VvUH!ilwn;(53&qmOD2|o^ zjf2T%Q@&nO-bfC4qc2)s1)FO)Ry;H~vw!NH%vwuhb2>NJNtWQMm+2xY-bOB-P{^2M zBbPr|MzX(uCIUJ?O@%1e~mvxT?hyKN+Z{M0dp8a^J2~PkjKAfe3)LZqF#(-)$ zY$g0WboOlu`XDv9Df=w%O-svJB@cokroDA)6N9L!*OwgaEjg*s%$v=M*5+0&w=+ZDgWtDN%V>UALHib{QeuE- z1Z$3hw@WlYXca9;Og)nSu7JSM5S47hym5*zZ;(>KvKg~!O?jYxwkKH?BLW_6W~uq! zyW3?I!_^*|RaP?eWAd3FzvDLaIae||4Gk$xM(e5wBk#9IawE%J$d>xrz~Cq2WihB-XYRO?1==OB%cFU=Y_yu?dX+OWk2j}LJuE#V)htVd5uevfO%*ZfU5<1P)VD=J^F|7H zS199F1WB+_?app%1za)o-=O=l@OKsOTvOi>WAa(stYpBhg$_rOZcWY_%iGAipu)(r z#cJ^lJx`%)LBR50=A2hOb|{o@;$6%rCgv)rU}+2o)u8*qX$XV*-!zNIaV!19RfWvW zCBTYHbG1oU#pu8TwU&c6%gWx-qlutq?L(G2*ZLptGU^9WpLDDIi-G>fbLM$6Rj{~$?ydE*>qV@;W8D;jP%=utoNLl3|F&II$rt?J{%JBE%pAT;n=9(SU8;H z!gcZGHXUuM46h`)yUYC@FHqtrAHsT9_IU2OJbYa^gXyfsBk)=d-O9$n+%vzCCKRPf zOZr`vblx(l;78%d1(4|aWDm8X^q9#>m5rC5fAZ!QB}y>U6=#H*5rG!fGmIVFhb4#Q zEK^nZ0;-x$=Gh4QWQ-5k3`|_1-^QV59j`Rx_8g+7IsRlp|ky>4o$ai7eN%?0I zVUx|U3!9Y!b> zO;+VM;aJZd0*W@^L2MjVvr<$gsp#16h# zkoXQ55V(N$N(Wh|1%6f&x_qEn|KhDL+}~)S0;tbGE-h&4{^Wsh(4x~p(f`}A3Kbdu zSXuoQRR5R5U$1`ksMfEN1Yo|3=H^V<0Q8lY$5~lhqgE9DqMVB}F+LvE)Fi;e%^g)& zXJ=Rk9BGtPRSB`a5ln4y~oL#i#0<{M7YWA@C@#a>{sruPD#^@;#90-ND}bwKK)@ zF)@*e;=>1z_WvT&GeG|%)3Xx!r%bP$lSEhgWiZO?3f=RIT1jg;x*j%)&@ftLIni7Z zghMec9M6_J1RT5=si^z`t=o`Zv-;MF2lpFyx86=6LPtU_P>zA8b2o}=kjmE9a0YSt zBm~CM4&Qt8QL%^q=4n2&@891|q@p0>2FiR9kXQ@@^g9#|&#|7VfARr>Aa?J{Cx)h` zYKxUFn~$+*_JJldkw2|UVoXfXc;sZ|hQxoET>p#q{hPz@_OXTrsF?=@xdHmtI z^2zRQCZ78B)g>b}HCUGcERfIc#3_LtKmFleO_V-&KauIUHvxE^oBbv^s^S*SaxdRxT3#Zq|eZb?zJZwqRo7YICw(@a7v-<&V)FG(gfvQnm(9SE_q7PlL4Bg>q3G~73`kJ)TlTn^pG^VL1Tjp8<^m!h}vDAC& z0L>*x%6`;WYOKcVvJURfkb>kc#2dMh0=+xfaxIp;_P}vhD{tVCNXIo+@O)c$xK!Vv zVuGU*D`?}@?-!f=5dm!m8rrS&ELO};>jUY>+Y{SSnfyLiwRAp2@)vdv79#5EkKP7t zzP)wfI$3Epm;j`msoXultHVO|9X8?3S0y@V!+Ar(^*+}WR*4-NqwivTtOiZHHj1%xWpy@#MU!x_+z8L~>>zTb?ha-5%I({xitC)4JfUft%wL>4 zon6lkj1tW`fcwFnJ9nZ9{3>S~4B?b>%zfobwDkEJM`qvCa)$a+eT;D{&%WSo$RYIuS0;_`D!|k;ynU4i> zzf<(PPd^Av5&O2KP@&uKV)5)FEY z9hi1_=s=5K?SAyst#1p~d=Q#U70oU!uR}j%8QzLLU}BQ4#8g#51>Jp8X|eV>_&lrd zGp|)rBvpGD;yclh*?6hh^5Q|c{hZ6sIzgmqnI~ra-sVU*KKZ5Br+!=Pbd0>Y!Lf(W zEb60zf-qCL?fij1hGc7NYo+-JQ%v=(r9hbL7K`ZV+1ZDJ0*jDN(4f3j#9G_%(uHr! zE1lN*+iL2}%7x9mqY#i7thNe^r8tp6bda)ajHu0Q%w0EUd-(JwDYQEW;o=e`hr_Q_ z>J$oOF8eZ_d*Q|d8G7c^wfA}x_L~PC`lH8WDx^ehxsS(muPqQ24<5X0uY=j_GWKm8 z_IDCi7+IJOks%AeOjcS1<%LcW%E$0{9DB%Jt&<&?O^r%Y)Y!~L9`A%P)BH?HvCI>z zb?X0p4!z~w_lb(I{%P&eWSN1FRKjBE;BuGt$2r?%&meD%n56nZI(aSD$f>F=>bW9S z_DvW3%ka^K8M$$F6!!u2q{NQ4k_EFvQuWL0vS zmO`m$jRd@oCom5thZM%5#$G?*Kqj`5?J9Xpr8u_wKkopxF4+Y6k)JFLoN3HH}l?~RdR3(>J=Qg|^Mx=Ev{grM7NZ602s)O;YvJQEv zbaDarxWx;D^`6Afm0ssc2Pf&;4C+5LCb{ATnKNNKf;1N9;`;L3iT>oP?=VlePTo=S zM2pEKRenA@yuMo@mpB-KL&9}$1X$3h?sF=h%`&_ zXJ=6i{VAL#Vow?r$+7rUDAu3_0;(lCKsccAHiqB3bE3RMP_tmvVR?&B z{HGVflmifuG>9~+B&}Yge-{~yL`#BMneRu%6pc4LmtT$BY?}xsn`FddD|v!X*`h?$ zu_%T~P|Q&KZC={9O=@?S!iY&>tXS0Oj)+LVH@#evp@ynnEYryP?u@70PYPdLREVij@i&~jJ675w_;ylftcoiR z3GS(bg;z&-Z}ja~gcq08*&NFQ{Sl-s4E|b1gKHh(iOg#ep-2hk>ds`@bivdohipd` z`W`2{MTq)FTI9mg5_M$NT^rfU-shxd=f_6TiCs-U_Ln~2xx5Mqu`ra4iqSiDQ{Q>| zSPz~VNFlvfcqj0^HTwkJk?2S9HT}3_bqeh8P?7?!U=G?4It~tz{x}b2r(W>}VCQ<2 z_u7ghXZ6Z{n+^)KG%WiqYsYK0*m0MFKcL!jLRLg1%=D{o z1@!6TovEQ9O7Gz08z8w@dVq%~%F4>h@!b%K@U~6*y4`2L+T;B(&D$3^Fv)?QIUS21 zCd9X`lFyZbjLmfi2nZRs@#tKs__2F#1nIwfCtx<$EM^yNX#(siYM(;B>hrRKiOK;2 zHf;q5#JX|xZ52m)G>B{gP zy@CUvUUIZ1=cW|Cc`9|K&c3}HjP{n#U%{2d2?a`Lmbm^fkZh4HV$w~I(V+uvI$r#B!7G_SAvH+sJ< zd*sAF_`ARo~zK0WtB*gbge6VG$r%$J6BAa&Kz@(HL`p#+o+pccj#)@Z_hdEz3-3o;n<#}toX%25M4tIb z{y|C%;VEtcCC&^Fau_vQX^J2_?$D?CZJ2_BLa#3UUPi0WR~UExP=KJX6GC4*7b{2| z$MwN+n!x#HTFbtK47g)(t?#m9Z`wP+>!WcHXoa6~w`?kI2dTq~1%{Or9<-+fkm z_u}H4orCWLGsZePT$y5HAR~?5mqNoOvuJPO`UR(ZGCxnRQR$b;=*e+A{8) zRF?jUeA~%mz9|Gz$ceNRr~LfaIf5VJ;b99rS9!GlF76pXxwvn7sjve-J+W9OeI*RC z9JJvoDmnE}0nF$&HbPSNjNk zRx9p$9BA*^VW_*0~ij!3_NTFE%inHE$`uqM0P(%da^ zd|X*cianM0p33Z;K{W^Z&ic}H-Q9yDD`6d-*zc>}7yD5nng&7ZYbSIO#0wJi3KYX$ zvni9MVrP~`=%Qoo^_QCk>RbjL=Z>pAzg|3X5FIOky&SnFP;Xh+Px8Yi;@D^pL4WI6 zTr9`Hz#x4x`z_G#=b<=aRFho%<@BOf4Xey-cYi-{<)hbVs@KDQEFbNfWNuCul_t&DU1Mg|OO_<3)I?I)n z=?@ns<}OZ)GSV6W`v@nbIshFLu;aLv!6tLw21?l1ES|0jiGJ15v1D!MnkCHz3iQwYhe)8m(w8FOLMxvcXUt61IK-+Y^Q>ydc ztT525Z?f5o@$9^R^hgz972)BC?3Zg*;j551D=d09 zSj@<__rC9!T7ha)l(kHQ&N`8RY{ge#ea&KR*L3<8U8Bl8bXNe!Wc15Ebfjc2r*iXs z@Tb^-3J3C;T1b#hN=h1syS1R&(PowD!SZX+zTt`yrCw#IC_Au!(E%zgamQ5#&Ve*R z^AUG>cVV#4Kz6fNCv)}l$$1x*5}k@31LK^@#O!VpY;xiTI_tZngGG#Enjem^gUtGN z>j$S6{k$%r+!T_g6Xju*AoY`BeU?4lZE^d1XUTA&>-6+2%w1lPC|!AHL%pIWJ2oDV zijWN_({727(85i~EYZ&y@zh$2w2WYPzqWQbCIDZwlx26KLfrj%${T|_Mpc|LANxmn z*&XFl`Oc;L{PL$HA~cAbW|>~+|C(tyBhYEN-KCKLHpY>b)uJ|_XmZDR8CFaq0l)j1 zoG)&uP+in8eExVxtAW+QY$YO`Oupp`srzV6g>kEr@KWquro(sHM7~?w=^=RW$|}Qe zczpzw^D=Z*x9M8v?aJ#Yd2hh?LD+Vq>-F#(g6`%_1!rgLqR8$$RDk^7?!Kh z*L(qB_*^Uq!-Uz5S099d{tW#6_Ywa*Y>F$(j0VA{qFR)hz6s&0hPTPKv0?b4FK)VH z%Hx?16!+Fp-FFAqiN<^iVd0f=U@Zr0IfP-A3k?Das{j4`ksNZ&t%k - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/xdocs/images/svg/diagrams-cli2.js b/xdocs/images/svg/diagrams-cli2.js deleted file mode 100644 index 9f1a9a277..000000000 --- a/xdocs/images/svg/diagrams-cli2.js +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -var Option = new Interface("Option"); -Option.addMethod("process(...)"); -Option.addMethod("canProcess(...)"); -Option.addMethod("getTriggers()"); -Option.addMethod("getPrefixes()"); -Option.addMethod("validate(...)"); -Option.addMethod("helpLines(...)"); -Option.addMethod("appendUsage(...)"); -Option.addMethod("getPreferredName()"); -Option.addMethod("getDescription()"); -Option.addMethod("getId()"); -Option.addMethod("findOption(...)"); - -var Group = new Interface("Group"); -Group.addMethod("appendUsage(...)"); -Group.addNote("-a | -b | -c | -d | -e"); - -var Parent = new Interface("Parent"); -Parent.addMethod("processParent(...)"); -Parent.addNote("-f "); - -var Argument = new Interface("Argument"); -Argument.addMethod("getInitialSeparator()"); -Argument.addMethod("processValues(...)"); -Argument.addMethod("validate(...)"); -Argument.addNote(" [ ...]"); - -var CommandLine = new Interface("CommandLine"); -CommandLine.addMethod("hasOption(...)"); -CommandLine.addMethod("getOption(...)"); -CommandLine.addMethod("getValue(...)"); -CommandLine.addMethod("getValues(...)"); -CommandLine.addMethod("getSwitch(...)"); -CommandLine.addMethod("getProperty(...)"); -CommandLine.addMethod("getProperties()"); -CommandLine.addMethod("getOptionCount(...)"); -CommandLine.addMethod("getOptions()"); -CommandLine.addMethod("getOptionTriggers()"); - -var WriteableCommandLine = new Interface("WriteableCommandLine"); -WriteableCommandLine.addMethod("addOption(...)"); -WriteableCommandLine.addMethod("addValue(...)"); -WriteableCommandLine.addMethod("addSwitch(...)"); -WriteableCommandLine.addMethod("addProperty(...)"); -WriteableCommandLine.addMethod("looksLikeOption(...)"); - - - - - -var PropertyOption = new Class("PropertyOption"); -PropertyOption.addAttribute("optionString"); -PropertyOption.addAttribute("description"); -PropertyOption.addAttribute("prefixes"); -PropertyOption.addNote("-Dproperty=value"); - -var DefaultOption = new Class("DefaultOption"); -DefaultOption.addAttribute("optionString"); -DefaultOption.addAttribute("description"); -DefaultOption.addAttribute("prefixes"); -DefaultOption.addNote("-f (--file, --filelist)"); - -var Command = new Class("Command"); -Command.addAttribute("preferredName"); -Command.addAttribute("aliases"); -Command.addAttribute("required"); -Command.addAttribute("triggers"); -Command.addNote("update (up, upd)"); - -var Switch = new Class("Switch"); -Switch.addAttribute("enabledPrefix"); -Switch.addAttribute("disabledPrefix"); -Switch.addAttribute("preferredName"); -Switch.addAttribute("aliases"); -Switch.addAttribute("required"); -Switch.addAttribute("triggers"); -Switch.addAttribute("prefixes"); -Switch.addNote("+d|-d (+display|-display)"); - -var SourceDestArgument = new Class("SourceDestArgument"); -SourceDestArgument.addAttribute("preferredName"); -SourceDestArgument.addAttribute("aliases"); -SourceDestArgument.addAttribute("required"); -SourceDestArgument.addAttribute("triggers"); -SourceDestArgument.addNote(" ... "); - - - - -var Parser = new Class("Parser"); -Parser.addMethod("parse(...)"); -Parser.addMethod("parseAndHelp(...)"); -Parser.addMethod("setGroup(...)"); -Parser.addMethod("setHelpFormatter(...)"); -Parser.addMethod("setHelpOption(...)"); -Parser.addMethod("setHelpTrigger(...)"); - -var DefaultingCommandLine = new Class("DefaultingCommandLine"); -DefaultingCommandLine.addMethod("appendCommandLine(...)"); -DefaultingCommandLine.addMethod("insertCommandLine(...)"); -DefaultingCommandLine.addMethod("commandLines()"); - -var PropertiesCommandLine = new Class("PropertiesCommandLine"); -PropertiesCommandLine.addAttribute("properties"); -PropertiesCommandLine.addNote("java.util.Properties"); - -var PreferencesCommandLine = new Class("PreferencesCommandLine"); -PreferencesCommandLine.addAttribute("preferences"); -PreferencesCommandLine.addNote("java.util.prefs.Preferences"); - - - - - -var ArgumentBuilder = new Class("ArgumentBuilder"); -ArgumentBuilder.addMethod("withId(...)"); -ArgumentBuilder.addMethod("withName(...)"); -ArgumentBuilder.addMethod("withDescription(...)"); -ArgumentBuilder.addMethod("withConsumeRemaining(...)"); -ArgumentBuilder.addMethod("withValidator(...)"); -ArgumentBuilder.addMethod("withMinimum(...)"); -ArgumentBuilder.addMethod("withMaximum(...)"); -ArgumentBuilder.addMethod("withDefault(...)"); -ArgumentBuilder.addMethod("withDefaults(...)"); -ArgumentBuilder.addMethod("withInitialSeparator(...)"); -ArgumentBuilder.addMethod("withSubsequentSeparator(...)"); -ArgumentBuilder.addMethod("create()"); -ArgumentBuilder.addMethod("reset()"); - -var CommandBuilder = new Class("CommandBuilder"); -CommandBuilder.addMethod("withId(...)"); -CommandBuilder.addMethod("withName(...)"); -CommandBuilder.addMethod("withDescription(...)"); -CommandBuilder.addMethod("withArgument(...)"); -CommandBuilder.addMethod("withChildren(...)"); -CommandBuilder.addMethod("withRequired(...)"); -CommandBuilder.addMethod("create()"); -CommandBuilder.addMethod("reset()"); - -var DefaultOptionBuilder = new Class("DefaultOptionBuilder"); -DefaultOptionBuilder.addMethod("withId(...)"); -DefaultOptionBuilder.addMethod("withShortName(...)"); -DefaultOptionBuilder.addMethod("withLongName(...)"); -DefaultOptionBuilder.addMethod("withDescription(...)"); -DefaultOptionBuilder.addMethod("withArgument(...)"); -DefaultOptionBuilder.addMethod("withChildren(...)"); -DefaultOptionBuilder.addMethod("withRequired(...)"); -DefaultOptionBuilder.addMethod("create()"); -DefaultOptionBuilder.addMethod("reset()"); -DefaultOptionBuilder.addAttribute("shortPrefix"); -DefaultOptionBuilder.addAttribute("longPrefix"); -DefaultOptionBuilder.addAttribute("burstEnabled"); - -var DefaultOptionBuilder = new Class("DefaultOptionBuilder"); -DefaultOptionBuilder.addMethod("withId(...)"); -DefaultOptionBuilder.addMethod("withShortName(...)"); -DefaultOptionBuilder.addMethod("withLongName(...)"); -DefaultOptionBuilder.addMethod("withDescription(...)"); -DefaultOptionBuilder.addMethod("withArgument(...)"); -DefaultOptionBuilder.addMethod("withChildren(...)"); -DefaultOptionBuilder.addMethod("withRequired(...)"); -DefaultOptionBuilder.addMethod("create()"); -DefaultOptionBuilder.addMethod("reset()"); - -var GroupBuilder = new Class("GroupBuilder"); -GroupBuilder.addMethod("withName(...)"); -GroupBuilder.addMethod("withDescription(...)"); -GroupBuilder.addMethod("withOption(...)"); -GroupBuilder.addMethod("withMinimum(...)"); -GroupBuilder.addMethod("withMaximum(...)"); -GroupBuilder.addMethod("create()"); -GroupBuilder.addMethod("reset()"); - -var PatternBuilder = new Class("PatternBuilder"); -PatternBuilder.addMethod("withPattern(...)"); -PatternBuilder.addMethod("create()"); -PatternBuilder.addMethod("reset()"); -PatternBuilder.addAttribute("groupBuilder"); -PatternBuilder.addAttribute("optionBuilder"); -PatternBuilder.addAttribute("argumentBuilder"); - -var SwitchBuilder = new Class("SwitchBuilder"); -SwitchBuilder.addMethod("withId(...)"); -SwitchBuilder.addMethod("withName(...)"); -SwitchBuilder.addMethod("withDescription(...)"); -SwitchBuilder.addMethod("withArgument(...)"); -SwitchBuilder.addMethod("withChildren(...)"); -SwitchBuilder.addMethod("withRequired(...)"); -SwitchBuilder.addMethod("create()"); -SwitchBuilder.addMethod("reset()"); -SwitchBuilder.addAttribute("enabledPrefix"); -SwitchBuilder.addAttribute("disabledPrefix"); - - - -var Validator = new Class("Validator"); -Validator.addMethod("validate(...)"); - -var ClassValidator = new Class("ClassValidator"); -ClassValidator.addAttribute("classLoader"); -ClassValidator.addAttribute("instance"); -ClassValidator.addAttribute("loadable"); - -var DateValidator = new Class("DateValidator"); -DateValidator.addAttribute("formats"); -DateValidator.addAttribute("minimum"); -DateValidator.addAttribute("maximum"); - -var EnumValidator = new Class("EnumValidator"); -EnumValidator.addAttribute("validValues"); - -var FileValidator = new Class("FileValidator"); -FileValidator.addAttribute("directory"); -FileValidator.addAttribute("existing"); -FileValidator.addAttribute("file"); -FileValidator.addAttribute("hidden"); -FileValidator.addAttribute("readable"); -FileValidator.addAttribute("writable"); - -var FileValidator = new Class("FileValidator"); -FileValidator.addAttribute("format"); -FileValidator.addAttribute("minimum"); -FileValidator.addAttribute("maximum"); - -var UrlValidator = new Class("UrlValidator"); -UrlValidator.addAttribute("format"); -UrlValidator.addAttribute("minimum"); -UrlValidator.addAttribute("maximum"); - - - - -var Comparators = new Class("Comparators"); -Comparators.addMethod("chain(...)"); -Comparators.addMethod("commandFirst(...)"); -Comparators.addMethod("commandLast(...)"); -Comparators.addMethod("defaultOptionFirst(...)"); -Comparators.addMethod("defaultOptionLast(...)"); -Comparators.addMethod("groupFirst(...)"); -Comparators.addMethod("groupLast(...)"); -Comparators.addMethod("namedFirst(...)"); -Comparators.addMethod("namedLast(...)"); -Comparators.addMethod("preferredNameFirst(...)"); -Comparators.addMethod("preferredNameLast(...)"); -Comparators.addMethod("requiredFirst(...)"); -Comparators.addMethod("requiredLast(...)"); -Comparators.addMethod("switchFirst(...)"); -Comparators.addMethod("switchLast(...)"); - -var HelpFormatter = new Class("HelpFormatter"); -HelpFormatter.addMethod("print()"); -HelpFormatter.addMethod("printDivider()"); -HelpFormatter.addMethod("printException()"); -HelpFormatter.addMethod("printFooter()"); -HelpFormatter.addMethod("printGutterLeft()"); -HelpFormatter.addMethod("printGutterRight()"); -HelpFormatter.addMethod("printHeader()"); -HelpFormatter.addMethod("printHelp()"); -HelpFormatter.addMethod("printUsage()"); -HelpFormatter.addAttribute("comparator"); -HelpFormatter.addAttribute("displaySettings"); -HelpFormatter.addAttribute("divider"); -HelpFormatter.addAttribute("exception"); -HelpFormatter.addAttribute("footer"); -HelpFormatter.addAttribute("fullUsageSettings"); -HelpFormatter.addAttribute("group"); -HelpFormatter.addAttribute("gutterCenter"); -HelpFormatter.addAttribute("gutterLeft"); -HelpFormatter.addAttribute("gutterRight"); -HelpFormatter.addAttribute("header"); -HelpFormatter.addAttribute("lineUsageSettings"); -HelpFormatter.addAttribute("pageWidth"); -HelpFormatter.addAttribute("printWriter"); -HelpFormatter.addAttribute("shellCommand"); diff --git a/xdocs/images/svg/diagrams.css b/xdocs/images/svg/diagrams.css deleted file mode 100644 index d8691da08..000000000 --- a/xdocs/images/svg/diagrams.css +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -.option .outline, .option polygon.note { - fill:rgb(191,255,255); -} -.group rect.outline, .group polygon.note { - fill:rgb(255,191,191); -} - -.parent rect.outline, .parent polygon.note { - fill:rgb(191,255,191); -} -.argument rect.outline, .argument polygon.note { - fill:rgb(191,191,255); -} -.property rect.outline, .property polygon.note { - fill:rgb(255,191,255); -} - -.package rect { - fill:rgb(255,255,191); -} - -.package rect.inner { - fill: rgb(255,255,255); - stroke: none; -} - -text.title { - text-anchor: middle; -} - -.type text { - fill: rgb(0,0,0); -} -rect, line, polygon, polyline { - stroke:rgb(0,0,0); - stroke-width:2; - stroke-linejoin: bevel; - stroke-linecap: round; -} - -.implements, .extends { - fill: none; - marker-end: url(util.svg#HollowArrow); -} - -.implements, .note.connect { - stroke-dasharray: 5; -} diff --git a/xdocs/images/svg/diagrams.js b/xdocs/images/svg/diagrams.js deleted file mode 100644 index 4e8a5a72e..000000000 --- a/xdocs/images/svg/diagrams.js +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -var textHeight = 10; -var padding = 10; -var namespace = "http://www.w3.org/2000/svg"; - -var displayAttributes = true; -var displayMethods = true; -var displayNotes = true; - -function Type(name){ - this.width = 160; - this.style = "type"; - - this.insert = function(evt){ - y = 0; - y = this.insertOutline(evt,y); - y = this.insertName(evt,y); - if(displayAttributes==true){ - y = this.insertAttributes(evt,y); - } - if(displayMethods==true){ - y = this.insertMethods(evt,y); - } - if(displayNotes==true){ - y = this.insertNotes(evt,y); - } - } - - this.height = function(){ - height = 0; - height += this.heightName(); - if(displayAttributes==true){ - height += this.heightAttributes(); - } - if(displayMethods==true){ - height += this.heightMethods(); - } - return height; - } - - - - - - - this.insertOutline = function(evt,y){ - - style = evt.target.getAttributeNS(null, "class"); - evt.target.setAttributeNS(null,"class",style+" "+this.style); - - e = document.createElementNS(namespace, "rect"); - e.setAttributeNS(null, "x", 0); - e.setAttributeNS(null, "y", 0); - e.setAttributeNS(null, "width", this.width); - e.setAttributeNS(null, "height", this.height()); - e.setAttributeNS(null, "class", "outline"); - evt.target.appendChild(e); - - return y; - } - - - - - - - - this.name = name; - - this.heightName = function(){ - return padding * 2 + textHeight; - } - - this.insertName = function(evt,y){ - - y += padding; - y += textHeight; - - e = document.createElementNS(namespace, "text"); - e.setAttributeNS(null, "x", this.width/2); - e.setAttributeNS(null, "y", y); - e.setAttributeNS(null, "class", "title"); - e.appendChild(document.createTextNode(this.name)); - evt.target.appendChild(e); - - y += padding; - - return y; - } - - - - - - - - this.attributeList = new Array(); - this.attributeCount = 0; - - this.addAttribute = function(text){ - this.attributeList[this.attributeCount++]=text; - } - - this.heightAttributes = function(){ - if(this.attributeCount>0){ - return padding * 2 + this.attributeCount*textHeight; - } - else{ - return padding; - } - } - - this.insertAttributes = function(evt,y){ - - e = document.createElementNS(namespace, "line"); - e.setAttributeNS(null, "x1", 0); - e.setAttributeNS(null, "y1", y); - e.setAttributeNS(null, "x2", this.width); - e.setAttributeNS(null, "y2", y); - e.setAttributeNS(null, "class", "divider"); - evt.target.appendChild(e); - - y += padding; - - for(i=0;i0){ - y += padding; - } - - return y; - } - - - - - - this.methodList = new Array(); - this.methodCount = 0; - - this.addMethod = function(text){ - this.methodList[this.methodCount++]=text; - } - - this.heightMethods = function(){ - if(this.methodCount>0){ - return padding * 2 + this.methodCount*textHeight; - } - else{ - return padding; - } - } - - this.insertMethods = function(evt,y){ - - e = document.createElementNS(namespace, "line"); - e.setAttributeNS(null, "x1", 0); - e.setAttributeNS(null, "y1", y); - e.setAttributeNS(null, "x2", this.width); - e.setAttributeNS(null, "y2", y); - e.setAttributeNS(null, "class", "divider"); - evt.target.appendChild(e); - - y += padding; - - for(i=0;i0){ - y += padding; - } - - return y; - } - - - - - - this.noteList = new Array(); - this.noteCount = 0; - - this.addNote = function(text){ - this.noteList[this.noteCount++]=text; - } - - this.insertNotes = function(evt,y){ - if(this.noteCount>0){ - joinTop = y; - - y += padding; - - e = document.createElementNS(namespace, "line"); - e.setAttributeNS(null, "x1", this.width/2-padding*2); - e.setAttributeNS(null, "y1", y); - e.setAttributeNS(null, "x2", this.width/2+padding*2); - e.setAttributeNS(null, "y2", joinTop); - e.setAttributeNS(null, "class", "note connect"); - evt.target.appendChild(e); - - - - height = this.heightNotes(); - - e = document.createElementNS(namespace, "polygon"); - e.setAttributeNS(null, "points", "0,"+(y+padding)+" 0,"+(y+height)+" "+this.width+","+(y+height)+" "+this.width+","+y+" "+padding+","+y); - e.setAttributeNS(null, "class", "note"); - evt.target.appendChild(e); - - e = document.createElementNS(namespace, "polygon"); - e.setAttributeNS(null, "points", ""+padding+","+y+" 0,"+(y+padding)+" "+padding+","+(y+padding)); - e.setAttributeNS(null, "class", "note corner"); - evt.target.appendChild(e); - - y += padding; - - - for(i=0;i0){ - return padding*2 + this.noteCount*textHeight; - } - } -} - -function Interface(name){ - this.superclass = Type; - this.superclass(name); - delete this.superclass; - this.rounded = true; - - this.insertOutline = function(evt,y){ - - style = evt.target.getAttributeNS(null, "class"); - evt.target.setAttributeNS(null,"class",style+" "+this.style); - - e = document.createElementNS(namespace, "rect"); - e.setAttributeNS(null, "x", 0); - e.setAttributeNS(null, "y", 0); - e.setAttributeNS(null, "width", this.width); - e.setAttributeNS(null, "height", this.height()); - e.setAttributeNS(null, "rx", padding*1.5); - e.setAttributeNS(null, "ry", padding*1.5); - e.setAttributeNS(null, "class", "outline"); - evt.target.appendChild(e); - - return y; - } - - this.heightAttributes = function(){ - return 0; - } - - this.insertAttributes = function(evt,y){ - return y; - } - -} -Interface.prototype = new Type; - -function Class(name){ - this.superclass = Type; - this.superclass(name); - delete this.superclass; - this.rounded = false; -} -Class.prototype = new Type; - - - - -function PackageSymbol(name,width,height){ - this.name = name; - this.nameWidth = 150; - this.width = width; - this.height = height; - - this.insert = function(evt){ - - style = evt.target.getAttributeNS(null, "class"); - evt.target.setAttributeNS(null,"class",style+" package"); - - first = evt.target.getFirstChild(); - - e = document.createElementNS(namespace, "rect"); - e.setAttributeNS(null, "x", 0); - e.setAttributeNS(null, "y", 0); - e.setAttributeNS(null, "width", this.nameWidth); - e.setAttributeNS(null, "height", textHeight+padding); - e.setAttributeNS(null, "class", "outline"); - e.appendChild(document.createTextNode(this.name)); - evt.target.insertBefore(e,first); - - e = document.createElementNS(namespace, "text"); - e.setAttributeNS(null, "x", this.nameWidth/2); - e.setAttributeNS(null, "y", textHeight+padding/2); - e.setAttributeNS(null, "class", "title"); - e.appendChild(document.createTextNode(this.name)); - evt.target.insertBefore(e,first); - - e = document.createElementNS(namespace, "rect"); - e.setAttributeNS(null, "x", 0); - e.setAttributeNS(null, "y", textHeight+padding); - e.setAttributeNS(null, "width", this.width); - e.setAttributeNS(null, "height", this.height-textHeight-padding); - e.setAttributeNS(null, "class", "outline"); - e.appendChild(document.createTextNode(this.name)); - evt.target.insertBefore(e,first); - - e = document.createElementNS(namespace, "rect"); - e.setAttributeNS(null, "x", padding); - e.setAttributeNS(null, "y", textHeight+padding*2); - e.setAttributeNS(null, "width", this.width-padding*2); - e.setAttributeNS(null, "height", this.height-textHeight-padding*3); - e.setAttributeNS(null, "class", "inner"); - e.appendChild(document.createTextNode(this.name)); - evt.target.insertBefore(e,first); - - - } -} - diff --git a/xdocs/images/svg/options.svg b/xdocs/images/svg/options.svg deleted file mode 100644 index cdb5160f9..000000000 --- a/xdocs/images/svg/options.svg +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/xdocs/images/svg/util.svg b/xdocs/images/svg/util.svg deleted file mode 100644 index b86d760c4..000000000 --- a/xdocs/images/svg/util.svg +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/xdocs/style/project.css b/xdocs/style/project.css deleted file mode 100644 index c1d541c82..000000000 --- a/xdocs/style/project.css +++ /dev/null @@ -1 +0,0 @@ -@import url("http://commons.apache.org/style/commons-maven.css"); From 114867a5ec5d436b50fbaf02261a95cfd0f71745 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Wed, 21 Apr 2010 09:02:56 +0000 Subject: [PATCH 0162/1663] Upgrade to commons-parent version 15 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@936207 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d849234ab..71a4f8dd3 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ org.apache.commons commons-parent - 14 + 15 4.0.0 commons-cli From 96c3d7ddba36c2292d8127aa4a56edb4f501daf3 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Wed, 21 Apr 2010 09:29:42 +0000 Subject: [PATCH 0163/1663] Generate custom Mailing List pages for components (using "mvn commons:mail-page") See http://commons.apache.org/commons-build-plugin/mail-page.html git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@936225 13f79535-47bb-0310-9956-ffa450edef68 --- src/site/xdoc/mail-lists.xml | 202 +++++++++++++++++++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 src/site/xdoc/mail-lists.xml diff --git a/src/site/xdoc/mail-lists.xml b/src/site/xdoc/mail-lists.xml new file mode 100644 index 000000000..40ed1d13e --- /dev/null +++ b/src/site/xdoc/mail-lists.xml @@ -0,0 +1,202 @@ + + + + + + Commons CLI Mailing Lists + Commons Documentation Team + + + +
      +

      + Commons CLI shares mailing lists with all the other + Commons Components. + To make it easier for people to only read messages related to components they are interested in, + the convention in Commons is to prefix the subject line of messages with the component's name, + for example: +

        +
      • [cli] Problem with the ...
      • +
      +

      +

      + Questions related to the usage of Commons CLI should be posted to the + User List. +
      + The Developer List + is for questions and discussion related to the development of Commons CLI. +
      + Please do not cross-post; developers are also subscribed to the user list. +

      +

      + Note: please don't send patches or attachments to any of the mailing lists. + Patches are best handled via the Issue Tracking system. + Otherwise, please upload the file to a public server and include the URL in the mail. +

      +
      + +
      +

      + Please prefix the subject line of any messages for Commons CLI + with [cli] - thanks! +
      +
      +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      NameSubscribeUnsubscribePostArchiveOther Archives
      + Commons User List +

      + Questions on using Commons CLI. +

      +
      SubscribeUnsubscribePostmail-archives.apache.orgmarkmail.org
      + www.mail-archive.com
      + news.gmane.org +
      + Commons Developer List +

      + Discussion of development of Commons CLI. +

      +
      SubscribeUnsubscribePostmail-archives.apache.orgmarkmail.org
      + www.mail-archive.com
      + news.gmane.org +
      + Commons Issues List +

      + Only for e-mails automatically generated by the issue tracking system. +

      +
      SubscribeUnsubscriberead onlymail-archives.apache.orgmarkmail.org
      + www.mail-archive.com +
      + Commons Commits List +

      + Only for e-mails automatically generated by the source control sytem. +

      +
      SubscribeUnsubscriberead onlymail-archives.apache.orgmarkmail.org
      + www.mail-archive.com +
      + +
      +
      +

      + Other mailing lists which you may find useful include: +

      + + + + + + + + + + + + + + + + + + +
      NameSubscribeUnsubscribePostArchiveOther Archives
      + Apache Announce List +

      + General announcements of Apache project releases. +

      +
      SubscribeUnsubscriberead onlymail-archives.apache.orgmarkmail.org
      + old.nabble.com
      + www.mail-archive.com
      + news.gmane.org +
      + +
      + +
      From e7c2198454153e0d74535e21cafbf1583a92de55 Mon Sep 17 00:00:00 2001 From: "Gary D. Gregory" Date: Wed, 2 Jun 2010 15:23:46 +0000 Subject: [PATCH 0164/1663] [CLI-200] https://issues.apache.org/jira/browse/CLI-200. particular spelled wrong in Javadoc. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@950593 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli/CommandLine.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/java/org/apache/commons/cli/CommandLine.java b/src/java/org/apache/commons/cli/CommandLine.java index 891797725..3a5fc306e 100644 --- a/src/java/org/apache/commons/cli/CommandLine.java +++ b/src/java/org/apache/commons/cli/CommandLine.java @@ -102,7 +102,7 @@ public Object getOptionObject(String opt) * Return a version of this Option converted to a particular type. * * @param opt the name of the option - * @return the value parsed into a particluar object + * @return the value parsed into a particular object * @throws ParseException if there are problems turning the option value into the desired type * @see PatternOptionBuilder * @since 1.2 From bc5f93f062d83ba1407c707725bfb5d55dc0a86a Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Tue, 15 Jun 2010 12:07:20 +0000 Subject: [PATCH 0165/1663] Improved the javadoc explaining the stopAtNonOption parameter git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@954846 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/CommandLineParser.java | 11 ++++++++--- src/java/org/apache/commons/cli/DefaultParser.java | 10 ++++++++-- src/java/org/apache/commons/cli/Parser.java | 13 ++++++++----- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/java/org/apache/commons/cli/CommandLineParser.java b/src/java/org/apache/commons/cli/CommandLineParser.java index 302439965..073136a93 100644 --- a/src/java/org/apache/commons/cli/CommandLineParser.java +++ b/src/java/org/apache/commons/cli/CommandLineParser.java @@ -63,8 +63,10 @@ CommandLine parse(Options options, String[] arguments, Properties properties) * * @param options the specified Options * @param arguments the command line arguments - * @param stopAtNonOption specifies whether to continue parsing the - * arguments if a non option is encountered. + * @param stopAtNonOption if true an unrecognized argument stops + * the parsing and the remaining arguments are added to the + * {@link CommandLine}s args list. If false an unrecognized + * argument triggers a ParseException. * * @return the list of atomic option and value tokens * @throws ParseException if there are any problems encountered @@ -79,7 +81,10 @@ CommandLine parse(Options options, String[] arguments, Properties properties) * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs - * @param stopAtNonOption specifies whether to continue parsing the + * @param stopAtNonOption if true an unrecognized argument stops + * the parsing and the remaining arguments are added to the + * {@link CommandLine}s args list. If false an unrecognized + * argument triggers a ParseException. * * @return the list of atomic option and value tokens * @throws ParseException if there are any problems encountered diff --git a/src/java/org/apache/commons/cli/DefaultParser.java b/src/java/org/apache/commons/cli/DefaultParser.java index d3e6bf7a6..daf16610f 100644 --- a/src/java/org/apache/commons/cli/DefaultParser.java +++ b/src/java/org/apache/commons/cli/DefaultParser.java @@ -32,8 +32,14 @@ public class DefaultParser implements CommandLineParser { protected CommandLine cmd; protected Options options; + + /** + * Flag indicating how unrecognized tokens are handled. true to stop + * the parsing and add the remaining tokens to the args list. + * false to throw an exception. + */ protected boolean stopAtNonOption; - + /** The token currently processed. */ protected String currentToken; @@ -251,7 +257,7 @@ private void handleUnknownToken(String token) throws ParseException if (stopAtNonOption) { skipParsing = true; - } + } } /** diff --git a/src/java/org/apache/commons/cli/Parser.java b/src/java/org/apache/commons/cli/Parser.java index 2b99dd8bb..694e24151 100644 --- a/src/java/org/apache/commons/cli/Parser.java +++ b/src/java/org/apache/commons/cli/Parser.java @@ -108,9 +108,10 @@ public CommandLine parse(Options options, String[] arguments, Properties propert * * @param options the Options * @param arguments the arguments - * @param stopAtNonOption specifies whether to stop interpreting the - * arguments when a non option has been encountered - * and to add them to the CommandLines args list. + * @param stopAtNonOption if true an unrecognized argument stops + * the parsing and the remaining arguments are added to the + * {@link CommandLine}s args list. If false an unrecognized + * argument triggers a ParseException. * @return the CommandLine * @throws ParseException if an error occurs when parsing the arguments. */ @@ -126,8 +127,10 @@ public CommandLine parse(Options options, String[] arguments, boolean stopAtNonO * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs - * @param stopAtNonOption stop parsing the arguments when the first - * non option is encountered. + * @param stopAtNonOption if true an unrecognized argument stops + * the parsing and the remaining arguments are added to the + * {@link CommandLine}s args list. If false an unrecognized + * argument triggers a ParseException. * * @return the list of atomic option and value tokens * From 180a16def56be368c2c33a56c1778b8d7ce170c7 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Tue, 15 Jun 2010 14:11:04 +0000 Subject: [PATCH 0166/1663] Added a parameter in HelpFormatter to specify the separator displayed between a long option and its value (CLI-169) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@954899 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/HelpFormatter.java | 48 +++++++++++++++---- .../apache/commons/cli/HelpFormatterTest.java | 42 ++++++++++++++++ 2 files changed, 80 insertions(+), 10 deletions(-) diff --git a/src/java/org/apache/commons/cli/HelpFormatter.java b/src/java/org/apache/commons/cli/HelpFormatter.java index d4068d076..14b477ffd 100644 --- a/src/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/java/org/apache/commons/cli/HelpFormatter.java @@ -24,9 +24,6 @@ import java.util.Comparator; import java.util.Iterator; import java.util.List; -import java.util.StringTokenizer; -import java.io.InputStream; -import java.io.ByteArrayOutputStream; /** * A formatter of help messages for the current command line options @@ -60,6 +57,9 @@ public class HelpFormatter /** default prefix for long Option */ public static final String DEFAULT_LONG_OPT_PREFIX = "--"; + /** default separator displayed between a long Option and its value */ + public static final String DEFAULT_LONG_OPT_SEPARATOR = " "; + /** default name for an argument */ public static final String DEFAULT_ARG_NAME = "arg"; @@ -122,6 +122,9 @@ public class HelpFormatter */ public String defaultLongOptPrefix = DEFAULT_LONG_OPT_PREFIX; + /** The separator displayed between the long option and its value. */ + private String longOptSeparator = DEFAULT_LONG_OPT_SEPARATOR; + /** * the name of the argument * @@ -277,6 +280,30 @@ public String getLongOptPrefix() return defaultLongOptPrefix; } + /** + * Set the separator displayed between a long option and its value. + * Ensure that the separator specified is supported by the parser used, + * typically ' ' or '='. + * + * @param longOptSeparator the separator, typically ' ' or '='. + * @since 1.3 + */ + public void setLongOptSeparator(String longOptSeparator) + { + this.longOptSeparator = longOptSeparator; + } + + /** + * Returns the separator displayed between a long option and its value. + * + * @return the separator + * @since 1.3 + */ + public String getLongOptSeparator() + { + return longOptSeparator; + } + /** * Sets the 'argName'. * @@ -500,13 +527,12 @@ public void printHelp(PrintWriter pw, int width, String cmdLineSyntax, } /** - *

      Prints the usage statement for the specified application.

      + * Prints the usage statement for the specified application. * * @param pw The PrintWriter to print the usage statement * @param width The number of characters to display per line * @param app The application name * @param options The command line Options - * */ public void printUsage(PrintWriter pw, int width, String app, Options options) { @@ -607,7 +633,7 @@ private void appendOptionGroup(final StringBuffer buff, final OptionGroup group) * @param option the Option to append * @param required whether the Option is required or not */ - private static void appendOption(final StringBuffer buff, final Option option, final boolean required) + private void appendOption(final StringBuffer buff, final Option option, final boolean required) { if (!required) { @@ -626,7 +652,8 @@ private static void appendOption(final StringBuffer buff, final Option option, f // if the Option has a value if (option.hasArg() && option.hasArgName()) { - buff.append(" <").append(option.getArgName()).append(">"); + buff.append(option.getOpt() == null ? longOptSeparator : " "); + buff.append("<").append(option.getArgName()).append(">"); } // if the Option is not a required option @@ -652,8 +679,8 @@ public void printUsage(PrintWriter pw, int width, String cmdLineSyntax) } /** - *

      Print the help for the specified Options to the specified writer, - * using the specified width, left padding and description padding.

      + * Print the help for the specified Options to the specified writer, + * using the specified width, left padding and description padding. * * @param pw The printWriter to write the help to * @param width The number of characters to display per line @@ -756,7 +783,8 @@ protected StringBuffer renderOptions(StringBuffer sb, int width, Options options { if (option.hasArgName()) { - optBuf.append(" <").append(option.getArgName()).append(">"); + optBuf.append(option.hasLongOpt() ? longOptSeparator : " "); + optBuf.append("<").append(option.getArgName()).append(">"); } else { diff --git a/src/test/org/apache/commons/cli/HelpFormatterTest.java b/src/test/org/apache/commons/cli/HelpFormatterTest.java index 211b9bd5c..eae437e79 100644 --- a/src/test/org/apache/commons/cli/HelpFormatterTest.java +++ b/src/test/org/apache/commons/cli/HelpFormatterTest.java @@ -451,4 +451,46 @@ public void testOptionWithoutShortFormat2() ,out.toString()); } + public void testHelpWithLongOptSeparator() throws Exception + { + Options options = new Options(); + options.addOption( "f", true, "the file" ); + options.addOption(OptionBuilder.withLongOpt("size").withDescription("the size").hasArg().withArgName("SIZE").create('s')); + options.addOption(OptionBuilder.withLongOpt("age").withDescription("the age").hasArg().create()); + + HelpFormatter formatter = new HelpFormatter(); + assertEquals(HelpFormatter.DEFAULT_LONG_OPT_SEPARATOR, formatter.getLongOptSeparator()); + formatter.setLongOptSeparator("="); + assertEquals("=", formatter.getLongOptSeparator()); + + StringWriter out = new StringWriter(); + + formatter.printHelp(new PrintWriter(out), 80, "create", "header", options, 2, 2, "footer"); + + assertEquals( + "usage: create" + EOL + + "header" + EOL + + " --age= the age" + EOL + + " -f the file" + EOL + + " -s,--size= the size" + EOL + + "footer" + EOL, + out.toString()); + } + + public void testUsageWithLongOptSeparator() throws Exception + { + Options options = new Options(); + options.addOption( "f", true, "the file" ); + options.addOption(OptionBuilder.withLongOpt("size").withDescription("the size").hasArg().withArgName("SIZE").create('s')); + options.addOption(OptionBuilder.withLongOpt("age").withDescription("the age").hasArg().create()); + + HelpFormatter formatter = new HelpFormatter(); + formatter.setLongOptSeparator("="); + + StringWriter out = new StringWriter(); + + formatter.printUsage(new PrintWriter(out), 80, "create", options); + + assertEquals("usage: create [--age=] [-f ] [-s ]", out.toString().trim()); + } } From 10b14afb9ff42a3f216296f526f65d001b545e3f Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Tue, 15 Jun 2010 21:26:15 +0000 Subject: [PATCH 0167/1663] Deprecated PosixParser, GnuParser and BasicParser in favor of DefaultParser Updated the documentation accordingly git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955057 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/BasicParser.java | 1 + .../org/apache/commons/cli/GnuParser.java | 1 + src/java/org/apache/commons/cli/Parser.java | 1 + .../org/apache/commons/cli/PosixParser.java | 1 + src/site/xdoc/usage.xml | 22 ++++++++----------- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/java/org/apache/commons/cli/BasicParser.java b/src/java/org/apache/commons/cli/BasicParser.java index 05bc66386..1b8066ce0 100644 --- a/src/java/org/apache/commons/cli/BasicParser.java +++ b/src/java/org/apache/commons/cli/BasicParser.java @@ -23,6 +23,7 @@ * * @author John Keyes (john at integralsource.com) * @version $Revision$, $Date$ + * @deprecated Use the {@link DefaultParser} instead */ public class BasicParser extends Parser { diff --git a/src/java/org/apache/commons/cli/GnuParser.java b/src/java/org/apache/commons/cli/GnuParser.java index 312a60966..ad998924d 100644 --- a/src/java/org/apache/commons/cli/GnuParser.java +++ b/src/java/org/apache/commons/cli/GnuParser.java @@ -26,6 +26,7 @@ * * @author John Keyes (john at integralsource.com) * @version $Revision$, $Date$ + * @deprecated Use the {@link DefaultParser} instead */ public class GnuParser extends Parser { diff --git a/src/java/org/apache/commons/cli/Parser.java b/src/java/org/apache/commons/cli/Parser.java index 694e24151..6b3953620 100644 --- a/src/java/org/apache/commons/cli/Parser.java +++ b/src/java/org/apache/commons/cli/Parser.java @@ -30,6 +30,7 @@ * * @author John Keyes (john at integralsource.com) * @version $Revision$, $Date$ + * @deprecated The two-pass parsing with the flatten method is not enough flexible to handle complex cases */ public abstract class Parser implements CommandLineParser { diff --git a/src/java/org/apache/commons/cli/PosixParser.java b/src/java/org/apache/commons/cli/PosixParser.java index e6add97ed..c49784980 100644 --- a/src/java/org/apache/commons/cli/PosixParser.java +++ b/src/java/org/apache/commons/cli/PosixParser.java @@ -28,6 +28,7 @@ * * @author John Keyes (john at integralsource.com) * @version $Revision$, $Date$ + * @deprecated Use the {@link DefaultParser} instead */ public class PosixParser extends Parser { diff --git a/src/site/xdoc/usage.xml b/src/site/xdoc/usage.xml index f27d65607..5f282c1b8 100644 --- a/src/site/xdoc/usage.xml +++ b/src/site/xdoc/usage.xml @@ -69,11 +69,11 @@ options.addOption("t", false, "display current time");

      The parse methods of CommandLineParser are used - to parse the command line arguments. The PosixPaser is - great when you need to handle options that are one character long, - like the t option in this example. + to parse the command line arguments. There may be several implementations + of the CommandLineParser interface, the recommended one is the + DefaultParser.

      - CommandLineParser parser = new PosixParser(); + CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse( options, args);

      Now we need to check if the t option is present. To do @@ -241,15 +241,13 @@ options.addOption( property );

      - We now need to create a Parser. This will parse the command + We now need to create a CommandLineParser. This will parse the command line arguments, using the rules specified by the Options and return an instance of CommandLine. - This time we will use a GnuParser - which is able to handle options that are more than one character long.

      public static void main( String[] args ) { // create the parser - CommandLineParser parser = new GnuParser(); + CommandLineParser parser = new DefaultParser(); try { // parse the command line arguments CommandLine line = parser.parse( options, args ); @@ -310,10 +308,8 @@ formatter.printHelp( "ant", options );

      One of the most widely used command line applications in the *nix world - is ls. To parse a command line for an application like this - we will use the PosixParser. - Due to the large number of options required for ls this - example will only cover a small proportion of the options. The following + is ls. Due to the large number of options required for ls + this example will only cover a small proportion of the options. The following is a section of the help output.

      Usage: ls [OPTION]... [FILE]... @@ -335,7 +331,7 @@ Sort entries alphabetically if none of -cftuSUX nor --sort. Options for this example.

      // create the command line parser -CommandLineParser parser = new PosixParser(); +CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); From 3433f467554985a6bd9bf530a4810376be6fe250 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 00:00:14 +0000 Subject: [PATCH 0168/1663] The processing of the default options is no longer stopped by a flag with a false value (CLI-201) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955096 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli/Parser.java | 2 +- src/test/org/apache/commons/cli/ValueTest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/java/org/apache/commons/cli/Parser.java b/src/java/org/apache/commons/cli/Parser.java index 6b3953620..c106932aa 100644 --- a/src/java/org/apache/commons/cli/Parser.java +++ b/src/java/org/apache/commons/cli/Parser.java @@ -287,7 +287,7 @@ else if (!("yes".equalsIgnoreCase(value) { // if the value is not yes, true or 1 then don't add the // option to the CommandLine - break; + continue; } cmd.addOption(opt); diff --git a/src/test/org/apache/commons/cli/ValueTest.java b/src/test/org/apache/commons/cli/ValueTest.java index c7d764a60..93564dec1 100644 --- a/src/test/org/apache/commons/cli/ValueTest.java +++ b/src/test/org/apache/commons/cli/ValueTest.java @@ -212,7 +212,7 @@ public void testPropertyOptionFlags() throws Exception cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); - assertTrue( !cmd.hasOption("e") ); + assertTrue( cmd.hasOption("e") ); // this option accepts as argument properties = new Properties(); @@ -233,7 +233,7 @@ public void testPropertyOptionFlags() throws Exception cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); - assertTrue( !cmd.hasOption("e") ); + assertTrue( cmd.hasOption("e") ); } public void testPropertyOptionMultipleValues() throws Exception From a2cf820dd69e55050a8db004c305a6133c3feb2e Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 00:14:26 +0000 Subject: [PATCH 0169/1663] Added the missing parse methods accepting a map with the default options to DefaultParser Moved the related tests from ValueTest to ParserTestCase git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955099 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/DefaultParser.java | 88 ++++++++++++- .../apache/commons/cli/ParserTestCase.java | 117 ++++++++++++++++++ .../org/apache/commons/cli/ValueTest.java | 102 --------------- 3 files changed, 203 insertions(+), 104 deletions(-) diff --git a/src/java/org/apache/commons/cli/DefaultParser.java b/src/java/org/apache/commons/cli/DefaultParser.java index daf16610f..c7de0a288 100644 --- a/src/java/org/apache/commons/cli/DefaultParser.java +++ b/src/java/org/apache/commons/cli/DefaultParser.java @@ -18,8 +18,10 @@ package org.apache.commons.cli; import java.util.ArrayList; -import java.util.List; +import java.util.Enumeration; import java.util.Iterator; +import java.util.List; +import java.util.Properties; /** * Default parser. @@ -54,10 +56,46 @@ public class DefaultParser implements CommandLineParser public CommandLine parse(Options options, String[] arguments) throws ParseException { - return parse(options, arguments, false); + return parse(options, arguments, null); + } + + /** + * Parse the arguments according to the specified options and properties. + * + * @param options the specified Options + * @param arguments the command line arguments + * @param properties command line option name-value pairs + * @return the list of atomic option and value tokens + * + * @throws ParseException if there are any problems encountered + * while parsing the command line tokens. + */ + public CommandLine parse(Options options, String[] arguments, Properties properties) throws ParseException + { + return parse(options, arguments, properties, false); } public CommandLine parse(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException + { + return parse(options, arguments, null, stopAtNonOption); + } + + /** + * Parse the arguments according to the specified options and properties. + * + * @param options the specified Options + * @param arguments the command line arguments + * @param properties command line option name-value pairs + * @param stopAtNonOption if true an unrecognized argument stops + * the parsing and the remaining arguments are added to the + * {@link CommandLine}s args list. If false an unrecognized + * argument triggers a ParseException. + * + * @return the list of atomic option and value tokens + * @throws ParseException if there are any problems encountered + * while parsing the command line tokens. + */ + public CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption) throws ParseException { this.options = options; this.stopAtNonOption = stopAtNonOption; @@ -85,11 +123,57 @@ public CommandLine parse(Options options, String[] arguments, boolean stopAtNonO // check the arguments of the last option checkRequiredArgs(); + // add the default options + handleProperties(properties); + checkRequiredOptions(); return cmd; } + /** + * Sets the values of Options using the values in properties. + * + * @param properties The value properties to be processed. + */ + private void handleProperties(Properties properties) + { + if (properties == null) + { + return; + } + + for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) + { + String option = e.nextElement().toString(); + + if (!cmd.hasOption(option)) + { + Option opt = options.getOption(option); + + // get the value from the properties + String value = properties.getProperty(option); + + if (opt.hasArg()) + { + if (opt.getValues() == null || opt.getValues().length == 0) + { + opt.addValueForProcessing(value); + } + } + else if (!("yes".equalsIgnoreCase(value) + || "true".equalsIgnoreCase(value) + || "1".equalsIgnoreCase(value))) + { + // if the value is not yes, true or 1 then don't add the option to the CommandLine + continue; + } + + cmd.addOption(opt); + } + } + } + /** * Throws a {@link MissingOptionException} if all of the required options * are not present. diff --git a/src/test/org/apache/commons/cli/ParserTestCase.java b/src/test/org/apache/commons/cli/ParserTestCase.java index 3f5beba0c..30373d15b 100644 --- a/src/test/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/org/apache/commons/cli/ParserTestCase.java @@ -869,4 +869,121 @@ public void testUnlimitedArgs() throws Exception assertTrue("Confirm -f is set", cl.hasOption("f")); assertEquals("number of arg for -f", 1, cl.getOptionValues("f").length); } + + private CommandLine parse(CommandLineParser parser, Options opts, String[] args, Properties properties) throws ParseException { + if (parser instanceof Parser) { + return ((Parser) parser).parse(opts, args, properties); + } else if (parser instanceof DefaultParser) { + return ((DefaultParser) parser).parse(opts, args, properties); + } else { + throw new UnsupportedOperationException("Default options not supported by this parser"); + } + } + + public void testPropertyOptionSingularValue() throws Exception + { + Options opts = new Options(); + opts.addOption(OptionBuilder.hasOptionalArgs(2).withLongOpt("hide").create()); + + Properties properties = new Properties(); + properties.setProperty( "hide", "seek" ); + + CommandLine cmd = parse(parser, opts, null, properties); + assertTrue( cmd.hasOption("hide") ); + assertEquals( "seek", cmd.getOptionValue("hide") ); + assertTrue( !cmd.hasOption("fake") ); + } + + public void testPropertyOptionFlags() throws Exception + { + Options opts = new Options(); + opts.addOption("a", false, "toggle -a"); + opts.addOption("c", "c", false, "toggle -c"); + opts.addOption(OptionBuilder.hasOptionalArg().create('e')); + + Properties properties = new Properties(); + properties.setProperty("a", "true"); + properties.setProperty("c", "yes"); + properties.setProperty("e", "1"); + + CommandLine cmd = parse(parser, opts, null, properties); + assertTrue(cmd.hasOption("a")); + assertTrue(cmd.hasOption("c")); + assertTrue(cmd.hasOption("e")); + + + properties = new Properties(); + properties.setProperty("a", "false"); + properties.setProperty("c", "no"); + properties.setProperty("e", "0"); + + cmd = parse(parser, opts, null, properties); + assertTrue(!cmd.hasOption("a")); + assertTrue(!cmd.hasOption("c")); + assertTrue(cmd.hasOption("e")); // this option accepts an argument + + + properties = new Properties(); + properties.setProperty("a", "TRUE"); + properties.setProperty("c", "nO"); + properties.setProperty("e", "TrUe"); + + cmd = parse(parser, opts, null, properties); + assertTrue(cmd.hasOption("a")); + assertTrue(!cmd.hasOption("c")); + assertTrue(cmd.hasOption("e")); + + + properties = new Properties(); + properties.setProperty("a", "just a string"); + properties.setProperty("e", ""); + + cmd = parse(parser, opts, null, properties); + assertTrue(!cmd.hasOption("a")); + assertTrue(!cmd.hasOption("c")); + assertTrue(cmd.hasOption("e")); + + + properties = new Properties(); + properties.setProperty("a", "0"); + properties.setProperty("c", "1"); + + cmd = parse(parser, opts, null, properties); + assertTrue(!cmd.hasOption("a")); + assertTrue(cmd.hasOption("c")); + } + + public void testPropertyOptionMultipleValues() throws Exception + { + Options opts = new Options(); + opts.addOption(OptionBuilder.hasArgs().withValueSeparator(',').create('k')); + + Properties properties = new Properties(); + properties.setProperty( "k", "one,two" ); + + String[] values = new String[] { "one", "two" }; + + CommandLine cmd = parse(parser, opts, null, properties); + assertTrue( cmd.hasOption("k") ); + assertTrue( Arrays.equals( values, cmd.getOptionValues('k') ) ); + } + + public void testPropertyOverrideValues() throws Exception + { + Options opts = new Options(); + opts.addOption(OptionBuilder.hasOptionalArgs(2).create('i')); + opts.addOption(OptionBuilder.hasOptionalArgs().create('j')); + + String[] args = new String[] { "-j", "found", "-i", "ink" }; + + Properties properties = new Properties(); + properties.setProperty( "j", "seek" ); + + CommandLine cmd = parse(parser, opts, args, properties); + assertTrue( cmd.hasOption("j") ); + assertEquals( "found", cmd.getOptionValue("j") ); + assertTrue( cmd.hasOption("i") ); + assertEquals( "ink", cmd.getOptionValue("i") ); + assertTrue( !cmd.hasOption("fake") ); + } } diff --git a/src/test/org/apache/commons/cli/ValueTest.java b/src/test/org/apache/commons/cli/ValueTest.java index 93564dec1..bc374b258 100644 --- a/src/test/org/apache/commons/cli/ValueTest.java +++ b/src/test/org/apache/commons/cli/ValueTest.java @@ -17,9 +17,6 @@ package org.apache.commons.cli; -import java.util.Arrays; -import java.util.Properties; - import junit.framework.TestCase; public class ValueTest extends TestCase @@ -40,7 +37,6 @@ public void setUp() throws Exception opts.addOption(OptionBuilder.hasOptionalArgs(2).withLongOpt("hide").create()); opts.addOption(OptionBuilder.hasOptionalArgs(2).create('i')); opts.addOption(OptionBuilder.hasOptionalArgs().create('j')); - opts.addOption(OptionBuilder.hasArgs().withValueSeparator(',').create('k')); String[] args = new String[] { "-a", "-b", "foo", @@ -175,102 +171,4 @@ public void testLongOptionalNArgValues() throws Exception assertEquals( cmd.getArgs().length, 1 ); assertEquals( "head", cmd.getArgs()[0] ); } - - public void testPropertyOptionSingularValue() throws Exception - { - Properties properties = new Properties(); - properties.setProperty( "hide", "seek" ); - - Parser parser = new PosixParser(); - - CommandLine cmd = parser.parse(opts, null, properties); - assertTrue( cmd.hasOption("hide") ); - assertEquals( "seek", cmd.getOptionValue("hide") ); - assertTrue( !cmd.hasOption("fake") ); - } - - public void testPropertyOptionFlags() throws Exception - { - Properties properties = new Properties(); - properties.setProperty( "a", "true" ); - properties.setProperty( "c", "yes" ); - properties.setProperty( "e", "1" ); - - Parser parser = new PosixParser(); - - CommandLine cmd = parser.parse(opts, null, properties); - assertTrue( cmd.hasOption("a") ); - assertTrue( cmd.hasOption("c") ); - assertTrue( cmd.hasOption("e") ); - - - properties = new Properties(); - properties.setProperty( "a", "false" ); - properties.setProperty( "c", "no" ); - properties.setProperty( "e", "0" ); - - cmd = parser.parse(opts, null, properties); - assertTrue( !cmd.hasOption("a") ); - assertTrue( !cmd.hasOption("c") ); - assertTrue( cmd.hasOption("e") ); // this option accepts as argument - - - properties = new Properties(); - properties.setProperty( "a", "TRUE" ); - properties.setProperty( "c", "nO" ); - properties.setProperty( "e", "TrUe" ); - - cmd = parser.parse(opts, null, properties); - assertTrue( cmd.hasOption("a") ); - assertTrue( !cmd.hasOption("c") ); - assertTrue( cmd.hasOption("e") ); - - - properties = new Properties(); - properties.setProperty( "a", "just a string" ); - properties.setProperty( "e", "" ); - - cmd = parser.parse(opts, null, properties); - assertTrue( !cmd.hasOption("a") ); - assertTrue( !cmd.hasOption("c") ); - assertTrue( cmd.hasOption("e") ); - } - - public void testPropertyOptionMultipleValues() throws Exception - { - Properties properties = new Properties(); - properties.setProperty( "k", "one,two" ); - - Parser parser = new PosixParser(); - - String[] values = new String[] { - "one", "two" - }; - - CommandLine cmd = parser.parse(opts, null, properties); - assertTrue( cmd.hasOption("k") ); - assertTrue( Arrays.equals( values, cmd.getOptionValues('k') ) ); - } - - public void testPropertyOverrideValues() throws Exception - { - String[] args = new String[] { - "-j", - "found", - "-i", - "ink" - }; - - Properties properties = new Properties(); - properties.setProperty( "j", "seek" ); - - Parser parser = new PosixParser(); - CommandLine cmd = parser.parse(opts, args, properties); - assertTrue( cmd.hasOption("j") ); - assertEquals( "found", cmd.getOptionValue("j") ); - assertTrue( cmd.hasOption("i") ); - assertEquals( "ink", cmd.getOptionValue("i") ); - assertTrue( !cmd.hasOption("fake") ); - } - } From 20002f7f4e971349a1c95dd3b05846c5b824b65c Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 08:35:18 +0000 Subject: [PATCH 0170/1663] Restricted quote stripping to values containing exactly 2 quotes, one at the beginning and one at the end (CLI-185) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955156 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli/Util.java | 10 ++++------ src/test/org/apache/commons/cli/UtilTest.java | 4 ++++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/java/org/apache/commons/cli/Util.java b/src/java/org/apache/commons/cli/Util.java index c147b9555..bceee2597 100644 --- a/src/java/org/apache/commons/cli/Util.java +++ b/src/java/org/apache/commons/cli/Util.java @@ -62,14 +62,12 @@ else if (str.startsWith("-")) */ static String stripLeadingAndTrailingQuotes(String str) { - if (str.startsWith("\"")) + int length = str.length(); + if (length > 1 && str.startsWith("\"") && str.endsWith("\"") && str.substring(1, length - 1).indexOf('"') == -1) { - str = str.substring(1, str.length()); - } - if (str.endsWith("\"")) - { - str = str.substring(0, str.length() - 1); + str = str.substring(1, length - 1); } + return str; } } diff --git a/src/test/org/apache/commons/cli/UtilTest.java b/src/test/org/apache/commons/cli/UtilTest.java index c8c614ae0..ab95dd5cc 100644 --- a/src/test/org/apache/commons/cli/UtilTest.java +++ b/src/test/org/apache/commons/cli/UtilTest.java @@ -35,5 +35,9 @@ public void testStripLeadingHyphens() public void testStripLeadingAndTrailingQuotes() { assertEquals("foo", Util.stripLeadingAndTrailingQuotes("\"foo\"")); + assertEquals("foo \"bar\"", Util.stripLeadingAndTrailingQuotes("foo \"bar\"")); + assertEquals("\"foo\" bar", Util.stripLeadingAndTrailingQuotes("\"foo\" bar")); + assertEquals("\"foo\" and \"bar\"", Util.stripLeadingAndTrailingQuotes("\"foo\" and \"bar\"")); + assertEquals("\"", Util.stripLeadingAndTrailingQuotes("\"")); } } From 106f3b8dd48d32cbfcba4a42e1161505c2e3cac6 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 09:36:54 +0000 Subject: [PATCH 0171/1663] Move the XCF logo to the site directory git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955167 13f79535-47bb-0310-9956-ffa450edef68 --- src/media/media/logo.xcf | Bin 20269 -> 0 bytes src/{media => site/resources/images}/logo.xcf | Bin 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/media/media/logo.xcf rename src/{media => site/resources/images}/logo.xcf (100%) diff --git a/src/media/media/logo.xcf b/src/media/media/logo.xcf deleted file mode 100644 index fb1cd2b90f815dd587e2ea881d6f73a5ff1f03fe..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 20269 zcmeHv2Xs`|x$ZerHC@v+(nvF--g_DK-Wx(1B!LQ&P@}2P3EdPMP>f?B4#h1P+heee z3*dr7vna;cB)(4GeK(1to4h11H;H|1$EI2D`}d4MI8OYs?tN>$_tu@YHah3*{hz(} zzyI>>{r`vl!9~ONl|6m-zQKjP9LMpo_-7sp{j?}NkAL(iK1I7YjtYJT6cLII#fXxC zqUy)1;(CS_E$Uso6!#nvnu6AHb8T21}j94D#c zxS$_%T--qDa`s+XY93nx*0yw}uF=Do%r zPVT*?=L+vN{&31^*Q#mP8eG%6o<~VRk)lu^^qb;Apy!tU!pZ9sc#Z}l?yHeW@#O6ZCx&?2>Yfx#-kKP5a$@ebYaA7LyO^4Y zCefJzoq_hNF|g*gi(ccYw$jx&RTDkEONn=l;~Mo64zz9vg}2hmY3P!lR;Tm6*TwmA zH>?vhE-#gq`^xF*QODhMPEL+Ys~D#WD_(qSe9}Gj+?NK+hG-xTOn>feZ{%*@eT<>7 z_m4xu_z|gRsCYO=?{IVWI}aGK>+S=_8E>_k`^pLi1$!Ff&h;O-!;J3qI=vGOckdlo z__ZOjc~9J>W`p|53AJMj0M4*Uj7@vs^sH-;rv;epZE^PjO$>_&Cc7rA5C!%s?|R+F z6D@IhVv74%WD=0u6E04Tl^mZ$3-3xY*%3|N9M=4~Qp-cznzyb=@8#(SmqF*yWSA#z&}= zTP|pZX;Q`Aa=OOcLO1VHa{li1!d=`{kzfg3YL^5p+!IV+f%N`vj=5L7Qy z|8M;x<@j+g>oF@UG{?JmxEr4&1!p4{gE^CvQ;Q_xZi1J0lt#$ifR;~b<2WbeFn5vy zCgCCu`aKR(NDX_JfF6v&=G?HlTwtSw*&>&lcS8z!XqsCMo6V8WAQwTu8n~_G7f5=EbjrKH>Z!*&4sJuVPm)?u1k-|tzec^S+?|m-C zyYzS#bQtA0)vZUXJB3f<STP$CvfMFKG| z5lMN87BzpNR${S4D)r%gL^6?&NGg!<(wjaqnOq@M+?LCrX#)OJ0a{6OaLR0_{dehdZQmI?T+9ONeCaxhwsk6QunyH90W>6)71x z1tsMb^2ui{8zY}1rp!K(h$0ns^dRwNYBny&%4btq~g2JMr!u;IqEL@gWH_Vzn zXLfT#C1^jyki|YA4RA!pr)K3978e&4g#JOOY*bQlHy~cqhsO{Q=K`5C1oHkEiNi9 zt7>SO+rMz}!hyN7fFyqA9kw|rJi%F5QP=2lHP%;^^ zKNlB)yn5#B?!m>wL-V^^JmeyYTx|#liAyi2BzCmAW>gksrNl*sI&3zqcT{`|24Bb* z3JU%mvz|G-XTk93$ikjhQ2&%CmTCR$Q7L&94K3}Roo%z~%k$F{B7=hhEEa#OEhGZV z;LOeuX9X*i{`b$u1#R*5*hjqO~@*(Z|Urr*WEs=t|U7-Iwa6yGVq39 zn=FBju;}=t)U@=BjLe*Z@)@o7(u<@DU$ZSLwV--dXYatkybf1QVMbh7ke@-T;WfY3 z>P`MZAtZi@5IJXFXp(XklOb%(AS6Fssp5Df5A4fM)7V z7OTw>5*87Ym{CyWnmfq2=cNblH6~khdhv|5zC|M=i~8DT6lcUZEIO4;3bO=5pj2z2 z+N8)4v8j0#O`QWn#QiCHsY2`Lh|4T%nmd1F>5|2LbLt9HBZEx73aMB`Moj7>S8B9+ zqZxdNO3E&8>=;-~^vxLmuON3)ntwu0RddgxrOTHN_0F!zPY$;l)G~=kAQ1cpnos6M zjam5H!V@w}8`}F9j|?wh^dIp8@J}BQmXudByKi{;%4I{nt<|}Sp#gf8k5~u`%m2n} z_+ZX-W@~7iv!tQz?hAfJ;-k`A!;=f@+6G2etXe+Q+ftR25aO>>!XooR*y!Jpjm0E< z4gSHg8Q>Ghz2pCgksGWLDTVdzgG*MfUg0ITXca_`DUv||8}I_P&d=`QGsf?k|JUeO ztzI$g>E5Dc-9tn%1;HQ4{3*3&TXb4ceOuqO>C@=%bWh}cZ2B0z4|OjB`Trya_%I>8 zm-?6Y%zYGtAL*Z6lb00cVIKB$p5FhBk(+E$_mY2&_bXPd7#V1*D@ch5G_tkh#om#_ zqCr7GJO=`Hcj0K^Eo|ZEEnc>A#pqy1Lvebv-R!HNl@o*ae<067)BYOqFG*??zJ88a zNL|;0CCitO&Y#;@mKhh~uUE@S>;yty#Ebs`&j_dC<+^9pNNPbZWKxg!Vl{`BE*o9Y zJ*z4=DI&tOX+8MLE`v(VmJDclDb5di& z9aalqfWXL`cr)+!CrbcSHaX`Gc{>D(1`n0TqQKzJoYOV0x2LnUp|UVDIW{8178nrV z&-)7lcv0gG1A(CdR*@ZhcLGORNJ)r^iU&=qh`8hHO;K6DlN##NKJ}o0D|5T63hpG92yau zl2ZoG3@%&*d(3?6KMTQeHS?{`{L-r0`ue(>%Ce%otc=v;g!tH)Xc_{e4hfG*&MK~* z)iG~ips#xl-1-IP9~I0q$ERfjXpn0zDP*1<&KbQ&goOq>?DpW$sD$+ViWx2KU0rkA zngK=rnZ^wTGB7leo}CBqP*{+cla-N{l9UjKnTLfq>_L3c$F^YVxTtD|t95pZs{yn? za?Eb{8W@a8O3TR1;7Wpx}tO)a=6Yn)(@V{6J5aFlKbD z(CEzp_Rz=}pfQ4Di3tE(UOIn2v&rn|ALxjPO@@0fDJ>}~09f+^JcXM4mJLoPDmsRb z`6WR#FbMtm`B|auxMbm%q$EE(2&6{Kp3S)XT*DLK!$>lkH8lj5t)s8t*-{y zRjY?52@a2njR%~I1qS8$j~HT=!&mA}W{ZCSP$=Zk;s->l^VKkY`dA7355yVd2nh|t zLNlbxK(SON2PD?gh#>fe&-FU=0~)yu(ED=$W)Q;v`3DFC)XW-x2F{RU1;kcsM4I11 zVOeXbL?V{38h9(MUJv;2l^&-aJpVaE^B$be%Xx)B{-w;vhuVv<6%c;`CktE-g%_v^ z{PTh@u|P9TJr5yD#X0>Le!5nwN2=7hXlfcN4r zs)Pa9gQz(fzh1S0yHmKIabNK`{gCt6{tK`X@kMJH>?U@-@S6ewuk`jHLJx4nJQyv$ z4%3S9K|lojm!3&Uq(U~vsVW)w7tD-oFxn9w<^^9c2P%`x6#~U)VC$V~AMSId0`}I^ zn4HyT%v+P)h4B;keyUMVYar!5(`uA*9|`m9FlE2OI6b=$ERoT(g_+($!hLEsXw?cI zZx1|rn1HOnt1w{*46>1IO>2V@e;#Oo5tjRi;Xrx*=O7_f00mURMw<`FzhinE7>Lip z>;WdN3cd%^7BYDx&ttYa!eg-2fVxFbZ$T8X;Wmpw!+agM|4UCFT2nwUpg%SV(D3Bx zO^75VHZ;(zRS_@($uB?xo20kcBI46?0PSh_GQA18|4*}$q8t|Tij2oZ1T(5JT0>xA zORMV}8nA7dYD4d3LD`BXU5qU;OxZG@u zgbQeB?dVC!8Pi5$p>ARizrfrnN`Gu6gJ1E{N#iGedc z{Y(K91~aEUSb&iPMWuO3u(O%oM8bVmeHYU)rJ*g4F({JYoM&7u z(_0WhZX!US(g!xjLjbg642(=IWZ;vq|MV6fg3u|^$xznbrqsq3|QmX2k-f zqD|r79v1dkFs!`r7vBAmF#!9c5)yU>^Y88DFHFV^gwJ{L&pmF^S8onv;MSubOswvR zg@pS{O&)fFMi@ycFa5a>d19>rcm#;H4B*hS3%yqouhkZ$L;}UD6!12LzG>%b3yt>T zP=??=!Vc*c62q?56{STx{IOeyH>Yi?B_Plq5*eSK&vwd7MuGY7Rgd?vL5_nZHW0*S z8)NLPBV&^@i|*{rNztb(?fcl1Cq~$Tu7Q}a7Y_}OpzVBGc1i8jcHT>(hAqHC!fZ8G z{Z;3En!3rB9iM>sP|O-;+lDk!UO z!P&sb(1IRVt!c(k%>8Lr4Nh9(qa!1uqT>>hame8mIDeCwQ&?W#Oh-J62D_MXB#X=J zCkE!KDb7g;XpRLzD$rYYc2-tqR!%`#Esm51<`4F^H&tRU73ek6n9F-jH6?jYpiVl) za?%-HPButza)y(n&Ys?Rb6aPWWhdTo1>}T2nNeAs>%_5HateTJb}pa$Q4WA2E(=O) zX127ox3xA_iabz(wda$06yad}mBH8vWwyYj=S$ds47o|Bmd z$By&Fo3t{?eDX(t$Jhx(#l+*>FE<}JJu59f(t$mp5{klB^}2Vr!AJf#;NqBA>>PlL zLqkGBBcj+rV|r?0Y(%ittRqG7Eb9#*Zmg*wm=6(!{(G>)76h39JO&An^~cc>q4of? z9$Las4%mGo7?3&8Dzu6MKLNbA0H_lzw&E-e+Z%_?YBA|F*yl16f%Z396R}BvW8Rxa zfOD-tdjo*V>}TOEpAho)RRg9mKm?7sjRw3{>?_dnzBe^$l}ag4-e8+m9k2U$2A&C{ ziGUPo7lI?{uM|p=l2-uw%4lcI%ke;{{FERz1Al}Dq@2)4A_cU?LAMawZ-G?k!%M#) zBndX~*jcE7mT@hTFgy%P1xTtAn$V4k3k7~%50iRN0mfZFt>ADz8zmTpem_O=M*$V5 zxEm+N9p;G8E6V?gC^1EvDPsIh0SGakdw;f7-ixVWVm!7z2zmbo<&%5sY{xh*1i^=h zR}kBnLv`yVfcoBoK$&v{!I)cPh!1OU<3bqi_J|YL2pu~y5DKqJ5QVd1Gv&EPESTbT zH(YKC1BtoMornh^Jj}63F#>}=+-DRbVvj)0BEE8GeS;`1_5s`jkor?dlGRMC)HB0 z5m8Upv5+FWcs34!VX?xyp=i9GhK#X$hGYe{!4-Qw8aq8*N+{SxWATjEiRRweG<&sR zQt5p!Mb^;NO-<=7c+O&EEXF+!Rw9~=NsO~*HxU7|dd8*qP@$ee(9|7OvT3?GgjlT} z)+jjy*PP&xr=G<|S-oqjerkGCO<2cYYr=R&%i(zoYcfH-P`nmfy}zm#OnQU4QidIiRCO(@$w3T^5m^XGz!=pdo{!ZXL;49*8JZ6+NpEjC$0(@)i71!^o{e}k zN;G+6V$6j|KT=UfAoP=N@b)%%3x17YEVssypCX+63kT~mKH>sX(9p`cCqc!#AX{KF zE&q)P7bOzV5Qv575(a_{%}w_t_=Q$vL2e=|U<7t-Dz9V8usA*Ih*f4Q>dk0j8tGkI zk2Scv-XrvWCaWXh8xs#7&z~uYa8U~;8?OIq0WSXk$`3O0B&`$B3CICUgkau^O_*Jc z;c(HT#Y}*_`V3#jJRv2tuq(==5piEaTRA6mOFa37+XWX(*P_WUAn;DB3z{K9It#QL znO&Z{PfS=)ZC-}un*90^7l}EkFmgw6E*P@p_e1$({dPGK>xnB2_Y7vbWJit;j z{rB*cMu9742%wP6BrsdbRMy)khQYGhn4@QIn`)U&0HK@g1RDW)JkJQ2)_d*C)TmhQ z9DC;SSQd<#xg4+VV{yqZGUtIR;;ZLn1gJbtjM=BZ)12txNZDZS(lhz`t5*}}r(89e zeb)I1U9LOJ0tlv{xT%NmcxtH zrq=r#Sd1#R4wU=okuY*of0N6o@!SYZ^^`Q}agQELp`xazQ^QVDCh-9uyvkg!RcR9l^$1 zBg`t@gnuS=By$0jGC|66%gMk2886^n>>k9Ea>@e39s_rtZ3kg8m@Vj&(=Bzc7tG?O z3T2m)eY!#RjZDm^Gy*qetfF8bH<4M$Y!i#1PE^fYa#KE**zd2rew&N1-gKBA7j99gjq|< zO(YI8qfeJEdh9ir47*|1#B3`dotyQ^6lMZ~#Jj-`5?}BU!vwF%xnM>FTo7gP*cQwa z?`Pv;qei|SW<&XUH`yGSP2|~#h1_4*BaTuadG1U1IQCayBJV~$)(FSUp0vE%PF7Eu zk#4M(khYD;LdHBjzcl=zeK7rgg%XNFTV>_6bUoa%HndkRLHW;4)}uW#jpv*8%9NSy z{l!1!y_gy&#uI-Aso_6E`SrbZ@jvId^nc~Jd>jRo@1(l**pW|_8l1^~g&>&l79BZY zvy9Vqf#=4;eL|6MoGMa8icWK6+{g3;fk1@+Shfima0}rDjQ5W`Whj^s#k2+b8#OXI zNf&c}MCgIC%8>SEv*IiXIU10G>ntLHL|^WI@DPut> zRT%@r<5HYCdAV7svB7>C9}$)V`7bgYAcx~MZ}TFVE-)sesH(oHrLD80xiTZnC})jC za=kq+tGKGZv3YiT`|O6&v@nyB0*X?#IV7o|2CILb7b#5P&WfhlZEfw{3s!8{u&lEr z+9bodnn>Xnl~dQ+(b3k{*}G`j>XnPz$`Y(RGkx(E|_6FOSqog(8I|zPxks$o$Txy87mM%eH>+ds~NQrUj~fcO4v3Z(kTvfkC}M_Th^YytM9nQIQc`R1Wj)!|x&KC)ur1G~2m)u)E| z`vt`mcHZ~oD=!~h)e!He(L0=Tw!DB$Q(mO9=XGz~xv{q-(yUTwg0g!bI`-Pr>l>nt zT3c@K_Qwz2*PdzfmCKZd@S=f-UOsbj-%v@YPGgF$UiB>K1yWPuthIZ0uWm~8lZ%B? zT~y7|-B0Wut&A}F#W!vE;R^>>R7Zdv0-=u~x_0&9a~EIU(U#(;(gfu#dg3C-36=Ju zMGyaQ_fSc&3X3L`TT&Vpt{j?`VKdtE=0Ec4tB(xk1jvz*!<`k%{hjmnoOE_;CE-fYYKP`ZM5wqkQGzQ!j0Aj-g(JPzQuK!7!PB_QEGF zTzh?IbIcUEM4!~T=gdD{{^8=B0JX_Ot_rPLfAs9}@6L|Xf!v4tGcS+@!^x}m#_jIKYe^~yfNN&v=I`qy@&walunYaN; zk#DqX$LrTFJ~_S1u-c8sE}wgBVNL*eF6RD?rE91HvKKsl>1UT7pPyy%5rFpRB284& z_LEo7-80+Z$~8ydxqM`8b-0F2_YcrVC30@9={=8}|Jhad@)DZ@pq%>`k#Eeb9Vafo z`EaL~*Jr@%prR#*FI{`%p{@*n1$fGHzlZ*7EkS`6YhvrpH$M3BEBDQaq!;ttf9J)z z_&E=rIDc$wBP};$mjEl!zyI6^m!A1feVkb#fzkWDL}_%yCPdq;QPpdXzWbB69-fO)Rfk<`^1}1E-Q7YWCr#QUZRU@-hSfRPu|)$TorHCsg-KIH7cVZKRMW9 z&mG)%`h5~n2gx%hR0I_)-uLng-<_N8C-Witvv{a-lrBAV;luY%>>h5&jtdJ3i_IvV z(NLBgq&LSkZagx6@x`qzNoF}x5TyF(y445W`<7LO`%0t+CbFEs$DA@}`^#59eD}ou z_5HJIDykZ0cXhWE$Cy>>pq$=aq@}|ZQ6{BKu5)B}-nZ|O^{uHEx!4CfbKo2)z1mT< zVDD@1{nORA+~41}cE$3QE0^{+WY{!PA8kbW(4OaCJ$(PX;@BWdKv+h@(AJ%6J9F(C zi9{Kgx9D*?Bs?pS8ltO5A31UP+I!<~ymn#>?vsc1tm&%E zN=eJB?^(8HX?sDK&PO6QMpdnNYMdE9xnF$k@I%j?di%opQ?IxWj;-h@jyB0Xb~moF zf5U^jwl42&o-t!q=fJ|=rkpUnOyZ+;I9t{odJFVFCBqw6K5yN_Pr8ph`^4_eLoNAH zW|9a@PGOG9pEZB^s%49M=eG0hf11-+mg>;SL}FAFwyoZC7}5o?f#J`p>l$9YZq2g6 z*7DR~19=SrlC?xKy*;V0zO}u5PBW6N3eqC|HLzfKZ)DDlo+WGHbs)4pz5$V``Q_DB zr8$YA@JsMmEKN+RGTCENvvTutoXIgrs8qn?ptUY2CZn*j7TSV@A2HI{td5WndjO*1 zVga-kJ`x$RW&|s2fk=>$LomVTzwlzY)*Ohy8T9iLa+u8RvS195`NyynVgv|1zL^c+ z3rhGx8i^X!Um#D!6GiZya`3zW=`TK>JAp9&4gw$~P(Z0Ml>1152TEa~zm!Bz87e{| z#D(}{m?p}mK$;(Ue;Osy@sTs7M2ZUCOOg47%omEXc%FN41IKH95k{gUx_M&qFb^V8<66T2(;2yt5HZLo?5%rs0L;bilf4VOge)#GBvNHv>+X;B9p0% z_E=|OSy^Fvl)pwo4nQbTXf2M&XoT{$CRSOJn;c?N$>f?Dm02-i(awt2{*k3aUA5^U zer8*2Ze7QMCChM|1`$VMjZ7O5nO<67Uz!>b7MDYnOBc*3O$ahsLe`GVsVFFO^{={r z&w>39uAEbl81Jl@y>RW0y>#2+3{;6lK3aQndB^CwH47Sx@+)UAS~vE{!AI^NYRHUF z%z66zYv#4K^)21_;G;)hed+Q0dK;=6+UGCd^x(ngUOD#Y+NMO4OrrFQE$i91|JkQ@ zE$L|Pn7?w%?nB3pKmYwz?X@+o^DpmRJ<#3Lw`k?|Cr_R`_4M}9d2_pZ`W7s||FKt3 zpWHuO>`?ot{1a-1cE9rW+2?kS^vvxU7+U*1_o;Iy4sKl7J@?0F4{hpq)s$B>^lf?i z>^rBQ-Z472v8uGJzGvg1x6Z$~ZC0E?rZ7g9%-{3IwfA3tWJPB~WqEb;(5{y*Tzc)` zrUi3896z+CB|jk|Jie%R*U9&;p4>aym=hNk8e7o4^W_Vt9_e#hlEw&%S;B zsU<~03b9ldS-bv)tM8xK*_jn=^wnBZ+s015|L(DEbDY;sJv=wfUm+1IthtMyym0M} zT^*?wg;=Zz$XWFGxr;~FR02eZl#a5M?#owR+%zM`AQMY{!)rIZ`0kbG*Vji~eQjq; zoDPdDHKq3-IDhrE9nGg22Ly+n#-Aue`FQA%f8tEqnUH#b=fm!;$fDS;fnr zxyWv>9N#uGQbSs#Cr9%2+gG9%-?!V~&AK~BGcmL7# zd-wSLjgSx~f55Ix9O+hUNM^UJmgE-#cj1|3#a{Vg^7kxo)zy>RT?8^o{`(G`fA6)O zkbkBQX}$Z;T?J5$(MrTB(w|EgpIuq%P>KW|b-KjV;l0-%Y)dl1krEJiVw}`56{ugV zwB{^)?Ctm8*wvP7R><|x-{;?X=jhs+2rV)>wGp_za^=O1Gor4(xu-A3?kiUqA}d!s zb>Z6SeG3ai^$MjSvSQhxx8FOpw?8k$WDH7c-FEDq%P($ePWD&H)&421+g`fz?khXm z)6XB@ySOseUuUqV&jJn@fBnF+`lKME(Vp&F`@>V`kAHu-COIrLzNB~O^JmW-d7wK# z+@v*y7tY)9{JHbT9vmojKe1y`eVW71KQeFjs@+c?IkanuD=XX@7?n4B0sStXj}gQdd)!lN4&v8v>)!3My*rYs>Rf zBdjKq=N7d{eF+Q2*CHiVb#+z6nQ?ZL&V(&2-By<(QzR_Jh71k`w%Ar+0zUj4av+dq zfh0w`N44GRXGE?L5|D8h9OS1{%9T35pkTTMtr|(Yl;TMkL5Z~6Pm%D8oCPu6s?@yt zbKE0E7pcLNl=~TS`jP%Xd82fD3$)mlz^l_?fmF!yXW5ld;N!W2WZ{C#y9ZYka$gb< zp}Yvn3ch>LK%epnDRUZ?UTmXa*(r3)&bAbCeB5_k;ek6+%6r8pdXxrBDWD1rRi-fp z*n{m>6Yv3LHT@gBznngO3-ZD!0wlEWV!8iXy-p(s3^3tqI-9>=XkvD8d1)T7fdcyl z5qDl7R^XeQn52wsfVYf<@Bke!2>^~rN}mnH#K#2toAJ#}PDy!jR#H)8&*G(o4B{4g=w4X)Pqjy6|iRy2c-V!1vjCabckxxOGdKCRf*JG^YPzi#fx#s_}@ zaIm;G-YmmO6v*|#X%(|NI@{?mV#(^&qdm3h4ghBvo>zCT*t~UR&y1>ut|glvKJe(C zuEndj?tb!xSB~r+Di8OC8^abmJimGV=;EH{`r5|M;Y|0kVv2cLfZ^s(=DrDO9fkZ8jS=dRkkc0p5NT2gv(%jnn> zPaoXel^<%*S(9pq_a47|`Q-i$i~D-#FWtQVr8D&vr4>yJ$DTiT=FkebO0igF%bC0J z;a#g{=SEol0>U$0D}M0e@xxm?GHpgnRLS7(H-7TrxgT!oYpSZK>s)>Cjr6F{@T98Y z{iiOxd_T;RRAx?UUVq@p@6IoYFeqeltu15r=4XHO*5P$C<1L23)Y%Ul|M7=s4=$UT z6&n$g-MZ_`ICoMRfVc)AAy6F z*rqMVuDtW&CLD(7f=dA^-aU5TOn?fB%$U^i5P<`Q9k%kq+dmx657OK67ae@_t;dJ* zt>m_Gwxh5WEqUtVkAJkMJI$iAdqG77K!pH@7R@{EfP)L;hnE!E&EeH+k6t))aL{R% zlF*)`lZl>3&VFzSZ?_ph&p-w3j(OTxKX4Zuj2~WF6zm`Cdf>#>a|im;O7ncGf$ z@WDyoIVh56@c{eW7tTL9T;S#X-{jr0Vuv}jV)c=$AD$sO^e|tj3awsu}4=(<2xF86JA7o7Kr_-v&&Cj1Yx}_<`;A{K)uPC-@O$jaA zk6*p=;(artbvU}Alev_Rokw5Bw!p4Y|24fw{EC)6B?s>UUIK2bEuW(#95n|zBVNXXykHrKvLt% zJ^LT%E1+G81KhlWDI_`wrVbx>Ya?pb9)0JX=hxLn=oA`TcGm+>zk2lHq1xnNe~Ue# zym!OcmIW121{qEzreO-P+%I+R!+{!w+CRBv>x-8!AKTi3E|vPQ!g*T`K6PNr{26(v zDOnY5!)sRcRmJ%!qzb>JmTfP+^A3(xQUcUUU2wsIebN2~zlegK?MKg?Il8^OAl#(F z5obaB${i1F|IYk54fTy}y$c5Cl*U<}vj&0sOF{}191zf%g!h!f8ypbAmm~F_wfoeIDDYXS3Wp0cG~fxG zEFgwPFaXKko;wB;Fd+Ku1|R_k6{16Tik%KB=#zcI6o@_0z>%rLq7rgm{-x(j8#>Fl zp;w{<`1U{2A*0r0!S_-44h!G8;IIM7L2))6j{0%+2l#$OAmWlz@VQq)Y?Q;SWM_!i zU3n2k_-3B_LV$DsC}&Z51z+)bRdromWlod{r=MWYrry#>JslW|Ro0|3*X-t*b+t2R z_b!~@l4Dn4w})f;^Uv<=%f}5bl=~&t%v;poQdy8+K5PDW)-9-vpwnIM^mCh=6AV(J z*f+dvVC|ZLn)IlM#Gxb*2>0Fq*^wxnzc~%_a`K8X;uxsU(YRIvoGvfk+jY=34p4v9p&io_g-#m2>iGy)aoc_yKys?na^sN}aKI=i%4K zFTZ{A$*l-<=y5zft$|ps3yd%6SiR@Ssf(9RAKBSg5Ud8jrrsbF%ke3=B`l-1f8+j_ z&Rsr#WZRq+GhX3sAeAT#0aml#5D=BqxOk`g%sZzaM}z`?$lJh2rgOx`hnm$YU0_^E z_qONGUwC2Dj0hYA9DnyL4N`_!Q9*Hfu+~SaFoqTMeed}Bmmgq3gA-`blVX&qY?(7# zYmx($60yt}Gh^K|Z@jRriJ}Uxy>}iS-wg0mICpVRd5lRRm1)DummYlKiPhCO&EQU5 z8-HR^ZlFdNRyKd#s!o_Mt=1A-vt;+9JNt42v8t!9U3hAFWu(a%Ubb+{wxun3aiO8H zxh>1?-!@zuqlY(pef+IMYh9@}OK3s&n$4?v8;Y{Ci)M6>EE}AW;twyv9Xj&#?v*Xs zq5ig%+Mb1jolP|rm36Z^=C)QO2NEN>H5=D1>BjPz&A};!6_w>B#l@u+RaGUK(f%H( znZRDCq98Tg;;YsN1c%c{|M-3^DLx`l532^55QP7aP)C3PUtZt?Gkmp3UncrnO!!KR6 zcm9VjMNwDJg8tE=WsB!gB}9h({*f$cBKSxCFD*|G-yHd!>K|=t9`iK3GhA#QYJS9V zwTNWbu0Xl(-ujwPQID+dT8yREj1q!^|Cg*5(cs#06#U;@wVgzR|H5VRA1Vs8pDHq3 z|06|`IJw?i(Dhyv_MesEZ#9Yqg??cuN_KVkKVZ`|_Ac!0Svokh*k0SU1he)euG8PC z4AB*w++M*|D6$HFevy<{ZD1|*!!!!j;+{~AmDi&Mp6#}sW+lHJdLL6>uOQo zfbxBmU!wdg%5PErfbs>}gT9{Sx3m8oNAY{kG#U9HEbA4gIpt*Xf4F!? Date: Wed, 16 Jun 2010 09:41:26 +0000 Subject: [PATCH 0172/1663] Switched to the Maven 2 default directory layout (part 1) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955169 13f79535-47bb-0310-9956-ffa450edef68 --- src/test/{ => java}/org/apache/commons/cli/ApplicationTest.java | 0 .../{ => java}/org/apache/commons/cli/ArgumentIsOptionTest.java | 0 src/test/{ => java}/org/apache/commons/cli/BasicParserTest.java | 0 src/test/{ => java}/org/apache/commons/cli/BugsTest.java | 0 src/test/{ => java}/org/apache/commons/cli/CommandLineTest.java | 0 src/test/{ => java}/org/apache/commons/cli/DefaultParserTest.java | 0 src/test/{ => java}/org/apache/commons/cli/GnuParserTest.java | 0 src/test/{ => java}/org/apache/commons/cli/HelpFormatterTest.java | 0 src/test/{ => java}/org/apache/commons/cli/OptionBuilderTest.java | 0 src/test/{ => java}/org/apache/commons/cli/OptionGroupTest.java | 0 src/test/{ => java}/org/apache/commons/cli/OptionTest.java | 0 src/test/{ => java}/org/apache/commons/cli/OptionsTest.java | 0 src/test/{ => java}/org/apache/commons/cli/ParserTestCase.java | 0 .../org/apache/commons/cli/PatternOptionBuilderTest.java | 0 src/test/{ => java}/org/apache/commons/cli/PosixParserTest.java | 0 src/test/{ => java}/org/apache/commons/cli/UtilTest.java | 0 src/test/{ => java}/org/apache/commons/cli/ValueTest.java | 0 src/test/{ => java}/org/apache/commons/cli/ValuesTest.java | 0 src/test/{ => java}/org/apache/commons/cli/bug/BugCLI133Test.java | 0 src/test/{ => java}/org/apache/commons/cli/bug/BugCLI13Test.java | 0 src/test/{ => java}/org/apache/commons/cli/bug/BugCLI148Test.java | 0 src/test/{ => java}/org/apache/commons/cli/bug/BugCLI162Test.java | 0 src/test/{ => java}/org/apache/commons/cli/bug/BugCLI18Test.java | 0 src/test/{ => java}/org/apache/commons/cli/bug/BugCLI71Test.java | 0 24 files changed, 0 insertions(+), 0 deletions(-) rename src/test/{ => java}/org/apache/commons/cli/ApplicationTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/ArgumentIsOptionTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/BasicParserTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/BugsTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/CommandLineTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/DefaultParserTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/GnuParserTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/HelpFormatterTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/OptionBuilderTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/OptionGroupTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/OptionTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/OptionsTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/ParserTestCase.java (100%) rename src/test/{ => java}/org/apache/commons/cli/PatternOptionBuilderTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/PosixParserTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/UtilTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/ValueTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/ValuesTest.java (100%) rename src/test/{ => java}/org/apache/commons/cli/bug/BugCLI133Test.java (100%) rename src/test/{ => java}/org/apache/commons/cli/bug/BugCLI13Test.java (100%) rename src/test/{ => java}/org/apache/commons/cli/bug/BugCLI148Test.java (100%) rename src/test/{ => java}/org/apache/commons/cli/bug/BugCLI162Test.java (100%) rename src/test/{ => java}/org/apache/commons/cli/bug/BugCLI18Test.java (100%) rename src/test/{ => java}/org/apache/commons/cli/bug/BugCLI71Test.java (100%) diff --git a/src/test/org/apache/commons/cli/ApplicationTest.java b/src/test/java/org/apache/commons/cli/ApplicationTest.java similarity index 100% rename from src/test/org/apache/commons/cli/ApplicationTest.java rename to src/test/java/org/apache/commons/cli/ApplicationTest.java diff --git a/src/test/org/apache/commons/cli/ArgumentIsOptionTest.java b/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java similarity index 100% rename from src/test/org/apache/commons/cli/ArgumentIsOptionTest.java rename to src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java diff --git a/src/test/org/apache/commons/cli/BasicParserTest.java b/src/test/java/org/apache/commons/cli/BasicParserTest.java similarity index 100% rename from src/test/org/apache/commons/cli/BasicParserTest.java rename to src/test/java/org/apache/commons/cli/BasicParserTest.java diff --git a/src/test/org/apache/commons/cli/BugsTest.java b/src/test/java/org/apache/commons/cli/BugsTest.java similarity index 100% rename from src/test/org/apache/commons/cli/BugsTest.java rename to src/test/java/org/apache/commons/cli/BugsTest.java diff --git a/src/test/org/apache/commons/cli/CommandLineTest.java b/src/test/java/org/apache/commons/cli/CommandLineTest.java similarity index 100% rename from src/test/org/apache/commons/cli/CommandLineTest.java rename to src/test/java/org/apache/commons/cli/CommandLineTest.java diff --git a/src/test/org/apache/commons/cli/DefaultParserTest.java b/src/test/java/org/apache/commons/cli/DefaultParserTest.java similarity index 100% rename from src/test/org/apache/commons/cli/DefaultParserTest.java rename to src/test/java/org/apache/commons/cli/DefaultParserTest.java diff --git a/src/test/org/apache/commons/cli/GnuParserTest.java b/src/test/java/org/apache/commons/cli/GnuParserTest.java similarity index 100% rename from src/test/org/apache/commons/cli/GnuParserTest.java rename to src/test/java/org/apache/commons/cli/GnuParserTest.java diff --git a/src/test/org/apache/commons/cli/HelpFormatterTest.java b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java similarity index 100% rename from src/test/org/apache/commons/cli/HelpFormatterTest.java rename to src/test/java/org/apache/commons/cli/HelpFormatterTest.java diff --git a/src/test/org/apache/commons/cli/OptionBuilderTest.java b/src/test/java/org/apache/commons/cli/OptionBuilderTest.java similarity index 100% rename from src/test/org/apache/commons/cli/OptionBuilderTest.java rename to src/test/java/org/apache/commons/cli/OptionBuilderTest.java diff --git a/src/test/org/apache/commons/cli/OptionGroupTest.java b/src/test/java/org/apache/commons/cli/OptionGroupTest.java similarity index 100% rename from src/test/org/apache/commons/cli/OptionGroupTest.java rename to src/test/java/org/apache/commons/cli/OptionGroupTest.java diff --git a/src/test/org/apache/commons/cli/OptionTest.java b/src/test/java/org/apache/commons/cli/OptionTest.java similarity index 100% rename from src/test/org/apache/commons/cli/OptionTest.java rename to src/test/java/org/apache/commons/cli/OptionTest.java diff --git a/src/test/org/apache/commons/cli/OptionsTest.java b/src/test/java/org/apache/commons/cli/OptionsTest.java similarity index 100% rename from src/test/org/apache/commons/cli/OptionsTest.java rename to src/test/java/org/apache/commons/cli/OptionsTest.java diff --git a/src/test/org/apache/commons/cli/ParserTestCase.java b/src/test/java/org/apache/commons/cli/ParserTestCase.java similarity index 100% rename from src/test/org/apache/commons/cli/ParserTestCase.java rename to src/test/java/org/apache/commons/cli/ParserTestCase.java diff --git a/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java b/src/test/java/org/apache/commons/cli/PatternOptionBuilderTest.java similarity index 100% rename from src/test/org/apache/commons/cli/PatternOptionBuilderTest.java rename to src/test/java/org/apache/commons/cli/PatternOptionBuilderTest.java diff --git a/src/test/org/apache/commons/cli/PosixParserTest.java b/src/test/java/org/apache/commons/cli/PosixParserTest.java similarity index 100% rename from src/test/org/apache/commons/cli/PosixParserTest.java rename to src/test/java/org/apache/commons/cli/PosixParserTest.java diff --git a/src/test/org/apache/commons/cli/UtilTest.java b/src/test/java/org/apache/commons/cli/UtilTest.java similarity index 100% rename from src/test/org/apache/commons/cli/UtilTest.java rename to src/test/java/org/apache/commons/cli/UtilTest.java diff --git a/src/test/org/apache/commons/cli/ValueTest.java b/src/test/java/org/apache/commons/cli/ValueTest.java similarity index 100% rename from src/test/org/apache/commons/cli/ValueTest.java rename to src/test/java/org/apache/commons/cli/ValueTest.java diff --git a/src/test/org/apache/commons/cli/ValuesTest.java b/src/test/java/org/apache/commons/cli/ValuesTest.java similarity index 100% rename from src/test/org/apache/commons/cli/ValuesTest.java rename to src/test/java/org/apache/commons/cli/ValuesTest.java diff --git a/src/test/org/apache/commons/cli/bug/BugCLI133Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI133Test.java similarity index 100% rename from src/test/org/apache/commons/cli/bug/BugCLI133Test.java rename to src/test/java/org/apache/commons/cli/bug/BugCLI133Test.java diff --git a/src/test/org/apache/commons/cli/bug/BugCLI13Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI13Test.java similarity index 100% rename from src/test/org/apache/commons/cli/bug/BugCLI13Test.java rename to src/test/java/org/apache/commons/cli/bug/BugCLI13Test.java diff --git a/src/test/org/apache/commons/cli/bug/BugCLI148Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI148Test.java similarity index 100% rename from src/test/org/apache/commons/cli/bug/BugCLI148Test.java rename to src/test/java/org/apache/commons/cli/bug/BugCLI148Test.java diff --git a/src/test/org/apache/commons/cli/bug/BugCLI162Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI162Test.java similarity index 100% rename from src/test/org/apache/commons/cli/bug/BugCLI162Test.java rename to src/test/java/org/apache/commons/cli/bug/BugCLI162Test.java diff --git a/src/test/org/apache/commons/cli/bug/BugCLI18Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI18Test.java similarity index 100% rename from src/test/org/apache/commons/cli/bug/BugCLI18Test.java rename to src/test/java/org/apache/commons/cli/bug/BugCLI18Test.java diff --git a/src/test/org/apache/commons/cli/bug/BugCLI71Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java similarity index 100% rename from src/test/org/apache/commons/cli/bug/BugCLI71Test.java rename to src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java From 406a35f1a128944b7c51dcbc4a1f04c3f8bec3e6 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 09:42:17 +0000 Subject: [PATCH 0173/1663] Switched to the Maven 2 default directory layout (part 2) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955170 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/pom.xml b/pom.xml index 71a4f8dd3..59380c80d 100644 --- a/pom.xml +++ b/pom.xml @@ -164,8 +164,6 @@ - src/java - src/test . From 1596f3bbe57986361da4ac1a23634dd5b00d10df Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 09:45:00 +0000 Subject: [PATCH 0174/1663] Switched to the Maven 2 default directory layout (part 3) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955173 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/commons/cli/AlreadySelectedException.java | 0 .../java/org/apache/commons/cli/AmbiguousOptionException.java | 0 src/{ => main}/java/org/apache/commons/cli/BasicParser.java | 0 src/{ => main}/java/org/apache/commons/cli/CommandLine.java | 0 src/{ => main}/java/org/apache/commons/cli/CommandLineParser.java | 0 src/{ => main}/java/org/apache/commons/cli/DefaultParser.java | 0 src/{ => main}/java/org/apache/commons/cli/GnuParser.java | 0 src/{ => main}/java/org/apache/commons/cli/HelpFormatter.java | 0 .../java/org/apache/commons/cli/MissingArgumentException.java | 0 .../java/org/apache/commons/cli/MissingOptionException.java | 0 src/{ => main}/java/org/apache/commons/cli/Option.java | 0 src/{ => main}/java/org/apache/commons/cli/OptionBuilder.java | 0 src/{ => main}/java/org/apache/commons/cli/OptionGroup.java | 0 src/{ => main}/java/org/apache/commons/cli/OptionValidator.java | 0 src/{ => main}/java/org/apache/commons/cli/Options.java | 0 src/{ => main}/java/org/apache/commons/cli/ParseException.java | 0 src/{ => main}/java/org/apache/commons/cli/Parser.java | 0 .../java/org/apache/commons/cli/PatternOptionBuilder.java | 0 src/{ => main}/java/org/apache/commons/cli/PosixParser.java | 0 src/{ => main}/java/org/apache/commons/cli/TypeHandler.java | 0 .../java/org/apache/commons/cli/UnrecognizedOptionException.java | 0 src/{ => main}/java/org/apache/commons/cli/Util.java | 0 src/{ => main}/java/org/apache/commons/cli/overview.html | 0 src/{ => main}/java/org/apache/commons/cli/package.html | 0 24 files changed, 0 insertions(+), 0 deletions(-) rename src/{ => main}/java/org/apache/commons/cli/AlreadySelectedException.java (100%) rename src/{ => main}/java/org/apache/commons/cli/AmbiguousOptionException.java (100%) rename src/{ => main}/java/org/apache/commons/cli/BasicParser.java (100%) rename src/{ => main}/java/org/apache/commons/cli/CommandLine.java (100%) rename src/{ => main}/java/org/apache/commons/cli/CommandLineParser.java (100%) rename src/{ => main}/java/org/apache/commons/cli/DefaultParser.java (100%) rename src/{ => main}/java/org/apache/commons/cli/GnuParser.java (100%) rename src/{ => main}/java/org/apache/commons/cli/HelpFormatter.java (100%) rename src/{ => main}/java/org/apache/commons/cli/MissingArgumentException.java (100%) rename src/{ => main}/java/org/apache/commons/cli/MissingOptionException.java (100%) rename src/{ => main}/java/org/apache/commons/cli/Option.java (100%) rename src/{ => main}/java/org/apache/commons/cli/OptionBuilder.java (100%) rename src/{ => main}/java/org/apache/commons/cli/OptionGroup.java (100%) rename src/{ => main}/java/org/apache/commons/cli/OptionValidator.java (100%) rename src/{ => main}/java/org/apache/commons/cli/Options.java (100%) rename src/{ => main}/java/org/apache/commons/cli/ParseException.java (100%) rename src/{ => main}/java/org/apache/commons/cli/Parser.java (100%) rename src/{ => main}/java/org/apache/commons/cli/PatternOptionBuilder.java (100%) rename src/{ => main}/java/org/apache/commons/cli/PosixParser.java (100%) rename src/{ => main}/java/org/apache/commons/cli/TypeHandler.java (100%) rename src/{ => main}/java/org/apache/commons/cli/UnrecognizedOptionException.java (100%) rename src/{ => main}/java/org/apache/commons/cli/Util.java (100%) rename src/{ => main}/java/org/apache/commons/cli/overview.html (100%) rename src/{ => main}/java/org/apache/commons/cli/package.html (100%) diff --git a/src/java/org/apache/commons/cli/AlreadySelectedException.java b/src/main/java/org/apache/commons/cli/AlreadySelectedException.java similarity index 100% rename from src/java/org/apache/commons/cli/AlreadySelectedException.java rename to src/main/java/org/apache/commons/cli/AlreadySelectedException.java diff --git a/src/java/org/apache/commons/cli/AmbiguousOptionException.java b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java similarity index 100% rename from src/java/org/apache/commons/cli/AmbiguousOptionException.java rename to src/main/java/org/apache/commons/cli/AmbiguousOptionException.java diff --git a/src/java/org/apache/commons/cli/BasicParser.java b/src/main/java/org/apache/commons/cli/BasicParser.java similarity index 100% rename from src/java/org/apache/commons/cli/BasicParser.java rename to src/main/java/org/apache/commons/cli/BasicParser.java diff --git a/src/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java similarity index 100% rename from src/java/org/apache/commons/cli/CommandLine.java rename to src/main/java/org/apache/commons/cli/CommandLine.java diff --git a/src/java/org/apache/commons/cli/CommandLineParser.java b/src/main/java/org/apache/commons/cli/CommandLineParser.java similarity index 100% rename from src/java/org/apache/commons/cli/CommandLineParser.java rename to src/main/java/org/apache/commons/cli/CommandLineParser.java diff --git a/src/java/org/apache/commons/cli/DefaultParser.java b/src/main/java/org/apache/commons/cli/DefaultParser.java similarity index 100% rename from src/java/org/apache/commons/cli/DefaultParser.java rename to src/main/java/org/apache/commons/cli/DefaultParser.java diff --git a/src/java/org/apache/commons/cli/GnuParser.java b/src/main/java/org/apache/commons/cli/GnuParser.java similarity index 100% rename from src/java/org/apache/commons/cli/GnuParser.java rename to src/main/java/org/apache/commons/cli/GnuParser.java diff --git a/src/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java similarity index 100% rename from src/java/org/apache/commons/cli/HelpFormatter.java rename to src/main/java/org/apache/commons/cli/HelpFormatter.java diff --git a/src/java/org/apache/commons/cli/MissingArgumentException.java b/src/main/java/org/apache/commons/cli/MissingArgumentException.java similarity index 100% rename from src/java/org/apache/commons/cli/MissingArgumentException.java rename to src/main/java/org/apache/commons/cli/MissingArgumentException.java diff --git a/src/java/org/apache/commons/cli/MissingOptionException.java b/src/main/java/org/apache/commons/cli/MissingOptionException.java similarity index 100% rename from src/java/org/apache/commons/cli/MissingOptionException.java rename to src/main/java/org/apache/commons/cli/MissingOptionException.java diff --git a/src/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java similarity index 100% rename from src/java/org/apache/commons/cli/Option.java rename to src/main/java/org/apache/commons/cli/Option.java diff --git a/src/java/org/apache/commons/cli/OptionBuilder.java b/src/main/java/org/apache/commons/cli/OptionBuilder.java similarity index 100% rename from src/java/org/apache/commons/cli/OptionBuilder.java rename to src/main/java/org/apache/commons/cli/OptionBuilder.java diff --git a/src/java/org/apache/commons/cli/OptionGroup.java b/src/main/java/org/apache/commons/cli/OptionGroup.java similarity index 100% rename from src/java/org/apache/commons/cli/OptionGroup.java rename to src/main/java/org/apache/commons/cli/OptionGroup.java diff --git a/src/java/org/apache/commons/cli/OptionValidator.java b/src/main/java/org/apache/commons/cli/OptionValidator.java similarity index 100% rename from src/java/org/apache/commons/cli/OptionValidator.java rename to src/main/java/org/apache/commons/cli/OptionValidator.java diff --git a/src/java/org/apache/commons/cli/Options.java b/src/main/java/org/apache/commons/cli/Options.java similarity index 100% rename from src/java/org/apache/commons/cli/Options.java rename to src/main/java/org/apache/commons/cli/Options.java diff --git a/src/java/org/apache/commons/cli/ParseException.java b/src/main/java/org/apache/commons/cli/ParseException.java similarity index 100% rename from src/java/org/apache/commons/cli/ParseException.java rename to src/main/java/org/apache/commons/cli/ParseException.java diff --git a/src/java/org/apache/commons/cli/Parser.java b/src/main/java/org/apache/commons/cli/Parser.java similarity index 100% rename from src/java/org/apache/commons/cli/Parser.java rename to src/main/java/org/apache/commons/cli/Parser.java diff --git a/src/java/org/apache/commons/cli/PatternOptionBuilder.java b/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java similarity index 100% rename from src/java/org/apache/commons/cli/PatternOptionBuilder.java rename to src/main/java/org/apache/commons/cli/PatternOptionBuilder.java diff --git a/src/java/org/apache/commons/cli/PosixParser.java b/src/main/java/org/apache/commons/cli/PosixParser.java similarity index 100% rename from src/java/org/apache/commons/cli/PosixParser.java rename to src/main/java/org/apache/commons/cli/PosixParser.java diff --git a/src/java/org/apache/commons/cli/TypeHandler.java b/src/main/java/org/apache/commons/cli/TypeHandler.java similarity index 100% rename from src/java/org/apache/commons/cli/TypeHandler.java rename to src/main/java/org/apache/commons/cli/TypeHandler.java diff --git a/src/java/org/apache/commons/cli/UnrecognizedOptionException.java b/src/main/java/org/apache/commons/cli/UnrecognizedOptionException.java similarity index 100% rename from src/java/org/apache/commons/cli/UnrecognizedOptionException.java rename to src/main/java/org/apache/commons/cli/UnrecognizedOptionException.java diff --git a/src/java/org/apache/commons/cli/Util.java b/src/main/java/org/apache/commons/cli/Util.java similarity index 100% rename from src/java/org/apache/commons/cli/Util.java rename to src/main/java/org/apache/commons/cli/Util.java diff --git a/src/java/org/apache/commons/cli/overview.html b/src/main/java/org/apache/commons/cli/overview.html similarity index 100% rename from src/java/org/apache/commons/cli/overview.html rename to src/main/java/org/apache/commons/cli/overview.html diff --git a/src/java/org/apache/commons/cli/package.html b/src/main/java/org/apache/commons/cli/package.html similarity index 100% rename from src/java/org/apache/commons/cli/package.html rename to src/main/java/org/apache/commons/cli/package.html From 1a09ed40ab3036e2be9884f9b4e0b5afa5bbbfa4 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 09:54:03 +0000 Subject: [PATCH 0175/1663] Removed the unused manifest file git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955174 13f79535-47bb-0310-9956-ffa450edef68 --- src/conf/MANIFEST.MF | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 src/conf/MANIFEST.MF diff --git a/src/conf/MANIFEST.MF b/src/conf/MANIFEST.MF deleted file mode 100644 index cd23a6e02..000000000 --- a/src/conf/MANIFEST.MF +++ /dev/null @@ -1,21 +0,0 @@ -Manifest-Version: 1.0 -Implementation-Title: Commons CLI -Implementation-Vendor: The Apache Software Foundation -Implementation-Vendor-Id: org.apache -Implementation-Version: 1.2-SNAPSHOT -Specification-Title: Commons CLI -Specification-Vendor: The Apache Software Foundation -Specification-Version: 1.2-SNAPSHOT -X-Compile-Source-JDK: 1.3 -X-Compile-Target-JDK: 1.3 -Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt -Import-Package: org.apache.commons.cli;version="1.2.0.SNAPSHOT" -Export-Package: org.apache.commons.cli;version="1.2.0.SNAPSHOT" -Bundle-Version: 1.2.0.SNAPSHOT -Bundle-Name: Commons CLI -Bundle-Description: Commons CLI provides a simple API for presenting, - processing and validating a command line interface. -Bundle-DocURL: http://commons.apache.org/cli/ -Bundle-ManifestVersion: 2 -Bundle-Vendor: The Apache Software Foundation -Bundle-SymbolicName: org.apache.commons.cli From d3ca03e53bfe79b956cc4149845c6fad8fb85fac Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 09:55:18 +0000 Subject: [PATCH 0176/1663] Removed the unnecessary section from the pom git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955175 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/pom.xml b/pom.xml index 59380c80d..3a490c8b1 100644 --- a/pom.xml +++ b/pom.xml @@ -164,16 +164,6 @@ - - - . - META-INF - - NOTICE.txt - LICENSE.txt - - - maven-assembly-plugin From d8df5107a76b1a7fa579ec91f5482be901d18435 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 10:32:08 +0000 Subject: [PATCH 0177/1663] Fixed some of the checkstyle errors git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955185 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/CommandLine.java | 11 +++++++---- .../java/org/apache/commons/cli/HelpFormatter.java | 6 +++--- src/main/java/org/apache/commons/cli/Option.java | 3 ++- .../java/org/apache/commons/cli/OptionBuilder.java | 7 +++++-- src/main/java/org/apache/commons/cli/OptionGroup.java | 1 + src/main/java/org/apache/commons/cli/Options.java | 1 + 6 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java index 3a5fc306e..9cd1b9d06 100644 --- a/src/main/java/org/apache/commons/cli/CommandLine.java +++ b/src/main/java/org/apache/commons/cli/CommandLine.java @@ -42,6 +42,7 @@ */ public class CommandLine implements Serializable { + /** The serial version UID. */ private static final long serialVersionUID = 1L; /** the unrecognised options/arguments */ @@ -89,11 +90,13 @@ public boolean hasOption(char opt) */ public Object getOptionObject(String opt) { - try { + try + { return getParsedOptionValue(opt); - } catch(ParseException pe) { - System.err.println("Exception found converting " + opt + " to desired type: " + - pe.getMessage() ); + } + catch (ParseException pe) + { + System.err.println("Exception found converting " + opt + " to desired type: " + pe.getMessage()); return null; } } diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java index 14b477ffd..52ade639a 100644 --- a/src/main/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java @@ -763,8 +763,8 @@ protected StringBuffer renderOptions(StringBuffer sb, int width, Options options for (Iterator i = optList.iterator(); i.hasNext();) { Option option = (Option) i.next(); - optBuf = new StringBuffer(8); - + optBuf = new StringBuffer(); + if (option.getOpt() == null) { optBuf.append(lpad).append(" " + defaultLongOptPrefix).append(option.getLongOpt()); @@ -874,7 +874,7 @@ protected StringBuffer renderWrappedText(StringBuffer sb, int width, return sb; } - if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) + if ((text.length() > width) && (pos == nextLineTabStop - 1)) { pos = width; } diff --git a/src/main/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java index 80839baf2..e4c416888 100644 --- a/src/main/java/org/apache/commons/cli/Option.java +++ b/src/main/java/org/apache/commons/cli/Option.java @@ -38,6 +38,7 @@ */ public class Option implements Cloneable, Serializable { + /** The serial version UID. */ private static final long serialVersionUID = 1L; /** constant that specifies the number of argument values has not been specified */ @@ -619,7 +620,7 @@ public boolean equals(Object o) public int hashCode() { int result; - result = (opt != null ? opt.hashCode() : 0); + result = opt != null ? opt.hashCode() : 0; result = 31 * result + (longOpt != null ? longOpt.hashCode() : 0); return result; } diff --git a/src/main/java/org/apache/commons/cli/OptionBuilder.java b/src/main/java/org/apache/commons/cli/OptionBuilder.java index 60b496786..ca8fbe243 100644 --- a/src/main/java/org/apache/commons/cli/OptionBuilder.java +++ b/src/main/java/org/apache/commons/cli/OptionBuilder.java @@ -346,7 +346,8 @@ public static Option create() throws IllegalArgumentException public static Option create(String opt) throws IllegalArgumentException { Option option = null; - try { + try + { // create the option option = new Option(opt, description); @@ -358,7 +359,9 @@ public static Option create(String opt) throws IllegalArgumentException option.setType(type); option.setValueSeparator(valuesep); option.setArgName(argName); - } finally { + } + finally + { // reset the OptionBuilder properties OptionBuilder.reset(); } diff --git a/src/main/java/org/apache/commons/cli/OptionGroup.java b/src/main/java/org/apache/commons/cli/OptionGroup.java index 67cd5e21e..5d23c201d 100644 --- a/src/main/java/org/apache/commons/cli/OptionGroup.java +++ b/src/main/java/org/apache/commons/cli/OptionGroup.java @@ -31,6 +31,7 @@ */ public class OptionGroup implements Serializable { + /** The serial version UID. */ private static final long serialVersionUID = 1L; /** hold the options */ diff --git a/src/main/java/org/apache/commons/cli/Options.java b/src/main/java/org/apache/commons/cli/Options.java index 0f3a9811d..ba6b941a2 100644 --- a/src/main/java/org/apache/commons/cli/Options.java +++ b/src/main/java/org/apache/commons/cli/Options.java @@ -45,6 +45,7 @@ */ public class Options implements Serializable { + /** The serial version UID. */ private static final long serialVersionUID = 1L; /** a map of the options with the character key */ From d36b987c3257c01b42353cf7d2eb69ca325860aa Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 15:48:56 +0000 Subject: [PATCH 0178/1663] A space character is no longer accepted as a valid short option git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955277 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/OptionValidator.java | 13 ++++++------- .../org/apache/commons/cli/OptionBuilderTest.java | 8 ++++++++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/OptionValidator.java b/src/main/java/org/apache/commons/cli/OptionValidator.java index d824a50df..2a291f9a0 100644 --- a/src/main/java/org/apache/commons/cli/OptionValidator.java +++ b/src/main/java/org/apache/commons/cli/OptionValidator.java @@ -49,15 +49,15 @@ static void validateOption(String opt) throws IllegalArgumentException { return; } - + // handle the single character opt - else if (opt.length() == 1) + if (opt.length() == 1) { char ch = opt.charAt(0); if (!isValidOpt(ch)) { - throw new IllegalArgumentException("illegal option value '" + ch + "'"); + throw new IllegalArgumentException("Illegal option name '" + ch + "'"); } } @@ -70,7 +70,7 @@ else if (opt.length() == 1) { if (!isValidChar(chars[i])) { - throw new IllegalArgumentException("opt contains illegal character value '" + chars[i] + "'"); + throw new IllegalArgumentException("The option '" + opt + "' contains an illegal character : '" + chars[i] + "'"); } } } @@ -80,12 +80,11 @@ else if (opt.length() == 1) * Returns whether the specified character is a valid Option. * * @param c the option to validate - * @return true if c is a letter, ' ', '?' or '@', - * otherwise false. + * @return true if c is a letter, '?' or '@', otherwise false. */ private static boolean isValidOpt(char c) { - return isValidChar(c) || c == ' ' || c == '?' || c == '@'; + return isValidChar(c) || c == '?' || c == '@'; } /** diff --git a/src/test/java/org/apache/commons/cli/OptionBuilderTest.java b/src/test/java/org/apache/commons/cli/OptionBuilderTest.java index b445a674e..0d2f8f38a 100644 --- a/src/test/java/org/apache/commons/cli/OptionBuilderTest.java +++ b/src/test/java/org/apache/commons/cli/OptionBuilderTest.java @@ -97,6 +97,14 @@ public void testSpecialOptChars() throws Exception // '@' Option opt2 = OptionBuilder.withDescription("read from stdin").create('@'); assertEquals("@", opt2.getOpt()); + + // ' ' + try { + OptionBuilder.create(' '); + fail( "IllegalArgumentException not caught" ); + } catch (IllegalArgumentException e) { + // success + } } public void testOptionArgNumbers() From f588f55ad6ee8d64fcb9956847dfa8c064d888ee Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 16:27:03 +0000 Subject: [PATCH 0179/1663] Improved the test coverage for the CommandLine class git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955289 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/CommandLineTest.java | 13 +++++++++++++ .../org/apache/commons/cli/bug/BugCLI71Test.java | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/cli/CommandLineTest.java b/src/test/java/org/apache/commons/cli/CommandLineTest.java index 5ed76602b..fed4ac38e 100644 --- a/src/test/java/org/apache/commons/cli/CommandLineTest.java +++ b/src/test/java/org/apache/commons/cli/CommandLineTest.java @@ -48,4 +48,17 @@ public void testGetOptionProperties() throws Exception assertEquals("property with long format", "bar", cl.getOptionProperties("property").getProperty("foo")); } + + public void testGetOptions() + { + CommandLine cmd = new CommandLine(); + assertNotNull(cmd.getOptions()); + assertEquals(0, cmd.getOptions().length); + + cmd.addOption(new Option("a", null)); + cmd.addOption(new Option("b", null)); + cmd.addOption(new Option("c", null)); + + assertEquals(3, cmd.getOptions().length); + } } diff --git a/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java index c0d8ec1e5..8f5f0f392 100644 --- a/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java +++ b/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java @@ -78,7 +78,7 @@ public void testGetsDefaultIfOptional() throws Exception { CommandLine line = parser.parse( options, args); assertEquals( "Caesar", line.getOptionValue("a") ); - assertEquals( "a", line.getOptionValue("k", "a") ); + assertEquals( "a", line.getOptionValue('k', "a") ); } } From 5560a086886c4d6dba2c30eb75e57e3167765c6e Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 16 Jun 2010 22:59:59 +0000 Subject: [PATCH 0180/1663] Default options are now taken into account for the required options (CLI-202) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955420 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/DefaultParser.java | 5 +-- .../java/org/apache/commons/cli/Parser.java | 32 +++++++++++++------ .../apache/commons/cli/ParserTestCase.java | 12 +++++++ 3 files changed, 37 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/DefaultParser.java b/src/main/java/org/apache/commons/cli/DefaultParser.java index c7de0a288..f82308116 100644 --- a/src/main/java/org/apache/commons/cli/DefaultParser.java +++ b/src/main/java/org/apache/commons/cli/DefaultParser.java @@ -136,7 +136,7 @@ public CommandLine parse(Options options, String[] arguments, Properties propert * * @param properties The value properties to be processed. */ - private void handleProperties(Properties properties) + private void handleProperties(Properties properties) throws ParseException { if (properties == null) { @@ -169,7 +169,8 @@ else if (!("yes".equalsIgnoreCase(value) continue; } - cmd.addOption(opt); + handleOption(opt); + currentOption = null; } } } diff --git a/src/main/java/org/apache/commons/cli/Parser.java b/src/main/java/org/apache/commons/cli/Parser.java index c106932aa..eecfb8210 100644 --- a/src/main/java/org/apache/commons/cli/Parser.java +++ b/src/main/java/org/apache/commons/cli/Parser.java @@ -249,7 +249,7 @@ else if (t.startsWith("-")) * * @param properties The value properties to be processed. */ - protected void processProperties(Properties properties) + protected void processProperties(Properties properties) throws ParseException { if (properties == null) { @@ -291,6 +291,7 @@ else if (!("yes".equalsIgnoreCase(value) } cmd.addOption(opt); + updateRequiredOptions(opt); } } } @@ -376,7 +377,27 @@ protected void processOption(String arg, ListIterator iter) throws ParseExceptio // get the option represented by arg Option opt = (Option) getOptions().getOption(arg).clone(); + + // update the required options and groups + updateRequiredOptions(opt); + + // if the option takes an argument value + if (opt.hasArg()) + { + processArgs(opt, iter); + } + + // set the option on the command line + cmd.addOption(opt); + } + /** + * Removes the option or its group from the list of expected elements. + * + * @param opt + */ + private void updateRequiredOptions(Option opt) throws ParseException + { // if the option is a required option remove the option from // the requiredOptions list if (opt.isRequired()) @@ -397,14 +418,5 @@ protected void processOption(String arg, ListIterator iter) throws ParseExceptio group.setSelected(opt); } - - // if the option takes an argument value - if (opt.hasArg()) - { - processArgs(opt, iter); - } - - // set the option on the command line - cmd.addOption(opt); } } diff --git a/src/test/java/org/apache/commons/cli/ParserTestCase.java b/src/test/java/org/apache/commons/cli/ParserTestCase.java index 30373d15b..effebdb15 100644 --- a/src/test/java/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/java/org/apache/commons/cli/ParserTestCase.java @@ -986,4 +986,16 @@ public void testPropertyOverrideValues() throws Exception assertEquals( "ink", cmd.getOptionValue("i") ); assertTrue( !cmd.hasOption("fake") ); } + + public void testPropertyOptionRequired() throws Exception + { + Options opts = new Options(); + opts.addOption(OptionBuilder.isRequired().create("f")); + + Properties properties = new Properties(); + properties.setProperty("f", "true"); + + CommandLine cmd = parse(parser, opts, null, properties); + assertTrue(cmd.hasOption("f")); + } } From 324b7f901b91614927926a5bab1d9e0e2325f018 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Thu, 17 Jun 2010 07:57:38 +0000 Subject: [PATCH 0181/1663] Fixed the bugs with the default options and the option groups (CLI-203 and CLI-204) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@955501 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/DefaultParser.java | 14 ++++-- .../java/org/apache/commons/cli/Parser.java | 16 +++++-- .../apache/commons/cli/OptionGroupTest.java | 16 ++++++- .../apache/commons/cli/ParserTestCase.java | 43 +++++++++++++++++++ 4 files changed, 81 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/DefaultParser.java b/src/main/java/org/apache/commons/cli/DefaultParser.java index f82308116..2f957b147 100644 --- a/src/main/java/org/apache/commons/cli/DefaultParser.java +++ b/src/main/java/org/apache/commons/cli/DefaultParser.java @@ -147,10 +147,18 @@ private void handleProperties(Properties properties) throws ParseException { String option = e.nextElement().toString(); - if (!cmd.hasOption(option)) + Option opt = options.getOption(option); + if (opt == null) + { + throw new UnrecognizedOptionException("Default option wasn't defined", option); + } + + // if the option is part of a group, check if another option of the group has been selected + OptionGroup group = options.getOptionGroup(opt); + boolean selected = group != null && group.getSelected() != null; + + if (!cmd.hasOption(option) && !selected) { - Option opt = options.getOption(option); - // get the value from the properties String value = properties.getProperty(option); diff --git a/src/main/java/org/apache/commons/cli/Parser.java b/src/main/java/org/apache/commons/cli/Parser.java index eecfb8210..ba4b6bc68 100644 --- a/src/main/java/org/apache/commons/cli/Parser.java +++ b/src/main/java/org/apache/commons/cli/Parser.java @@ -259,11 +259,19 @@ protected void processProperties(Properties properties) throws ParseException for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) { String option = e.nextElement().toString(); - - if (!cmd.hasOption(option)) + + Option opt = options.getOption(option); + if (opt == null) + { + throw new UnrecognizedOptionException("Default option wasn't defined", option); + } + + // if the option is part of a group, check if another option of the group has been selected + OptionGroup group = options.getOptionGroup(opt); + boolean selected = group != null && group.getSelected() != null; + + if (!cmd.hasOption(option) && !selected) { - Option opt = getOptions().getOption(option); - // get the value from the properties instance String value = properties.getProperty(option); diff --git a/src/test/java/org/apache/commons/cli/OptionGroupTest.java b/src/test/java/org/apache/commons/cli/OptionGroupTest.java index eea69eea7..dfcd0f435 100644 --- a/src/test/java/org/apache/commons/cli/OptionGroupTest.java +++ b/src/test/java/org/apache/commons/cli/OptionGroupTest.java @@ -17,6 +17,8 @@ package org.apache.commons.cli; +import java.util.Properties; + import junit.framework.TestCase; /** @@ -26,7 +28,7 @@ public class OptionGroupTest extends TestCase { private Options _options = null; - private CommandLineParser parser = new PosixParser(); + private Parser parser = new PosixParser(); public void setUp() { @@ -186,6 +188,18 @@ public void testTwoOptionsFromDifferentGroup() throws Exception assertTrue( "Confirm NO extra args", cl.getArgList().size() == 0); } + public void testTwoOptionsFromGroupWithProperties() throws Exception + { + String[] args = new String[] { "-f" }; + + Properties properties = new Properties(); + properties.put("d", "true"); + + CommandLine cl = parser.parse( _options, args, properties); + assertTrue(cl.hasOption("f")); + assertTrue(!cl.hasOption("d")); + } + public void testValidLongOnlyOptions() throws Exception { CommandLine cl1 = parser.parse(_options, new String[]{"--export"}); diff --git a/src/test/java/org/apache/commons/cli/ParserTestCase.java b/src/test/java/org/apache/commons/cli/ParserTestCase.java index effebdb15..c996fcb40 100644 --- a/src/test/java/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/java/org/apache/commons/cli/ParserTestCase.java @@ -998,4 +998,47 @@ public void testPropertyOptionRequired() throws Exception CommandLine cmd = parse(parser, opts, null, properties); assertTrue(cmd.hasOption("f")); } + + public void testPropertyOptionUnexpected() throws Exception + { + Options opts = new Options(); + + Properties properties = new Properties(); + properties.setProperty("f", "true"); + + try { + parse(parser, opts, null, properties); + fail("UnrecognizedOptionException expected"); + } catch (UnrecognizedOptionException e) { + // expected + } + } + + public void testPropertyOptionGroup() throws Exception + { + Options opts = new Options(); + + OptionGroup group1 = new OptionGroup(); + group1.addOption(new Option("a", null)); + group1.addOption(new Option("b", null)); + opts.addOptionGroup(group1); + + OptionGroup group2 = new OptionGroup(); + group2.addOption(new Option("x", null)); + group2.addOption(new Option("y", null)); + opts.addOptionGroup(group2); + + String[] args = new String[] { "-a" }; + + Properties properties = new Properties(); + properties.put("b", "true"); + properties.put("x", "true"); + + CommandLine cmd = parse(parser, opts, args, properties); + + assertTrue(cmd.hasOption("a")); + assertFalse(cmd.hasOption("b")); + assertTrue(cmd.hasOption("x")); + assertFalse(cmd.hasOption("y")); + } } From 4381ba54c845402f18760fb04ff1f6db1922f6b2 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Sat, 19 Jun 2010 22:01:51 +0000 Subject: [PATCH 0182/1663] Ensure the consistency of the fields initial values in OptionBuilder before and after the creation of an option (fixes CLI-186) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@956302 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/OptionBuilder.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/OptionBuilder.java b/src/main/java/org/apache/commons/cli/OptionBuilder.java index ca8fbe243..33a24a6d5 100644 --- a/src/main/java/org/apache/commons/cli/OptionBuilder.java +++ b/src/main/java/org/apache/commons/cli/OptionBuilder.java @@ -57,6 +57,12 @@ public final class OptionBuilder /** option builder instance */ private static OptionBuilder instance = new OptionBuilder(); + static + { + // ensure the consistency of the initial values + reset(); + } + /** * private constructor to prevent instances being created */ @@ -76,9 +82,6 @@ private static void reset() type = null; required = false; numberOfArgs = Option.UNINITIALIZED; - - - // PMM 9/6/02 - these were missing optionalArg = false; valuesep = (char) 0; } From 4d2c8a22d1e1831858029b8ef225a07f4445a221 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Sat, 19 Jun 2010 22:06:00 +0000 Subject: [PATCH 0183/1663] The default argument name displayed is now properly controlled by the help formatter (CLI-205) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@956303 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/HelpFormatter.java | 20 ++++++++++--------- .../java/org/apache/commons/cli/Option.java | 8 +++----- .../org/apache/commons/cli/OptionBuilder.java | 2 +- .../apache/commons/cli/HelpFormatterTest.java | 16 +++++++++++++++ 4 files changed, 31 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java index 52ade639a..6d73237d6 100644 --- a/src/main/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java @@ -648,14 +648,14 @@ private void appendOption(final StringBuffer buff, final Option option, final bo { buff.append("--").append(option.getLongOpt()); } - - // if the Option has a value - if (option.hasArg() && option.hasArgName()) + + // if the Option has a value and a non blank argname + if (option.hasArg() && (option.getArgName() == null || option.getArgName().length() != 0)) { buff.append(option.getOpt() == null ? longOptSeparator : " "); - buff.append("<").append(option.getArgName()).append(">"); + buff.append("<").append(option.getArgName() != null ? option.getArgName() : getArgName()).append(">"); } - + // if the Option is not a required option if (!required) { @@ -781,14 +781,16 @@ protected StringBuffer renderOptions(StringBuffer sb, int width, Options options if (option.hasArg()) { - if (option.hasArgName()) + String argName = option.getArgName(); + if (argName != null && argName.length() == 0) { - optBuf.append(option.hasLongOpt() ? longOptSeparator : " "); - optBuf.append("<").append(option.getArgName()).append(">"); + // if the option has a blank argname + optBuf.append(' '); } else { - optBuf.append(' '); + optBuf.append(option.hasLongOpt() ? longOptSeparator : " "); + optBuf.append("<").append(argName != null ? option.getArgName() : getArgName()).append(">"); } } diff --git a/src/main/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java index e4c416888..ce12780a3 100644 --- a/src/main/java/org/apache/commons/cli/Option.java +++ b/src/main/java/org/apache/commons/cli/Option.java @@ -54,7 +54,7 @@ public class Option implements Cloneable, Serializable private String longOpt; /** the name of the argument for this option */ - private String argName = "arg"; + private String argName; /** description of the option */ private String description; @@ -319,11 +319,9 @@ public String getArgName() } /** - * Returns whether the display name for the argument value - * has been set. + * Returns whether the display name for the argument value has been set. * - * @return if the display name for the argument value has been - * set. + * @return if the display name for the argument value has been set. */ public boolean hasArgName() { diff --git a/src/main/java/org/apache/commons/cli/OptionBuilder.java b/src/main/java/org/apache/commons/cli/OptionBuilder.java index 33a24a6d5..a22d829a2 100644 --- a/src/main/java/org/apache/commons/cli/OptionBuilder.java +++ b/src/main/java/org/apache/commons/cli/OptionBuilder.java @@ -77,7 +77,7 @@ private OptionBuilder() private static void reset() { description = null; - argName = "arg"; + argName = null; longopt = null; type = null; required = false; diff --git a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java index eae437e79..1fb36a9dc 100644 --- a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java +++ b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java @@ -305,6 +305,22 @@ public void testPrintOptionWithEmptyArgNameUsage() assertEquals("usage: app -f" + EOL, out.toString()); } + public void testDefaultArgName() + { + Option option = OptionBuilder.hasArg().isRequired().create("f"); + + Options options = new Options(); + options.addOption(option); + + StringWriter out = new StringWriter(); + + HelpFormatter formatter = new HelpFormatter(); + formatter.setArgName("argument"); + formatter.printUsage(new PrintWriter(out), 80, "app", options); + + assertEquals("usage: app -f " + EOL, out.toString()); + } + public void testRtrim() { HelpFormatter formatter = new HelpFormatter(); From 83770d84c972bd879aa001c491e9a7fea843d209 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Sun, 20 Jun 2010 23:03:22 +0000 Subject: [PATCH 0184/1663] Split of testPrintWrapped() into smaller test methods git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@956426 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli/HelpFormatterTest.java | 113 +++++++++++------- 1 file changed, 73 insertions(+), 40 deletions(-) diff --git a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java index 1fb36a9dc..5fd856e2e 100644 --- a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java +++ b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java @@ -40,57 +40,90 @@ public void testFindWrapPos() throws Exception HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; - //text width should be max 8; the wrap position is 7 + // text width should be max 8; the wrap position is 7 assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0)); - //starting from 8 must give -1 - the wrap pos is after end + + // starting from 8 must give -1 - the wrap pos is after end assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8)); - //if there is no a good position before width to make a wrapping look for the next one + + // if there is no a good position before width to make a wrapping look for the next one text = "aaaa aa"; assertEquals("wrap position 3", 4, hf.findWrapPos(text, 3, 0)); } - public void testPrintWrapped() throws Exception + public void testRenderWrappedTextSingleLine() { - StringBuffer sb = new StringBuffer(); - HelpFormatter hf = new HelpFormatter(); - + // single line text + int width = 12; + int padding = 0; String text = "This is a test."; - - String expected = "This is a" + hf.getNewLine() + "test."; - hf.renderWrappedText(sb, 12, 0, text); + String expected = "This is a" + EOL + + "test."; + + StringBuffer sb = new StringBuffer(); + new HelpFormatter().renderWrappedText(sb, width, padding, text); assertEquals("single line text", expected, sb.toString()); + } - sb.setLength(0); - expected = "This is a" + hf.getNewLine() + " test."; - hf.renderWrappedText(sb, 12, 4, text); + public void testRenderWrappedTextSingleLinePadded() + { + // single line padded text + int width = 12; + int padding = 4; + String text = "This is a test."; + String expected = "This is a" + EOL + + " test."; + + StringBuffer sb = new StringBuffer(); + new HelpFormatter().renderWrappedText(sb, width, padding, text); assertEquals("single line padded text", expected, sb.toString()); + } - text = " -p,--period PERIOD is time duration of form " + - "DATE[-DATE] where DATE has form YYYY[MM[DD]]"; - - sb.setLength(0); - expected = " -p,--period PERIOD is time duration of" + - hf.getNewLine() + - " form DATE[-DATE] where DATE" + - hf.getNewLine() + - " has form YYYY[MM[DD]]"; - hf.renderWrappedText(sb, 53, 24, text); + public void testRenderWrappedTextSingleLinePadded2() + { + // single line padded text 2 + int width = 53; + int padding = 24; + String text = " -p,--period PERIOD is time duration of form " + + "DATE[-DATE] where DATE has form YYYY[MM[DD]]"; + String expected = " -p,--period PERIOD is time duration of" + EOL + + " form DATE[-DATE] where DATE" + EOL + + " has form YYYY[MM[DD]]"; + + StringBuffer sb = new StringBuffer(); + new HelpFormatter().renderWrappedText(sb, width, padding, text); assertEquals("single line padded text 2", expected, sb.toString()); + } - text = "aaaa aaaa aaaa" + hf.getNewLine() + - "aaaaaa" + hf.getNewLine() + - "aaaaa"; - - expected = text; - sb.setLength(0); - hf.renderWrappedText(sb, 16, 0, text); + public void testRenderWrappedTextMultiLine() + { + // multi line text + int width = 16; + int padding = 0; + String text = "aaaa aaaa aaaa" + EOL + + "aaaaaa" + EOL + + "aaaaa"; + String expected = text; + + StringBuffer sb = new StringBuffer(); + new HelpFormatter().renderWrappedText(sb, width, padding, text); assertEquals("multi line text", expected, sb.toString()); + } - expected = "aaaa aaaa aaaa" + hf.getNewLine() + - " aaaaaa" + hf.getNewLine() + - " aaaaa"; - sb.setLength(0); - hf.renderWrappedText(sb, 16, 4, text); + public void testRenderWrappedTextMultiLinePadded() + { + // multi-line padded text + int width = 16; + int padding = 4; + String text = "aaaa aaaa aaaa" + EOL + + "aaaaaa" + EOL + + "aaaaa"; + String expected = "aaaa aaaa aaaa" + EOL + + " aaaaaa" + EOL + + " aaaaa"; + + StringBuffer sb = new StringBuffer(); + new HelpFormatter().renderWrappedText(sb, width, padding, text); assertEquals("multi-line padded text", expected, sb.toString()); } @@ -111,7 +144,7 @@ public void testPrintOptions() throws Exception assertEquals("simple non-wrapped option", expected, sb.toString()); int nextLineTabStop = leftPad + descPad + "-a".length(); - expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + hf.getNewLine() + + expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + EOL + hf.createPadding(nextLineTabStop) + "aaaa aaaa"; sb.setLength(0); hf.renderOptions(sb, nextLineTabStop + 17, options, leftPad, descPad); @@ -125,7 +158,7 @@ public void testPrintOptions() throws Exception assertEquals("long non-wrapped option", expected, sb.toString()); nextLineTabStop = leftPad + descPad + "-a,--aaa".length(); - expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + + expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL + hf.createPadding(nextLineTabStop) + "dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); @@ -134,9 +167,9 @@ public void testPrintOptions() throws Exception options = new Options(). addOption("a", "aaa", false, "dddd dddd dddd dddd"). addOption("b", false, "feeee eeee eeee eeee"); - expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + - hf.createPadding(nextLineTabStop) + "dddd dddd" + hf.getNewLine() + - lpad + "-b " + dpad + "feeee eeee" + hf.getNewLine() + + expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL + + hf.createPadding(nextLineTabStop) + "dddd dddd" + EOL + + lpad + "-b " + dpad + "feeee eeee" + EOL + hf.createPadding(nextLineTabStop) + "eeee eeee"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); From dd1fd38c378836ebc7869d475c84725339c221b4 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Tue, 22 Jun 2010 12:50:09 +0000 Subject: [PATCH 0185/1663] Tab police git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@956864 13f79535-47bb-0310-9956-ffa450edef68 --- src/test/java/org/apache/commons/cli/ParserTestCase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/apache/commons/cli/ParserTestCase.java b/src/test/java/org/apache/commons/cli/ParserTestCase.java index c996fcb40..064da250b 100644 --- a/src/test/java/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/java/org/apache/commons/cli/ParserTestCase.java @@ -761,7 +761,7 @@ public void testOptionGroupLong() throws Exception public void testReuseOptionsTwice() throws Exception { Options opts = new Options(); - opts.addOption(OptionBuilder.isRequired().create('v')); + opts.addOption(OptionBuilder.isRequired().create('v')); // first parsing parser.parse(opts, new String[] { "-v" }); From 23df383408513eddaf3e6dc4244c89fd48427695 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 7 Jul 2010 12:55:18 +0000 Subject: [PATCH 0186/1663] Simplified the createPadding() method git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@961361 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/HelpFormatter.java | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java index 6d73237d6..91a01d9d5 100644 --- a/src/main/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java @@ -19,6 +19,7 @@ import java.io.PrintWriter; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; @@ -860,8 +861,7 @@ protected StringBuffer renderWrappedText(StringBuffer sb, int width, nextLineTabStop = 1; } - // all following lines must be padded with nextLineTabStop space - // characters + // all following lines must be padded with nextLineTabStop space characters final String padding = createPadding(nextLineTabStop); while (true) @@ -888,7 +888,7 @@ protected StringBuffer renderWrappedText(StringBuffer sb, int width, /** * Finds the next text wrap position after startPos for the * text in text with the column width width. - * The wrap point is the last postion before startPos+width having a + * The wrap point is the last position before startPos+width having a * whitespace character (space, \n, \r). * * @param text The text being searched for the wrap position @@ -953,14 +953,10 @@ else if (startPos + width >= text.length()) */ protected String createPadding(int len) { - StringBuffer sb = new StringBuffer(len); - - for (int i = 0; i < len; ++i) - { - sb.append(' '); - } - - return sb.toString(); + char[] padding = new char[len]; + Arrays.fill(padding, ' '); + + return new String(padding); } /** From 777cb81088d47472df21a452edd5ba568d4b3fdf Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 7 Jul 2010 13:48:12 +0000 Subject: [PATCH 0187/1663] Ensure the wrap width is never exceeded and cut the words longer that the width if necessary (CLI-193) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@961374 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/HelpFormatter.java | 20 ++++++----------- .../apache/commons/cli/HelpFormatterTest.java | 22 +++++++++++++++++-- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java index 91a01d9d5..7d8a901de 100644 --- a/src/main/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java @@ -889,7 +889,8 @@ protected StringBuffer renderWrappedText(StringBuffer sb, int width, * Finds the next text wrap position after startPos for the * text in text with the column width width. * The wrap point is the last position before startPos+width having a - * whitespace character (space, \n, \r). + * whitespace character (space, \n, \r). If there is no whitespace character + * before startPos+width, it will return startPos+width. * * @param text The text being searched for the wrap position * @param width width of the wrapped text @@ -900,8 +901,8 @@ protected StringBuffer renderWrappedText(StringBuffer sb, int width, */ protected int findWrapPos(String text, int width, int startPos) { - int pos = -1; - + int pos; + // the line ends before the max wrap pos or a new line char found if (((pos = text.indexOf('\n', startPos)) != -1 && pos <= width) || ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width)) @@ -931,17 +932,10 @@ else if (startPos + width >= text.length()) return pos; } - // must look for the first whitespace chearacter after startPos - // + width + // if we didn't find one, simply chop at startPos+width pos = startPos + width; - - while ((pos <= text.length()) && ((c = text.charAt(pos)) != ' ') - && (c != '\n') && (c != '\r')) - { - ++pos; - } - - return (pos == text.length()) ? (-1) : pos; + + return pos == text.length() ? -1 : pos; } /** diff --git a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java index 5fd856e2e..562c82960 100644 --- a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java +++ b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java @@ -46,9 +46,27 @@ public void testFindWrapPos() throws Exception // starting from 8 must give -1 - the wrap pos is after end assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8)); - // if there is no a good position before width to make a wrapping look for the next one + // words longer than the width are cut text = "aaaa aa"; - assertEquals("wrap position 3", 4, hf.findWrapPos(text, 3, 0)); + assertEquals("wrap position 3", 3, hf.findWrapPos(text, 3, 0)); + + // last word length is equal to the width + text = "aaaaaa aaaaaa"; + assertEquals("wrap position 4", 6, hf.findWrapPos(text, 6, 0)); + assertEquals("wrap position 4", -1, hf.findWrapPos(text, 6, 7)); + } + + public void testRenderWrappedTextWordCut() + { + int width = 7; + int padding = 0; + String text = "Thisisatest."; + String expected = "Thisisa" + EOL + + "test."; + + StringBuffer sb = new StringBuffer(); + new HelpFormatter().renderWrappedText(sb, width, padding, text); + assertEquals("cut and wrap", expected, sb.toString()); } public void testRenderWrappedTextSingleLine() From b61751f56e924dee1aa967eab3793011ac972f07 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 7 Jul 2010 14:21:10 +0000 Subject: [PATCH 0188/1663] Updated the assembly descriptors git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@961387 13f79535-47bb-0310-9956-ffa450edef68 --- src/assembly/bin.xml | 2 +- src/assembly/src.xml | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/assembly/bin.xml b/src/assembly/bin.xml index 576229197..2dfa532a2 100644 --- a/src/assembly/bin.xml +++ b/src/assembly/bin.xml @@ -31,7 +31,7 @@ target - + *.jar diff --git a/src/assembly/src.xml b/src/assembly/src.xml index fc31b07f2..3294ba3a6 100644 --- a/src/assembly/src.xml +++ b/src/assembly/src.xml @@ -24,10 +24,6 @@ - build.xml - build.properties - CLI2Converter.java - CLI2ConverterTest.java LICENSE.txt NOTICE.txt pom.xml From 0004b2768b9fd1a2cf7d4dc68970de5729ffeaae Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 7 Jul 2010 14:36:46 +0000 Subject: [PATCH 0189/1663] Updated the current revision in the javadoc git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@961391 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/overview.html | 2 +- src/main/java/org/apache/commons/cli/package.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/overview.html b/src/main/java/org/apache/commons/cli/overview.html index eec9ce72c..3eab8062a 100644 --- a/src/main/java/org/apache/commons/cli/overview.html +++ b/src/main/java/org/apache/commons/cli/overview.html @@ -16,7 +16,7 @@ --> -

      Commons CLI -- version 1.2

      +

      Commons CLI -- version 1.3

      The commons-cli package aides in parsing command-line arguments.

      diff --git a/src/main/java/org/apache/commons/cli/package.html b/src/main/java/org/apache/commons/cli/package.html index 20ebdde95..6040bdd9f 100644 --- a/src/main/java/org/apache/commons/cli/package.html +++ b/src/main/java/org/apache/commons/cli/package.html @@ -16,6 +16,6 @@ --> - Commons CLI 1.2 + Commons CLI 1.3 From 99222749ca9b0d9338ed5df796db9c32b82424b8 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 7 Jul 2010 14:39:27 +0000 Subject: [PATCH 0190/1663] Changed the links to the javadoc from the site documentation, the target directory is now independent from the version git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@961393 13f79535-47bb-0310-9956-ffa450edef68 --- src/site/xdoc/introduction.xml | 8 ++++---- src/site/xdoc/properties.xml | 4 ++-- src/site/xdoc/usage.xml | 16 ++++++++-------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/site/xdoc/introduction.xml b/src/site/xdoc/introduction.xml index 0557d37a1..84d5f1499 100644 --- a/src/site/xdoc/introduction.xml +++ b/src/site/xdoc/introduction.xml @@ -39,9 +39,9 @@ to define the interface to the application.

      - CLI uses the + CLI uses the Options class, as a container for - + Option instances. There are two ways to create Options in CLI. One of them is via the constructors, the other way is via the factory methods defined in @@ -66,11 +66,11 @@

      The parse method defined on - + CommandLineParser takes an Options instance and a String[] of arguments and returns a - + CommandLine.

      diff --git a/src/site/xdoc/properties.xml b/src/site/xdoc/properties.xml index 2976747ac..e24b79f17 100644 --- a/src/site/xdoc/properties.xml +++ b/src/site/xdoc/properties.xml @@ -28,10 +28,10 @@

      The following are the properties that each - Option has. All of these + Option has. All of these can be set using the accessors or using the methods defined in the - OptionBuilder. + OptionBuilder.

      diff --git a/src/site/xdoc/usage.xml b/src/site/xdoc/usage.xml index 5f282c1b8..85f9b895a 100644 --- a/src/site/xdoc/usage.xml +++ b/src/site/xdoc/usage.xml @@ -45,7 +45,7 @@

      - An + An Options object must be created and the Option must be added to it.

      @@ -78,7 +78,7 @@ CommandLine cmd = parser.parse( options, args);

      Now we need to check if the t option is present. To do this we will interrogate the - CommandLine + CommandLine object. The hasOption method takes a java.lang.String parameter and returns true if the option represented by the java.lang.String is present, otherwise @@ -212,11 +212,11 @@ Option find = OptionBuilder.withArgName( "file" )

      Now that we have created each - Option we need + Option we need to create the - Options + Options instance. This is achieved using the - addOption + addOption method of Options.

      Options options = new Options(); @@ -243,7 +243,7 @@ options.addOption( property );

      We now need to create a CommandLineParser. This will parse the command line arguments, using the rules specified by the Options and - return an instance of CommandLine. + return an instance of CommandLine.

      public static void main( String[] args ) { // create the parser @@ -274,7 +274,7 @@ if( line.hasOption( "buildfile" ) ) {

      CLI also provides the means to automatically generate usage and help information. This is achieved with the - HelpFormatter + HelpFormatter class.

      // automatically generate the help statement @@ -328,7 +328,7 @@ Sort entries alphabetically if none of -cftuSUX nor --sort. -C list entries by columns

      The following is the code that is used to create the - Options for this example. + Options for this example.

      // create the command line parser CommandLineParser parser = new DefaultParser(); From 483f811dfefdc6bee162481425f261d983f15e4a Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 21 Jul 2010 16:40:40 +0000 Subject: [PATCH 0191/1663] Indented lines in the header and footer are now preserved (CLI-207) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@966306 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/HelpFormatter.java | 34 ++++++++++++++++++- .../apache/commons/cli/HelpFormatterTest.java | 20 +++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java index 7d8a901de..4329a8bdc 100644 --- a/src/main/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java @@ -17,7 +17,10 @@ package org.apache.commons.cli; +import java.io.BufferedReader; +import java.io.IOException; import java.io.PrintWriter; +import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -724,7 +727,7 @@ public void printWrapped(PrintWriter pw, int width, int nextLineTabStop, String { StringBuffer sb = new StringBuffer(text.length()); - renderWrappedText(sb, width, nextLineTabStop, text); + renderWrappedTextBlock(sb, width, nextLineTabStop, text); pw.println(sb.toString()); } @@ -885,6 +888,35 @@ protected StringBuffer renderWrappedText(StringBuffer sb, int width, } } + /** + * Render the specified text width a maximum width. This method differs + * from renderWrappedText by not removing leading spaces after a new line. + * + * @param sb The StringBuffer to place the rendered text into. + * @param width The number of characters to display per line + * @param nextLineTabStop The position on the next line for the first tab. + * @param text The text to be rendered. + */ + private StringBuffer renderWrappedTextBlock(StringBuffer sb, int width, int nextLineTabStop, String text) { + try { + BufferedReader in = new BufferedReader(new StringReader(text)); + String line; + boolean firstLine = true; + while ((line = in.readLine()) != null) { + if (!firstLine) { + sb.append(getNewLine()); + } else { + firstLine = false; + } + renderWrappedText(sb, width, nextLineTabStop, line); + } + } catch (IOException e) { + // cannot happen + } + + return sb; + } + /** * Finds the next text wrap position after startPos for the * text in text with the column width width. diff --git a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java index 562c82960..02a6adf9e 100644 --- a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java +++ b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java @@ -428,6 +428,26 @@ public void testHeaderStartingWithLineSeparator() , out.toString()); } + public void testIndentedHeaderAndFooter() + { + // related to CLI-207 + Options options = new Options(); + HelpFormatter formatter = new HelpFormatter(); + String header = " Header1\n Header2"; + String footer = " Footer1\n Footer2"; + StringWriter out = new StringWriter(); + formatter.printHelp(new PrintWriter(out), 80, "foobar", header, options, 2, 2, footer, true); + + assertEquals( + "usage: foobar" + EOL + + " Header1" + EOL + + " Header2" + EOL + + "" + EOL + + " Footer1" + EOL + + " Footer2" + EOL + , out.toString()); + } + public void testOptionWithoutShortFormat() { // related to Bugzilla #19383 (CLI-67) From 3d57a495145916d1cd183cced771935c06da786a Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 21 Jul 2010 16:49:25 +0000 Subject: [PATCH 0192/1663] Removed the direct usage of the deprecated fields in HelpFormatter git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@966310 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/HelpFormatter.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java index 4329a8bdc..e44c71950 100644 --- a/src/main/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java @@ -367,7 +367,7 @@ public void setOptionComparator(Comparator comparator) */ public void printHelp(String cmdLineSyntax, Options options) { - printHelp(defaultWidth, cmdLineSyntax, null, options, null, false); + printHelp(getWidth(), cmdLineSyntax, null, options, null, false); } /** @@ -382,7 +382,7 @@ public void printHelp(String cmdLineSyntax, Options options) */ public void printHelp(String cmdLineSyntax, Options options, boolean autoUsage) { - printHelp(defaultWidth, cmdLineSyntax, null, options, null, autoUsage); + printHelp(getWidth(), cmdLineSyntax, null, options, null, autoUsage); } /** @@ -414,7 +414,7 @@ public void printHelp(String cmdLineSyntax, String header, Options options, Stri */ public void printHelp(String cmdLineSyntax, String header, Options options, String footer, boolean autoUsage) { - printHelp(defaultWidth, cmdLineSyntax, header, options, footer, autoUsage); + printHelp(getWidth(), cmdLineSyntax, header, options, footer, autoUsage); } /** @@ -451,7 +451,7 @@ public void printHelp(int width, String cmdLineSyntax, String header, { PrintWriter pw = new PrintWriter(System.out); - printHelp(pw, width, cmdLineSyntax, header, options, defaultLeftPad, defaultDescPad, footer, autoUsage); + printHelp(pw, width, cmdLineSyntax, header, options, getLeftPadding(), getDescPadding(), footer, autoUsage); pw.flush(); } @@ -541,7 +541,7 @@ public void printHelp(PrintWriter pw, int width, String cmdLineSyntax, public void printUsage(PrintWriter pw, int width, String app, Options options) { // initialise the string buffer - StringBuffer buff = new StringBuffer(defaultSyntaxPrefix).append(app).append(" "); + StringBuffer buff = new StringBuffer(getSyntaxPrefix()).append(app).append(" "); // create a list for processed option groups final Collection processedGroups = new ArrayList(); @@ -679,7 +679,7 @@ public void printUsage(PrintWriter pw, int width, String cmdLineSyntax) { int argPos = cmdLineSyntax.indexOf(' ') + 1; - printWrapped(pw, width, defaultSyntaxPrefix.length() + argPos, defaultSyntaxPrefix + cmdLineSyntax); + printWrapped(pw, width, getSyntaxPrefix().length() + argPos, getSyntaxPrefix() + cmdLineSyntax); } /** @@ -771,15 +771,15 @@ protected StringBuffer renderOptions(StringBuffer sb, int width, Options options if (option.getOpt() == null) { - optBuf.append(lpad).append(" " + defaultLongOptPrefix).append(option.getLongOpt()); + optBuf.append(lpad).append(" ").append(getLongOptPrefix()).append(option.getLongOpt()); } else { - optBuf.append(lpad).append(defaultOptPrefix).append(option.getOpt()); + optBuf.append(lpad).append(getOptPrefix()).append(option.getOpt()); if (option.hasLongOpt()) { - optBuf.append(',').append(defaultLongOptPrefix).append(option.getLongOpt()); + optBuf.append(',').append(getLongOptPrefix()).append(option.getLongOpt()); } } @@ -827,7 +827,7 @@ protected StringBuffer renderOptions(StringBuffer sb, int width, Options options if (i.hasNext()) { - sb.append(defaultNewLine); + sb.append(getNewLine()); } } @@ -856,7 +856,7 @@ protected StringBuffer renderWrappedText(StringBuffer sb, int width, return sb; } - sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); + sb.append(rtrim(text.substring(0, pos))).append(getNewLine()); if (nextLineTabStop >= width) { @@ -884,7 +884,7 @@ protected StringBuffer renderWrappedText(StringBuffer sb, int width, pos = width; } - sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); + sb.append(rtrim(text.substring(0, pos))).append(getNewLine()); } } From b88c9ba0b2c8a8a21862d405bf24098f7037dbed Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 19 Sep 2010 00:46:00 +0000 Subject: [PATCH 0193/1663] Fixing javadoc for isRequired per CLI-208 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@998575 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/Option.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java index ce12780a3..c7d9cebdb 100644 --- a/src/main/java/org/apache/commons/cli/Option.java +++ b/src/main/java/org/apache/commons/cli/Option.java @@ -279,9 +279,9 @@ public void setDescription(String description) } /** - * Query to see if this Option requires an argument + * Query to see if this Option is mandatory * - * @return boolean flag indicating if an argument is required + * @return boolean flag indicating whether this Option is mandatory */ public boolean isRequired() { From 0ef85fe1117d2b0c8a74558d811c30e8ceb9be62 Mon Sep 17 00:00:00 2001 From: Niall Kegan Pemberton Date: Wed, 6 Oct 2010 16:38:08 +0000 Subject: [PATCH 0194/1663] COMMONSSITE-57 Fix announce mod_mbox link (I used version 1.4-SNAPSHOT of the commons-build-plugin to do this - need to release it and update commons-parent at some point) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1005115 13f79535-47bb-0310-9956-ffa450edef68 --- src/site/xdoc/mail-lists.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/site/xdoc/mail-lists.xml b/src/site/xdoc/mail-lists.xml index 40ed1d13e..cfc89fdb8 100644 --- a/src/site/xdoc/mail-lists.xml +++ b/src/site/xdoc/mail-lists.xml @@ -188,7 +188,7 @@ limitations under the License.
      - + * * - * - * + * + * * * *
      Subscribe Unsubscribe read onlymail-archives.apache.orgmail-archives.apache.org markmail.org
      old.nabble.com
      www.mail-archive.com
      From 4eb17f5ab2ee09cc00f4ce4d2e26cc7ddffa8cc9 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Fri, 29 Oct 2010 10:23:33 +0000 Subject: [PATCH 0195/1663] Added a note about the thread safety in OptionBuilder (CLI-209) git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1028667 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/OptionBuilder.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/apache/commons/cli/OptionBuilder.java b/src/main/java/org/apache/commons/cli/OptionBuilder.java index a22d829a2..7a9972292 100644 --- a/src/main/java/org/apache/commons/cli/OptionBuilder.java +++ b/src/main/java/org/apache/commons/cli/OptionBuilder.java @@ -24,6 +24,8 @@ * * http://c2.com/cgi-bin/wiki?BuilderPattern.

      * + *

      This class is NOT thread safe. If several thread were to use this class they must be synchronized.

      + * * @author John Keyes (john at integralsource.com) * @version $Revision$, $Date$ * @since 1.0 From 1f19ed708f7812b614c3a1245d2cd62b82c1999b Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Fri, 29 Oct 2010 12:08:20 +0000 Subject: [PATCH 0196/1663] Synchronising access is not sufficient to make the class thread safe. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1028709 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/OptionBuilder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/cli/OptionBuilder.java b/src/main/java/org/apache/commons/cli/OptionBuilder.java index 7a9972292..5cae375f2 100644 --- a/src/main/java/org/apache/commons/cli/OptionBuilder.java +++ b/src/main/java/org/apache/commons/cli/OptionBuilder.java @@ -24,7 +24,7 @@ * * http://c2.com/cgi-bin/wiki?BuilderPattern.

      * - *

      This class is NOT thread safe. If several thread were to use this class they must be synchronized.

      + *

      This class is NOT thread safe. See CLI-209

      * * @author John Keyes (john at integralsource.com) * @version $Revision$, $Date$ From 5de96d7ca64e24990ceafd811f046706f689a8f3 Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Fri, 29 Oct 2010 14:22:34 +0000 Subject: [PATCH 0197/1663] Changed the accessibility of the CommandLine constructor to allow custom parsers to be implemented outside of the org.apache.commons.cli package git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1028757 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/CommandLine.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java index 9cd1b9d06..667ea4319 100644 --- a/src/main/java/org/apache/commons/cli/CommandLine.java +++ b/src/main/java/org/apache/commons/cli/CommandLine.java @@ -54,7 +54,7 @@ public class CommandLine implements Serializable /** * Creates a command line. */ - CommandLine() + protected CommandLine() { // nothing to do } @@ -344,7 +344,7 @@ public String toString() { * * @param arg the unrecognised option/argument. */ - void addArg(String arg) + protected void addArg(String arg) { args.add(arg); } @@ -354,7 +354,7 @@ void addArg(String arg) * * @param opt the processed option */ - void addOption(Option opt) + protected void addOption(Option opt) { options.add(opt); } From e3fda7d610c6167790f1edb60e1c00efdd3c6000 Mon Sep 17 00:00:00 2001 From: "Gary D. Gregory" Date: Mon, 31 Jan 2011 21:15:30 +0000 Subject: [PATCH 0198/1663] Copyright git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1065786 13f79535-47bb-0310-9956-ffa450edef68 --- NOTICE.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NOTICE.txt b/NOTICE.txt index 72eb32a90..b3ace17ad 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -1,5 +1,5 @@ Apache Commons CLI -Copyright 2001-2009 The Apache Software Foundation +Copyright 2001-2011 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). From 02431899e5f9d1bd1960f58650435f769705ba1d Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Wed, 23 Feb 2011 20:18:23 +0000 Subject: [PATCH 0199/1663] Removed the null descriptions from the string representation of the option groups git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1073925 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/OptionGroup.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/OptionGroup.java b/src/main/java/org/apache/commons/cli/OptionGroup.java index 5d23c201d..bdf5e3cdd 100644 --- a/src/main/java/org/apache/commons/cli/OptionGroup.java +++ b/src/main/java/org/apache/commons/cli/OptionGroup.java @@ -159,10 +159,13 @@ public String toString() buff.append("--"); buff.append(option.getLongOpt()); } - - buff.append(" "); - buff.append(option.getDescription()); - + + if (option.getDescription() != null) + { + buff.append(" "); + buff.append(option.getDescription()); + } + if (iter.hasNext()) { buff.append(", "); From 6455089c496544a748a71a9a97101a55b59b958c Mon Sep 17 00:00:00 2001 From: "Gary D. Gregory" Date: Wed, 9 Mar 2011 15:59:57 +0000 Subject: [PATCH 0200/1663] Follow branding reqs from http://www.apache.org/foundation/marks/pmcs#graphics git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1079860 13f79535-47bb-0310-9956-ffa450edef68 --- src/{site/resources/images => media}/logo.xcf | Bin 20269 -> 21179 bytes src/site/resources/images/logo.jpg | Bin 5776 -> 0 bytes src/site/resources/images/logo.png | Bin 10153 -> 11003 bytes 3 files changed, 0 insertions(+), 0 deletions(-) rename src/{site/resources/images => media}/logo.xcf (89%) delete mode 100644 src/site/resources/images/logo.jpg diff --git a/src/site/resources/images/logo.xcf b/src/media/logo.xcf similarity index 89% rename from src/site/resources/images/logo.xcf rename to src/media/logo.xcf index fb1cd2b90f815dd587e2ea881d6f73a5ff1f03fe..df9cbda2c250920107cf9e46a32155bd29705cce 100644 GIT binary patch delta 1305 zcmZuwT}TvB6h5PwVj>EeTG`&rY7NJ~hY%mED5!ANT@wjTO}-#KUQ&-r%xw(xXP zxZYL8h-e$I2@rrPnC^+=?db|djSh=yR8nM7iK`*xc!5A(!%S&1Gh&(=YAp4Jm7$mx zi!-ln#JCcaSZi~uy*6;#oKz!PgB!HE`80FA^$zb%8pG0%sw=F`-3(-EBhul-gsz%Q z)rTUo!TV$3upyhPC*!qOIUOFM+v? zx465elihS`KEQ6z^|B{8T@g^3pJQ){8s><+?})^)%(Q2@ytCznQ?mfukn3-O@B4w< z;q3NuaxK4!ItqynpCLN&AoH=gwyuK8P_YFNfWmwwKk z%#@R+s7Wa~4$79;PA}(J{XkDWMi7qa@J~s);YOmNj>@dVRZ_0RCUb)tR+F;Eha6FL zlWQbpk6c2KmNZo|972{c2dRZ3}_UD6=A&Vh3E)SV%OlO)I$7lW*_^N2uJ6xJ) z6NagVQ%sY?Cc>*)hB|9@IX3ME7izi>1#UP(2>Fygh7=PR` zGP@f1=gZdu;SllQ7w;K|^JkW-t)*^{^=(&^b!&6075D8Q^zY`oVw_F*2?3Ca{|K-M z{3HrMj(oX!e**jk;3@zK`zL`%z%w8VyayJnCEq8j*;i)0?m5sOxV+YmV^ClU8oL49 h10LpoJ}{5`XYhN0C~ywImi;N<5^xQ$tdqT8{sPalC&d5& delta 514 zcmY+BJxBvV5QX1rehi8T;!i|#k%$3FF2N#21O*WyBzI>Fh>*g@&dSCh2o|=2$|4qm zR#6Zv`wX=06iqOmm81v za^oU`G}js6(Sg7X5d8(xZ^5ixpa?oq4fIscIg!6x<2VkFBjS z&R8CA7q6%|^WF&1&0OGwl+4+-bbnG=w`*#Q1D03WXKT;o-Ki-TK&S+SFM&wjtOh?i zlWNhfd1M^1{OUEIbxZ0_O}zsWPr%d!klHpIG5?UWR5MP zV8d7@tw81q&^QRKK(?HE=9Bs#^X;UMgh-6=A}vKYRBcJF&fUv=c5Gg2aHh?p`8B#9 iFnomnW(+%z)-~!`azGvk``2H{EBR(U{f1lCvh{ym?^Z(q diff --git a/src/site/resources/images/logo.jpg b/src/site/resources/images/logo.jpg deleted file mode 100644 index bcb742221707b247a0231d132867f702cc005368..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5776 zcmb7HcT^MKww{m#P)ZWIp;tq10V$!E&=CR%A|-$d2uLpi(t8a>kPgzMNKpi=bWo)C z-lYgiQBV+g_`BD;?qBb%x6iCub7p^guXSdx{mr+}C(joFxR$!6IsgKJ0F8?UoSy;o zD(<)Op11ATd>lOO*^KOOvtc!Lub6qxLX^^xC1Oqz*l9`#6m6e*FgNuWOi;0Dm}0omU!UQP~iz4mcuz9qhBY;&&|ZHh^_Ky>hSqa zBUPr%PM_!gGI$Z4EYWZp2jbOZKibE0c9*p}C;(^2n*Ec;3Dv67*uhm-GS!<7oA-^c zb##8}OX|wWT-xR^)9GT@fWgXAT|B9{EhU&<(mYnf@x~y@vV4f}5yLH!fgKw30fpu@O$NiF)c}zE>l8%9DL3khMo$!Yki}MG0iE z^2s!*>t|pyyZJc~M87wF4!FX)LypK-epNBPaN~Tr{I)E{>bc+RB_UP<9YTnJ_o8zSPr3E%w|<@)MBT4f6}h4g zvAu<8va62Xp=5w_RYk99SZ~VIb2MA4d52jssR=ODjQRqgOBNJ{0-{($ieh^_M96*! z?JKHLw-^lL_QZ0Th7r+;^p;}pA;)+0t@soucqxHe)$yLK-xHkq#nQ9&i+Eam4*cmC8pMB**gp;9`cGF}u$ux1 z`o92({sPqC01@b-$wVOW%4usD0w{ zRhJT1-@~j4tbEniB78bmcgocAr}|>s!)%(WdR~h8WWTc%7D#RCZS?z+j1rQ&E~xHV zw-0$f$&R*%BhyZwzY1cdzljcFow+3EsTD-`u@;nD5kg$b6{I$M5%*S&$}~GkWpeIlwUXb}dYk z#r)%EbOz=sf0|obsAL;V!K~6hj>il4u~mNPbJ;6G9g?TspYL8j{6j-R9ql_m>76f6 z>KbFG@$;B_WhC2AT7ABnMJkJXta`-8x_P;_X_AUQ-w#Z868`KRt}f}?R@D2PNl(T`0 zw2~0aAmd?_@y_fz2c~IXZ=3`CH+eBLx|l6&f|9VH*`#le-`Pj)*O~rV!{QYv{eYb{ zq-Mcxv|m)3Ou6Z9+!1=u{h?1P!78PR{~&Z*a=6Af*n3!+F_mGyyLhO{?0RQ|o~4gZ zfywB{Pz8RItt=0Y=;AD0!Q7b-ozA6M=p^Pn$7GGIS5M|rXLKp2B;$J{`j0hU#=RhS zZ(cCj6)3l(vMZPE+G;c+X!BXef1`CGXeAm@R$rB>e$^XufWS}&jH*oz7cizy!y!mbL@!hMNbCzTzuW9ODAjE1OTqeIf;NJSR)4jUj zYE>7%0~3OuGC4FxvX&0Beuw{-Ygbg25Pz%S>12^j3^nHX25sb(s!kgF2V-t#MSaef zZ2Pq?3o?m5m2DLCJV>+sL8j}**Nr@Qj=KtRwL8k3 ztI8$2S+c0+bvoBFQ2!)S)}dpEO}U=jVL@G6iY=3GwNjcqVDwR~tEbw+Gp*mNs;ozL zgbx24b-RsmSJd?EuBS|0vI#C!E}iL!Zcv3f!E~Bx@-Wa{*3L%ohlA4STfz0>#t>!o zFn|)}tByK*z)Nq5!RMg{wj0}5)qYEz^qH(2Y40A-eW{U(sM{{HU2fAjOiIa%3y@c} zx**jtl1i(n@%6@Yz+LR!kP_GG)+gt@uyf!&w;bJ1w-=6E7P4z3zUA+uSp6zsChuX- zBui2zsYWLJ$}JM zIxuBPPk&%A^Rqlg3F3aWtBR1jzH>k3 z4T+hH>XW;o>fAajOgTNqd$Z>5!CuoY?gg>cK*Hu?rx=p|)|U1uTY|o+)mZ)oq4UBo zgeVb+i1Gwjt?Oe?$))6C=OlUWBV(P6xc7s(G_70d3+%cVVBfN!uai? zHwCG$7?amsr~Mg$fHsH;cltq}W(@L1tUQCQc9%bCf3;0NGXjwf_;o*f=ep!$ zj{WHgiifo+i+-?oKqa5^NilWj zv0%trCNKU_jbuD(rC6E!zSld%cOQvYP0S4ksO_R6(+ar*52rPyd#mO}c*~M0O!P^+ zc-q>R-qeq5X2W0ejcFNcVO&B6bV=*AtC!}FZEyrL3urdA@VvGxeXjgm$=tS5XL?%& z#a$Y3#6pYWgGsQXWvRUFkcgLo7ve}jC^TYxIt6{PWtQoX70TVipzD( zuvWMa>Mi|va1N+yv-*S|KgjnV5VI9=fK|)u3x9H+0HZe+zwP}dXc=;@hO8+~KZA>o z1!Y_Al`IJEzDdPTV3a<&G}3>2T~@_=bpveXxt9ri{)BwB^_G6S zFsE)e^G5FR_vm(6ir_}4Mswm^5xpEjHJu<)oN=|$)U^t%CuWU6v!s5cl%}jg)GRlg zn@xs@tlj*?!#Z`HZ_qjPQk}i{EO=LcE*>;bb?4#t-NrHG_jGwkr-S>G?iH(`#Td=9 zLpNjZP5UP4qldVkrlYsYcgcM*Z#Hs#1CCu{3ejgh3Z@N9%1g*sPM9QXtgDt*2P=ZY zFjd-crc&xXNq*pvgu;t^lv$3>R{Mdo9dU%aeb=DHOJ18ecIvhpHGMi%ma^W`_@L+F z(9RMup^7S=wyd#YmfXgp0rU4kTv7MjbM8qAVP}Py@P&{ve}?!|@bamR$lB-8%=m zFSz2L`Szcg3x1Gl(o9lVU&@uKz`u{*kWm|4X|51K@*SOn(<#2myh? z|CX)@;13nz-9iX(5ye8b>lbu5wDeb>UgSL+RC`q=7cOOS7$38$-(v4&MOn0adKc~I zu^s!6=NyoZuM!q&5|OcmlyxelR;z{eWa-F+T|X@nqEIbD>nnt4E(%g{%OY3}+IxIv ztN5%3vqWHgiyIQGy-)K)meAHL#@(C}o-kSZUEL6aV83?l6pDSS2dl1b$la$&OMzA5 zmQZ@3b^sYJYA~Vv<2Z(eZM5tww3tn;iK`^^*4l`%V`8biPeZiMMuTovlG7!&=;(sP z58jS(U0EGmTi-GfkGSAYisdRyWg|JhssgRtFy*Yr)hKr>Bh6xv zP-whZfzmKCZi=8-X%}-4SkV-GF?Cz9ukUI{Hm2a(+t=gvY_0Et?~H`?*Kuk^F)B%e z)&{L_7#?Rw(|k^o!qUv8R`}b)Ez)i%-C9FbTxX&fV}8}jBCpaS;qWC`+E8hK`b$bW z?@0a1u8g0HyrGTUff`)XZo^HAT=Wglb(T%nVs-6KbC9ml51aIi9{S7{=_$f8>T+Kd z?2WE96r^nVR$qS7vy~N({UWGbQ_J}~P>5H|V2O^keP!gD-!=FOan2c)TdZhW`bI#>zo4pGBoqCT+ReIs%h+(Wgp9k#&k*yDGcQM@GUyWQA zYFp%T+=b(w!O+O%>>)-tX}BqO`8ArJc(|5D$jIfw^mQzh_6z8yP_&7S1S&8&SBb2v zc7H30#W}wp?5xms-r;_?Lj-UabNg@B9)P_!0h*c+k?!6xG-z!)Vry)=ISb@ z{#@#N->j;QB7t#j@{T3*4R8hrUtxXowsp z5%G?RHW^)+QI`o6v3TlbZ%6dF-IE&j4(vGg5jj?{uDWwC?)W}sqVzL+X20QC4PzFM z^6{VsGNUL+s*3I+#TB}tLbO)64XimU_!whcVk_Te@%k~^qj0(D#0fK)zL^?g32F~d zCIFH1!K@73yz^4=%4xWDW*&m-PPrkHDkw<`X8hTy55MB{ih(^>KW(S}>|<*q zYZf=}?VPN>Sp6geo}Ua-YkqoT)0K&vu7)zuyX5rAp4kQAv~EOp=YUoAuYsI9x4tlU zAB!-B8@m~vt?em-X@JAV6$s_G$c$6t)QEmQYS2)QCUPHqH)?$mvVw$aZRNO!Agnta*1U`a#vmP0jMSPXO?()5cYiPe*o#- B3YGu> diff --git a/src/site/resources/images/logo.png b/src/site/resources/images/logo.png index 7c689339b56e61ec5c04ffff32653aad0cee3165..442355059a40243df7a5ed80f633bd2cf02c0db6 100644 GIT binary patch literal 11003 zcmZ8nWmuG3yGB4t8tHCnLFtl?p&7bFK)R6*6{NccN$F1MlunV9?vfH1KtRH?W`F()o`qVfgjN!DalGfy%&!I zd|Y(o{`_Md^}~ErNkL6F+KV$o9u|&afcn7=N{5Qc^2j>PmC}oefq;C_wfrPJI9$p= zR*s-I5A7-2W72qXIYmYNo&#j|T`N}e(aw&C`;C)jktXN0rVv!@>6|hnB~#P2Rmp(y z{psT15PW0`@G(K^ZpC~FKIXPI;L|fTF)MGbMGg{eQVhWkajt;;0U^~^kV%`zh-eunIz z!{P9ncZa&$ySo%QEymnTEG!JXyae2^(O;Z5)^t8kiHXf;%XErMrt$f(l zHa3pV%%n1Q|IR;fyUmBV_0proSW#VFZwRW@YDrwIj zVPawyUG(?&>o?e?*tQoH7jvBBFsb{pRuf(FHr!n7PxD%jXL`m>{<96&metiwb!jn1 zem}>`&#yxz;-UDGpFbism1OegPZlwnxKnR2iF5C>e$xAq-W|7yFdARQyVG90yp|S& z`o_k;SwH+vI#|INV!S%e$3_49y1qXA=TF^Qt5K4Kv^1LxFMt1bA@9>KHg$s;-z;N)9RZWVYH3kU$C&qbDDJ;zZ4KK z9EcaReET+iz}(OYVNyZXB^Z>ygqPCZNqdAPnWip zqB>S4rf^~o-SEGEeKn1YIMlMm*iyMo*f%#fIelViC0EH_uuK0K9ws1SQK@k}JUVjF z)YfJca9k{);wZD;pDN5NDv}3j5Wc(nwt6f1V8^YcZ})qKoQzB`ue>^Vn1Iu=O{t!$ zY77|jW!wErwGTCJZf+_lC+pq8h+$Gm1{y>4^r9FQV#7y9lr=Rq>Ctc~EXlE*J8z1F z0`Hnj%FDkVS5#DRYNzjv!lJ-}TG8z6>}(cgIMr<@B_=YcWeS-O4{n`>kBzA$WM?}; z^qt$!LZ5MRJ`G046To0*WR$VAwvH-X}0H2Zx8M1u1E1&p<>vVwTs{X|6ARs1Y9vL0& zpUhW?Im>6@%HBhSZaTV-j!se7p0R29 zvD6%h=ME>aa-nooR;t#6JY4u{Z8Q}_{z4uJU(YO{;reF4^nAs{^v1L^wmentg68DN%&#>PCV9*(q>uTOp|v0huxxTh__R#zs)x4v$Q%$9nPvN1Amw zEE~KkAw9i}%6X>v@#DvNU}LF--DIIqXn0~Gq3iXjIj_t5D@d!)`EJDK<{OL5kwjgP zU$z?(Adxhy>+1M4O-;Gk+1X{StO`piDxMzxtbEaF28A+#LiCJ>hjcKOn&|TK(r^Th zLjObTeC)*svJQnf8pk^m4UP9THP1m&%q=W@?C9v&b*+qw&d9`sN>5K89ud)PU)}N6 zSKZN(i@SLp`QmU6PfAJ(0~c4`#pU_Oj~_XG`UVHLK3iu?X=@XuXJn-KXe@4TTegE` z0r|y06$FyL`Bz?)%YGq@0uAc>AZczf@kPq}cgvoNm6-P_oqQ}+M1K@1BRe~mG={er zO?^W{Ze=A-Wo2b}c=#(-RUEKHs_%@t0>u*(6HgDytMkCH2d<2aj6eZLiyI6M4@cbQ ze}6ewR1fOkua&l@NtTO=*rdTNsjJ^BwQs*uX#3z%i-ZWf@2-!Fp2)`0h$A7<#0?I8 z1@A#Y!+xcv7F!wsUgLVYF2$)|gOtRg%6Bk7HT6b$sma;QVYQtcq__McSme9Q>LC70 z^b-iubuaD1d$1GJ1Hse#vS99pMn*XKk|(3<>#vOiZ+1XYMD_f=Y+F!SS}LWfNiYyi zZowC>ZKk!b(^y(r*?+X~^=v&D4>1|}F6|XD8oa-Mj_nu5Z0+rPV+2=iDDuJb%V!%H z7z~Y$q9FD4_nVKU@yd6Us7lMo#Q662^{r<(cXnT`1;s^2V_R^Bg@&eg7UP^!Z-?=l z_n>ZFfp0T|9&P|`c>YdHQ4u3kjkTwz2cLu_G>WH_3>2cq_QR{Lf8wB`OwP~S#Ao3n zfByWr=wt=-J8;u085tC?of~J~(H~yjgoK4r{y41eavDDT_i*x0!_3UNJs7Q2a4vj) zUVki8mfTJ;%7+aS{YJqjXN?Dptucw{8sPD|juFCrWUL=6oM*TDn? zG#kFplxp+7>BGpUz1gH7Bt!;-yuS8^n6`PH2s9|!+m|Q6@O$cs(sFW~|7PR&cni*c z-}l(u&2SbNisq5_yf2$n>q$g6b91Y+{Zcj*DPp@&XB8eBD=;;l&i`aDC#aLx+lCH- zc{oVSw}%oCtB&>-WC#^*7#p5%Pj4@;$1e?SQzQ*j(^$DE67t|UJhwK-L(>jlaxH?C zIHpI%(-EhqF0!(+uYXPCj?{y$FMm5k^wp@z38cZdhB;GvrCYF|`7JFA(jxx1Mmno& z4}Y3ilwwCHDJUYr^cmF`S7Flv{QRGXBAZ?m>a_Uy|J^Sxg1f=fM7^r^+mw`)iUcsR zu=rGMT6lWFfSi_vAlW}8ZY$hszq;f7TKHP5l+Hj1J1l0{2Iy$|WB=ixrlDaZD66wJ zC=?v^8XDrPYMB^FE<#ioI5@L}I@ScKoZN#01MI^i`yLe3vRUsYHYcw#@PfGrr8vtFiBgs4v^m|j@h{I1V}vJ zhaVtn5gmPUufAEMrNoI+(CH)rU)Pip3%f<#eL(1!l_@y7ktn&8e-o0oI2aq~6zUN>u9@5b}est|F%KVM2qhrNZ& zeJHmtg47~kPWDA#hC7J!U`-h5wLnjb7Oy+ZH5`(jKw!q7mGmY)b ztIQ$a4ra@_)5XtWool@dQF_ z?rH?%JT4pZ_;a+7CgjQhKR;KE!ZA|}#ih2}E@iG%qvQOIgN>AskU%0DHsbOO?`ak8 zyOUMwmDYDM`ub#`u7Le6%f#T~;$mq_Frg8vrk4qQc3A7ar6!XP*OPdxEXy?W z2=0`%Qo!1Cu-YN&d-3Z7jkqsanY@(LhvNhJO$l0kc7pW1Lc^5N(a}jzuIn;OoU` z>=u$8>V+ccivpbkiPc`*Mvd54tA5qTS0r49A)vt0fP&9*TiWzVBR?yokOKA7r%xm@ zHG&Z`g%l$KoWuaTmWUny{y|rFi+fcFSBSCs@g6s1tUcf-&6LRWsqRl4N`bT^;bTX} zlz<2xr{b@svLZjkuc&@j7z6{DvvZ{kft>XbsjtIFc?RPoA8ZseIuA-F$4#US8n9kE zgjO(=W?~;>6y>uxRGW4rZ{AlY;J2o$$4c%vR#zuvEk#t+WjPH+oyOD4AowBZNWB88 zwzh0e?Pv1sx4+w1^e|)8m^jx-gXo>igo$Ud-n&`jA$4AFKFRS!4bt10pPzprG4xL_ zK0V#;#sN?u7C%^5RA`x`PJmC5Vw9)Ou;9rDbeeBPsu|JRNPHtBBd6O*>YE_wLwU$c zBYagnk<0;PG>|ZAaVs32peS)oi>~wkrj^MY8*ux_0K4@#;g!w%rn#a50pT#(> z%0W}O0&CENxoX;M-vc&>`I<+9%Pzr*^(377Up(H=7QBlLDO@aEX!GJhMCp78GCdJi z8B29^nU2p|XF!qI9rdp|bV`{uv20a6Vh{#ARZOOm+xWf`AdZs?izE{5k z28Qi6`yvpm@CthI8YyBfTCNGa+dO@&FDh&n;!z5y%1JvHt)isro8o(!I*6tWe!Su%J07vuD z!SLVh=W2||$X<&xA+s%Zi6f zRH_uWn5-d_qiVL;LZYce`7e71`yROasW{-(BgF1o12N4zsYdZIm^D3Dr=g{l)keB~ zm6WS1uWp6DxzPP^m>!JF=u%?u7+SZuZ*a1Ldugus-W8cP~z*s8B z87oS)iy64N$Lof;0MXgU+bidJ^m?`3XQWds>4^ql{=@X2bH>)ucWy5at!sOSt%(~v zz<&21i-8AqrL2{fl)N%Dq(H+adr$u2?Rv-6>WgeZ+KgSgAA4^nC?Fwm=vF)*$0!pU zzrENGZd&z)lm@y*j5#rHYBIlh^QH!1%Oo#e$+Y7`A$h;EE{R_ys=>j*30YZ=5!q)` z5T4wEg1-9Kr3Hv?!cZ}1>W9Fa&sV?S)_ols$?43L43fa5m2gN%yiRi$$wJVdbT(*) zGDYz-^T+7ujN;`v7<(qpRmzG z`i)r8->0`1q4MtqI1Ra`rlyjm;O+DxA{2lgqshlmSVbxoiY&@xWq@fk*w3Ylg$X*$ zzc=paiszO?_{(miTu6ZtT7MU;b8_{nO;ejSWcBY<@*K{Q1JC~D zb=&RnFokFoRhE=|BQ^6kC*OuA0nn%f(4Og%|Gt+FQ%DMjo}r=^ce%+T2zQF{Z|s-R zfw10x8luBi$@xUa9+PtVO-|H+a;P|Zth}4sC@s$J`B`ZcBWE+3$`uMVH8#eEjeY_s zhZ2xev{F}{C>{wwj7IqWP79Q|2tg%@HHU+OE+!Qe)zstxQ~dsC3MY5eviXt-21Sc(e4nQv%8+b};~YybtO8^DMZ z^miZ3+DifBRF0+=B>`c`#oczq7XmK2{c{ZXMQ@o-xx+N_Hypv`_kgxFI2prOz!1H? zg*=ZJKRGTnelGCQxkrSNT?Q!6`Kmgy&d> z#R;r6(17~DWK@h6N=r+_5! z1pv)RxQ%T}@E!_c;^GGDZKn|=4$*bKAownsh{rQizhi#w+oAny`m>1%4TNe0NW=T- z{g+}@EwGl%)S2D*czm(z^94E-T``1Yd^;g zI%M}#K`sf2)p@zyt@j1CTIg)o+0*-dcQ@y%u|szn^(IRmhd*&ZjHL-WXO{++UEjX+ zJn8xuh)pZ8OqT+7f}W3$a4*Y?2Ei?tm!q>py*7su80WuQ;{jQQfQkx{I)Hvf(@N3+ zoNv*M5^gzXSH)sbqe;|%pkdWji>)`*{(P?lxq;UkOXq%i z-xWn9IIF~h=?h-WwYme9P#)Fu97!@u{Q~FTydkU|=H{w*nY>~%qp|yRRVYStef&b~ zLV%~5DhZ+^*%A$vw6l z$m;cb%RD*YMryb=>KSc{Q82q!A?Lyk1@`iD^(3QCdWBTvofTCEJ&JaJBO_vIg_NKB z9)@t87PHglLm*-ly^gG#v0bpORT^c@X?h*)d84&j=C2a~_lV?I5a@sr-Y%+j=v^YM><6n5-Z7lJ5w^m82{eNe=nlT zY!$63>bEVau|^>4tW>J>_GznIiFvjuF)U)vjCo_BaOcL&7NYyv>L0bw$MceGw*Vd9 z!5ug};#l2Khs?%@!L7mM58++_+f{KSXZynL9asLypB;5cc)jN%B&ZX_j`I zTQ4YkM8E!A@_d%NbD+#Y`d4_%7tHeD^%z+Ziq#%UubH+xpMU$xOI5fM{ddri+12)? zrHA7Pp0$O`Cs0u#>T@ZCl{8>$U@00|p}r>_z=B^E79Yw&Flhxp#F(nl*83rAP!Fsp zg7pINByBqUlu0uqQ@=xhk^L)f6o)cI?sCsG?l>1bjtXi*NC;{{Q4#18-5#X_ z?LOzvEe5bL=vB-+_TM+NtHcOSn4kfDRxsh?ft!(={f4AYh+NpA&PJS?_5VhPqzQyN zdJc}!)B=DmR0sze9hZ`M8vs(nr=^VpLhAP39?CVd2)C+>!2zOp5$x-JN=qX{peRu9 z%B#~3`V_u6F#-~nCK1p&SI248I40z>N^Ug?Ccp96sfiM3WF&cRz}JF6UNHF2n^fF( zqtm_y_~hBMXEom~fP&wAvzy`QDDs4a^PA+u8J^YR{p}S{H%E9BEEWt>L{a=0u}q6w z-1im}e||tgkFJ~d*~zgpKzMxfbgZm{7`sCVzeeoe-MO-JP+Jm;{ajT)k-FH2sVS|| z+f+`2k3jii-q5(11|8SvLDKv5b%j}%sZY-bB2>vnM%qa@^U6@{S2;PkX5g@KSw%!e z^|I#pzY#w0WVhN^>6sGXjQNTM%o7b|9e{3Mf!4SGllcY%Pf|-h$rCWT=7X|w7eE?c z1If7PN=u)?pe`?`!}n4vl^2wCAWV(qJ7m&5V?dP@Qb(ot8`u6koXwP!dVoyc!U<<4 zJLZB|FMb8n$-K0@%=veR4!n!h-s8+>Xl@B65JmdJXamD4SMRLI)O$v zF*9R1Y!<5~l|c3EC|*TF%qh)(c~p%bdLNfpp;1ChY~E1JiLf`@OFppo{;e?hicd^z z6~Q8%q+N)$umQm4;CPm(rmpT=2F}^;x6Wk*teiJB{G~>Gyr!E}cDcd77L{3(yv(Zvo_gLGVa$^Sq=`47W>#1}eZ#3v&}n zaBa&Fd?S=X=6;u28vE?O!96A7;^9$eGXZIy>vgi)NTfmhkoLO@s-)!h>@7ViO~8d_ z6lDl!r4NT_S8S{q>i{#?4ch)V1IA)Ve6?Ku-J&+h@y{>08^s=gPg*f>Bo=HNW!bzr zi+a%<6S|hx$Lgh_f&aUC3pc5+`^V24tzPdt9~zl#n3Sgv#*8Twte?`y4KsmAS0M%L z?7+Wv59W~Pa!l)FqMj8SZm;a<1l>lPP!~*k=tY$Y&CjBwE#JTek0K8ug@0d{*5Tb? zkseoybuvlZXyLcICzy$oD*l&_iW;TCNYPKct=J%^kI9FSkg%i?X8}45G87@5kR`L36T4Z`ThiM1ZI3)&o|Q0>2Qg)g)200RFQh|}%N%_dski&~j*qehd$g1c zEMHv>=JHLnVcbWYE|AM^a9G0kIinD9%42&YqYv*k6%Hg?!+|bTH{(P(nELC*mw)nz zX2wTXcjlc|x7r*B&{(moOl%kV$hnvwxOg8}6afKSV!&+jsEbNj0_YPemWA-~U3O|E-8x9H z3WM7io0{>{7m-P+JfiUzfb;3T!%>x0q7XF{|wXX6nbO4 z@af_5k~(p~atYSE@xFKCm5oh_8PRG^dA$hH1Ad$?CjUzj%w^2Pa$93*xSS%NYw1v^ zC-zO7e`)ZC#MDrbOyh(p@!ap@Yi*}lrYA|;=J!3Dx=N0e%DRMGh6jBV;eYud943Xv zpxlgOF)=YclU(Zx>iSVL*ohIL{<_W4FC}EagkG&FC^>Ql<;F>`IZmD^RUYH?@2(a&T zax5dp#{bMN5T=??qcB&RiMH4R8FVTQ_=@mzJjpx!+1c5~BrReB`ibEKRVy)S2}pap zOel6Y|D17t`{rm)>pNmL6~r*){r$zz@MtRT)_`#70HN|E!17mO?~-p`aoXP5G4Bb% zRIU@rn2`oyX+jf4%G1bPad+qc#CEumt8MML;5j`iaKk5x)oGuSk{S)sO_XF7vqwzE zNJT_M6t(YAR<*Ty6kN&XUq(6exzPX`l ziuPzx)7Q0$8-n^iz(z#V^`0j@ zvZkgq04~({oWGS-P%u)AS!1CNhi*Aqt3Tx6BLiY1As@M3fqdK`jtUghu_sA zVX|Pv$krL1q$I7n#0?W*7b+)IV%{|b(h9ohpYZj+zKyBl1Z#J$tjk`9{S-hXbfn~z z6nbE(uC#d#TEvNmA{Z^DfWx=6|)~1 zL23W9LNioH!fhJ^acpGF;&i=RQAw%$yWm>1M8IFNtH+BZ~ zx~wDNQVC7aI}(tRTDNwN9ed^j;xCQi4>TSS`{+Qcc9;&joYfNoSN^>`3j8UV2>VI0(^4ajGzK`@ zh34S*B%}f(=yqw%<*>5p4ZwYkcIE#y34>uUG<7+zeFEEI*P5#4O)L!h=U|HfsV1|- zD>b{oe}qpkLO=~A`g1vFrdL)~&ixA8N!`A$w*87uHSV{Lue{m13uEuwC= zC(99HCPejaX#CYmC@5&fNHLpbZj&5xt%fG1W?kg+jg1oKMN&a=fuvA5P=vDZ8A_OG z?3G>Jw3OjfVjZ;AGJ5dFuZK5|jJN0H#2!&z6H^a%DHpnwb(@BcUu8#UJ{95}a$VlJ zvmyk&(^GK5`^h$I8=J<%9fQ6>|GB&_J45ntq}hZyt40=DNl2U5#sCS;7e>U zymm&+9R?}M9J(o_@^|lraaF$nr~C3pAqG#=)6~Vndd+W~fR7BEY!ygLVD3!fF(e*s}WY=^xfIn-T9aZ@GDEk5kJ8c^z8M@zQDT&@h|jvKT%dISHC z^ta0-+FO)(Y@DQ!0m7XyG8k&vkS)yQAlE`o_wyzOy82$rKi}adK7|x*+UQHl(}i!xRyj>DUsf za#GXAnF@=VQ-XlokD0hq4pB;_Um675aFtdeYbPW{l0oHt7p})=wG6bN3j^&7b(SR~ p1(BFV>?j|WCZU$^T4PTC;o-MorLXuP`yh^;D#@wIR!P79_| zE)Vg{aL=6Bd+oi}x>4$?3fLIr7zhXm*f7Nxng|Gp9N=#YGzj?FWS*4{exaJZRCs~# z_up4RcXITk)jI?POoD&kh_mbd58%ZoZZH+OC-aEtCBpL=XSmqJhF1W! z{?=6ceU8u6ZEp9p@cl8pV)CHd{>&G5E;n~XxBcIRvdo1zltx&&p(1W>+-?MiGhc>g zU=^|or2qdn2Il?o*Mza8@kErgMN7jb=t|C4mDb2C_q#eymZBX4Gv9Ylx?t5+`3DlDD#KBPm&yhZaWb(9U^6>DqDa$Icv$3(UuoUPZUS3^YHR4)W zSU4xkMu#m@;yh96<7{?V{7e@4hR0x!jztgV&xtdj?(} ziKl$2s;Z08x_UzT+_>xg6%*Q%v3_`QRt9_Ez?RqJuSM?qv@{Y9S*}J*QceduyCQd; zSFhSF#t0Tx)S1586oYM8s4tuRc`-t5jvk_O4E8jg<5h52M6{!m)1SlY`n>nw$rhMa z+uvDhX%RZ|ED&s4508wL|92sElbIhJ9B_rp7_TrMQ?+3ekPs7_`fwO`{qFty_}0(Q z&&X)~M}B~W;|kvjbhY(ueSQ5~J3EZ8=9ib3>hnc%F%=ab*!8ZD788`l$Hr`JY}BtM zBL*5hP7HRb=mZ59e_SmrEn*MI%T6+b_}-`znu`2eDM&6{5Tj0}?E ziVB;tWJWmE+10JD#6}n3pH@TU@%e7 zQwJNH^IKo=FH4^s4P|5?#6o^|ZZ=F#&ST@_*~0J2KFYYhdv|nrC~>z>uRh-2;JEs! zqoZSZc=-EwtA(!-1Yj2eF2|VT;^Jn0f>DHAcNNXd=-`#r)nFDY8>`}Yoak4VmkqYy zT=uVS>x?>e4Gn#6FD>gAk1o9A6R1=Sw@+F(dcb1+{JKA)F4h^vjCmX{Y3S*VM7egZ zr!cFP&6cU=dOzN|v#AgbF}_Tj$Pp$~rr|ugymZ}n7RYwo`W)8Y-oE)mB!vd;hAM{-FgwP(_Og z9hJ(S)P3_N;AEvGD~mi~M9av?h;aw3w&)rD)2D_yIy#1i;|ny=X0dzUzZ-XZFC6{S z6haEa8|E2!*Y{mlQ#n-14KC3Q4)X3q4Z?6*B*Q&Zmw z^mKK-yT5gGh}69ip}?`&j3wi(d((^aW>TkSd~c=Ag?=Ox95eK_lqX_VcDD6IM!ycJ zuYs*?<>FDd@9oEt9hdgkZvq~Fb>Dn@sbyttEt;!p<5z{-_~*pqKJKYtLFmH5f>Z12 z&V^UEas8stW*?%W)~i z%_mH_pmFlWU!bI!$JkHSTQ&_m~QNi&Sa3oqA2FF zJ-FWKdG9Ns7yzPD^sMXM`DQ-^(RZLiqgc1@b=0eXiy_jT;kebV_wO7WY8YUBguNRZ zD=Xy0#5#Iu7O0SClk@SQ!l6 zrzUYbc;X?ueRy~nLFJ8hgu$N1E#S7V9x;G82JU)Bf~k+4%zz#oNNmpq4aXvL1+$$i zSCicaXAg%fLHTWlWK8!JZhd?B?Z1lsn%DaB<%{~2x}pZr6C8?+{QLw~FoUH=^TvZX zdHTpnI2=O7#KfeU!G)-VmT%6JSr7`6FhAhWEx@Nd|2x}#C{qf0z)2cAU*Qe9^<)-G zfY{^DIdPwB2M3424qoy&l9(a87K7Taou?f!*{%<}%#r{grG^+`v!E(mEHdYL6*V^E zTj3P3$nXX>qmkvD{7mnCC@m}uQWeNpsT)4u8qllJM;wQ8tp>&0@MKO{@mlZWP)qnO zROzUz9=GU2MdVClg(>38%9yI6w}gKxX1QK$519|g1|5+2OGNT#PtNS%zf9+R9D45m zWoZfRpzw$3dOSHlhE~VA6AJZvIX0uw|qw(jx%8sK* zU}Ho*u#9bOZ4twYYYcz0ROnEIfxudJP*qkg(Up~xL-EI1Fwq}PP9}KJNoK%fHtG*goN2gU(H1ymaj9Pl&NDNZ<6c!e?nW;Busj{BVb91k*sE9NOF&~L{bZ`h| z5`WQ}qIdSvzHFp19AquJ?pwku8N;zc>3s z^ieIwJKT@B`a{tP&)*?S_f4s=3((O8XFK;iT#m0rj#-d9Q-^(G)Ke8%|K%kH3bmVf zrg;m<>SkL)UkD!_mYTW&^k&kkY0ToVZY6;Z866V?!GS>7A?r?D|Gz1GX(wY7b(CIxN2BaEa{qewMD;OH&z7Kr|)l+{7)4`_4k@o^e#--|+9Dl5MF0wc(caHr?jNR*-*M% zH8(gK1!ZXd)98nmXyWk&gehp{SYONcDxGSp>AZhXNAV>?%wgSg!;j`Vq5!u=QL$E` z09zHQt(_;{Vm|HYOR)k7j0HRXOl5$i+C2M&IaRE3g?;y@oeAuqhaxj*pXqyjwb|J~ z9z@>9BHK;3`^^>$nK|>&!!90`9SP^88LJ-}V_CrZAxe%+9kqN87Es#69~TV~-3-^1?<0B-!bw#9y-4BCz@r--$0L3@h) z=NXIuC(#X?kkEu0LU6tRg#SK-^+W_RpUGPdhgx;U+rXC9sXfhFF? zEp@5HPiqpWDxQTK=C!wz(rZf5&h>t2S^XKpS4W|ccug8z zhf%~jM@D4hTKz_|vv1vg_t$&=wN+K#TVbT9?LYGBd+so_MUJk&t#0KryLGNpIBKWR zI?BYGIy&uSWI(5;ZsW&h_SP_8g$w9$&|6tNeOZPsBG1gsOfBjE0Pfdfde{CM;L&=M zHSVdio4o0tzncQzJ0ox?i~MEDSwD~z%;I0{e<|)S!_Hwj9h)hXeZ_q9;fz%12TzT@ zi2XtXDc~2>HR|priA}o50CF}XAjYCad^zWa?gMjHgaYGFa#H+@{ z3BZQ(`Rz$4wS<-O#eGQRY&}U2xe%zLUMt)NX(cuBh*2es?BJsZcPp}c3`XMn-Tgdp zK%L4H7iDM1+N zlyo|a|0w_O1M>+61v)6+5n}Vu-8PkmC)B>`G%;uEK6@g{3`|U}lgRw_-5x`bBagK< z7qD%b>)>AVqzWT)O3KG#>PMU5Sh56(I~FF7&h$-r=G{-a;#AXz3)SrG z>|X*jmxufMKvNnTihOADAtPhdQGi0+n}~EUq&7;+GjZe3b*pnEqUWqT0nae9w0?sL zqTeOxID+)zhUMeu4hFG@mzI_ysQvY6zCo(8&rTv3V7Iro^BKY7&o*f*1}7$z?=XHz zV}FJ9oXyY`(xAnVJloF6j;9djv7X8SNe7puDEeAwl%11v>@4JQx`r;=J5MVlD3~6- z((U8v?#}NGt%`rQ??O&W`h?wfUjSt_K?Jujb0421VWi1?1jk8`Uw?>acypevR$r$z zFJ1_L0}-L!bbil*??7FoRi;~g;x zNfAAYcbw;F;A6Lw-f!QK{=}3NS+$%R!`7)i*Dab+R@q1_NI>teuZ9f_NJ^E(V%mIY zDY?0ilY$%Sd*PFIjrw->_S}rnu{DVCjVzjq4Hp#f=uZyIMGq}iRd%570+hjLzcAwa zRBor!x(JQ3s_N8W6ye1@*=cKVWlB;KA}s*|n7QBgOzVp0EI6z0-@li#&7S-On$&OI zJ};9)f0XxOBgor3eH-O_FNaGZg(%Y#eC{Q-HBm1U{4&-O?Fm&vgb&1B)TA#ESMnk8 z(iv2EoQM!|dW499Acf{nPU~4|Y2m83>aCl~&(VU%_b_@*=Est_zyI>ScpIOnT7Gr= zBmaq{j);5+Te$v{*hX|hCb7#=`V}0VbtGD49B9$(++6!rOV$2j{l@CsUUB~iFR@Ez zl#X`kXVw-LU7(71q5cFNT4iM=U>gdg-+(lcnwq-YWX(H#>~RmGYN=d}Iw=Q^L{K!s zYP4q_ODXJ%>>cQuuAI!k**LNz?ERDF51f{rJ%&lb=ekCd=b=Apy~UmszKc3akfPn$I|H|`#+i}2srsd@1xP~bu{e2H+OCRrV zJcTF#t-QZJA!JfU@Gp{%EY7Aud)sv(pFurDSsv{AQR+^Ess~Iyg-InChAp1k<*>{% z>UKC^`BcC`%KG9|{4XxPr*^X148MSYahKOc6mwqR5*~#=fHKMJC38HDU=%9h;?rW5 z+MXW&e{|rJO&1&zck;4v{zj0@}g5Cy6iIsoUas;UYOhH$!KnR75PSuHh~0z%yL z_s{(kTq=hagO@K~0_{hKkaw8M_q-pL!h}sBk4`@zsc2|uST(gbG@OI@g8#uV8;N_Go{^D}l_g>` zLlZMpl;j0Id1oYnn#)AW&h8Mje_MmO3@{+QsHmu5V`BpW#<0;0Y-5<+(2B#S@_c_0 zUS2{q-quf_f}`+>iHY&?HFR}#H8q3F;y&j5)-bMb1#(hBL7=E=*q$<2g_;^QkA>ok z7olSoS-jQ&R*qL&>o)+Ge!L+w2aEw79sOrR_N0~1VP!d$&oOr-@{gPQNh@BC)fX>b zY+lGLsNLt$@u3Gr08I#J5nxK`oJMS{tio>lcsA`|DfsmAvDA`OBWx7i=PZI*g31yp z7?Zg74W*@}V0r+F5Or+%$N}sB#}>D@O>7ad*ffZ+QITT5(p)X}{^2LlOij4mx_Avm z`97VWpOpnjiJ-$$;1m*9f58X}&702k9l+jU~uGzhju~>Nr{PEjw{Vyzv@EY8yXlu z&Ao(hdYZ3vV>>Vk>7C7QAXM8u*e9o>)M5j0ZajtOY}jmB^7sApcIscG5O&eU^I}xD zX3qN#@9w3a#-JwF0tjW42F7L#9L* zO&71#(2gbk6dqU(Gs#30AsY=HjOA90H7g|G;wFMZf=$fW$YK!11{M2@d=2vJ+7L_& zyj@%faL=S)N)O2h)7rBzpEk@T1W!i<5%XvCn=}~Is#iM~so){^Zs6vJe1PeNWE|%v z*q6%}c3iTK#<$x9Ykr!EE}lJq))9v&`#d*NcA=Ux zTIO^g7vV9AI~*RDMBe~GrwgwMr=^H4OoB3)o6U=HVQs}IQz;dAr9MRn>6fB>Me{~6 z)?6%-f7CR-?HPY67E$TFEEkasd19<}aD$nxA#@jN4J|+(M}X*z!XOt7VzUdC9MkwLVRMuy! zBbQF4<(iVZX_CQjb)m(IkDs3mt9w2tFL#IXw8Pm2cW=hh4K9VF?8JK~LKMYDmT1Bt zg-I9`WqT{EQmq`Dtii}*W>u_e5;}m!hf=AZ1sxAGdQIQRjn|xA#Q2=xhNwp0pp`;4 z6??LMou$btsOfc_!O);~(A*#A>Nm+Nn=9S-Th~sOG9l8*i*s_@648SLI3-5*1h4Ey znEHD@L)@887_}h+l2035AsQVPic!*Xue}l9V#6lP~^NdYrX2 zqsAInd8;2vRKXGTQH>BFp({B`cdF*{f(~iQN}7gGL3Xjo=P(ACYB{f@WG~PXMA2kSo0dW81wtGPb5m0j zU^%Z~$y{)lzkkp8-uCB+YRKoY{sk$wk>Jx7#pKYxvz~>0K*m(E{uw`6AwI)j7(bK9 zP}$Zd#LoWmy#WNq2-AeY&^@(ht(q8_m^xl_I!8`VPKL#+62An^@a5k4hfGj0a&jn~ z1xF%Map%QZa%!^x>UqmrSzF8t>}RPfpb1gLm%dEbyjyno^z+~4w%;~SD3x6D`SWL> zZVjB!tCpwC5sx977zQ`qBoAG|0eLz9P_e9XxX_k3$p!3s+z zd2Y-BoBe1x-j)xPptaVwZ-oA={E1ybFd{shkuf%=%Bhp*Fle>`5>d_^u7cd~5*WwW z_d@Q};SV7EZL20y1KK(|kH^-M#nXfY1lMO9&r$B!Xt`(7<3w;#wY27!3xH5s*Lk|l zbGI3STQR=tXgN>IFb{U8AOmoSasbkM#i7^Jl(3rTmuviVhsoIg5uJ$!r|hza7Jr>|F{_$M^bFs0OdLM&O5k1T_p!7XVSx%YR~Gx6gr zCU@tS$jMsD!#@DqZifVn28VB(O+3?YpkZPv)9HadrDxk@P}0mH{yrF8B;>T#288LT z7e|SZMcNOHgkMm%6-kR&7qAG7|0I2Y zakZPGW+vFpiWICqYe<)xB0C=uOf!)!h)bn(nZ<@36%N(G|G1Yo{IrvYMDjXgmWGiW@~UUy{_lONWMs>5wk$kXHCnggMAl;snzL|7fS#p{16^ zhc0l_hcPrnkn|!l1(J?ui@<_VrQ&pt;~rVX)1T{|lYq{Uh6^w3NQG-mvS)lHhN*K% z<30FG%C}){(h28t5T@rQ;+~;G)h+(c;^t%l*(cL@wo4mE1Qm;( zQ>56_wk@kg*R>s zk=U-GOU`h4Sj7XsvIKH=!0c;=kN4#h)w~{unc#Mgwr6mtJ^G7x?|7@ELnts)c@l>Y z`4jOHMy1xq`WypI*2QzErVkjgDHl}#gyw5JEdcXvRoCHJyA(GT8r#Kok=~lFRFY98 z`y3r}eeJ18<;u&q7uqnn37>mUh6udi-y|yxCB{?1$2)Y1io0u}Gm58ZT%*hv&KG4Z zEyNF>gB@G!If6nf8H6?9%eg$yPsdKI=B@S_9tvfB_9!DGu#gRj_@K!cQ3_;=u*fbT zV2GC-&|)PGx+p*)#Ub>YivnB>6sT-te<{^9K*|mWpS{r2(UDV7n0v}d%wD*kEZ8h|M&~)n(^=AtfH2DQv{jXn#o4U>9=O zhN(@Gy-#`Eh}~2wLb#VdYqJdi5dv*}gh6hQv?Rs#`>?oaP*#d}Ymn1}YOgM~(dfH> z#fz4kJIUvA**ZT;x=0V1{wZcp>a?xu+L$_{ltLpNMM9=?vO5*n%r=x#rk~#3Kc@53 ziP9;$wP+B*(*bP%o&{hlv=hX@;F6Jpk4@bcy#2DrHx~}hw{-@%aX{TT-2%J>Bfy0D z>;5FUqzeb}XjD1QVko=_b%)k(R)=E&RzZ&dytv&wA`+6XU%$HI3cs;CnUoK$$|R2s zbwo&`Wn|m~w6Az@PIt$sn&BVnNXf{225MG&#Qn{go~E28(x1V{3!~3l&P2q-{d>G? z(2KuwbYS3+5n%tdGoN+e7=voKN1MyY_E((^21^E_!`;ouC=$M*%Y|Io}iT)+~ZdVK6~r{(B)!d~B{2}+FE;FOBz)sU28 z@~)f6S?}LJpvL~6otug)g^rCvtgKdL@VSUZBzFp^ooU=@Nl8IS$m0CFF#8(?TxFlj@)_MC-4#S{RdN=BjI!^H^Ta;f>r z6n&y4!P`uk6vEQ;z$N3gnt--NI0LncAWAcYdp*^3U5pABv&ErUd8Tpq*jo*S(g;Ty z$0D4HYjZR?EzM(E{D$LA&%;{#yNrKc1R%qp=TTBo@!Je~^1wjH<r5p`}GsHPSHD zPA)MaViDIg3@u?4=A&A)4OY>btKr45*nm+L?&!lD!*TAu;M zrn;)?d=Z#iocaxYR!yezdx?ZJr;QGm8&C6HaNoEbcV+3xcmG;do8z+Z2Wa;$Oj zihg%5kQgJ%T|Ab;JkZkV-@9?(cDmk4%0n*f3S7tOKn@&ol3We z2;S@7(Bhv3Skly=sqvguQq6~ff!nZFqgyS93U%n85Bu0_`qczo3mfZJ2G40Yv6Py4j|OA_&1UL+b7?hN|<6xj;RWpG8celInzXx38Y$b}oX(&9DHIw*U)h4z0hQ z+^Jw;eUH(=IzSCqRK?{{X;MihRXkveoW06sDw_`rW7Oyo!}Bk_XIz_&f$nPuE|cx* z3vmc_o_~nf3{eIMjeO#ZDjb;g!UOV!iEos4+g43Zf`*ZSz#yD;?Tygir?AQ5FnU^* z1l?-s9==7X&pEDkiH2Jxe8aKlToE59niDAve<1t=2KuBbR&;+ePom_SmJj&{1nYU+Hp; zPJEL6SJj?LNrv8oc+!`auDqn=1= zRdGi=W>ku{r>(AoJIC>2*-wFHD^_>~QyNQq;l~zu@G1VS^at83kJp>%#|1xCWqwCx z6S}5w=1^;DRAtRb$)Fc|eAdw=*Gyu?(zg7nZK;8c#cMo;75*A(&P7%h6x&|p!SNsB zm*5##CNq$YJt|cc*g!S4JxA%VwNj`mo&+T#*dPc;7om01CwCDcPk*?uO=T)_EmOb@ zL_)0TpV>C$45m;fPJb_4+%ZsX1a_XPIa?Ez?tR6F$SY3HOg!iS-BQ3Snybtj|AP)3 zLDPY@sCk0);d$q+XP}}1HGzF%`4C=m0r}2f1x@Z;L234SdbHbElEnEGay&?7&;G%!4n-7 zZEDTZ{`MxDGftZZ{Jb4awpNuV%2!XmS)jc|X(C{~*-yq&iK0eZnLfLb<@{Y&KvKS> z=+u6o|6h}jAw;DV)JbYGO1AgZNc(2HLRITyd@*vXSIA+!L6^29=3rLoVJeDn)wE^A qn-RyOxmM?uG44dIF3RA)Nao^-OnX7^KY@qp5MXkuFY07Wg8v854`avx From 40c4892e932afba6ac2ace430ee59a465565bd50 Mon Sep 17 00:00:00 2001 From: "Gary D. Gregory" Date: Wed, 9 Mar 2011 16:00:23 +0000 Subject: [PATCH 0201/1663] Ignore resources generated by Maven eclipse:eclipse git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1079861 13f79535-47bb-0310-9956-ffa450edef68 From 62a3b36efc78e53c233c2fb49cc8199c5eabec1d Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Tue, 12 Apr 2011 15:55:03 +0000 Subject: [PATCH 0202/1663] Option type is now set to String by default (Fixes CLI-215) The type is now explicitly a Class instance instead of an unspecified Object git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1091485 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/commons/cli/CommandLine.java | 10 ++++------ src/main/java/org/apache/commons/cli/Option.java | 4 ++-- .../java/org/apache/commons/cli/OptionBuilder.java | 6 +++--- .../org/apache/commons/cli/PatternOptionBuilder.java | 4 ++-- .../java/org/apache/commons/cli/CommandLineTest.java | 12 ++++++++++++ .../org/apache/commons/cli/OptionBuilderTest.java | 10 +++++----- 6 files changed, 28 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java index 667ea4319..81d89dd19 100644 --- a/src/main/java/org/apache/commons/cli/CommandLine.java +++ b/src/main/java/org/apache/commons/cli/CommandLine.java @@ -113,16 +113,14 @@ public Object getOptionObject(String opt) public Object getParsedOptionValue(String opt) throws ParseException { String res = getOptionValue(opt); - Option option = resolveOption(opt); - if (option == null) + + if (option == null || res == null) { return null; } - - Object type = option.getType(); - - return (res == null) ? null : TypeHandler.createValue(res, type); + + return TypeHandler.createValue(res, option.getType()); } /** diff --git a/src/main/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java index c7d9cebdb..66c7ef99e 100644 --- a/src/main/java/org/apache/commons/cli/Option.java +++ b/src/main/java/org/apache/commons/cli/Option.java @@ -69,7 +69,7 @@ public class Option implements Cloneable, Serializable private int numberOfArgs = UNINITIALIZED; /** the type of this Option */ - private Object type; + private Class type = String.class; /** the list of argument values **/ private List values = new ArrayList(); @@ -193,7 +193,7 @@ public Object getType() * * @param type the type of this Option */ - public void setType(Object type) + public void setType(Class type) { this.type = type; } diff --git a/src/main/java/org/apache/commons/cli/OptionBuilder.java b/src/main/java/org/apache/commons/cli/OptionBuilder.java index 5cae375f2..6fd1b43aa 100644 --- a/src/main/java/org/apache/commons/cli/OptionBuilder.java +++ b/src/main/java/org/apache/commons/cli/OptionBuilder.java @@ -48,7 +48,7 @@ public final class OptionBuilder private static int numberOfArgs = Option.UNINITIALIZED; /** option type */ - private static Object type; + private static Class type; /** option can have an optional argument value */ private static boolean optionalArg; @@ -81,7 +81,7 @@ private static void reset() description = null; argName = null; longopt = null; - type = null; + type = String.class; required = false; numberOfArgs = Option.UNINITIALIZED; optionalArg = false; @@ -287,7 +287,7 @@ public static OptionBuilder hasOptionalArgs(int numArgs) * @param newType the type of the Options argument value * @return the OptionBuilder instance */ - public static OptionBuilder withType(Object newType) + public static OptionBuilder withType(Class newType) { OptionBuilder.type = newType; diff --git a/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java b/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java index a3f92e50a..200f98684 100644 --- a/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java +++ b/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java @@ -91,7 +91,7 @@ public class PatternOptionBuilder * @param ch the specified character * @return The class that ch represents */ - public static Object getValueClass(char ch) + public static Class getValueClass(char ch) { switch (ch) { @@ -149,7 +149,7 @@ public static Options parsePattern(String pattern) { char opt = ' '; boolean required = false; - Object type = null; + Class type = null; Options options = new Options(); diff --git a/src/test/java/org/apache/commons/cli/CommandLineTest.java b/src/test/java/org/apache/commons/cli/CommandLineTest.java index fed4ac38e..f7fc7ff21 100644 --- a/src/test/java/org/apache/commons/cli/CommandLineTest.java +++ b/src/test/java/org/apache/commons/cli/CommandLineTest.java @@ -61,4 +61,16 @@ public void testGetOptions() assertEquals(3, cmd.getOptions().length); } + + public void testGetParsedOptionValue() throws Exception { + Options options = new Options(); + options.addOption(OptionBuilder.hasArg().withType(Number.class).create("i")); + options.addOption(OptionBuilder.hasArg().create("f")); + + CommandLineParser parser = new DefaultParser(); + CommandLine cmd = parser.parse(options, new String[] { "-i", "123", "-f", "foo" }); + + assertEquals(123, ((Number) cmd.getParsedOptionValue("i")).intValue()); + assertEquals("foo", cmd.getParsedOptionValue("f")); + } } diff --git a/src/test/java/org/apache/commons/cli/OptionBuilderTest.java b/src/test/java/org/apache/commons/cli/OptionBuilderTest.java index 0d2f8f38a..c69789bcd 100644 --- a/src/test/java/org/apache/commons/cli/OptionBuilderTest.java +++ b/src/test/java/org/apache/commons/cli/OptionBuilderTest.java @@ -26,14 +26,14 @@ public void testCompleteOption( ) { .hasArg( ) .isRequired( ) .hasArgs( ) - .withType( new Float( 10 ) ) + .withType( Float.class ) .withDescription( "this is a simple option" ) .create( 's' ); assertEquals( "s", simple.getOpt() ); assertEquals( "simple option", simple.getLongOpt() ); assertEquals( "this is a simple option", simple.getDescription() ); - assertEquals( simple.getType().getClass(), Float.class ); + assertEquals( simple.getType(), Float.class ); assertTrue( simple.hasArg() ); assertTrue( simple.isRequired() ); assertTrue( simple.hasArgs() ); @@ -44,14 +44,14 @@ public void testTwoCompleteOptions( ) { .hasArg( ) .isRequired( ) .hasArgs( ) - .withType( new Float( 10 ) ) + .withType( Float.class ) .withDescription( "this is a simple option" ) .create( 's' ); assertEquals( "s", simple.getOpt() ); assertEquals( "simple option", simple.getLongOpt() ); assertEquals( "this is a simple option", simple.getDescription() ); - assertEquals( simple.getType().getClass(), Float.class ); + assertEquals( simple.getType(), Float.class ); assertTrue( simple.hasArg() ); assertTrue( simple.isRequired() ); assertTrue( simple.hasArgs() ); @@ -64,7 +64,7 @@ public void testTwoCompleteOptions( ) { assertEquals( "d", simple.getOpt() ); assertEquals( "dimple option", simple.getLongOpt() ); assertEquals( "this is a dimple option", simple.getDescription() ); - assertNull( simple.getType() ); + assertEquals( String.class, simple.getType() ); assertTrue( simple.hasArg() ); assertTrue( !simple.isRequired() ); assertTrue( !simple.hasArgs() ); From a1b5d44432c057cf675f051bb20379937565f4ef Mon Sep 17 00:00:00 2001 From: Emmanuel Bourg Date: Tue, 12 Apr 2011 18:57:29 +0000 Subject: [PATCH 0203/1663] Moving to Java 5 git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1091539 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 6 +-- .../commons/cli/AmbiguousOptionException.java | 8 ++-- .../org/apache/commons/cli/CommandLine.java | 27 ++++++------- .../org/apache/commons/cli/DefaultParser.java | 22 +++++------ .../org/apache/commons/cli/HelpFormatter.java | 37 ++++++++---------- .../commons/cli/MissingOptionException.java | 2 +- .../java/org/apache/commons/cli/Option.java | 14 +++---- .../org/apache/commons/cli/OptionGroup.java | 14 +++---- .../apache/commons/cli/OptionValidator.java | 8 ++-- .../java/org/apache/commons/cli/Options.java | 38 +++++++++---------- 10 files changed, 80 insertions(+), 96 deletions(-) diff --git a/pom.xml b/pom.xml index 3a490c8b1..5d1973fb2 100644 --- a/pom.xml +++ b/pom.xml @@ -151,10 +151,10 @@ - 1.4 - 1.4 + 1.5 + 1.5 cli - 1.2 + 1.3 commons-cli-${commons.release.version} org.apache.commons.cli CLI diff --git a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java index 1092d8630..ffb94e7c7 100644 --- a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java +++ b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java @@ -30,7 +30,7 @@ public class AmbiguousOptionException extends UnrecognizedOptionException { /** The list of options matching the partial name specified */ - private Collection matchingOptions; + private Collection matchingOptions; /** * Constructs a new AmbiguousOptionException. @@ -38,7 +38,7 @@ public class AmbiguousOptionException extends UnrecognizedOptionException * @param option the partial option name * @param matchingOptions the options matching the name */ - public AmbiguousOptionException(String option, Collection matchingOptions) + public AmbiguousOptionException(String option, Collection matchingOptions) { super(createMessage(option, matchingOptions), option); this.matchingOptions = matchingOptions; @@ -47,7 +47,7 @@ public AmbiguousOptionException(String option, Collection matchingOptions) /** * Returns the options matching the partial name. */ - public Collection getMatchingOptions() + public Collection getMatchingOptions() { return matchingOptions; } @@ -59,7 +59,7 @@ public Collection getMatchingOptions() * @param matchingOptions * @return */ - private static String createMessage(String option, Collection matchingOptions) + private static String createMessage(String option, Collection matchingOptions) { StringBuffer buff = new StringBuffer("Ambiguous option: '"); buff.append(option); diff --git a/src/main/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java index 81d89dd19..6c05ac8b0 100644 --- a/src/main/java/org/apache/commons/cli/CommandLine.java +++ b/src/main/java/org/apache/commons/cli/CommandLine.java @@ -46,10 +46,10 @@ public class CommandLine implements Serializable private static final long serialVersionUID = 1L; /** the unrecognised options/arguments */ - private List args = new LinkedList(); + private List args = new LinkedList(); /** the processed options */ - private List options = new ArrayList(); + private List
      a-a flag
      b@-b [classname]
      c>-c [filename]
      d+-d [classname] (creates object via empty contructor)
      e%-e [number] (creates Double/Long instance depeding on existing of a '.')
      d+-d [classname] (creates object via empty constructor)
      e%-e [number] (creates Double/Long instance depending on existing of a '.')
      f/-f [url]
      g:-g [string]
      From 29fefd2767b887e62cf17ca4412179b43f6ee4f6 Mon Sep 17 00:00:00 2001 From: Thomas Neidhart Date: Sun, 27 Jan 2013 22:00:23 +0000 Subject: [PATCH 0242/1663] Fix checkstyle warnings, minor formatting, typos, complete javadoc for not yet implemented methods. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1439197 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/commons/cli/Option.java | 2 +- .../apache/commons/cli/OptionValidator.java | 10 ++++++++- .../java/org/apache/commons/cli/Parser.java | 6 +++-- .../org/apache/commons/cli/TypeHandler.java | 22 +++++++++++++------ .../java/org/apache/commons/cli/Util.java | 7 ++++++ 5 files changed, 36 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java index fc4fa0c8a..aeb6046d6 100644 --- a/src/main/java/org/apache/commons/cli/Option.java +++ b/src/main/java/org/apache/commons/cli/Option.java @@ -26,7 +26,7 @@ * if any exists, a flag indicating if an argument is required for * this option, and a self-documenting description of the option.

      * - *

      An Option is not created independantly, but is create through + *

      An Option is not created independently, but is create through * an instance of {@link Options}.

      * * @see org.apache.commons.cli.Options diff --git a/src/main/java/org/apache/commons/cli/OptionValidator.java b/src/main/java/org/apache/commons/cli/OptionValidator.java index dba442a90..bcd633256 100644 --- a/src/main/java/org/apache/commons/cli/OptionValidator.java +++ b/src/main/java/org/apache/commons/cli/OptionValidator.java @@ -26,6 +26,13 @@ */ class OptionValidator { + /** + * Hide constructor for a utility class. + */ + private OptionValidator() + { + } + /** * Validates whether opt is a permissable Option * shortOpt. The rules that specify if the opt @@ -68,7 +75,8 @@ static void validateOption(String opt) throws IllegalArgumentException { if (!isValidChar(ch)) { - throw new IllegalArgumentException("The option '" + opt + "' contains an illegal character : '" + ch + "'"); + throw new IllegalArgumentException("The option '" + opt + "' contains an illegal " + + "character : '" + ch + "'"); } } } diff --git a/src/main/java/org/apache/commons/cli/Parser.java b/src/main/java/org/apache/commons/cli/Parser.java index c706ea725..88d48561c 100644 --- a/src/main/java/org/apache/commons/cli/Parser.java +++ b/src/main/java/org/apache/commons/cli/Parser.java @@ -68,7 +68,8 @@ protected List getRequiredOptions() * flattening when a non option has been encountered * @return a String array of the flattened arguments */ - protected abstract String[] flatten(Options opts, String[] arguments, boolean stopAtNonOption) throws ParseException; + protected abstract String[] flatten(Options opts, String[] arguments, boolean stopAtNonOption) + throws ParseException; /** * Parses the specified arguments based @@ -139,7 +140,8 @@ public CommandLine parse(Options options, String[] arguments, boolean stopAtNonO * * @since 1.1 */ - public CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption) throws ParseException + public CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption) + throws ParseException { // clear out the data in options in case it's been used before (CLI-71) for (Option opt : options.helpOptions()) { diff --git a/src/main/java/org/apache/commons/cli/TypeHandler.java b/src/main/java/org/apache/commons/cli/TypeHandler.java index 581ca2839..55d2c7225 100644 --- a/src/main/java/org/apache/commons/cli/TypeHandler.java +++ b/src/main/java/org/apache/commons/cli/TypeHandler.java @@ -25,13 +25,13 @@ import java.util.Date; /** - * This is a temporary implementation. TypeHandler will handle the - * pluggableness of OptionTypes and it will direct all of these types - * of conversion functionalities to ConvertUtils component in Commons - * already. BeanUtils I think. - * - * @version $Revision$, $Date$ - */ + * This is a temporary implementation. TypeHandler will handle the + * pluggableness of OptionTypes and it will direct all of these types + * of conversion functionalities to ConvertUtils component in Commons + * already. BeanUtils I think. + * + * @version $Revision$, $Date$ + */ public class TypeHandler { /** @@ -178,10 +178,14 @@ public static Class createClass(String classname) throws ParseException /** * Returns the date represented by str. + *

      + * This method is not yet implemented and always throws an + * {@link UnsupportedOperationException}. * * @param str the date string * @return The date if str is a valid date string, * otherwise return null. + * @throws UnsupportedOperationException always */ public static Date createDate(String str) throws ParseException { @@ -220,9 +224,13 @@ public static File createFile(String str) throws ParseException /** * Returns the File[] represented by str. + *

      + * This method is not yet implemented and always throws an + * {@link UnsupportedOperationException}. * * @param str the paths to the files * @return The File[] represented by str. + * @throws UnsupportedOperationException always */ public static File[] createFiles(String str) throws ParseException { diff --git a/src/main/java/org/apache/commons/cli/Util.java b/src/main/java/org/apache/commons/cli/Util.java index bceee2597..1de0fcb4b 100644 --- a/src/main/java/org/apache/commons/cli/Util.java +++ b/src/main/java/org/apache/commons/cli/Util.java @@ -25,6 +25,13 @@ */ class Util { + /** + * Hide constructor for a utility class. + */ + private Util() + { + } + /** * Remove the hyphens from the begining of str and * return the new String. From d1690bda07a267c3c64146a8c5219cbe82d4fafa Mon Sep 17 00:00:00 2001 From: Thomas Neidhart Date: Sun, 27 Jan 2013 22:14:30 +0000 Subject: [PATCH 0243/1663] Fix more checkstyle warnings. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1439199 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/AmbiguousOptionException.java | 1 + src/main/java/org/apache/commons/cli/Parser.java | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java index 4cc614f58..2c3954d21 100644 --- a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java +++ b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java @@ -51,6 +51,7 @@ public AmbiguousOptionException(String option, Collection matchingOption /** * Returns the options matching the partial name. + * @return a collection of options matching the name */ public Collection getMatchingOptions() { diff --git a/src/main/java/org/apache/commons/cli/Parser.java b/src/main/java/org/apache/commons/cli/Parser.java index 88d48561c..a049e51ac 100644 --- a/src/main/java/org/apache/commons/cli/Parser.java +++ b/src/main/java/org/apache/commons/cli/Parser.java @@ -144,12 +144,14 @@ public CommandLine parse(Options options, String[] arguments, Properties propert throws ParseException { // clear out the data in options in case it's been used before (CLI-71) - for (Option opt : options.helpOptions()) { + for (Option opt : options.helpOptions()) + { opt.clearValues(); } // clear the data from the groups - for (OptionGroup group : options.getOptionGroups()) { + for (OptionGroup group : options.getOptionGroups()) + { group.setSelected(null); } From dbf7907923021b2eaff05d11e357eff9369d549b Mon Sep 17 00:00:00 2001 From: Thomas Neidhart Date: Sun, 27 Jan 2013 22:14:59 +0000 Subject: [PATCH 0244/1663] Correct header template, allow legacy package.html. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1439200 13f79535-47bb-0310-9956-ffa450edef68 --- src/conf/HEADER.txt | 26 ++++++++++++-------------- src/conf/checkstyle.xml | 4 +++- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/conf/HEADER.txt b/src/conf/HEADER.txt index ca8d6667d..c27ff4917 100644 --- a/src/conf/HEADER.txt +++ b/src/conf/HEADER.txt @@ -1,19 +1,17 @@ -^/\*\s*$ -^ \* Licensed to the Apache Software Foundation \(ASF\) under one\s*$ -^ \* or more contributor license agreements. See the NOTICE file\s*$ -^ \* distributed with this work for additional information\s*$ -^ \* regarding copyright ownership. The ASF licenses this file\s*$ -^ \* to you under the Apache License, Version 2.0 \(the\s*$ -^ \* "License"\)\; you may not use this file except in compliance\s*$ -^ \* with the License. You may obtain a copy of the License at\s*$ +^/\*\*\s*$ +^ \* Licensed to the Apache Software Foundation \(ASF\) under one or more\s*$ +^ \* contributor license agreements. See the NOTICE file distributed with\s*$ +^ \* this work for additional information regarding copyright ownership.\s*$ +^ \* The ASF licenses this file to You under the Apache License, Version 2.0\s*$ +^ \* \(the \"License\"\); you may not use this file except in compliance with\s*$ +^ \* the License. You may obtain a copy of the License at\s*$ ^ \*\s*$ ^ \*\s+http://www\.apache\.org/licenses/LICENSE-2\.0\s*$ ^ \*\s*$ -^ \* Unless required by applicable law or agreed to in writing,\s*$ -^ \* software distributed under the License is distributed on an\s*$ -^ \* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\s*$ -^ \* KIND, either express or implied. See the License for the\s*$ -^ \* specific language governing permissions and limitations\s*$ -^ \* under the License.\s*$ +^ \* Unless required by applicable law or agreed to in writing, software\s*$ +^ \* distributed under the License is distributed on an "AS IS" BASIS,\s*$ +^ \* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\s*$ +^ \* See the License for the specific language governing permissions and\s*$ +^ \* limitations under the License.\s*$ ^ \*/\s*$ ^\s*$ diff --git a/src/conf/checkstyle.xml b/src/conf/checkstyle.xml index 9dc3a2907..7f3255f09 100644 --- a/src/conf/checkstyle.xml +++ b/src/conf/checkstyle.xml @@ -27,7 +27,9 @@ limitations under the License. - + + + From 4e409619b5254daa58c551822d287b3da32a4b56 Mon Sep 17 00:00:00 2001 From: Thomas Neidhart Date: Mon, 28 Jan 2013 09:25:56 +0000 Subject: [PATCH 0245/1663] Update copyright. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1439317 13f79535-47bb-0310-9956-ffa450edef68 --- NOTICE.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NOTICE.txt b/NOTICE.txt index b3ace17ad..813a9cee9 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -1,5 +1,5 @@ Apache Commons CLI -Copyright 2001-2011 The Apache Software Foundation +Copyright 2001-2013 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). From f481ae3e7a6ec5462800da6349c50e9eaae35eaf Mon Sep 17 00:00:00 2001 From: Thomas Neidhart Date: Mon, 28 Jan 2013 14:02:58 +0000 Subject: [PATCH 0246/1663] Fix javadoc typos. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1439408 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/HelpFormatter.java | 4 ++-- src/main/java/org/apache/commons/cli/OptionValidator.java | 2 +- src/main/java/org/apache/commons/cli/Util.java | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java index 3816082c6..9195e9dc4 100644 --- a/src/main/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java @@ -512,7 +512,7 @@ public void printHelp(PrintWriter pw, int width, String cmdLineSyntax, * @param pw the writer to which the help will be written * @param width the number of characters to be displayed on each line * @param cmdLineSyntax the syntax for this application - * @param header the banner to display at the begining of the help + * @param header the banner to display at the beginning of the help * @param options the Options instance * @param leftPad the number of characters of padding to be prefixed * to each line @@ -965,7 +965,7 @@ private Appendable renderWrappedTextBlock(StringBuffer sb, int width, int nextLi * @param width width of the wrapped text * @param startPos position from which to start the lookup whitespace * character - * @return postion on which the text must be wrapped or -1 if the wrap + * @return position on which the text must be wrapped or -1 if the wrap * position is at the end of the text */ protected int findWrapPos(String text, int width, int startPos) diff --git a/src/main/java/org/apache/commons/cli/OptionValidator.java b/src/main/java/org/apache/commons/cli/OptionValidator.java index bcd633256..f50655251 100644 --- a/src/main/java/org/apache/commons/cli/OptionValidator.java +++ b/src/main/java/org/apache/commons/cli/OptionValidator.java @@ -34,7 +34,7 @@ private OptionValidator() } /** - * Validates whether opt is a permissable Option + * Validates whether opt is a permissible Option * shortOpt. The rules that specify if the opt * is valid are: * diff --git a/src/main/java/org/apache/commons/cli/Util.java b/src/main/java/org/apache/commons/cli/Util.java index 1de0fcb4b..bb4e4d539 100644 --- a/src/main/java/org/apache/commons/cli/Util.java +++ b/src/main/java/org/apache/commons/cli/Util.java @@ -33,7 +33,7 @@ private Util() } /** - * Remove the hyphens from the begining of str and + * Remove the hyphens from the beginning of str and * return the new String. * * @param str The string from which the hyphens should be removed. From 1e6aa8c501a30c0d92a756fd7dad42244e5b10dd Mon Sep 17 00:00:00 2001 From: Thomas Neidhart Date: Mon, 28 Jan 2013 14:12:13 +0000 Subject: [PATCH 0247/1663] Complete javadoc, fix typos, fix findbugs warning: make comparator serializable. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1439414 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/commons/cli/HelpFormatter.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java index 9195e9dc4..d6a5f1786 100644 --- a/src/main/java/org/apache/commons/cli/HelpFormatter.java +++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java @@ -20,6 +20,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; +import java.io.Serializable; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; @@ -364,6 +365,7 @@ public String getArgName() * Comparator used to sort the options when they output in help text. * Defaults to case-insensitive alphabetical sorting by option key. * + * @return the {@link Comparator} currently in use to sort the options * @since 1.2 */ public Comparator

      + * Note: this method is kept for binary compatibility and the + * input type is supposed to be a {@link Class} object. + * + * @param type the type of this Option + * @deprecated since 1.3, use {@link #setType(Class)} instead + */ + @Deprecated + public void setType(Object type) + { + setType((Class) type); + } + /** * Sets the type of this Option. * diff --git a/src/main/java/org/apache/commons/cli/OptionBuilder.java b/src/main/java/org/apache/commons/cli/OptionBuilder.java index 6fd1b43aa..74c303e9d 100644 --- a/src/main/java/org/apache/commons/cli/OptionBuilder.java +++ b/src/main/java/org/apache/commons/cli/OptionBuilder.java @@ -280,6 +280,23 @@ public static OptionBuilder hasOptionalArgs(int numArgs) return instance; } + /** + * The next Option created will have a value that will be an instance + * of type. + *

      + * Note: this method is kept for binary compatibility and the + * input type is supposed to be a {@link Class} object. + * + * @param newType the type of the Options argument value + * @return the OptionBuilder instance + * @deprecated since 1.3, use {@link #withType(Class)} instead + */ + @Deprecated + public static OptionBuilder withType(Object newType) + { + return withType((Class) newType); + } + /** * The next Option created will have a value that will be an instance * of type. From 57e7048a032802183ad2f017cdd36cc798ab594e Mon Sep 17 00:00:00 2001 From: Thomas Neidhart Date: Wed, 30 Jan 2013 09:27:30 +0000 Subject: [PATCH 0265/1663] Prefer a checkstyle suppression over a private constructor for package private class, otherwise the code coverage drops without a clean way to test the ctor. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1440316 13f79535-47bb-0310-9956-ffa450edef68 --- src/conf/checkstyle-suppressions.xml | 5 +++++ src/main/java/org/apache/commons/cli/OptionValidator.java | 7 ------- src/main/java/org/apache/commons/cli/Util.java | 7 ------- 3 files changed, 5 insertions(+), 14 deletions(-) diff --git a/src/conf/checkstyle-suppressions.xml b/src/conf/checkstyle-suppressions.xml index e7a64061e..46d96357b 100644 --- a/src/conf/checkstyle-suppressions.xml +++ b/src/conf/checkstyle-suppressions.xml @@ -30,4 +30,9 @@ + + + + diff --git a/src/main/java/org/apache/commons/cli/OptionValidator.java b/src/main/java/org/apache/commons/cli/OptionValidator.java index 28f09f190..3df6d269e 100644 --- a/src/main/java/org/apache/commons/cli/OptionValidator.java +++ b/src/main/java/org/apache/commons/cli/OptionValidator.java @@ -26,13 +26,6 @@ */ final class OptionValidator { - /** - * Hide constructor for a utility class. - */ - private OptionValidator() - { - } - /** * Validates whether opt is a permissible Option * shortOpt. The rules that specify if the opt diff --git a/src/main/java/org/apache/commons/cli/Util.java b/src/main/java/org/apache/commons/cli/Util.java index 1ce031633..8087ece34 100644 --- a/src/main/java/org/apache/commons/cli/Util.java +++ b/src/main/java/org/apache/commons/cli/Util.java @@ -25,13 +25,6 @@ */ final class Util { - /** - * Hide constructor for a utility class. - */ - private Util() - { - } - /** * Remove the hyphens from the beginning of str and * return the new String. From dacc862f13fbe2424c3439dac09ea1aaa42a0e59 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Wed, 30 Jan 2013 16:48:37 +0000 Subject: [PATCH 0266/1663] Missing @Deprecated tag git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1440515 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/Parser.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/apache/commons/cli/Parser.java b/src/main/java/org/apache/commons/cli/Parser.java index cb22fac4a..ca2b31e16 100644 --- a/src/main/java/org/apache/commons/cli/Parser.java +++ b/src/main/java/org/apache/commons/cli/Parser.java @@ -31,6 +31,7 @@ * @version $Revision$, $Date$ * @deprecated The two-pass parsing with the flatten method is not enough flexible to handle complex cases */ +@Deprecated public abstract class Parser implements CommandLineParser { /** commandline instance */ From 853dabc79acc7c7ebab2a3d1e52788f3526be580 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Wed, 30 Jan 2013 16:49:00 +0000 Subject: [PATCH 0267/1663] Missing @Deprecated tag git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1440516 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/CommandLine.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java index e68d727fc..34829a226 100644 --- a/src/main/java/org/apache/commons/cli/CommandLine.java +++ b/src/main/java/org/apache/commons/cli/CommandLine.java @@ -88,6 +88,7 @@ public boolean hasOption(char opt) * @return the type of this Option * @deprecated due to System.err message. Instead use getParsedOptionValue(String) */ + @Deprecated public Object getOptionObject(String opt) { try From 445ddaaa89bdcd003645b02b600fde1d3730d715 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Wed, 30 Jan 2013 16:51:58 +0000 Subject: [PATCH 0268/1663] Missing @Override git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1440517 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/commons/cli/GnuParser.java | 1 + .../java/org/apache/commons/cli/Option.java | 4 +++ .../org/apache/commons/cli/OptionGroup.java | 1 + .../java/org/apache/commons/cli/Options.java | 1 + .../org/apache/commons/cli/PosixParser.java | 1 + .../commons/cli/ArgumentIsOptionTest.java | 1 + .../apache/commons/cli/BasicParserTest.java | 25 +++++++++++++++++++ .../apache/commons/cli/DefaultParserTest.java | 1 + .../org/apache/commons/cli/GnuParserTest.java | 24 +++++++++++++++++- .../apache/commons/cli/OptionGroupTest.java | 1 + .../org/apache/commons/cli/OptionTest.java | 2 ++ .../apache/commons/cli/ParserTestCase.java | 1 + .../apache/commons/cli/PosixParserTest.java | 10 ++++++++ .../org/apache/commons/cli/ValueTest.java | 1 + .../org/apache/commons/cli/ValuesTest.java | 1 + .../apache/commons/cli/bug/BugCLI148Test.java | 1 + .../apache/commons/cli/bug/BugCLI71Test.java | 1 + 17 files changed, 76 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/apache/commons/cli/GnuParser.java b/src/main/java/org/apache/commons/cli/GnuParser.java index f9582adac..371c5f909 100644 --- a/src/main/java/org/apache/commons/cli/GnuParser.java +++ b/src/main/java/org/apache/commons/cli/GnuParser.java @@ -48,6 +48,7 @@ public class GnuParser extends Parser * a non option has been encountered * @return a String array of the flattened arguments */ + @Override protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { List tokens = new ArrayList(); diff --git a/src/main/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java index 5f0119394..a4bc555c1 100644 --- a/src/main/java/org/apache/commons/cli/Option.java +++ b/src/main/java/org/apache/commons/cli/Option.java @@ -560,6 +560,7 @@ public List getValuesList() * * @return Stringified form of this object */ + @Override public String toString() { StringBuilder buf = new StringBuilder().append("[ option: "); @@ -604,6 +605,7 @@ private boolean hasNoValues() return values.isEmpty(); } + @Override public boolean equals(Object o) { if (this == o) @@ -630,6 +632,7 @@ public boolean equals(Object o) return true; } + @Override public int hashCode() { int result; @@ -650,6 +653,7 @@ public int hashCode() * @throws RuntimeException if a {@link CloneNotSupportedException} has been thrown * by {@link super#clone()} */ + @Override public Object clone() { try diff --git a/src/main/java/org/apache/commons/cli/OptionGroup.java b/src/main/java/org/apache/commons/cli/OptionGroup.java index adb14010f..fb44671de 100644 --- a/src/main/java/org/apache/commons/cli/OptionGroup.java +++ b/src/main/java/org/apache/commons/cli/OptionGroup.java @@ -137,6 +137,7 @@ public boolean isRequired() * * @return the stringified representation of this group */ + @Override public String toString() { StringBuilder buff = new StringBuilder(); diff --git a/src/main/java/org/apache/commons/cli/Options.java b/src/main/java/org/apache/commons/cli/Options.java index c6393fbb8..9b18569c4 100644 --- a/src/main/java/org/apache/commons/cli/Options.java +++ b/src/main/java/org/apache/commons/cli/Options.java @@ -292,6 +292,7 @@ public OptionGroup getOptionGroup(Option opt) * * @return Stringified form of this object */ + @Override public String toString() { StringBuilder buf = new StringBuilder(); diff --git a/src/main/java/org/apache/commons/cli/PosixParser.java b/src/main/java/org/apache/commons/cli/PosixParser.java index 539b336ca..0e83451cf 100644 --- a/src/main/java/org/apache/commons/cli/PosixParser.java +++ b/src/main/java/org/apache/commons/cli/PosixParser.java @@ -94,6 +94,7 @@ private void init() * when an non option is found. * @return The flattened arguments String array. */ + @Override protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException { init(); diff --git a/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java b/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java index d71b0c4b8..a0c9cb1cb 100644 --- a/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java +++ b/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java @@ -24,6 +24,7 @@ public class ArgumentIsOptionTest extends TestCase private Options options = null; private CommandLineParser parser = null; + @Override public void setUp() { options = new Options().addOption("p", false, "Option p").addOption("attr", true, "Option accepts argument"); diff --git a/src/test/java/org/apache/commons/cli/BasicParserTest.java b/src/test/java/org/apache/commons/cli/BasicParserTest.java index 58ed510b5..61f648748 100644 --- a/src/test/java/org/apache/commons/cli/BasicParserTest.java +++ b/src/test/java/org/apache/commons/cli/BasicParserTest.java @@ -23,127 +23,152 @@ */ public class BasicParserTest extends ParserTestCase { + @Override public void setUp() { super.setUp(); parser = new BasicParser(); } + @Override public void testDoubleDash2() throws Exception { // not supported by the BasicParser } + @Override public void testLongWithoutEqualSingleDash() throws Exception { // not supported by the BasicParser } + @Override public void testAmbiguousLongWithoutEqualSingleDash() throws Exception { // not supported by the basicParser } + @Override public void testNegativeOption() throws Exception { // not supported by the BasicParser (CLI-184) } + @Override public void testPropertiesOption1() throws Exception { // not supported by the BasicParser } + @Override public void testPropertiesOption2() throws Exception { // not supported by the BasicParser } + @Override public void testShortWithEqual() throws Exception { // not supported by the BasicParser } + @Override public void testShortWithoutEqual() throws Exception { // not supported by the BasicParser } + @Override public void testLongWithEqualDoubleDash() throws Exception { // not supported by the BasicParser } + @Override public void testLongWithEqualSingleDash() throws Exception { // not supported by the BasicParser } + @Override public void testUnambiguousPartialLongOption1() throws Exception { // not supported by the BasicParser } + @Override public void testUnambiguousPartialLongOption2() throws Exception { // not supported by the BasicParser } + @Override public void testUnambiguousPartialLongOption3() throws Exception { // not supported by the BasicParser } + @Override public void testUnambiguousPartialLongOption4() throws Exception { // not supported by the BasicParser } + @Override public void testAmbiguousPartialLongOption1() throws Exception { // not supported by the BasicParser } + @Override public void testAmbiguousPartialLongOption2() throws Exception { // not supported by the BasicParser } + @Override public void testAmbiguousPartialLongOption3() throws Exception { // not supported by the BasicParser } + @Override public void testAmbiguousPartialLongOption4() throws Exception { // not supported by the BasicParser } + @Override public void testPartialLongOptionSingleDash() throws Exception { // not supported by the BasicParser } + @Override public void testBursting() throws Exception { // not supported by the BasicParser } + @Override public void testUnrecognizedOptionWithBursting() throws Exception { // not supported by the BasicParser } + @Override public void testMissingArgWithBursting() throws Exception { // not supported by the BasicParser } + @Override public void testStopBursting() throws Exception { // not supported by the BasicParser } + @Override public void testStopBursting2() throws Exception { // not supported by the BasicParser diff --git a/src/test/java/org/apache/commons/cli/DefaultParserTest.java b/src/test/java/org/apache/commons/cli/DefaultParserTest.java index abc628c59..2ef4b0ace 100644 --- a/src/test/java/org/apache/commons/cli/DefaultParserTest.java +++ b/src/test/java/org/apache/commons/cli/DefaultParserTest.java @@ -23,6 +23,7 @@ */ public class DefaultParserTest extends ParserTestCase { + @Override public void setUp() { super.setUp(); parser = new DefaultParser(); diff --git a/src/test/java/org/apache/commons/cli/GnuParserTest.java b/src/test/java/org/apache/commons/cli/GnuParserTest.java index 7093a9dc0..387cf49bc 100644 --- a/src/test/java/org/apache/commons/cli/GnuParserTest.java +++ b/src/test/java/org/apache/commons/cli/GnuParserTest.java @@ -19,112 +19,134 @@ public class GnuParserTest extends ParserTestCase { + @Override public void setUp() { super.setUp(); parser = new GnuParser(); } + @Override public void testDoubleDash2() throws Exception { // not supported by the GnuParser } + @Override public void testLongWithoutEqualSingleDash() throws Exception { // not supported by the GnuParser } + @Override public void testAmbiguousLongWithoutEqualSingleDash() throws Exception { // not supported by the GnuParser } + @Override public void testNegativeOption() throws Exception { // not supported by the GnuParser (CLI-184) } + @Override public void testLongWithUnexpectedArgument1() throws Exception { // not supported by the GnuParser } + @Override public void testLongWithUnexpectedArgument2() throws Exception { // not supported by the GnuParser } + @Override public void testShortWithUnexpectedArgument() throws Exception { // not supported by the GnuParser } + @Override public void testUnambiguousPartialLongOption1() throws Exception { // not supported by the GnuParser } + @Override public void testUnambiguousPartialLongOption2() throws Exception { // not supported by the GnuParser } + @Override public void testUnambiguousPartialLongOption3() throws Exception { // not supported by the GnuParser } + @Override public void testUnambiguousPartialLongOption4() throws Exception { // not supported by the GnuParser } + @Override public void testAmbiguousPartialLongOption1() throws Exception { // not supported by the GnuParser } + @Override public void testAmbiguousPartialLongOption2() throws Exception { // not supported by the GnuParser } - public void testAmbiguousPartialLongOption3() throws Exception + @Override +public void testAmbiguousPartialLongOption3() throws Exception { // not supported by the GnuParser } + @Override public void testAmbiguousPartialLongOption4() throws Exception { // not supported by the GnuParser } + @Override public void testPartialLongOptionSingleDash() throws Exception { // not supported by the GnuParser } + @Override public void testBursting() throws Exception { // not supported by the GnuParser } + @Override public void testUnrecognizedOptionWithBursting() throws Exception { // not supported by the GnuParser } + @Override public void testMissingArgWithBursting() throws Exception { // not supported by the GnuParser } + @Override public void testStopBursting() throws Exception { // not supported by the GnuParser } + @Override public void testStopBursting2() throws Exception { // not supported by the GnuParser diff --git a/src/test/java/org/apache/commons/cli/OptionGroupTest.java b/src/test/java/org/apache/commons/cli/OptionGroupTest.java index dfcd0f435..76e083d84 100644 --- a/src/test/java/org/apache/commons/cli/OptionGroupTest.java +++ b/src/test/java/org/apache/commons/cli/OptionGroupTest.java @@ -30,6 +30,7 @@ public class OptionGroupTest extends TestCase private Options _options = null; private Parser parser = new PosixParser(); + @Override public void setUp() { Option file = new Option( "f", "file", false, "file to process" ); diff --git a/src/test/java/org/apache/commons/cli/OptionTest.java b/src/test/java/org/apache/commons/cli/OptionTest.java index d7b069ba0..f5b7b99c8 100644 --- a/src/test/java/org/apache/commons/cli/OptionTest.java +++ b/src/test/java/org/apache/commons/cli/OptionTest.java @@ -31,6 +31,7 @@ public TestOption(String opt, boolean hasArg, String description) throws Illegal super(opt, hasArg, description); } + @Override public boolean addValue(String value) { addValueForProcessing(value); @@ -75,6 +76,7 @@ public DefaultOption(String opt, String description, String defaultValue) throws this.defaultValue = defaultValue; } + @Override public String getValue() { return super.getValue() != null ? super.getValue() : defaultValue; diff --git a/src/test/java/org/apache/commons/cli/ParserTestCase.java b/src/test/java/org/apache/commons/cli/ParserTestCase.java index 064da250b..81727cc85 100644 --- a/src/test/java/org/apache/commons/cli/ParserTestCase.java +++ b/src/test/java/org/apache/commons/cli/ParserTestCase.java @@ -35,6 +35,7 @@ public abstract class ParserTestCase extends TestCase protected Options options; + @Override public void setUp() { options = new Options() diff --git a/src/test/java/org/apache/commons/cli/PosixParserTest.java b/src/test/java/org/apache/commons/cli/PosixParserTest.java index 8f881857b..cd7da7c5d 100644 --- a/src/test/java/org/apache/commons/cli/PosixParserTest.java +++ b/src/test/java/org/apache/commons/cli/PosixParserTest.java @@ -24,52 +24,62 @@ */ public class PosixParserTest extends ParserTestCase { + @Override public void setUp() { super.setUp(); parser = new PosixParser(); } + @Override public void testDoubleDash2() throws Exception { // not supported by the PosixParser } + @Override public void testLongWithoutEqualSingleDash() throws Exception { // not supported by the PosixParser } + @Override public void testAmbiguousLongWithoutEqualSingleDash() throws Exception { // not supported by the PosixParser } + @Override public void testNegativeOption() throws Exception { // not supported by the PosixParser (CLI-184) } + @Override public void testLongWithUnexpectedArgument1() throws Exception { // not supported by the PosixParser } + @Override public void testLongWithEqualSingleDash() throws Exception { // not supported by the PosixParser } + @Override public void testShortWithEqual() throws Exception { // not supported by the PosixParser } + @Override public void testUnambiguousPartialLongOption4() throws Exception { // not supported by the PosixParser } + @Override public void testAmbiguousPartialLongOption4() throws Exception { // not supported by the PosixParser diff --git a/src/test/java/org/apache/commons/cli/ValueTest.java b/src/test/java/org/apache/commons/cli/ValueTest.java index bc374b258..72a0c2d4d 100644 --- a/src/test/java/org/apache/commons/cli/ValueTest.java +++ b/src/test/java/org/apache/commons/cli/ValueTest.java @@ -24,6 +24,7 @@ public class ValueTest extends TestCase private CommandLine _cl = null; private Options opts = new Options(); + @Override public void setUp() throws Exception { opts.addOption("a", false, "toggle -a"); diff --git a/src/test/java/org/apache/commons/cli/ValuesTest.java b/src/test/java/org/apache/commons/cli/ValuesTest.java index 7c5d8e418..fdd6ee2aa 100644 --- a/src/test/java/org/apache/commons/cli/ValuesTest.java +++ b/src/test/java/org/apache/commons/cli/ValuesTest.java @@ -24,6 +24,7 @@ public class ValuesTest extends TestCase { private CommandLine cmd; + @Override public void setUp() throws Exception { Options options = new Options(); diff --git a/src/test/java/org/apache/commons/cli/bug/BugCLI148Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI148Test.java index 28e2d1878..6c77c5e60 100644 --- a/src/test/java/org/apache/commons/cli/bug/BugCLI148Test.java +++ b/src/test/java/org/apache/commons/cli/bug/BugCLI148Test.java @@ -33,6 +33,7 @@ public class BugCLI148Test extends TestCase { private Options options; + @Override protected void setUp() throws Exception { options = new Options(); diff --git a/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java index 8f5f0f392..fa6ec172a 100644 --- a/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java +++ b/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java @@ -32,6 +32,7 @@ public class BugCLI71Test extends TestCase { private Options options; private CommandLineParser parser; + @Override public void setUp() { options = new Options(); From 1868e651c54c257d47ead2b91af6f03a9d5b7050 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Wed, 30 Jan 2013 17:05:51 +0000 Subject: [PATCH 0269/1663] Document unexpected list contents git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1440524 13f79535-47bb-0310-9956-ffa450edef68 --- src/main/java/org/apache/commons/cli/Options.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/apache/commons/cli/Options.java b/src/main/java/org/apache/commons/cli/Options.java index 9b18569c4..9d931212e 100644 --- a/src/main/java/org/apache/commons/cli/Options.java +++ b/src/main/java/org/apache/commons/cli/Options.java @@ -55,6 +55,8 @@ public class Options implements Serializable private Map longOpts = new LinkedHashMap(); /** a map of the required options */ + // N.B. This can contain either a String (addOption) or an OptionGroup (addOptionGroup) + // TODO this seems wrong private List requiredOpts = new ArrayList(); /** a map of the option groups */ From e3f81b63a29c821a183eed2fa5169a147580dd78 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Wed, 30 Jan 2013 17:10:23 +0000 Subject: [PATCH 0270/1663] Exception not thrown git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1440526 13f79535-47bb-0310-9956-ffa450edef68 --- src/test/java/org/apache/commons/cli/OptionTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/apache/commons/cli/OptionTest.java b/src/test/java/org/apache/commons/cli/OptionTest.java index f5b7b99c8..299e9971c 100644 --- a/src/test/java/org/apache/commons/cli/OptionTest.java +++ b/src/test/java/org/apache/commons/cli/OptionTest.java @@ -50,7 +50,7 @@ public void testClear() } // See http://issues.apache.org/jira/browse/CLI-21 - public void testClone() throws CloneNotSupportedException + public void testClone() { TestOption a = new TestOption("a", true, ""); TestOption b = (TestOption) a.clone(); @@ -83,7 +83,7 @@ public String getValue() } } - public void testSubclass() throws CloneNotSupportedException + public void testSubclass() { Option option = new DefaultOption("f", "file", "myfile.txt"); Option clone = (Option) option.clone(); From 1e01bbad08bb961b0e9af1d94e523394803fffdb Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Wed, 30 Jan 2013 17:11:24 +0000 Subject: [PATCH 0271/1663] Imports and raw tytpes git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1440528 13f79535-47bb-0310-9956-ffa450edef68 --- src/test/java/org/apache/commons/cli/BugsTest.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/test/java/org/apache/commons/cli/BugsTest.java b/src/test/java/org/apache/commons/cli/BugsTest.java index b246368c3..09c85da74 100644 --- a/src/test/java/org/apache/commons/cli/BugsTest.java +++ b/src/test/java/org/apache/commons/cli/BugsTest.java @@ -19,8 +19,6 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringWriter; import java.util.Iterator; import java.util.Properties; @@ -62,10 +60,10 @@ public void test11458() throws Exception assertEquals(values[1], "file2"); assertEquals(values[2], "file3"); - Iterator iter = cmd.iterator(); + Iterator