From 3ac60ae9b4c83ce37c9fe2641338f7ee07a34845 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 25 Jun 2006 20:20:15 +0000 Subject: [PATCH 01/28] Branching off the Avalon implementation git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@417063 13f79535-47bb-0310-9956-ffa450edef68 From 9e65354f1bdce4d47b42dd9d18d7d46a3ec05631 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 25 Jun 2006 20:33:16 +0000 Subject: [PATCH 02/28] An Avalon implementation of a commons vargs codebase - split onto its own branch so we can start focusing on the CLI parts individually git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@417069 13f79535-47bb-0310-9956-ffa450edef68 --- maven.xml | 6 - project.xml | 9 +- .../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 - .../org/apache/commons/cli2/Argument.java | 106 -- .../org/apache/commons/cli2/CommandLine.java | 214 ----- .../apache/commons/cli2/DisplaySetting.java | 154 --- src/java/org/apache/commons/cli2/Group.java | 64 -- .../org/apache/commons/cli2/HelpLine.java | 52 - src/java/org/apache/commons/cli2/Option.java | 196 ---- .../apache/commons/cli2/OptionException.java | 106 -- src/java/org/apache/commons/cli2/Parent.java | 40 - .../commons/cli2/WriteableCommandLine.java | 75 -- .../commons/cli2/builder/ArgumentBuilder.java | 285 ------ .../commons/cli2/builder/CommandBuilder.java | 186 ---- .../cli2/builder/DefaultOptionBuilder.java | 214 ----- .../commons/cli2/builder/GroupBuilder.java | 117 --- .../commons/cli2/builder/PatternBuilder.java | 201 ---- .../commons/cli2/builder/SwitchBuilder.java | 193 ---- .../cli2/commandline/CommandLineImpl.java | 119 --- .../commandline/DefaultingCommandLine.java | 171 ---- .../commons/cli2/commandline/Parser.java | 177 ---- .../commandline/PreferencesCommandLine.java | 169 ---- .../commandline/PropertiesCommandLine.java | 154 --- .../commandline/WriteableCommandLineImpl.java | 225 ----- .../commons/cli2/option/ArgumentImpl.java | 374 -------- .../apache/commons/cli2/option/Command.java | 174 ---- .../commons/cli2/option/DefaultOption.java | 220 ----- .../apache/commons/cli2/option/GroupImpl.java | 516 ---------- .../commons/cli2/option/HelpLineImpl.java | 109 --- .../commons/cli2/option/OptionImpl.java | 158 --- .../commons/cli2/option/ParentImpl.java | 250 ----- .../commons/cli2/option/PropertyOption.java | 166 ---- .../cli2/option/SourceDestArgument.java | 137 --- .../apache/commons/cli2/option/Switch.java | 247 ----- .../CLIMessageBundle_en_US.properties | 57 -- .../cli2/resource/ResourceConstants.java | 67 -- .../commons/cli2/resource/ResourceHelper.java | 159 --- .../apache/commons/cli2/util/Comparators.java | 455 --------- .../commons/cli2/util/HelpFormatter.java | 637 ------------ .../cli2/validation/ClassValidator.java | 200 ---- .../cli2/validation/DateValidator.java | 312 ------ .../cli2/validation/EnumValidator.java | 119 --- .../cli2/validation/FileValidator.java | 264 ----- .../validation/InvalidArgumentException.java | 33 - .../cli2/validation/NumberValidator.java | 199 ---- .../commons/cli2/validation/UrlValidator.java | 114 --- .../commons/cli2/validation/Validator.java | 42 - .../commons/cli2/validation/package.html | 16 - .../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 - .../org/apache/commons/cli2/CLITestCase.java | 84 -- .../commons/cli2/CommandLineDefaultsTest.java | 250 ----- .../commons/cli2/CommandLineTestCase.java | 511 ---------- .../commons/cli2/DocumentationTest.java | 444 --------- .../apache/commons/cli2/PrecedenceTest.java | 412 -------- .../cli2/WriteableCommandLineTestCase.java | 91 -- .../commons/cli2/application/AntTest.java | 197 ---- .../commons/cli2/application/CpTest.java | 470 --------- .../commons/cli2/application/CvsTest.java | 311 ------ .../commons/cli2/application/LsTest.java | 223 ----- .../apache/commons/cli2/bug/Bug13886Test.java | 88 -- .../apache/commons/cli2/bug/Bug13935Test.java | 59 -- .../apache/commons/cli2/bug/Bug15046Test.java | 81 -- .../apache/commons/cli2/bug/Bug15648Test.java | 59 -- .../apache/commons/cli2/bug/Bug27575Test.java | 40 - .../apache/commons/cli2/bug/Bug28005Test.java | 78 -- .../apache/commons/cli2/bug/Bug32533Test.java | 47 - .../apache/commons/cli2/bug/BugCLI18Test.java | 59 -- .../bug/BugLoopingOptionLookAlikeTest.java | 76 -- .../cli2/builder/ArgumentBuilderTest.java | 251 ----- .../builder/DefaultOptionBuilderTest.java | 199 ---- .../DefaultingCommandLineTest.java | 150 --- .../commons/cli2/commandline/ParserTest.java | 124 --- .../PreferencesCommandLineTest.java | 105 -- .../PropertiesCommandLineTest.java | 100 -- .../WriteableCommandLineImplTest.java | 35 - .../commons/cli2/jdepend/JDependTest.java | 108 --- .../commons/cli2/option/ArgumentTest.java | 645 ------------- .../commons/cli2/option/ArgumentTestCase.java | 27 - .../commons/cli2/option/CommandTest.java | 248 ----- .../cli2/option/DefaultOptionTest.java | 226 ----- .../apache/commons/cli2/option/GroupTest.java | 439 --------- .../commons/cli2/option/GroupTestCase.java | 30 - .../commons/cli2/option/NestedGroupTest.java | 191 ---- .../commons/cli2/option/OptionTestCase.java | 54 -- .../commons/cli2/option/ParentTest.java | 418 -------- .../commons/cli2/option/ParentTestCase.java | 25 - .../cli2/option/PropertyOptionTest.java | 232 ----- .../commons/cli2/option/SwitchTest.java | 307 ------ .../cli2/resource/ResourceHelperTest.java | 81 -- .../cli2/resource/TestBundle.properties | 10 - .../commons/cli2/util/ComparatorsTest.java | 220 ----- .../commons/cli2/util/HelpFormatterTest.java | 542 ----------- .../cli2/validation/ClassValidatorTest.java | 247 ----- .../cli2/validation/DateValidatorTest.java | 216 ----- .../cli2/validation/EnumValidatorTest.java | 65 -- .../cli2/validation/FileValidatorTest.java | 195 ---- .../cli2/validation/NumberValidatorTest.java | 167 ---- .../cli2/validation/TimeZoneTestSuite.java | 45 - .../cli2/validation/UrlValidatorTest.java | 92 -- .../validation/protect/ProtectedClass.java | 22 - 139 files changed, 5 insertions(+), 25779 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/java/org/apache/commons/cli2/Argument.java delete mode 100644 src/java/org/apache/commons/cli2/CommandLine.java delete mode 100644 src/java/org/apache/commons/cli2/DisplaySetting.java delete mode 100644 src/java/org/apache/commons/cli2/Group.java delete mode 100644 src/java/org/apache/commons/cli2/HelpLine.java delete mode 100644 src/java/org/apache/commons/cli2/Option.java delete mode 100644 src/java/org/apache/commons/cli2/OptionException.java delete mode 100644 src/java/org/apache/commons/cli2/Parent.java delete mode 100644 src/java/org/apache/commons/cli2/WriteableCommandLine.java delete mode 100644 src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java delete mode 100644 src/java/org/apache/commons/cli2/builder/CommandBuilder.java delete mode 100644 src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java delete mode 100644 src/java/org/apache/commons/cli2/builder/GroupBuilder.java delete mode 100644 src/java/org/apache/commons/cli2/builder/PatternBuilder.java delete mode 100644 src/java/org/apache/commons/cli2/builder/SwitchBuilder.java delete mode 100644 src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java delete mode 100644 src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java delete mode 100644 src/java/org/apache/commons/cli2/commandline/Parser.java delete mode 100644 src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java delete mode 100644 src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java delete mode 100644 src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java delete mode 100644 src/java/org/apache/commons/cli2/option/ArgumentImpl.java delete mode 100644 src/java/org/apache/commons/cli2/option/Command.java delete mode 100644 src/java/org/apache/commons/cli2/option/DefaultOption.java delete mode 100644 src/java/org/apache/commons/cli2/option/GroupImpl.java delete mode 100644 src/java/org/apache/commons/cli2/option/HelpLineImpl.java delete mode 100644 src/java/org/apache/commons/cli2/option/OptionImpl.java delete mode 100644 src/java/org/apache/commons/cli2/option/ParentImpl.java delete mode 100644 src/java/org/apache/commons/cli2/option/PropertyOption.java delete mode 100644 src/java/org/apache/commons/cli2/option/SourceDestArgument.java delete mode 100644 src/java/org/apache/commons/cli2/option/Switch.java delete mode 100644 src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties delete mode 100644 src/java/org/apache/commons/cli2/resource/ResourceConstants.java delete mode 100644 src/java/org/apache/commons/cli2/resource/ResourceHelper.java delete mode 100644 src/java/org/apache/commons/cli2/util/Comparators.java delete mode 100644 src/java/org/apache/commons/cli2/util/HelpFormatter.java delete mode 100644 src/java/org/apache/commons/cli2/validation/ClassValidator.java delete mode 100644 src/java/org/apache/commons/cli2/validation/DateValidator.java delete mode 100644 src/java/org/apache/commons/cli2/validation/EnumValidator.java delete mode 100644 src/java/org/apache/commons/cli2/validation/FileValidator.java delete mode 100644 src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java delete mode 100644 src/java/org/apache/commons/cli2/validation/NumberValidator.java delete mode 100644 src/java/org/apache/commons/cli2/validation/UrlValidator.java delete mode 100644 src/java/org/apache/commons/cli2/validation/Validator.java delete mode 100644 src/java/org/apache/commons/cli2/validation/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 delete mode 100644 src/test/org/apache/commons/cli2/CLITestCase.java delete mode 100644 src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java delete mode 100644 src/test/org/apache/commons/cli2/CommandLineTestCase.java delete mode 100644 src/test/org/apache/commons/cli2/DocumentationTest.java delete mode 100644 src/test/org/apache/commons/cli2/PrecedenceTest.java delete mode 100644 src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java delete mode 100644 src/test/org/apache/commons/cli2/application/AntTest.java delete mode 100644 src/test/org/apache/commons/cli2/application/CpTest.java delete mode 100644 src/test/org/apache/commons/cli2/application/CvsTest.java delete mode 100644 src/test/org/apache/commons/cli2/application/LsTest.java delete mode 100644 src/test/org/apache/commons/cli2/bug/Bug13886Test.java delete mode 100644 src/test/org/apache/commons/cli2/bug/Bug13935Test.java delete mode 100644 src/test/org/apache/commons/cli2/bug/Bug15046Test.java delete mode 100644 src/test/org/apache/commons/cli2/bug/Bug15648Test.java delete mode 100644 src/test/org/apache/commons/cli2/bug/Bug27575Test.java delete mode 100644 src/test/org/apache/commons/cli2/bug/Bug28005Test.java delete mode 100644 src/test/org/apache/commons/cli2/bug/Bug32533Test.java delete mode 100644 src/test/org/apache/commons/cli2/bug/BugCLI18Test.java delete mode 100644 src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java delete mode 100644 src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java delete mode 100644 src/test/org/apache/commons/cli2/builder/DefaultOptionBuilderTest.java delete mode 100644 src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java delete mode 100644 src/test/org/apache/commons/cli2/commandline/ParserTest.java delete mode 100644 src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java delete mode 100644 src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java delete mode 100644 src/test/org/apache/commons/cli2/commandline/WriteableCommandLineImplTest.java delete mode 100644 src/test/org/apache/commons/cli2/jdepend/JDependTest.java delete mode 100644 src/test/org/apache/commons/cli2/option/ArgumentTest.java delete mode 100644 src/test/org/apache/commons/cli2/option/ArgumentTestCase.java delete mode 100644 src/test/org/apache/commons/cli2/option/CommandTest.java delete mode 100644 src/test/org/apache/commons/cli2/option/DefaultOptionTest.java delete mode 100644 src/test/org/apache/commons/cli2/option/GroupTest.java delete mode 100644 src/test/org/apache/commons/cli2/option/GroupTestCase.java delete mode 100644 src/test/org/apache/commons/cli2/option/NestedGroupTest.java delete mode 100644 src/test/org/apache/commons/cli2/option/OptionTestCase.java delete mode 100644 src/test/org/apache/commons/cli2/option/ParentTest.java delete mode 100644 src/test/org/apache/commons/cli2/option/ParentTestCase.java delete mode 100644 src/test/org/apache/commons/cli2/option/PropertyOptionTest.java delete mode 100644 src/test/org/apache/commons/cli2/option/SwitchTest.java delete mode 100644 src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java delete mode 100644 src/test/org/apache/commons/cli2/resource/TestBundle.properties delete mode 100644 src/test/org/apache/commons/cli2/util/ComparatorsTest.java delete mode 100644 src/test/org/apache/commons/cli2/util/HelpFormatterTest.java delete mode 100644 src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java delete mode 100644 src/test/org/apache/commons/cli2/validation/DateValidatorTest.java delete mode 100644 src/test/org/apache/commons/cli2/validation/EnumValidatorTest.java delete mode 100644 src/test/org/apache/commons/cli2/validation/FileValidatorTest.java delete mode 100644 src/test/org/apache/commons/cli2/validation/NumberValidatorTest.java delete mode 100644 src/test/org/apache/commons/cli2/validation/TimeZoneTestSuite.java delete mode 100644 src/test/org/apache/commons/cli2/validation/UrlValidatorTest.java delete mode 100644 src/test/org/apache/commons/cli2/validation/protect/ProtectedClass.java diff --git a/maven.xml b/maven.xml index 30381eddd..3c75b354f 100644 --- a/maven.xml +++ b/maven.xml @@ -31,12 +31,6 @@ limitations under the License. - - Moving test bundle. - - - diff --git a/project.xml b/project.xml index 6ec86d4cb..de83d1ab8 100644 --- a/project.xml +++ b/project.xml @@ -18,12 +18,13 @@ org.apache.commons commons-cli CLI - 2.0-SNAPSHOT + avalon-implementation-SNAPSHOT 2002 - Commons CLI + Commons CLI - Avalon Implementation - Commons CLI provides a simple API for presenting, proecessing and - validating a command line interface. + Commons CLI provides a simple API for presenting, processing and + validating a command line interface. This is an implementation from + Avalon's code base. /images/logo.png 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:

