From 3ac60ae9b4c83ce37c9fe2641338f7ee07a34845 Mon Sep 17 00:00:00 2001
From: Henri Yandell Thrown when more than one option in an option group
- * has been provided. Construct a new A simple implementation of {@link Parser}'s abstract
- * {@link Parser#flatten(Options,String[],boolean) flatten} method. Note: 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. Dump state, suitable for debugging. Resets the members to their original state i.e. remove
- * all of This flatten method does so using the following rules:
- * AlreadySelectedException
- * with the specified detail message.options and stopAtNonOption
- * are not used in this flatten method.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;
-
-/**
- * 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
- * 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();
-
- /**
- * tokens entries.
- */
- private void init()
- {
- tokens.clear();
- }
-
- /**
- *
- *
- * 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.
Print the help for options with the specified
- * command line syntax. This method prints help information to
- * System.out.
Print the help for options with the specified
- * command line syntax. This method prints help information to
- * System.out.
Print the help for options with the specified
- * command line syntax. This method prints help information to
- * System.out.
Print the help for options with the specified
- * command line syntax. This method prints help information to
- * System.out.
Print the help for options with the specified
- * command line syntax. This method prints help information to
- * System.out.
Print the help for options with the specified
- * command line syntax. This method prints help information to
- * System.out.
Print the help for options with the specified
- * command line syntax.
Print the help for options with the specified
- * command line syntax.
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 onlyRender 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 afterstartPos 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.
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.
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.
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.
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 NULLopt that is either
- * ' '(special case), '?', '@' or a letteropt that only contains
- * letters.Returns whether the specified character is a valid Option.
- * - * @param c the option to validate - * @return true ifc 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 ifc 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.
Parser creates {@link CommandLine}s.
Subclasses must implement this method to reduce
- * the arguments that have been passed to the parse
- * method.
Parses the specified arguments
- * based on the specifed {@link Options}.
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}.
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.
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.
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.
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.
Resets the members to their original state i.e. remove
- * all of tokens entries, set eatTheRest
- * to false and set currentOption to 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. - *
stopAtNonOption is true then do not
- * burst anymore of arguments entries, just add each
- * successive entry without further processing. Otherwise, ignore
- * stopAtNonOption.arguments entry is "--"
- * just add the entry to the list of processed tokensarguments entry is "-"
- * just add the entry to the list of processed tokensarguments 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.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}.arguments entry is not handled
- * by any of the previous rules, then the entry is added to the list
- * of processed tokens.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.
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.
Breaks token into its constituent parts
- * using the following algorithm.
- *
stopAtNonOption IS set then add the special token
- * "--" followed by the remaining characters and also
- * the remaining tokens directly to the processed tokens list.stopAtNonOption IS NOT set then add that
- * character prepended with "-".Returns the Object of type obj
- * with the value of str.
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.
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 bystr, 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.
Returns the date represented by str.
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.
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.
str.
- */
- public static File createFile(String str)
- {
- return new File(str);
- }
-
- /**
- * Returns the File[] represented by str.
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.
Remove the hyphens from the begining of str and
- * return the new String.
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:
- *
- * ...
- * 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:
-
-- * This is a collection of tests that test real world - * applications command lines. - *
- * - *- * The following are the applications that are tested: - *
- * 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
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
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 - 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: -
-- For each option we create an Option instance that will model it, built - using the Builder instances above: -
-- We now create a Group instance consisting of all the above options: -
-- Once the model is built, a CommandLine needs to be parsed: -
-- 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: -
-- For those options that have an argument, the argument needs to be - extracted and processed: -
-- Each target for ant to process could then be processed in order as - specified: -
-- 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. -
-- 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: -
-- 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: -
-- 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: -
-
- Finally, the help can be printed to System.out with a simple call to
- print():
-
TODO what is cp
-TODO what is cvs
-- 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.
-
TODO what is ls
-c0%C6#{`oSN3)g#dbUOGZMYmW+!YITc zshS-ZA&IN)PY+WW@?mdFaOk|S;fwRsKBcq7!<)*g5$_WS zmCuo>>t`oo_JZ$ujp^x3BK+$^r 7nj>%|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@IpsFleWc fs$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;{xyfMFidjwbDe6xz9fM4h6MhJVTL bJ*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