http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/option/Switch.java ---------------------------------------------------------------------- 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 3c30e26..0000000 --- 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: <code>+d|-d</code> or <code>--enable-x|--disable-x</code>. - */ -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); - } -}
http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties ---------------------------------------------------------------------- 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 8112198..0000000 --- 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. http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/resource/ResourceConstants.java ---------------------------------------------------------------------- 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 2db366a..0000000 --- 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"; - -} http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/resource/ResourceHelper.java ---------------------------------------------------------------------- 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 a65adb8..0000000 --- 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); - } -} http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/util/Comparators.java ---------------------------------------------------------------------- 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 9f80623..0000000 --- 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; - } - } -} http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/util/HelpFormatter.java ---------------------------------------------------------------------- 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 a3a5fb3..0000000 --- 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; - } -} http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/validation/ClassValidator.java ---------------------------------------------------------------------- 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 b989845..0000000 --- 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 <code>ClassValidator</code> 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. - * - * <pre> - * ... - * ClassValidator validator = new ClassValidator(); - * validator.setInstance(true); - * - * ArgumentBuilder builder = new ArgumentBuilder(); - * Argument logger = - * builder.withName("logger"); - * .withValidator(validator); - * </pre> - * - * @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 <code>String</code> value in the list is - * replaced with it's <code>Class</code> 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; - } -} http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/validation/DateValidator.java ---------------------------------------------------------------------- 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 0820155..0000000 --- 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 <code>DateValidator</code> 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}). - * - * <pre> - * DateFormat date = new SimpleDateFormat("d/M/yy"); - * ... - * ArgumentBuilder builder = new ArgumentBuilder(); - * Argument dateFormat = - * builder.withName("date"); - * .withValidator(new DateValidator(dateFormat)); - * </pre> - * - * 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}). - * - * <pre> - * DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); - * ... - * ArgumentBuilder builder = new ArgumentBuilder(); - * Argument time = - * builder.withName("time"); - * .withValidator(new DateValidator(timeFormat)); - * </pre> - * - * @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 <code>String</code> value in the list is - * replaced with it's <code>Date</code> 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 <code>null</code>. - */ - 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 <code>null</code>. - */ - 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 <code>date</code> 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 <code>date</code> 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; - } -} http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/validation/EnumValidator.java ---------------------------------------------------------------------- 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 f685213..0000000 --- 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 <code>EnumValidator</code> 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'. - * - * <pre> - * 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)); - * </pre> - * - * @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; - } -} http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/validation/FileValidator.java ---------------------------------------------------------------------- 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 22b2e1d..0000000 --- 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 <code>FileValidator</code> 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: - * <ul> - * <li>writable</li> - * <li>readable</li> - * <li>hidden</li> - * <li>existing</li> - * <li>is a file</li> - * <li>is a directory</li> - * </ul> - * - * The following example shows how to limit the valid values - * for the config attribute to files that are readable, writeable, - * and that already existing. - * - * <pre> - * ... - * ArgumentBuilder builder = new ArgumentBuilder(); - * FileValidator validator = FileValidator.getExistingFileInstance(); - * validator.setReadable(true); - * validator.setWritable(true); - * - * Argument age = - * builder.withName("config"); - * .withValidator(validator); - * </pre> - * - * @author Rob Oxspring - * @author John Keyes - */ -public class FileValidator implements Validator { - - /** - * Returns a <code>FileValidator</code> for existing files/directories. - * - * @return a <code>FileValidator</code> for existing files/directories. - */ - public static FileValidator getExistingInstance() { - final FileValidator validator = new FileValidator(); - validator.setExisting(true); - return validator; - } - - /** - * Returns a <code>FileValidator</code> for existing files. - * - * @return a <code>FileValidator</code> for existing files. - */ - public static FileValidator getExistingFileInstance() { - final FileValidator validator = new FileValidator(); - validator.setExisting(true); - validator.setFile(true); - return validator; - } - - /** - * Returns a <code>FileValidator</code> for existing directories. - * - * @return a <code>FileValidator</code> 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 <code>values</code> - * {@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; - } -} http://git-wip-us.apache.org/repos/asf/commons-cli/blob/9e65354f/src/java/org/apache/commons/cli2/validation/InvalidArgumentException.java ---------------------------------------------------------------------- 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 ea10308..0000000 --- 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); - } -}