- *
    - *
  • opt is not NULL
  • - *
  • a single character opt that is either - * ' '(special case), '?', '@' or a letter
  • - *
  • a multi character opt that only contains - * letters.
  • - *
- * - * @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. - *

    - *
  • 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 - * @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/java/org/apache/commons/cli2/Argument.java b/src/java/org/apache/commons/cli2/Argument.java deleted file mode 100644 index b5fb46601..000000000 --- a/src/java/org/apache/commons/cli2/Argument.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright 2003-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; - -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 deleted file mode 100644 index cad65cae0..000000000 --- a/src/java/org/apache/commons/cli2/CommandLine.java +++ /dev/null @@ -1,214 +0,0 @@ -/** - * Copyright 2003-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; - -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 deleted file mode 100644 index eacd1cdc9..000000000 --- a/src/java/org/apache/commons/cli2/DisplaySetting.java +++ /dev/null @@ -1,154 +0,0 @@ -/** - * Copyright 2003-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; - -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 deleted file mode 100644 index 90ae08cd2..000000000 --- a/src/java/org/apache/commons/cli2/Group.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2003-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; - -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 deleted file mode 100644 index a7ad5b7df..000000000 --- a/src/java/org/apache/commons/cli2/HelpLine.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright 2003-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; - -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 deleted file mode 100644 index c65093981..000000000 --- a/src/java/org/apache/commons/cli2/Option.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 613f9aeef..000000000 --- a/src/java/org/apache/commons/cli2/OptionException.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index bf9d5a57a..000000000 --- a/src/java/org/apache/commons/cli2/Parent.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2003-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; - -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 deleted file mode 100644 index 64be37fd3..000000000 --- a/src/java/org/apache/commons/cli2/WriteableCommandLine.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright 2003-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; - -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 deleted file mode 100644 index f03999379..000000000 --- a/src/java/org/apache/commons/cli2/builder/ArgumentBuilder.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 5a8a8a224..000000000 --- a/src/java/org/apache/commons/cli2/builder/CommandBuilder.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index bc172d817..000000000 --- a/src/java/org/apache/commons/cli2/builder/DefaultOptionBuilder.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index a3755391d..000000000 --- a/src/java/org/apache/commons/cli2/builder/GroupBuilder.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 1bb9bc8ba..000000000 --- a/src/java/org/apache/commons/cli2/builder/PatternBuilder.java +++ /dev/null @@ -1,201 +0,0 @@ -/** - * Copyright 2003-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.builder; - -import java.util.HashSet; -import java.util.Iterator; -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 HashSet(); - - /** - * 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 deleted file mode 100644 index 0baab08ff..000000000 --- a/src/java/org/apache/commons/cli2/builder/SwitchBuilder.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index dd9abefef..000000000 --- a/src/java/org/apache/commons/cli2/commandline/CommandLineImpl.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 153f32d39..000000000 --- a/src/java/org/apache/commons/cli2/commandline/DefaultingCommandLine.java +++ /dev/null @@ -1,171 +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.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 deleted file mode 100644 index 3adbc47c2..000000000 --- a/src/java/org/apache/commons/cli2/commandline/Parser.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright 2003-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.cli2.commandline; - -import java.io.IOException; - -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 deleted file mode 100644 index ddfa82853..000000000 --- a/src/java/org/apache/commons/cli2/commandline/PreferencesCommandLine.java +++ /dev/null @@ -1,169 +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.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 deleted file mode 100644 index 1ae4f9485..000000000 --- a/src/java/org/apache/commons/cli2/commandline/PropertiesCommandLine.java +++ /dev/null @@ -1,154 +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.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 deleted file mode 100644 index c8299075c..000000000 --- a/src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright 2004-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.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(defaultSwitch); - } 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 deleted file mode 100644 index d64f2fc94..000000000 --- a/src/java/org/apache/commons/cli2/option/ArgumentImpl.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Copyright 2003-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.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; -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 allValues = stripBoundaryQuotes((String) arguments.next()); - - // should we ignore things that look like options? - if (allValues.equals(consumeRemaining)) { - while (arguments.hasNext() && (argumentCount < maximum)) { - ++argumentCount; - commandLine.addValue(option, arguments.next()); - } - } - // does it look like an option? - else if (commandLine.looksLikeOption(allValues)) { - 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 deleted file mode 100644 index c63909495..000000000 --- a/src/java/org/apache/commons/cli2/option/Command.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index b169b64ee..000000000 --- a/src/java/org/apache/commons/cli2/option/DefaultOption.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index eac83adc0..000000000 --- a/src/java/org/apache/commons/cli2/option/GroupImpl.java +++ /dev/null @@ -1,516 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 70a1dd5ae..000000000 --- a/src/java/org/apache/commons/cli2/option/HelpLineImpl.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 3b6c6be01..000000000 --- a/src/java/org/apache/commons/cli2/option/OptionImpl.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 7b58a7d5c..000000000 --- a/src/java/org/apache/commons/cli2/option/ParentImpl.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright 2003-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.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)); - arguments.add(newArgument.substring(initialIndex + 1)); - 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 deleted file mode 100644 index 7575d8421..000000000 --- a/src/java/org/apache/commons/cli2/option/PropertyOption.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index d6d440dac..000000000 --- a/src/java/org/apache/commons/cli2/option/SourceDestArgument.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 3c30e265b..000000000 --- a/src/java/org/apache/commons/cli2/option/Switch.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright 2003-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.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/CLIMessageBundle_en_US.properties b/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties deleted file mode 100644 index 81121984a..000000000 --- a/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties +++ /dev/null @@ -1,57 +0,0 @@ -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 deleted file mode 100644 index 2db366a9b..000000000 --- a/src/java/org/apache/commons/cli2/resource/ResourceConstants.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 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.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 deleted file mode 100644 index a65adb8e2..000000000 --- a/src/java/org/apache/commons/cli2/resource/ResourceHelper.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 9f8062329..000000000 --- a/src/java/org/apache/commons/cli2/util/Comparators.java +++ /dev/null @@ -1,455 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index a3a5fb370..000000000 --- a/src/java/org/apache/commons/cli2/util/HelpFormatter.java +++ /dev/null @@ -1,637 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index b989845b4..000000000 --- a/src/java/org/apache/commons/cli2/validation/ClassValidator.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 0820155dd..000000000 --- a/src/java/org/apache/commons/cli2/validation/DateValidator.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright 2003-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.cli2.validation; - -import java.text.DateFormat; -import java.text.ParsePosition; - -import java.util.Date; -import java.util.Iterator; -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) { - for (Iterator iter = formats.iterator(); iter.hasNext();) { - DateFormat format = (DateFormat) iter.next(); - } - - 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 deleted file mode 100644 index f685213cc..000000000 --- a/src/java/org/apache/commons/cli2/validation/EnumValidator.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 22b2e1d57..000000000 --- a/src/java/org/apache/commons/cli2/validation/FileValidator.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index ea1030843..000000000 --- a/src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 2b3f9409b..000000000 --- a/src/java/org/apache/commons/cli2/validation/NumberValidator.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index e73855b6b..000000000 --- a/src/java/org/apache/commons/cli2/validation/UrlValidator.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 9d5778ad2..000000000 --- a/src/java/org/apache/commons/cli2/validation/Validator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2003-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.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/java/org/apache/commons/cli2/validation/package.html b/src/java/org/apache/commons/cli2/validation/package.html deleted file mode 100644 index 63bc28b1d..000000000 --- a/src/java/org/apache/commons/cli2/validation/package.html +++ /dev/null @@ -1,16 +0,0 @@ - - -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/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: - *

    - *
  • Ant
  • - *
- *

- * - * @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); - } -} - diff --git a/src/test/org/apache/commons/cli2/CLITestCase.java b/src/test/org/apache/commons/cli2/CLITestCase.java deleted file mode 100644 index a16d15ab3..000000000 --- a/src/test/org/apache/commons/cli2/CLITestCase.java +++ /dev/null @@ -1,84 +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.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 deleted file mode 100644 index a05e8d31d..000000000 --- a/src/test/org/apache/commons/cli2/CommandLineDefaultsTest.java +++ /dev/null @@ -1,250 +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.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 deleted file mode 100644 index 38349dcd2..000000000 --- a/src/test/org/apache/commons/cli2/CommandLineTestCase.java +++ /dev/null @@ -1,511 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 634f03619..000000000 --- a/src/test/org/apache/commons/cli2/DocumentationTest.java +++ /dev/null @@ -1,444 +0,0 @@ -/** - * Copyright 2003-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; - -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 deleted file mode 100644 index 6af714212..000000000 --- a/src/test/org/apache/commons/cli2/PrecedenceTest.java +++ /dev/null @@ -1,412 +0,0 @@ -/** - * Copyright 2003-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; - -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 deleted file mode 100644 index 3fe3e5a25..000000000 --- a/src/test/org/apache/commons/cli2/WriteableCommandLineTestCase.java +++ /dev/null @@ -1,91 +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.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 deleted file mode 100644 index 0a0cbe05e..000000000 --- a/src/test/org/apache/commons/cli2/application/AntTest.java +++ /dev/null @@ -1,197 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 08e13c0a0..000000000 --- a/src/test/org/apache/commons/cli2/application/CpTest.java +++ /dev/null @@ -1,470 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index bee4a12c3..000000000 --- a/src/test/org/apache/commons/cli2/application/CvsTest.java +++ /dev/null @@ -1,311 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 6f597bfba..000000000 --- a/src/test/org/apache/commons/cli2/application/LsTest.java +++ /dev/null @@ -1,223 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 8742cf057..000000000 --- a/src/test/org/apache/commons/cli2/bug/Bug13886Test.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 6600ad47f..000000000 --- a/src/test/org/apache/commons/cli2/bug/Bug13935Test.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 60a6dc372..000000000 --- a/src/test/org/apache/commons/cli2/bug/Bug15046Test.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 44f91575d..000000000 --- a/src/test/org/apache/commons/cli2/bug/Bug15648Test.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 4bc611bb8..000000000 --- a/src/test/org/apache/commons/cli2/bug/Bug27575Test.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2003-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 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 deleted file mode 100644 index aecbf48ec..000000000 --- a/src/test/org/apache/commons/cli2/bug/Bug28005Test.java +++ /dev/null @@ -1,78 +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.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 deleted file mode 100644 index c9f94e5ff..000000000 --- a/src/test/org/apache/commons/cli2/bug/Bug32533Test.java +++ /dev/null @@ -1,47 +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.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/BugCLI18Test.java b/src/test/org/apache/commons/cli2/bug/BugCLI18Test.java deleted file mode 100644 index 224780d09..000000000 --- a/src/test/org/apache/commons/cli2/bug/BugCLI18Test.java +++ /dev/null @@ -1,59 +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.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/BugLoopingOptionLookAlikeTest.java b/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java deleted file mode 100644 index e95ba3dac..000000000 --- a/src/test/org/apache/commons/cli2/bug/BugLoopingOptionLookAlikeTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright 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.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 deleted file mode 100644 index 74eb46c11..000000000 --- a/src/test/org/apache/commons/cli2/builder/ArgumentBuilderTest.java +++ /dev/null @@ -1,251 +0,0 @@ -/* - * Copyright 2004-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.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 deleted file mode 100644 index 0c7bd5e70..000000000 --- a/src/test/org/apache/commons/cli2/builder/DefaultOptionBuilderTest.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2004-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.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 deleted file mode 100644 index 6125ee7e8..000000000 --- a/src/test/org/apache/commons/cli2/commandline/DefaultingCommandLineTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2004-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.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 deleted file mode 100644 index 096a91927..000000000 --- a/src/test/org/apache/commons/cli2/commandline/ParserTest.java +++ /dev/null @@ -1,124 +0,0 @@ -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 deleted file mode 100644 index d77c59824..000000000 --- a/src/test/org/apache/commons/cli2/commandline/PreferencesCommandLineTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2004-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.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 deleted file mode 100644 index 4cec1c475..000000000 --- a/src/test/org/apache/commons/cli2/commandline/PropertiesCommandLineTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2004-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.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 deleted file mode 100644 index 7fafe031f..000000000 --- a/src/test/org/apache/commons/cli2/commandline/WriteableCommandLineImplTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2004-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.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 deleted file mode 100644 index 6550c690a..000000000 --- a/src/test/org/apache/commons/cli2/jdepend/JDependTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 215e1ae9e..000000000 --- a/src/test/org/apache/commons/cli2/option/ArgumentTest.java +++ /dev/null @@ -1,645 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index abd481fcd..000000000 --- a/src/test/org/apache/commons/cli2/option/ArgumentTestCase.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 6c7693024..000000000 --- a/src/test/org/apache/commons/cli2/option/CommandTest.java +++ /dev/null @@ -1,248 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index d9dfa009a..000000000 --- a/src/test/org/apache/commons/cli2/option/DefaultOptionTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index f7686b8a7..000000000 --- a/src/test/org/apache/commons/cli2/option/GroupTest.java +++ /dev/null @@ -1,439 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 5df178c40..000000000 --- a/src/test/org/apache/commons/cli2/option/GroupTestCase.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index ebebe2d70..000000000 --- a/src/test/org/apache/commons/cli2/option/NestedGroupTest.java +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 55724b53d..000000000 --- a/src/test/org/apache/commons/cli2/option/OptionTestCase.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index a25d9f148..000000000 --- a/src/test/org/apache/commons/cli2/option/ParentTest.java +++ /dev/null @@ -1,418 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 5851c25c6..000000000 --- a/src/test/org/apache/commons/cli2/option/ParentTestCase.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 1d020f58b..000000000 --- a/src/test/org/apache/commons/cli2/option/PropertyOptionTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index ea5e38e4a..000000000 --- a/src/test/org/apache/commons/cli2/option/SwitchTest.java +++ /dev/null @@ -1,307 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 00d4fd57a..000000000 --- a/src/test/org/apache/commons/cli2/resource/ResourceHelperTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2003-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.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/resource/TestBundle.properties b/src/test/org/apache/commons/cli2/resource/TestBundle.properties deleted file mode 100644 index 3ae6d180e..000000000 --- a/src/test/org/apache/commons/cli2/resource/TestBundle.properties +++ /dev/null @@ -1,10 +0,0 @@ -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. - diff --git a/src/test/org/apache/commons/cli2/util/ComparatorsTest.java b/src/test/org/apache/commons/cli2/util/ComparatorsTest.java deleted file mode 100644 index c631da449..000000000 --- a/src/test/org/apache/commons/cli2/util/ComparatorsTest.java +++ /dev/null @@ -1,220 +0,0 @@ -/** - * Copyright 2003-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.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 deleted file mode 100644 index 72ea14106..000000000 --- a/src/test/org/apache/commons/cli2/util/HelpFormatterTest.java +++ /dev/null @@ -1,542 +0,0 @@ -/* - * Copyright 2003-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.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("Jakarta 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", "Jakarta 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("|*Jakarta 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("|*Jakarta 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("|*Jakarta 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 deleted file mode 100644 index 467b7b030..000000000 --- a/src/test/org/apache/commons/cli2/validation/ClassValidatorTest.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index b83c1c49a..000000000 --- a/src/test/org/apache/commons/cli2/validation/DateValidatorTest.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright 2003-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.cli2.validation; - -import java.text.DateFormat; -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 { - final Object[] array = new Object[] { "23-Dec-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 { - final Object[] array = new Object[] { "23-Jan-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 deleted file mode 100644 index eb65d3c60..000000000 --- a/src/test/org/apache/commons/cli2/validation/EnumValidatorTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2004-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.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 deleted file mode 100644 index 15060647a..000000000 --- a/src/test/org/apache/commons/cli2/validation/FileValidatorTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright 2004-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.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 deleted file mode 100644 index b698ba7a4..000000000 --- a/src/test/org/apache/commons/cli2/validation/NumberValidatorTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright 2003-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.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 deleted file mode 100644 index 238de6207..000000000 --- a/src/test/org/apache/commons/cli2/validation/TimeZoneTestSuite.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 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.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 deleted file mode 100644 index 7725fc5a5..000000000 --- a/src/test/org/apache/commons/cli2/validation/UrlValidatorTest.java +++ /dev/null @@ -1,92 +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.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 deleted file mode 100644 index fdac80fe1..000000000 --- a/src/test/org/apache/commons/cli2/validation/protect/ProtectedClass.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright 2003-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.validation.protect; - -class ProtectedClass { - protected ProtectedClass() { - // used to test something??? - } -} From 80124fda839dc594076c0c19d27eb80baaced6a0 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 17:18:33 +0000 Subject: [PATCH 03/28] CLI2 -> Avalon git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529017 13f79535-47bb-0310-9956-ffa450edef68 --- src/conf/MANIFEST.MF | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/conf/MANIFEST.MF b/src/conf/MANIFEST.MF index c7f076871..b108198fe 100644 --- a/src/conf/MANIFEST.MF +++ b/src/conf/MANIFEST.MF @@ -1,11 +1,6 @@ -Implementation-Title: Jakarta Commons CLI2 +Implementation-Title: Jakarta Commons Avalon CLI -Name: org/apache/commons/cli/ -Specification-Title: Jakarta Commons CLI +Name: org/apache/commons/cli/avalon +Specification-Title: Jakarta Commons Avalon 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 -Specification-Version: 2.0 +Specification-Version: 2.0 \ No newline at end of file From 28c80519cd084ebc9734b54cf26defe90de707f5 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 17:20:39 +0000 Subject: [PATCH 04/28] Not used for Avalon CLI git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529019 13f79535-47bb-0310-9956-ffa450edef68 --- src/test/data/.hidden.txt | 1 - src/test/data/readable.txt | 1 - src/test/data/writable.txt | 1 - 3 files changed, 3 deletions(-) delete mode 100644 src/test/data/.hidden.txt delete mode 100644 src/test/data/readable.txt delete mode 100644 src/test/data/writable.txt diff --git a/src/test/data/.hidden.txt b/src/test/data/.hidden.txt deleted file mode 100644 index d18fa71c2..000000000 --- a/src/test/data/.hidden.txt +++ /dev/null @@ -1 +0,0 @@ -Hidden text file. diff --git a/src/test/data/readable.txt b/src/test/data/readable.txt deleted file mode 100644 index cada839a9..000000000 --- a/src/test/data/readable.txt +++ /dev/null @@ -1 +0,0 @@ -Readable text file. diff --git a/src/test/data/writable.txt b/src/test/data/writable.txt deleted file mode 100644 index 53f7f5d97..000000000 --- a/src/test/data/writable.txt +++ /dev/null @@ -1 +0,0 @@ -Writable text file. From b0192c58a2aa1a96c6b7a5123c67be87ae36abf0 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 17:22:41 +0000 Subject: [PATCH 05/28] Fix ASF licence; add NON-NLS markers git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529021 13f79535-47bb-0310-9956-ffa450edef68 --- .../cli/avalon/AbstractParserControl.java | 28 +++++----- .../commons/cli/avalon/CLArgsParser.java | 55 ++++++++++--------- .../apache/commons/cli/avalon/CLOption.java | 29 +++++----- .../cli/avalon/CLOptionDescriptor.java | 35 ++++++------ .../org/apache/commons/cli/avalon/CLUtil.java | 39 ++++++------- .../commons/cli/avalon/ParserControl.java | 25 +++++---- .../org/apache/commons/cli/avalon/Token.java | 26 ++++----- 7 files changed, 121 insertions(+), 116 deletions(-) diff --git a/src/java/org/apache/commons/cli/avalon/AbstractParserControl.java b/src/java/org/apache/commons/cli/avalon/AbstractParserControl.java index f486df06c..08cd93914 100644 --- a/src/java/org/apache/commons/cli/avalon/AbstractParserControl.java +++ b/src/java/org/apache/commons/cli/avalon/AbstractParserControl.java @@ -1,26 +1,28 @@ -/* - * Copyright 2002-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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - * implied. - * + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.avalon; //Renamed from org.apache.avalon.excalibur.cli /** * Class to inherit from so when in future when new controls are added - * clients will no have to implement them. - * @version $Revision: 1.2 $ + * clients will not have to implement them. + * * @see ParserControl */ public abstract class AbstractParserControl diff --git a/src/java/org/apache/commons/cli/avalon/CLArgsParser.java b/src/java/org/apache/commons/cli/avalon/CLArgsParser.java index 19bd5c6e8..7eb7e2f77 100644 --- a/src/java/org/apache/commons/cli/avalon/CLArgsParser.java +++ b/src/java/org/apache/commons/cli/avalon/CLArgsParser.java @@ -1,19 +1,21 @@ -/* - * Copyright 2002-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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - * implied. - * + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.avalon; //Renamed from org.apache.avalon.excalibur.cli @@ -32,7 +34,6 @@ * Note that CLArgs uses a backing hashtable for the options index and so duplicate * arguments are only returned by getArguments(). * - * @version $Revision: 1.2 $ $Date: 2005/03/18 15:26:55 $ * @see ParserControl * @see CLOption * @see CLOptionDescriptor @@ -330,7 +331,7 @@ private final String describeDualOption( final int id ) if( Character.isLetter( (char)id ) ) { - sb.append( '-' ); + sb.append( '-' ); // $NON-NLS-1$ sb.append( (char)id ); hasCharOption = true; } @@ -340,9 +341,9 @@ private final String describeDualOption( final int id ) { if( hasCharOption ) { - sb.append( '/' ); + sb.append( '/' ); // $NON-NLS-1$ } - sb.append( "--" ); + sb.append( "--" ); // $NON-NLS-1$ sb.append( longOption ); } @@ -478,7 +479,7 @@ else if( STATE_REQUIRE_2ARGS == m_state ) { if( 1 == m_option.getArgumentCount() ) { - m_option.addArgument( "" ); + m_option.addArgument( "" ); // $NON-NLS-1$ m_options.addElement( m_option ); } else @@ -501,11 +502,11 @@ private final String getOptionDescription( final CLOptionDescriptor descriptor ) { if( m_isLong ) { - return "--" + descriptor.getName(); + return "--" + descriptor.getName(); // $NON-NLS-1$ } else { - return "-" + (char)descriptor.getId(); + return "-" + (char)descriptor.getId(); // $NON-NLS-1$ } } @@ -625,7 +626,7 @@ private final void parseShortOption() m_ch = getChar(); final CLOptionDescriptor descriptor = getDescriptorFor( m_ch ); m_isLong = false; - parseOption( descriptor, "-" + m_ch ); + parseOption( descriptor, "-" + m_ch ); // $NON-NLS-1$ if( STATE_NORMAL == m_state ) { @@ -638,7 +639,7 @@ private final void parseArguments() { if( STATE_REQUIRE_ARG == m_state ) { - if( '=' == m_ch || 0 == m_ch ) + if( '=' == m_ch || 0 == m_ch ) // $NON-NLS-1$ { getChar(); } @@ -651,7 +652,7 @@ private final void parseArguments() } else if( STATE_OPTIONAL_ARG == m_state ) { - if( '-' == m_ch || 0 == m_ch ) + if( '-' == m_ch || 0 == m_ch ) // $NON-NLS-1$ { getChar(); //consume stray character addOption( m_option ); @@ -659,7 +660,7 @@ else if( STATE_OPTIONAL_ARG == m_state ) return; } - if( '=' == m_ch ) + if( '=' == m_ch ) // $NON-NLS-1$ { getChar(); } @@ -700,9 +701,9 @@ else if( STATE_REQUIRE_2ARGS == m_state ) m_option.addArgument( token.getValue() ); } // Are we about to start a new option? - if (0 == m_ch && '-' == peekAtChar()){ + if (0 == m_ch && '-' == peekAtChar()){ // $NON-NLS-1$ // Yes, so the second argument is missing - m_option.addArgument( "" ); + m_option.addArgument( "" ); // $NON-NLS-1$ m_options.addElement( m_option ); m_state = STATE_NORMAL; } @@ -736,7 +737,7 @@ else if( STATE_REQUIRE_2ARGS == m_state ) private final void parseNormal() throws ParseException { - if( '-' != m_ch ) + if( '-' != m_ch ) // $NON-NLS-1$ { //Parse the arguments that are not options final String argument = nextToken( NULL_SEPARATORS ).getValue(); @@ -756,7 +757,7 @@ private final void parseNormal() m_ch = peekAtChar(); //if it is a short option then parse it else ... - if( '-' != m_ch ) + if( '-' != m_ch ) // $NON-NLS-1$ { parseShortOption(); } @@ -777,7 +778,7 @@ private final void parseNormal() final String optionName = nextToken( ARG_SEPARATORS ).getValue(); final CLOptionDescriptor descriptor = getDescriptorFor( optionName ); m_isLong = true; - parseOption( descriptor, "--" + optionName ); + parseOption( descriptor, "--" + optionName ); // $NON-NLS-1$ } } } diff --git a/src/java/org/apache/commons/cli/avalon/CLOption.java b/src/java/org/apache/commons/cli/avalon/CLOption.java index 5d163c254..d2fdd83a0 100644 --- a/src/java/org/apache/commons/cli/avalon/CLOption.java +++ b/src/java/org/apache/commons/cli/avalon/CLOption.java @@ -1,19 +1,21 @@ -/* - * Copyright 2002-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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - * implied. - * + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.avalon; // Renamed from org.apache.avalon.excalibur.cli @@ -22,7 +24,6 @@ /** * Basic class describing an instance of option. * - * @version $Revision: 1.2 $ $Date: 2005/03/18 15:26:55 $ */ public final class CLOption { @@ -162,11 +163,11 @@ public final String toString() if( null != m_arguments ) { - sb.append( ", " ); + sb.append( ", " ); // $NON-NLS-1$ sb.append( Arrays.asList( m_arguments ) ); } - sb.append( " ]" ); + sb.append( " ]" ); // $NON-NLS-1$ return sb.toString(); } diff --git a/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java b/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java index eb5d9a860..4b8566378 100644 --- a/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java +++ b/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java @@ -1,19 +1,21 @@ -/* - * Copyright 2002-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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - * implied. - * + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.avalon; //Renamed from org.apache.avalon.excalibur.cli @@ -22,7 +24,6 @@ * Typically, one creates a static array of CLOptionDescriptors, * and passes it to {@link CLArgsParser#CLArgsParser(String[], CLOptionDescriptor[])}. * - * @version $Revision: 1.2 $ $Date: 2005/03/18 15:26:55 $ * @see CLArgsParser * @see CLUtil */ @@ -212,15 +213,13 @@ public final String toString() final StringBuffer sb = new StringBuffer(); sb.append( "[OptionDescriptor " ); sb.append( m_name ); - sb.append( "[OptionDescriptor " ); - sb.append( m_name ); - sb.append( ", " ); + sb.append( ", " ); // $NON-NLS-1$ sb.append( m_id ); - sb.append( ", " ); + sb.append( ", " ); // $NON-NLS-1$ sb.append( m_flags ); - sb.append( ", " ); + sb.append( ", " ); // $NON-NLS-1$ sb.append( m_description ); - sb.append( " ]" ); + sb.append( " ]" ); // $NON-NLS-1$ return sb.toString(); } } diff --git a/src/java/org/apache/commons/cli/avalon/CLUtil.java b/src/java/org/apache/commons/cli/avalon/CLUtil.java index f3b2c44e8..1efd8d283 100644 --- a/src/java/org/apache/commons/cli/avalon/CLUtil.java +++ b/src/java/org/apache/commons/cli/avalon/CLUtil.java @@ -1,26 +1,27 @@ -/* - * Copyright 2002-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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - * implied. - * + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.avalon; //Renamed from org.apache.avalon.excalibur.cli /** * CLUtil offers basic utility operations for use both internal and external to package. * - * @version $Revision: 1.2 $ $Date: 2005/03/18 15:26:55 $ * @see CLOptionDescriptor */ public final class CLUtil @@ -36,7 +37,7 @@ public final class CLUtil */ public static final StringBuffer describeOptions( final CLOptionDescriptor[] options ) { - final String lSep = System.getProperty( "line.separator" ); + final String lSep = System.getProperty( "line.separator" ); // $NON-NLS-1$ final StringBuffer sb = new StringBuffer(); for( int i = 0; i < options.length; i++ ) @@ -57,11 +58,11 @@ public static final StringBuffer describeOptions( final CLOptionDescriptor[] opt argumentRequired = true; } - sb.append( '\t' ); + sb.append( '\t' ); // $NON-NLS-1$ if( Character.isLetter( ch ) ) { - sb.append( "-" ); + sb.append( "-" ); // $NON-NLS-1$ sb.append( ch ); needComma = true; } @@ -70,10 +71,10 @@ public static final StringBuffer describeOptions( final CLOptionDescriptor[] opt { if( needComma ) { - sb.append( ", " ); + sb.append( ", " ); // $NON-NLS-1$ } - sb.append( "--" ); + sb.append( "--" ); // $NON-NLS-1$ sb.append( name ); } @@ -95,12 +96,12 @@ public static final StringBuffer describeOptions( final CLOptionDescriptor[] opt description.substring( 0, MAX_DESCRIPTION_COLUMN_LENGTH ); description = description.substring( MAX_DESCRIPTION_COLUMN_LENGTH ); - sb.append( "\t\t" ); + sb.append( "\t\t" ); // $NON-NLS-1$ sb.append( descriptionPart ); sb.append( lSep ); } - sb.append( "\t\t" ); + sb.append( "\t\t" ); // $NON-NLS-1$ sb.append( description ); sb.append( lSep ); } diff --git a/src/java/org/apache/commons/cli/avalon/ParserControl.java b/src/java/org/apache/commons/cli/avalon/ParserControl.java index 958ea7a9d..9d7cf3623 100644 --- a/src/java/org/apache/commons/cli/avalon/ParserControl.java +++ b/src/java/org/apache/commons/cli/avalon/ParserControl.java @@ -1,26 +1,27 @@ -/* - * Copyright 2002-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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - * implied. - * + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.avalon; //Renamed from org.apache.avalon.excalibur.cli /** * ParserControl is used to control particular behaviour of the parser. * - * @version $Revision: 1.2 $ $Date: 2005/03/18 15:26:55 $ * @see AbstractParserControl */ public interface ParserControl diff --git a/src/java/org/apache/commons/cli/avalon/Token.java b/src/java/org/apache/commons/cli/avalon/Token.java index 466c1763e..8fd470360 100644 --- a/src/java/org/apache/commons/cli/avalon/Token.java +++ b/src/java/org/apache/commons/cli/avalon/Token.java @@ -1,27 +1,27 @@ -/* - * Copyright 2002-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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - * implied. - * + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.avalon; //Renamed from org.apache.avalon.excalibur.cli /** * Token handles tokenizing the CLI arguments * - * @version $Revision: 1.2 $ $Date: 2005/03/18 15:26:55 $ - * @since 4.0 */ class Token { From 46bacc08c6ab5df858ab0b20a19787b1bf607d6a Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 17:23:15 +0000 Subject: [PATCH 06/28] Fix ASF licence git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529022 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli/avalon/ClutilTestCase.java | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/test/org/apache/commons/cli/avalon/ClutilTestCase.java b/src/test/org/apache/commons/cli/avalon/ClutilTestCase.java index d48971396..2bf298341 100644 --- a/src/test/org/apache/commons/cli/avalon/ClutilTestCase.java +++ b/src/test/org/apache/commons/cli/avalon/ClutilTestCase.java @@ -1,19 +1,21 @@ -/* - * Copyright 2002-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 - * +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - * implied. - * + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.avalon; //Renamed from org.apache.avalon.excalibur.cli From a75fffafadbb7f6ce99841ed8697c9b664517a38 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 17:23:46 +0000 Subject: [PATCH 07/28] Not used for Avalon CLI git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529023 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/examples/ant.xml | 300 --------------------------------------- xdocs/examples/cp.xml | 35 ----- xdocs/examples/cvs.xml | 35 ----- xdocs/examples/index.xml | 42 ------ xdocs/examples/ls.xml | 35 ----- 5 files changed, 447 deletions(-) delete mode 100644 xdocs/examples/ant.xml delete mode 100644 xdocs/examples/cp.xml delete mode 100644 xdocs/examples/cvs.xml delete mode 100644 xdocs/examples/index.xml delete mode 100644 xdocs/examples/ls.xml diff --git a/xdocs/examples/ant.xml b/xdocs/examples/ant.xml deleted file mode 100644 index 8b135b3e8..000000000 --- a/xdocs/examples/ant.xml +++ /dev/null @@ -1,300 +0,0 @@ - - - - - - commons-dev - Examples - ant - - - -
-

- This example works through modelling Apache Ant using CLI2, the - example is based on Apache Ant version 1.6.1 compiled on February 12 - 2004. -

-

- "Apache Ant is a Java-based build tool. In theory, it is kind of like - Make, but without Make's wrinkles." - For more information please - visit http://ant.apache.org/ -

- -

- To model the ant options we first need to create some Builders so that - each of the option instances can be created: -

-final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); -final ArgumentBuilder abuilder = new ArgumentBuilder(); -final GroupBuilder gbuilder = new GroupBuilder(); -

- For each option we create an Option instance that will model it, built - using the Builder instances above: -

-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(); -

- We now create a Group instance consisting of all the above options: -

-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(); -
- -

- Once the model is built, a CommandLine needs to be parsed: -

-Parser parser = new Parser(); -parser.setGroup(options); -CommandLine cl = parser.parse(args); -

- The CommandLine can be tested for the presence of options using the - hasOption() methods which take either an option instance or a trigger - value to lookup against: -

-if(cl.hasOption(help)) { - //displayHelp(); - return; -} -if(cl.hasOption("-version")) { - //displayVersion(); - return; -} -

- For those options that have an argument, the argument needs to be - extracted and processed: -

-if(cl.hasOption(logfile)) { - String file = (String)cl.getValue(logfile); - //setLogFile(file); -} -

- Each target for ant to process could then be processed in order as - specified: -

-List targetList = cl.getValues(targets); -for (Iterator i = targetList.iterator(); i.hasNext();) { - String target = (String) i.next(); - //doTarget(target); -} -
- -

- 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, - and the group is the group of options that compose the model. -

-HelpFormatter hf = new HelpFormatter(); -hf.setShellCommand("ant"); -hf.setGroup(options); -

- The first section of help will display the full usage string for the - application, the appearence of this line can be adjusted using the - HelpFormatter's fullUsageSettings property: -

-hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_NAME); -hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_ARGUMENT); -hf.getFullUsageSettings().remove(DisplaySetting.DISPLAY_GROUP_EXPANDED); -

- The main body of the help is based on a line or more of information - about each option in the model. DisplaySettings can be used again to - adjust which items are included in this display and which aren't. In - this case, we don't want to display any groups as the top one is the - only one present and can be inferred: -

-hf.getDisplaySettings().remove(DisplaySetting.DISPLAY_GROUP_ARGUMENT); -

- Each of the options identified by the displaySettings above has some - usage information displayed, usually this will be a minimal set of - DisplaySettings but these can be adjusted to get the desired effect: -

-hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PROPERTY_OPTION); -hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PARENT_ARGUMENT); -hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED); -

- Finally, the help can be printed to System.out with a simple call to - print(): -

-hf.print(); -
-
- -
diff --git a/xdocs/examples/cp.xml b/xdocs/examples/cp.xml deleted file mode 100644 index dfc6574e8..000000000 --- a/xdocs/examples/cp.xml +++ /dev/null @@ -1,35 +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 34009c1ee..000000000 --- a/xdocs/examples/cvs.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - commons-dev - Examples - cvs - - - -
-

TODO what is cvs

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

- The examples section aims to show how a variety of applications and - tools could be modelled using CLI2. We make no claim that these tools - use CLI2 in their implementation but simply use their interfaces to - demonstrate commonly needed features. Some examples will make - simplifications to keep the documentation consise. -

-

- Many aspects of the API are touched upon but few are described in - 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. -

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

TODO what is ls

- - - - - - -
- -
From 7dc9e3ea541658b0e1086482744d3c0e28ae4375 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 17:24:22 +0000 Subject: [PATCH 08/28] Not used for Avalon CLI git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529024 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/images/commandlines.png | Bin 18192 -> 0 bytes xdocs/images/options.png | Bin 27463 -> 0 bytes 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 xdocs/images/commandlines.png delete mode 100644 xdocs/images/options.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#|<2o(eZVaP~}tAaoX1;CHxi|4=|0`r(# z;1{`xw5kFK<}L_t+!BzwSv=f-kU;-Dw^cTQU|{OOkt(%Q}-5M~ej2O)_8lNdN1NJd;l z-2-~GjHWkw^@Q>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`<@Fu5UYH8ftW1+lc*pp9@vZ+mR@S5y-}xB7JI0{HBU{V8sloF(-AZ-)Y;zeI zOj(QZ5Qb_j(nE17$&s#VbdWmh$E0O^!@ok2?(!tw6xMFcTlGaMZ?(0!pU9!Ou<`o& zBzcVK`x0|jC>_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!EIX<72JyD6R+S$9^df}porMKi<(|tZgxk}2gPmz}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<0}`ugXrRQx;zBO?nep8nWQifUwjSLFGV9hvl_ixl zFz1(*2H~pc=%js!dacx{ycwa$amAb%3lheS^guMjO{C{_u?9|o{PtfPVPQlNt<7v1 z&yM$dZj2YwAkfzK-ZZ!AmzQG9e4v4ysY0O=dqcyaQD6B_pR(2FtK8Nvh`DNL-@cXQ z7xaXwpW}W0^+%$n9xOx5-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_<+%%#=20Zif`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~(kWIOy<=95%sy41pca=EzzEP<9bpEA!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 zfz<<|v4WtVh@Qyb)6Cu*XgmV$wcIMttplw7udIxft1) zR`p(15~M7HguSuP$3$0Y(59nDFrfc4`Q|#b!+&8RjKcnU4uQWN2XuF^BEZTC#zJvX zG@+$GhK{!Fg|o%G%OqV%WB52y3Tr@5B6aNhg7lrRS}S!Ss&BELUgJvO7yfo(J*j|{ z9n6#_G&YgMe8d=c)Us>u%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<$eH+kkLn;6DiPn|+aX1LBAP0tNseaG0-|MaA*wyDEIaCDVKM ze*~#%0>}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*<&jMzp@b0YF`E!P}jZ8S+b0t`6qAvoxuKE7K5jL zP#TLWQh+18SOWupfqsd+$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)r<@Jeem0K@-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<;5fau=z4&<7Vp8<&GzX9sh?UUKxukYac$l3`_CVS|fzf%X1uo=En2Bwrx#Il6y)dBnc%hgPk9~ zx1sR?hu?9ee+oWjNRDR8Rm&C@RG%S+0n=(*mDHU*rP-&+QfVz3EgPMvz{Taa>!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<#Ix@YOCOgH z&c-!3vXF4_wO(FryvFu>&~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<|j^4z6tqT}YKA-`bMUD&i zcL(BESAH9A>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<^aRc{!B1?H3AU z3<=Lr-S|b#64vvanrHbLtq-q&$SLwt;4Vk6H+fif5;zM;9`WBc{{i^PkpSu$2*WHd z2}%(<8{vL#px^=(MOGuNV`EpLz(X{x77P$kUcmSNtzi7Kfj|0tm$Jm#&yW9z8Hm^c zGXE&`^n8Fj`Q^*b#M2iTJ}U3E796bxQ#_goC=iFL-9YY<&sgYygN~$VxUa3XSf1~a z`yePEM}iZ9*e_pY`mIVn21XW)j*zcI+}JSj_r>)(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<}}j+gY(3P7L5AnE4%KdmnQ;gb=&j;hjA) zGGaM-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<&=MqXh=0&e9(Z&R;pX)XaKnS?(wWvg`l> 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 z<0Izm@{)@!{AkKpV9Gmr90S)}Z~tC&}}#o3E3xR${vc+3k3X;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# 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<-2!tdqCZqrYK@EXG&}eVqfoB8|UW9-jBnDy% z(jbsKB?#o}4+7l-Px<>+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>Luv6m2aXUD<{+~ac zl@sG8MK+GXFkCo!cNcXMJQ3Jm7kWXU->v>?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||<12YsTBd5xQ2`ky>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}`m<~_yNZc0%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<1W z{4WU`9ur5XD#O#wPcq)Imz^klK@+>(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~@f<2BY9j2?659~A~eR@^9&W9QQ zsdg3HmzoTXjYaU&mOjy4#>f^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<)D8-yQ_RnF*qLzl@j<0mo1G~&%dF$1Na3N=*>)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^Fl<{^__{_Br*%<^`hawS{0WCyQtIb<>JUA$kX@B_eckdNaz1VP#c1{k8jofVs4U z9y7iw3UaKh-%v`bt4>RAQc(XCUd)}_h8c&gyk=7W?s{0yX2KyXJ$pt=BeY1?=<{x2 z)0rB~O@)Ct7<<a 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!fgLaaHK<3JDF30kbcJ;Zt!zXWq~&VY-~|F}ty* ze)Uj^rAJ3cx1(bM@dO?))1k7m$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=< zx}wVVipk&dzpdYDk!u0n{c+mnJ8>}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_E<`44lw~ z2jUa?K=?f-F%kD@zD5#pv&CUYCT^y%Fv|P)`1J2$41j*J%?xMME-g%y9@Om)qO|5{ z3%bj<-rRru@qsy$yyf7{hNQS}LGJ>O>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|N<~ukv7tXiOvVV3LFAmCE6@c%p^h}R12xOgN@6s@sbH{yR z#ifU1WgY%#%JuvUV21|&LJ?-B9jxdxIQN}jsH!U{i-XRq=5sKs@RLNiFSrq{)*bz+ z@K9Iu`dtPFxZg&-C2c)Bc;rRUVvh3dKVn~W-q_p}8W|Z;XV4@1V(+hgaGTVBjI$MY zdc4>ySka`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@?Y<n3^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&Aj<|lu%6g~_Sq^UsNnQysE0oLZ{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<*!(;<%yVk$zffJtz_I2k)E0~WI)3RmP!R-kyZxYui_t_?Xay+jMa9=&= z9GL{OaW#B8%po%ZI>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<=wr;R{n9w{5;Uc`3w#FA?|R3No{TOL|k*>#-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+$;@< zdD7TNOc`fDYURPP!>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$YXEo4AS<2f3HDX-W_+dh3>XZ2iF 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 zVU<;w0*J;C$acA^_ibo#0%}bYV8o zD9)I#*6}`W*KzpHftj_gXVqoF0qpx`j)+sW`hG?1jIsP0Wv0*LmJx4>x|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}HCUGcERfI<~Djj7#K02LM& z!;>c#3_LtKmFleO_V-&KauIUHvxE^oBbv^s^S*SaxdRxT3#Zq|eZb?zJZwqRo7YICw(@a7v-<&V)FG(gfvQnm(9SE_q7PlL4Bg>q3G~73`<~&ORV!zI4ni*lAJ|{jAmgqj)jj;>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<+SY?8mCV)$#$+t*3i^dkziKnZJQ3BQ7HWAO z>*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<2SoIFYcgK3pJ$yF&UM{<6r z%nVY$fqn}?6x3Bz;C(5WKhV9jFHq~e6I!X`mJ&d3hTi@AXbj_|+UNSJ_7P;Vl5?J2 zX1?iUHpbB#r`vussisCZu!%^#^R=%Lx2+zjkx^<5G0(I8fnL@$wyd9;dk<)02> 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<+o)^Bkx`5Hp$a(Gp4iAHDsG^xo#-D z*WEp{e@BpsA9X&S)=tGvsM`UzuOL(OOsjs}J76!{l@S4acWZ08rDbJRnA&3wFrkvh ztAatSLJ9;6v^#+GV3fy4LFCf&-awmMZoRE|`##RlY{RN_iEljHQVS+7#VZMkTdDkA z7X7OO0Q|FkC%gRXvt+r~R4lU^u;vdta0MXO@~UbnF^r9?&qLHcay!*!_Jf_Fq(iip zu}*rz*!z)h7eD=3TBeJdcPJ2_1iU`Zsn3FiiHt1g9k&9-(z1{q3Dj}6I+T=TtXP{F zp#xYLR^>&c3}Hj<$w%eBJ^ESsi$w~S-)9teDGB5CMFJ9Mq{J@cZyofV%6L4FmdBH@Hf*U zA;Odcm}GPVp4f>P{n#U%{2d2?a`Lmbm^fkZh4HV$w~I(V+uvI$r#B!7G_SAvH+sJ< zd<@XLH>*sAF_`ARo~zK0WtB*<7l7^AJDBYoR$PQDN9HGrn1b}m7oyAly3T^=b#oyx}C0qxAgh|Lk1tHU?g zsE>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$&HbP<4E-oMM=!yQeu`FJ>SNjNk zRx9p$9BA*^VW<(?1gZB&6_&{+*C+5EwTr$r0`UNyS{KG&-s z6YF$!Ou(%p{q(6mm&Y+Xav?~Cgtt;}@gz6>_*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|0j<5qyd^_%tDX7Qo14E3vcl0f`KTRC+oD%0 zVsWG!a+*ArzQ_>iGJ15v1D!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?a<}TFqiw;S=+g!U-plYqrJ#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 Date: Sun, 15 Apr 2007 17:24:55 +0000 Subject: [PATCH 09/28] Fix ASF licence git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529025 13f79535-47bb-0310-9956-ffa450edef68 --- maven.xml | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/maven.xml b/maven.xml index 3c75b354f..c7cbbdb9c 100644 --- a/maven.xml +++ b/maven.xml @@ -1,17 +1,18 @@ From 4dd97214009c207404e870ccd02eb7083096ff21 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 17:25:27 +0000 Subject: [PATCH 10/28] Not used for Avalon CLI git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529026 13f79535-47bb-0310-9956-ffa450edef68 --- xdocs/manual/builders.xml | 45 ---- xdocs/manual/commandlines.xml | 50 ----- xdocs/manual/index.xml | 192 ----------------- xdocs/manual/options.xml | 377 ---------------------------------- xdocs/manual/utilities.xml | 38 ---- xdocs/manual/validators.xml | 203 ------------------ 6 files changed, 905 deletions(-) delete mode 100644 xdocs/manual/builders.xml delete mode 100644 xdocs/manual/commandlines.xml delete mode 100644 xdocs/manual/index.xml delete mode 100644 xdocs/manual/options.xml delete mode 100644 xdocs/manual/utilities.xml delete mode 100644 xdocs/manual/validators.xml diff --git a/xdocs/manual/builders.xml b/xdocs/manual/builders.xml deleted file mode 100644 index 1adf0f90a..000000000 --- a/xdocs/manual/builders.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - commons-dev - CLI2 - Builders - - - -
-

TODO describe builders and resaons for their use

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

TODO PropertyOption

-

TODO SourceDestArgument

-
-
- -
diff --git a/xdocs/manual/commandlines.xml b/xdocs/manual/commandlines.xml deleted file mode 100644 index 5c53ed6c5..000000000 --- a/xdocs/manual/commandlines.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - commons-dev - CLI2 - CommandLines - - - -
- - - - - - - - - - - - - - - - - - - -
-
-

TODO commons-configuration

-
- -
diff --git a/xdocs/manual/index.xml b/xdocs/manual/index.xml deleted file mode 100644 index 9f42e49a8..000000000 --- a/xdocs/manual/index.xml +++ /dev/null @@ -1,192 +0,0 @@ - - - - - - commons-dev - CLI2 - Overview - - - -
-

- CLI Breaks down command line processing into three distinct phases, the - first of which is to create a model of the command line you wish to process. The - second phase is arguably the most important as it involves processing the - command line arguments of the application according to the model created. - Finally the parsed command line is available to be queried by the - application proper. The phases are discussed in more detail below. -

- -

- In CLI2 a command line is modelled as a Group composed of many Options. - There are a number different Option implementations available to be - used including DefaultOption, Switch and Command which may all have an - Argument and/or a Group of child options associated with them. An - example of where this parental relationship could be used is where you - need to allow for the following scenario where one option - only makes sense within the context of another: -

-

myapp --output path/to/file --xml

-

- Typically this command line would be modelled as a DefaultOption - (--output) with an Argument (to capture - path/to/file) and a Group of children consisting of a - DefaultOption (--xml) since the format only applies if the - output is specified -

-

- The various Option implementations provided need careful configuration - and constructors take a complex set of arguments. To ease the construction - of these options *Builder classes (e.g. DefaultOptionBuilder, GroupBuilder - and ArgumentBuilder) have been supplied following the - Builder Pattern - which essentially involves using the DefaultOptionBuilder class to create - instances of DefaultOption using descriptive method calls instead of - anonymous arguments to a constructor. The following example demonstrates how - the command line shown above could be modelled in code: -

- -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(); - -

- The Options and - Builders sections of the manual discuss these - features in greater detail. -

-

- Once all the options have been composed into a Group modelling the complete - option model then we are ready to parse a command line. -

-
- -

- The Parser class can be used to parse an array of arguments against the - option model into a CommandLine. The parsing is driven by the - parse(String[]) method which delegates to the option model to do - the actual parsing, with each Option implementation providing its own parsing - logic. The parseAndHelp(String[]) method attempts to simplify - the use of the former method by automatically handling any --help - options and displaying error messages where appropriate. -

-

- The HelpFormatter class is designed to allow the option model to be described - 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. -

-

- Any errors that occur while parsing result in an OptionException being thrown - which attempt to provide a meaningful message describing the problem to the - user. Parser's parseAndHelp(String[]) method catches any - OptionException and uses the HelpFormatter to display to the user: -

- -// configure the options -Group options = ...; - -// configure a HelpFormatter -HelpFormatter hf = new HelpFormatter(); - -// configure a parser -Parser p = new Parser(); -p.setGroup(options); -p.setHelpFormatter(hf); -p.setHelpTrigger("--help"); -CommandLine cl = p.parseAndHelp(new String[]{}); - -// abort application if no CommandLine was parsed -if(cl==null) { - System.exit(-1); -} - - -

- Assuming that OptionExceptions have been averted then the next step is to have - the application query the resulting CommandLine instance. -

-
- -

- The CommandLine interface provides lots of ways to look up information either - by Option instance or by a String representing any of the forms valid on the - command line. For example if an option is configured with multiple names - (e.g. -?, -h, --help) then any of the - those strings can be used to look up the value irrespective of which form - appeared on the command line. -

-

- The hasOption() family of methods can be used to simply test for - the presence of options, while the getValues() family of methods - can be used to retrieve the values associated with Arguments. The status of - any Switch options can be detected through the use of getSwitch() - methods which will return a Boolean if set or null otherwise: -

- -// 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); -} - -

- To enable complex CommandLine configurations alternative implementations are - 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. -

-
-
- -
diff --git a/xdocs/manual/options.xml b/xdocs/manual/options.xml deleted file mode 100644 index 4fc10b2d4..000000000 --- a/xdocs/manual/options.xml +++ /dev/null @@ -1,377 +0,0 @@ - - - - - - commons-dev - CLI2 - Options - - - -
- - -

- In CLI2 every element of the command line interface is modelled as an - Option instance, and has the following readonly properties that are - inherited by all other Option implementations: -

- - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
idint - Some people find it useful to give each option a unique identifer - so that they can use the options within a java switch - statement. This value is entirely optional and it is up to the - user to ensure any uniqueness. -
preferredNameString - Every option has a preferred name that can be used for the minimal - toString() implementation. Options can usually have - many additional names too. -
requiredboolean - True here indicates that the command line is invalid if this - option doesn't appear on it. -
-
- - - -a|-b|-c|-d|-e -

- Groups are possible the least intuitive form of Option since they - actually represent a collection of other options. Most member Options - can appear on a command line in any order with the exception of - Arguments; they must appear in the given order as there is no other - way to identify one from another. An additional restriction of the - standard Group implementation is that only the final argument can have - variable size (differing minimum and maximum). -

-

- Groups inherit all the properties of Options. -

- - - - - - - - - - - - - - -
PropertyTypeDescription
minimumint - The minimum number of member options that must be present on the - command line for this group to be valid. Typically this will - either be 0 where the group is optional or 1 to indicate at least - one of them is needed. This value does not count anonymous - options. -
maximumint - The maximum number of options from this Group that can appear in a - command line. This would typically be used if you wanted to - create an exclusive group where a maximum of 1 member is allowed - to appear. This value does not count anonymous options. -
-
- - - <arg1> [<arg2> ...] -

- Arguments are used to pass in values from the command line, for - example to pass in a list of files to be operated on. Arguments can - appear in two different situations within an option model, the most - frequently used situation is where the value found should be associated - with a Parent option; in this situation the value is expected to - immediately follow the Parent in the command line. The second - scenario where Arguments are used is when they are added to a Group - directly rather than being composed with a Parent first. These - 'anonymous' arguments have nothing that identifies them on the - command line other than the order in which they appear. -

-

- Multiple values may be parsed by a single argument and the minimum - and maximum attributes can used to control their validity, - additionally a Validator may be used to identify whether individual - values are valid. In some situations it can be useful to parse the - supplied string into multiple values and so the initialSeparator and - subsequentSeparator attributes can be used; assuming an - initialSeparator of '=' and a subsequentSeparator of ',', the - string '--file=a,b,c' would be split into a parent option '--file', - and the values 'a', 'b' and 'c'. -

-

- Arguments inherit all the properties of Options. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
minimumint - The minimum number of values that must be present for the - Argument to be valid. The default of 0 implies that the argument - is optional. -
maximumint - The maximum number of values that can appear in a valid command - line. A value less than minimum is not allowed. -
consumeRemainingString - A string that can be used to avoid parsing of the remaining - values as options. Typically '--' is used and allows file names - to be used as values even though they look like options. -
initialSeparatorchar - A character used to indicate the end of the parent option and the - beginning of the values. -
subsequentSeparatorchar - A character used to indicate the boundry between two values in a - single string. -
defaultValueObject - A value to be used when no other is supplied. -
-
- - - --parent <arg> --child1|--child2 -

- Parent options allow an argument to be tied to some othe option, - additionally a group of child options can also be added to the parent. - The argument and child options are only valid in the presence of the - parent option, must appear on the command line with the child options - following the argument. -

-

- Parents are not usable in themselves but DefaultOption, Switch and - Command all inherit the parent features. Parents inherit the - properties of Options. -

- - - - - - - - - - - - - - -
PropertyTypeDescription
argumentArgument - The Argument to delegate value processing to. This property is - optional. -
childrenGroup - The Group to delegate child processing to. This property is - optional. -
-
- - - - - --file (-f) -

- The default option allows an option to exist with both long and short - aliases. Ordinarily the short aliases would be a single character - long and allow a series of options -x -v -f to be - concatenated into a single element -xvf on the command - line. This bursting of concatenated options can be turned off if - necessary and the single character restriction can be ignored where - bursting is not required. -

-

- DefaultOptions inherit all the properties of Options and Parents. -

- - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
shortNameString - The short name of the option. At least one short or long name is - required. -
longNameString - The long name of the option. At least one short or long name is - required. -
burstEnabledboolean - Whether to allow this option to be concatenated with others. -
-
- - - - update (up,upd) -

- Commands are basically an option without an identifying prefix and - are usually found in applications that implement a suite of tools - within a single application. Any of a number of aliases can appear - on the command line with idenentical meaning. -

-

- Commands inherit all the properties of Options and Parents. -

-
- - - +display|-display -

- Switches allow the user to turn a feature on or off. This becomes - useful when the value would otherwise be taken from a different - source and could change, for example the default value could be - configurable by the user. A default switch value can be supplied in - case no other source exists and the application writer has a - preference. -

-

- Switches inherit all the properties of Options and Parents. -

- - - - - - - - - -
PropertyTypeDescription
defaultSwitchBoolean - The value to be used if the option has not been configured. If - not set the value null is used. -
-
- - - -Dproperty=value -

- Property options allow arbitrary name value pairs to be passed in by - the user. This style of option is often used to emulate the java - -D option. -

-

- PropertyOptions inherit the properties of Options. -

- - - - - - - - - -
PropertyTypeDescription
optionStringString - The prefix for this option, defaults to -D. -
-
- - - - - - <src1> [<src2> ...] <dest> -

- Groups have the restriction that only the final argument can have - variable size. Using the SourceDestArgument this rule can appear - to be relaxed by shifting the variable size argument to an earlier - position. A SourceDestArgument is implemented by composing two other - options together. This option would typically be used when modelling - commands like the unix cp command, -

- - - - - - - - - - - - - - -
PropertyTypeDescription
sourceArgument - The variable size first argument. -
destArgument - The fixed size last argument. -
-
-
- -
diff --git a/xdocs/manual/utilities.xml b/xdocs/manual/utilities.xml deleted file mode 100644 index 72746ba3f..000000000 --- a/xdocs/manual/utilities.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - commons-dev - CLI2 - Utilities - - - -
- - - - - -
-
-

TODO xml2cli

-

TODO cli2ant

-

TODO cli2html

-
- -
diff --git a/xdocs/manual/validators.xml b/xdocs/manual/validators.xml deleted file mode 100644 index 6d0a15fb9..000000000 --- a/xdocs/manual/validators.xml +++ /dev/null @@ -1,203 +0,0 @@ - - - - - - commons-dev - CLI2 - Validators - - - -
-

- CLI2 provides a mechanism to validate argument values. The Validator - interface must be implemented to create an argument validator. This interface has - a single method validate(java.util.List values) throws InvalidArgumentException. -

-

- CLI2 has some standard validators included. They validate the following: -

-
    -
  • Java class
  • -
  • date
  • -
  • enumeration
  • -
  • file path
  • -
  • number
  • -
  • URL
  • -
- - - - -

- The ClassValidator validates a value using three criteria: -

-
    -
  1. the value adheres to the Java Language Specification rules
  2. -
  3. the class specified by the name is loadable
  4. -
  5. the class specified by the name can be instantiated
  6. -
- // 1. -ClassValidator validator = new ClassValidator(); -// 2. -validator.setLoadable(true); -// 3. -validator.setLoadable(true); -

- TODO: add section about values being replaced with class instances -

-
- - -

- The DateValidator validates values against a - java.text.DateFormat. There are three helper methods - that create built-in validators. -

-
    -
  1. getDateInstance returns a validator for the default - date format for the default locale. -
  2. -
  3. getTimeInstance returns a validator for the default - time format for the default locale. -
  4. -
  5. getDateTimeInstance returns a validator for the default - date and time format for the default locale. -
  6. -
-

- A DateValidator can also be created by passing your - a custom DateFormat into the constructor. -

- DateFormat myFormat = DateFormat.getDateInstance( DateFormat.LONG, Locale.UK ); -DateValidator myValidator = new DateValidator( myFormat ); -

- In addition to basic format checking you can also check if the date/time specified - is before/after a specific date/time. The lower bound is set using the - setMinimum( java.util.Date ), and the upper bound is set using - the setMaximum( java.util.Date ). -

-

- TODO: add section about values being replaced with date instances -

-
- - -

- The EnumValidator validates values against a list of - allowed string values. The values that are allowed are specified in - a java.util.Set and passed in to the constructor. -

- Set enumSet = new TreeSet(); -enumSet.add("red"); -enumSet.add("green"); -enumSet.add("blue"); - -EnumValidator validator = new EnumValidator( enumSet ); -
- - -

- The FileValidator validates that values represent - existing files. You can also specify a combination of the - following additional criteria: -

-
    -
  1. value is a file
  2. -
  3. value is a directory
  4. -
  5. the file is writable
  6. -
  7. the file is readable
  8. -
  9. the file is hidden
  10. -
-

- Each of the criteria listed here are specified using the appropriate - setter. -

-

- There are three helper methods to create validators: -

-
    -
  1. getExistingInstance returns a validator that ensures - a value represents an existing file. -
  2. -
  3. getExistingFileInstance returns a validator that ensures - a value represents an existing file that is not a directory. -
  4. -
  5. getExistingDirectoryInstance returns a validator that ensures - a value represents an existing file this is a directory. -
  6. -
- // validate that the value represents a file that exists -FileValidator validator = FileValidator.getExistingInstance(); - -// ensure it's not a hidden file -validator.setHidden( false ); - -// ensure it's a writable file -validator.setWritable( true ); - -
- - -

- The NumberValidator validates that values adhere to - certain rules like the following: -

-
    -
  1. getCurrencyInstance returns a validator for the default - currency format for the default locale. -
  2. -
  3. getPercentInstance returns a validator for the default - percent format for the default locale. -
  4. -
  5. getIntegerInstance returns a validator for the default - integer format for the default locale. -
  6. -
  7. getNumberInstance returns a validator for the default - number format for the default locale. -
  8. -
-

- A NumberValidator can also be created by passing your - a custom NumberFormat into the constructor. -

- NumberFormat myFormat = NumberFormat.getCurrencyInstance( Locale.UK ); -NumberValidator myValidator = new NumberValidator( myFormat ); -

- In addition to basic format checking you can also check if the number specified - is less than or greater than a specific number. The lower bound is set using - the setMinimum( Number ), and the upper bound is set using - the setMaximum( Number ). -

-
- - -

- A UrlValidator validates that values are URLs and if you - choose it will also validate the protocol is of the type you have - specified. -

- UrlValidator validator = new UrlValidator(); - -// only accept https URLs -validator.setProtocol("https"); - -
- -
- -
From 822de479217a05854bbf8094925141f9530492d9 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 17:26:36 +0000 Subject: [PATCH 11/28] Fix ASF licence header Fix Avalon references git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529028 13f79535-47bb-0310-9956-ffa450edef68 --- project.xml | 88 +++++++---------------------------------------------- 1 file changed, 11 insertions(+), 77 deletions(-) diff --git a/project.xml b/project.xml index de83d1ab8..3eb4c42a6 100644 --- a/project.xml +++ b/project.xml @@ -1,10 +1,11 @@ - - commons-lang - commons-lang - 2.1 - - junit @@ -176,8 +110,8 @@ - src/java/org/apache/commons/cli2 - org/apache/commons/cli2 + src/java/org/apache/commons/cli/avalon + org/apache/commons/cli/avalon **/*.properties From 56b738751654df04a067724bd00280260466a558 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 17:27:22 +0000 Subject: [PATCH 12/28] Not used for Avalon CLI git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529031 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 0586b7f3c..000000000 --- a/gump.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - Commons CLI - - - - - - - - - - org.apache.commons.cli - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file From b133f48a9eece7f8b049c982ff999f1947bed20d Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 17:27:38 +0000 Subject: [PATCH 13/28] Not used for Avalon CLI git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529032 13f79535-47bb-0310-9956-ffa450edef68 --- build-gump.xml | 36 ------------------------------------ 1 file changed, 36 deletions(-) delete mode 100644 build-gump.xml 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 @@ - - - - - - - - - - - - - - - - - - - - - - From 089f3ef84f386a21718bad574849cadc9871006c Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 18:32:27 +0000 Subject: [PATCH 14/28] Update release notes git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529043 13f79535-47bb-0310-9956-ffa450edef68 --- RELEASE-NOTES.txt | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt index 19f743311..d62505d67 100644 --- a/RELEASE-NOTES.txt +++ b/RELEASE-NOTES.txt @@ -1,17 +1,16 @@ $Id$ - Commons CLI Package - Version 1.0 + Commons CLI Avalon Package + Version 2.0 Release Notes 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. +CLI Avalon package. + +Commons CLI Avalon provides a simple API for working with the command line arguments and options. For more information, read the documentation on the project site at http://jakarta.apache.org/commons/cli/ From 4b799deefa16558f8af0eaab299e8c0b09c9e2aa Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 18:33:27 +0000 Subject: [PATCH 15/28] Create minimal POM git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529044 13f79535-47bb-0310-9956-ffa450edef68 --- pom.xml | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 pom.xml diff --git a/pom.xml b/pom.xml new file mode 100644 index 000000000..d41820834 --- /dev/null +++ b/pom.xml @@ -0,0 +1,95 @@ + + + + + org.apache.commons + commons-parent + 1 + + 4.0.0 + commons-cli-avalon + commons-cli-avalon + 2.0-SNAPSHOT + CLI-Avalon + + 2002 + + Commons CLI (Avalon) provides a simple API for processing and + validating a command line interface. + + + http://jakarta.apache.org/commons/cli/ + + + jira + http://issues.apache.org/jira/browse/CLI + + + + scm:svn:http://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation + scm:svn:https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation + http://svn.apache.org/viewvc/jakarta/commons/proper/cli/branches/avalon-implementation + + + + + + + + junit + junit + 3.8.1 + test + + + + + jdepend + jdepend + 2.5 + test + + + + + + src/java + src/test + + + src/java/org/apache/commons/cli/avalon + org/apache/commons/cli/avalon + + **/*.properties + + + + . + META-INF + + NOTICE.txt + LICENSE.txt + + + + + + \ No newline at end of file From daad503971622a25b519cea836f22d3cf768c597 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 19:24:53 +0000 Subject: [PATCH 16/28] Not used for Avalon CLI git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529050 13f79535-47bb-0310-9956-ffa450edef68 --- doap_cli.rdf | 32 -------------------------------- 1 file changed, 32 deletions(-) delete mode 100644 doap_cli.rdf diff --git a/doap_cli.rdf b/doap_cli.rdf deleted file mode 100644 index e71b44c7d..000000000 --- a/doap_cli.rdf +++ /dev/null @@ -1,32 +0,0 @@ - - - - Apache Jakarta Commons CLI - - Java - - - - - - Commons CLI - - Commons CLI provides a simple API for presenting, proecessing and - validating a command line interface. - - - - - - - - - - commons-cli - 2002-12-27 - 1.0 - - - - - From 6ed97639a66d732ba087c14e6e687c80bfd8c33a Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 19:25:18 +0000 Subject: [PATCH 17/28] No longer reflects Maven.xml git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529051 13f79535-47bb-0310-9956-ffa450edef68 --- build.xml | 245 ------------------------------------------------------ 1 file changed, 245 deletions(-) delete mode 100644 build.xml 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 From ebe542f4461078b8df35a0750dfbc9fe7715e921 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 15 Apr 2007 22:58:56 +0000 Subject: [PATCH 18/28] Fix properties git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@529087 13f79535-47bb-0310-9956-ffa450edef68 --- src/conf/MANIFEST.MF | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/conf/MANIFEST.MF b/src/conf/MANIFEST.MF index b108198fe..1bb76907a 100644 --- a/src/conf/MANIFEST.MF +++ b/src/conf/MANIFEST.MF @@ -1,6 +1,6 @@ -Implementation-Title: Jakarta Commons Avalon CLI - -Name: org/apache/commons/cli/avalon -Specification-Title: Jakarta Commons Avalon CLI -Specification-Vendor: Apache Software Foundation +Implementation-Title: Jakarta Commons Avalon CLI + +Name: org/apache/commons/cli/avalon +Specification-Title: Jakarta Commons Avalon CLI +Specification-Vendor: Apache Software Foundation Specification-Version: 2.0 \ No newline at end of file From 5159f98d14721feefb6ecb60b589b64bedd9683f Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 20 May 2007 18:10:17 +0000 Subject: [PATCH 19/28] Add optional argument to help output git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@539899 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli/avalon/CLUtil.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/java/org/apache/commons/cli/avalon/CLUtil.java b/src/java/org/apache/commons/cli/avalon/CLUtil.java index 1efd8d283..07fbf3bfc 100644 --- a/src/java/org/apache/commons/cli/avalon/CLUtil.java +++ b/src/java/org/apache/commons/cli/avalon/CLUtil.java @@ -46,12 +46,15 @@ public static final StringBuffer describeOptions( final CLOptionDescriptor[] opt final String name = options[i].getName(); String description = options[i].getDescription(); int flags = options[i].getFlags(); + boolean argumentOptional = + ((flags & CLOptionDescriptor.ARGUMENT_OPTIONAL) == + CLOptionDescriptor.ARGUMENT_OPTIONAL); boolean argumentRequired = ((flags & CLOptionDescriptor.ARGUMENT_REQUIRED) == - CLOptionDescriptor.ARGUMENT_REQUIRED); + CLOptionDescriptor.ARGUMENT_REQUIRED); boolean twoArgumentsRequired = ((flags & CLOptionDescriptor.ARGUMENTS_REQUIRED_2) == - CLOptionDescriptor.ARGUMENTS_REQUIRED_2); + CLOptionDescriptor.ARGUMENTS_REQUIRED_2); boolean needComma = false; if( twoArgumentsRequired ) { @@ -78,6 +81,10 @@ public static final StringBuffer describeOptions( final CLOptionDescriptor[] opt sb.append( name ); } + if (argumentOptional) + { + sb.append(" [[=]]"); + } if( argumentRequired ) { sb.append( " " ); From 62051929d55a54d9de4801ac2c56713de336ec74 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 20 May 2007 18:11:02 +0000 Subject: [PATCH 20/28] Correct typo: optional args cannot be separate git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@539900 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli/avalon/package.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/java/org/apache/commons/cli/avalon/package.html b/src/java/org/apache/commons/cli/avalon/package.html index 62c30d4ba..373af6f10 100644 --- a/src/java/org/apache/commons/cli/avalon/package.html +++ b/src/java/org/apache/commons/cli/avalon/package.html @@ -143,9 +143,9 @@

Parsing Rules

argument "bc" while "-a bc" is an option 'a' with no argument, followed by the text "bc".

It is also possible to place an '=' sign between the option - and it's argument. So if we assume that a is an option that - requires an argument then the following are all equivalent; - "-a=bc", "-a bc" "-abc". + and its argument. So if we assume that a is an option that + requires an argument then the following are equivalent; + "-a=bc" and "-abc".

In the case of a long option with an optional argument, the '=' sign is required. From dcf0be7dadfc5914c3e3c6e8ca7c26e10a9e5a34 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 20 May 2007 18:11:36 +0000 Subject: [PATCH 21/28] Add NON-NLS marker git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@539901 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/commons/cli/avalon/Token.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/java/org/apache/commons/cli/avalon/Token.java b/src/java/org/apache/commons/cli/avalon/Token.java index 8fd470360..a603127e9 100644 --- a/src/java/org/apache/commons/cli/avalon/Token.java +++ b/src/java/org/apache/commons/cli/avalon/Token.java @@ -65,7 +65,7 @@ public final String toString() { final StringBuffer sb = new StringBuffer(); sb.append( m_type ); - sb.append( ":" ); + sb.append( ":" ); // $NON-NLS-1$ sb.append( m_value ); return sb.toString(); } From 8fc39d0cda61f33db356d0e365271098c119b719 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 20 May 2007 18:22:14 +0000 Subject: [PATCH 22/28] Remove deprecated method (OK as code has not been released) git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@539904 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli/avalon/CLOptionDescriptor.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java b/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java index 4b8566378..4daddd8e0 100644 --- a/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java +++ b/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java @@ -142,15 +142,6 @@ public CLOptionDescriptor( final String name, } } - /** - * @deprecated Use the correctly spelled {@link #getIncompatible} instead. - * @return the array of incompatible option ids - */ - protected final int[] getIncompatble() - { - return getIncompatible(); - } - /** * Get the array of incompatible option ids. * From 00aab5d694a86ee5d710e107ff4e9236c28c3320 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 20 May 2007 19:41:25 +0000 Subject: [PATCH 23/28] Remove deprecated constructor (OK as code has not been released) git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@539920 13f79535-47bb-0310-9956-ffa450edef68 --- .../cli/avalon/CLOptionDescriptor.java | 55 ++++++++----------- 1 file changed, 22 insertions(+), 33 deletions(-) diff --git a/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java b/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java index 4daddd8e0..07c753785 100644 --- a/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java +++ b/src/java/org/apache/commons/cli/avalon/CLOptionDescriptor.java @@ -59,9 +59,15 @@ public CLOptionDescriptor( final String name, final int id, final String description ) { - this( name, flags, id, description, - ((flags & CLOptionDescriptor.DUPLICATES_ALLOWED) > 0) - ? new int[0] : new int[]{id} ); + + checkFlags(flags); + + m_id = id; + m_name = name; + m_flags = flags; + m_description = description; + m_incompatible = ((flags & DUPLICATES_ALLOWED) > 0) + ? new int[0] : new int[] { id }; } /** @@ -71,21 +77,30 @@ public CLOptionDescriptor( final String name, * @param flags the flags * @param id the id/character option * @param description description of option usage - * @param incompatible an array listing the ids of all incompatible options - * @deprecated use the version with the array of CLOptionDescriptor's + * @param incompatible an array listing the descriptors of all incompatible options */ public CLOptionDescriptor( final String name, final int flags, final int id, final String description, - final int[] incompatible ) + final CLOptionDescriptor[] incompatible ) { + + checkFlags(flags); + m_id = id; m_name = name; m_flags = flags; m_description = description; - m_incompatible = incompatible; + m_incompatible = new int[incompatible.length]; + for (int i = 0; i < incompatible.length; i++) { + m_incompatible[i] = incompatible[i].getId(); + } + } + + // helper method - check for invalid flag combinations + private void checkFlags(final int flags) { int modeCount = 0; if( (ARGUMENT_REQUIRED & flags) == ARGUMENT_REQUIRED ) { @@ -116,32 +131,6 @@ else if( 1 != modeCount ) } } - /** - * Constructor. - * - * @param name the name/long option - * @param flags the flags - * @param id the id/character option - * @param description description of option usage - */ - public CLOptionDescriptor( final String name, - final int flags, - final int id, - final String description, - final CLOptionDescriptor[] incompatible ) - { - m_id = id; - m_name = name; - m_flags = flags; - m_description = description; - - m_incompatible = new int[incompatible.length]; - for( int i = 0; i < incompatible.length; i++ ) - { - m_incompatible[i] = incompatible[i].getId(); - } - } - /** * Get the array of incompatible option ids. * From 01de7d4e7e4b1df4b090916e5ef5148ce2152af5 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 20 May 2007 19:54:54 +0000 Subject: [PATCH 24/28] Remove deprecated method (OK as code has not been released) Improve toString() output Add toShortString() method for testing git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@539927 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/cli/avalon/CLOption.java | 45 ++++++++++++------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/src/java/org/apache/commons/cli/avalon/CLOption.java b/src/java/org/apache/commons/cli/avalon/CLOption.java index d2fdd83a0..242ad1c6a 100644 --- a/src/java/org/apache/commons/cli/avalon/CLOption.java +++ b/src/java/org/apache/commons/cli/avalon/CLOption.java @@ -71,19 +71,6 @@ public final String getArgument( final int index ) } } - /** - * Retrieve id of option. - * - * The id is eqivalent to character code if it can be a single letter option. - * - * @return the id - * @deprecated use getDescriptor().getId() instead - */ - public final int getId() - { - return m_descriptor == null ? TEXT_ARGUMENT : m_descriptor.getId(); - } - public final CLOptionDescriptor getDescriptor() { return m_descriptor; @@ -158,8 +145,14 @@ public final int getArgumentCount() public final String toString() { final StringBuffer sb = new StringBuffer(); - sb.append( "[Option " ); - sb.append( (char)m_descriptor.getId() ); + sb.append("["); + final char id = (char) m_descriptor.getId(); + if (id == TEXT_ARGUMENT) { + sb.append("Text "); + } else { + sb.append("Option "); + sb.append(id); + } if( null != m_arguments ) { @@ -171,4 +164,26 @@ public final String toString() return sb.toString(); } + + /* + * Convert to a shorter String for test purposes + * + * @return the string value + */ + final String toShortString() { + final StringBuffer sb = new StringBuffer(); + final char id = (char) m_descriptor.getId(); + if (id != TEXT_ARGUMENT) { + sb.append("-"); + sb.append(id); + } + + if (null != m_arguments) { + if (id != TEXT_ARGUMENT) { + sb.append("="); + } + sb.append(Arrays.asList(m_arguments)); + } + return sb.toString(); + } } From 3c221ef1b40313bcfa3b102984df23ad34ff9d33 Mon Sep 17 00:00:00 2001 From: Sebastian Bazley Date: Sun, 20 May 2007 23:07:14 +0000 Subject: [PATCH 25/28] Fix long optional args to require "=" as per documentation git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@539978 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/cli/avalon/CLArgsParser.java | 16 +++++++++---- .../commons/cli/avalon/ClutilTestCase.java | 24 +++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/src/java/org/apache/commons/cli/avalon/CLArgsParser.java b/src/java/org/apache/commons/cli/avalon/CLArgsParser.java index 7eb7e2f77..36e891926 100644 --- a/src/java/org/apache/commons/cli/avalon/CLArgsParser.java +++ b/src/java/org/apache/commons/cli/avalon/CLArgsParser.java @@ -450,11 +450,6 @@ else if( STATE_NO_OPTIONS == m_state ) //should never get to here when stringIndex != 0 addOption( new CLOption( m_args[m_argIndex++] ) ); } - else if( STATE_OPTIONAL_ARG == m_state && m_isLong && m_ch != 0) - { - m_state = STATE_NORMAL; - addOption( m_option ); - } else { parseArguments(); @@ -560,12 +555,15 @@ private final char readChar() return m_args[m_argIndex].charAt( m_stringIndex++ ); } + private char m_tokesep; // Keep track of token separator + private final Token nextToken( final char[] separators ) { m_ch = getChar(); if( isSeparator( m_ch, separators ) ) { + m_tokesep = m_ch; m_ch = getChar(); return new Token( TOKEN_SEPARATOR, null ); } @@ -579,6 +577,7 @@ private final Token nextToken( final char[] separators ) } while( !isSeparator( m_ch, separators ) ); + m_tokesep = m_ch; return new Token( TOKEN_STRING, sb.toString() ); } @@ -660,6 +659,13 @@ else if( STATE_OPTIONAL_ARG == m_state ) return; } + if (m_isLong && '=' != m_tokesep) // Long optional arg must have = as separator + { + addOption(m_option); + m_state = STATE_NORMAL; + return; + } + if( '=' == m_ch ) // $NON-NLS-1$ { getChar(); diff --git a/src/test/org/apache/commons/cli/avalon/ClutilTestCase.java b/src/test/org/apache/commons/cli/avalon/ClutilTestCase.java index 2bf298341..1e7f2eea4 100644 --- a/src/test/org/apache/commons/cli/avalon/ClutilTestCase.java +++ b/src/test/org/apache/commons/cli/avalon/ClutilTestCase.java @@ -196,6 +196,30 @@ public void testOptionalArgLong() assertEquals( option2.getArgument( 0 ), null ); } + public void testOptionalArgLongEquals() { + final CLOptionDescriptor[] options = new CLOptionDescriptor[] { ALL, TAINT }; + + // Check that optional args work woth long options + final String[] args = new String[] { "--taint=param", "-a" }; + + final CLArgsParser parser = new CLArgsParser(args, options); + + assertNull(parser.getErrorString(), parser.getErrorString()); + + final List clOptions = parser.getArguments(); + final int size = clOptions.size(); + + assertEquals("Option count", 2, size); + + final CLOption option0 = (CLOption) clOptions.get(0); + assertEquals("Option Code: " + option0.getDescriptor().getId(), TAINT_OPT, option0.getDescriptor().getId()); + assertEquals("Option Arg: " + option0.getArgument(0), "param", option0.getArgument(0)); + + final CLOption option2 = (CLOption) clOptions.get(1); + assertEquals(option2.getDescriptor().getId(), ALL_OPT); + assertEquals(option2.getArgument(0), null); + } + public void testShortOptArgUnenteredBeforeOtherOpt() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] From f92a8663d87ec708370b5f8d45204b522fd87a0e Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Mon, 28 May 2007 08:07:04 +0000 Subject: [PATCH 26/28] Removing dead file git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/avalon-implementation@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 14ae9816e..93d0738cd 100644 --- a/project.properties +++ b/project.properties @@ -22,7 +22,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 d5a4f4068cf6b84bf1b9cdf315c8104c2e2345e0 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 03:40:41 +0000 Subject: [PATCH 27/28] Moving to TLP git-svn-id: https://svn.apache.org/repos/asf/commons/commons/proper/cli/branches/avalon-implementation@560657 13f79535-47bb-0310-9956-ffa450edef68 From 6299268b33b8c038aa115e037ed459a1e17d5a60 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 29 Jul 2007 03:42:34 +0000 Subject: [PATCH 28/28] Moving to TLP git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/branches/avalon-implementation@560660 13f79535-47bb-0310-9956-ffa450edef68