You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by jk...@apache.org on 2005/09/13 04:33:02 UTC
svn commit: r280462 [2/4] - in /jakarta/commons/proper/cli/trunk/src:
java/org/apache/commons/cli2/ java/org/apache/commons/cli2/builder/
java/org/apache/commons/cli2/commandline/
java/org/apache/commons/cli2/option/ java/org/apache/commons/cli2/resour...
Modified: jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/GroupImpl.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/GroupImpl.java?rev=280462&r1=280461&r2=280462&view=diff
==============================================================================
--- jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/GroupImpl.java (original)
+++ jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/GroupImpl.java Mon Sep 12 19:32:04 2005
@@ -1,4 +1,4 @@
-/**
+/*
* Copyright 2003-2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -35,12 +35,13 @@
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 {
-
+public class GroupImpl
+ extends OptionImpl implements Group {
private final String name;
private final String description;
private final List options;
@@ -52,21 +53,19 @@
/**
* 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);
+ 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;
@@ -79,26 +78,23 @@
// anonymous Argument temporary storage
final List newAnonymous = new ArrayList();
-
+
// map (key=trigger & value=Option) temporary storage
- final SortedMap newOptionMap =
- new TreeMap(ReverseStringComparator.getInstance());
+ 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 {
+ } else {
final Set triggers = option.getTriggers();
-
+
for (Iterator j = triggers.iterator(); j.hasNext();) {
newOptionMap.put(j.next(), option);
}
@@ -107,13 +103,14 @@
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, String arg) {
+ public boolean canProcess(final WriteableCommandLine commandLine,
+ String arg) {
if (arg == null) {
return false;
}
@@ -125,21 +122,20 @@
// filter
final Map tailMap = optionMap.tailMap(arg);
-
+
// check if bursting is required
- for (final Iterator iter = tailMap.values().iterator();
- iter.hasNext();) {
-
+ 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)) {
+
+ if (commandLine.looksLikeOption(arg)) {
return false;
}
-
+
// anonymous argument(s) means we can process it
if (anonymous.size() > 0) {
return true;
@@ -156,29 +152,28 @@
return optionMap.keySet();
}
- public void process(
- final WriteableCommandLine commandLine,
- final ListIterator arguments)
+ 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();
-
+ final String arg = (String) arguments.next();
+
// if we have just tried to process this instance
- if(arg==previous) {
+ if (arg == previous) {
// rollback and abort
arguments.previous();
+
break;
}
+
// remember last processed instance
previous = arg;
-
- final Option opt = (Option)optionMap.get(arg);
+
+ final Option opt = (Option) optionMap.get(arg);
// option found
if (opt != null) {
@@ -188,30 +183,31 @@
// [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;
+ foundMemberOption = true;
arguments.previous();
option.process(commandLine, arguments);
}
}
+
// back track and abort this group if necessary
- if(!foundMemberOption) {
- arguments.previous();
- return;
+ if (!foundMemberOption) {
+ arguments.previous();
+
+ return;
}
} // [END argument may be anonymous
-
+
// [START argument is NOT anonymous
else {
// move iterator back, current value not used
@@ -219,14 +215,15 @@
// if there are no anonymous arguments then this group can't
// process the argument
- if(anonymous.isEmpty()){
+ 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();
+ final Argument argument = (Argument) i.next();
+
if (argument.canProcess(commandLine, arguments)) {
argument.process(commandLine, arguments);
}
@@ -238,48 +235,50 @@
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()){
+ if (option.isRequired()) {
option.validate(commandLine);
}
- if(option instanceof Group){
- 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,
- "cli.error.unexpected",
- unexpected.getPreferredName());
+ throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN,
+ unexpected.getPreferredName());
}
-
+
// too few option
if (present < minimum) {
- throw new OptionException(this, "cli.error.missing.option");
+ 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();
+ final Option option = (Option) i.next();
option.validate(commandLine);
}
}
@@ -292,39 +291,31 @@
return description;
}
- public void appendUsage(
- final StringBuffer buffer,
- final Set helpSettings,
- final Comparator comp) {
+ 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) {
-
+ 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);
+ (minimum == 0) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_OPTIONAL);
final boolean expanded =
- name == null
- || helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED);
+ (name == null) || helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED);
final boolean named =
- !expanded
- || (name != null
- && helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_NAME));
+ !expanded ||
+ ((name != null) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_NAME));
- final boolean arguments =
- helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT);
+ final boolean arguments = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT);
- final boolean outer =
- helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_OUTER);
+ final boolean outer = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_OUTER);
helpSettingsCopy.remove(DisplaySetting.DISPLAY_GROUP_OUTER);
@@ -337,27 +328,28 @@
if (named) {
buffer.append(name);
}
+
if (both) {
buffer.append(" (");
}
+
if (expanded) {
final Set childSettings;
- if (!helpSettingsCopy
- .contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) {
+
+ if (!helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) {
childSettings = DisplaySetting.NONE;
- }
- else {
+ } 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 {
+ } else {
// sort options if comparator is supplied
list = new ArrayList(options);
Collections.sort(list, comp);
@@ -365,7 +357,7 @@
// for each option.
for (final Iterator i = list.iterator(); i.hasNext();) {
- final Option option = (Option)i.next();
+ final Option option = (Option) i.next();
// append usage information
option.appendUsage(buffer, childSettings, comp);
@@ -376,43 +368,47 @@
}
}
}
+
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();
+
+ 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) {
+ 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)) {
+ 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 {
+ } else {
// sort options if comparator is supplied
list = new ArrayList(options);
Collections.sort(list, comp);
@@ -420,71 +416,73 @@
// 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));
+ 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));
+ 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;
+ 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 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 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;
+ 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);
@@ -492,9 +490,14 @@
}
}
+
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
@@ -503,13 +506,10 @@
return instance;
}
- private ReverseStringComparator() {
- // just making sure nobody else creates one
- }
-
- public int compare(final Object o1, final Object o2) {
- final String s1 = (String)o1;
- final String s2 = (String)o2;
+ public int compare(final Object o1,
+ final Object o2) {
+ final String s1 = (String) o1;
+ final String s2 = (String) o2;
return -s1.compareTo(s2);
}
Modified: jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/OptionImpl.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/OptionImpl.java?rev=280462&r1=280461&r2=280462&view=diff
==============================================================================
--- jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/OptionImpl.java (original)
+++ jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/OptionImpl.java Mon Sep 12 19:32:04 2005
@@ -1,4 +1,4 @@
-/**
+/*
* Copyright 2003-2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,6 +22,7 @@
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;
/**
@@ -29,7 +30,6 @@
* Option implementations.
*/
public abstract class OptionImpl implements Option {
-
private final int id;
private final boolean required;
@@ -38,18 +38,20 @@
* @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) {
+ public OptionImpl(final int id,
+ final boolean required) {
this.id = id;
this.required = required;
}
- public boolean canProcess(final WriteableCommandLine commandLine, final ListIterator arguments) {
+ public boolean canProcess(final WriteableCommandLine commandLine,
+ final ListIterator arguments) {
if (arguments.hasNext()) {
- final String argument = (String)arguments.next();
+ final String argument = (String) arguments.next();
arguments.previous();
+
return canProcess(commandLine, argument);
- }
- else {
+ } else {
return false;
}
}
@@ -57,6 +59,7 @@
public String toString() {
final StringBuffer buffer = new StringBuffer();
appendUsage(buffer, DisplaySetting.ALL, null);
+
return buffer.toString();
}
@@ -66,91 +69,90 @@
public boolean equals(final Object thatObj) {
if (thatObj instanceof OptionImpl) {
- final OptionImpl that = (OptionImpl)thatObj;
+ 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 (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);
- }
- }
+ 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() {
+ public int hashCode() {
int hashCode = getId();
- hashCode = hashCode * 37 + getPreferredName().hashCode();
+ hashCode = (hashCode * 37) + getPreferredName().hashCode();
+
if (getDescription() != null) {
- hashCode = hashCode * 37 + getDescription().hashCode();
+ hashCode = (hashCode * 37) + getDescription().hashCode();
}
- hashCode = hashCode * 37 + getPrefixes().hashCode();
- hashCode = hashCode * 37 + getTriggers().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 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()) {
+ 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) {
+ 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)) {
+
+ if (trigger.startsWith(prefix)) {
return;
}
}
-
- final ResourceHelper helper =
- ResourceHelper.getResourceHelper(OptionImpl.class);
- final String message =
- helper.getMessage("cli.error.trigger.needs.prefix",
- trigger,prefixes.toString());
+
+ final ResourceHelper helper = ResourceHelper.getResourceHelper();
+ final String message =
+ helper.getMessage(ResourceConstants.OPTION_TRIGGER_NEEDS_PREFIX, trigger,
+ prefixes.toString());
throw new IllegalArgumentException(message);
}
-
-
}
Modified: jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/PropertyOption.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/PropertyOption.java?rev=280462&r1=280461&r2=280462&view=diff
==============================================================================
--- jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/PropertyOption.java (original)
+++ jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/PropertyOption.java Mon Sep 12 19:32:04 2005
@@ -1,4 +1,4 @@
-/**
+/*
* Copyright 2003-2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -25,16 +25,21 @@
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 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;
@@ -53,54 +58,47 @@
* @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);
+ 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);
}
- /**
- * A default PropertyOption instance
- */
- public static final PropertyOption INSTANCE = new PropertyOption();
-
- public boolean canProcess(final WriteableCommandLine commandLine, final String argument) {
- return argument != null
- && argument.startsWith(optionString)
- && argument.length() > optionString.length();
+ 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)
+ public void process(final WriteableCommandLine commandLine,
+ final ListIterator arguments)
throws OptionException {
-
- final String arg = (String)arguments.next();
+ final String arg = (String) arguments.next();
if (!canProcess(commandLine, arg)) {
- throw new OptionException(this, "cli.error.unexpected", 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 {
+ } else {
property = arg.substring(propertyStart, equalsIndex);
value = arg.substring(equalsIndex + 1);
}
+
commandLine.addProperty(property, value);
}
@@ -112,31 +110,34 @@
// 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);
+ 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);
+ 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('>');
}
@@ -151,15 +152,14 @@
return description;
}
- public List helpLines(
- final int depth,
- final Set helpSettings,
- final Comparator comp) {
+ 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 {
+ } else {
return Collections.EMPTY_LIST;
}
}
Modified: jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/SourceDestArgument.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/SourceDestArgument.java?rev=280462&r1=280461&r2=280462&view=diff
==============================================================================
--- jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/SourceDestArgument.java (original)
+++ jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/SourceDestArgument.java Mon Sep 12 19:32:04 2005
@@ -1,4 +1,4 @@
-/**
+/*
* Copyright 2003-2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -25,6 +25,8 @@
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
@@ -32,74 +34,59 @@
* <code>cp</code> command where a number of source can be specified with
* exactly one destination specfied at the end.
*/
-public class SourceDestArgument extends ArgumentImpl {
- private static int sum(final int a, final int b) {
- return Math.max(a, Math.max(b, a + b));
- }
-
+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);
+ 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 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);
+ 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("The dest argument must enforce a fixed number of values");
+ throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.SOURCE_DEST_MUST_ENFORCE_VALUES));
}
}
- public void appendUsage(
- final StringBuffer buffer,
- final Set helpSettings,
- final Comparator comp) {
+ 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);
@@ -111,25 +98,30 @@
dest.appendUsage(buffer, helpSettings, comp);
}
- public List helpLines(int depth, Set helpSettings, Comparator 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)
+ 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());
}
@@ -138,7 +130,8 @@
dest.validate(commandLine, dest);
}
- public boolean canProcess(final WriteableCommandLine commandLine, final String arg) {
+ public boolean canProcess(final WriteableCommandLine commandLine,
+ final String arg) {
return source.canProcess(commandLine, arg) || dest.canProcess(commandLine, arg);
}
}
Modified: jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/Switch.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/Switch.java?rev=280462&r1=280461&r2=280462&view=diff
==============================================================================
--- jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/Switch.java (original)
+++ jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/Switch.java Mon Sep 12 19:32:04 2005
@@ -1,4 +1,4 @@
-/**
+/*
* Copyright 2003-2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -29,23 +29,27 @@
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>.
+ * For example: <code>+d|-d</code> or <code>--enable-x|--disable-x</code>.
*/
-public class Switch extends ParentImpl {
+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;
@@ -66,43 +70,42 @@
* @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
+ * 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) {
+ 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("enabledPrefix must be supplied");
+ throw new IllegalArgumentException(resources.getMessage(ResourceConstants.SWITCH_NO_ENABLED_PREFIX));
}
if (disabledPrefix == null) {
- throw new IllegalArgumentException("enabledPrefix must be supplied");
+ throw new IllegalArgumentException(ResourceConstants.SWITCH_NO_DISABLED_PREFIX);
}
if (enabledPrefix.startsWith(disabledPrefix)) {
- throw new IllegalArgumentException("The enabledPrefix cannot start the same as disabledPrefix");
+ throw new IllegalArgumentException(ResourceConstants.SWITCH_ENABLED_STARTS_WITH_DISABLED);
}
if (disabledPrefix.startsWith(enabledPrefix)) {
- throw new IllegalArgumentException("The disabledPrefix cannot start the same as enabledPrefix");
+ throw new IllegalArgumentException(ResourceConstants.SWITCH_DISABLED_STARTWS_WITH_ENABLED);
}
this.enabledPrefix = enabledPrefix;
this.disabledPrefix = disabledPrefix;
this.preferredName = preferredName;
- if (preferredName == null || preferredName.length() < 1) {
- throw new IllegalArgumentException("preferredName must be at least 1 character");
+ if ((preferredName == null) || (preferredName.length() < 1)) {
+ throw new IllegalArgumentException(ResourceConstants.SWITCH_PREFERRED_NAME_TOO_SHORT);
}
final Set newTriggers = new HashSet();
@@ -112,11 +115,11 @@
if (aliases == null) {
this.aliases = Collections.EMPTY_SET;
- }
- else {
+ } else {
this.aliases = Collections.unmodifiableSet(new HashSet(aliases));
+
for (final Iterator i = aliases.iterator(); i.hasNext();) {
- final String alias = (String)i.next();
+ final String alias = (String) i.next();
newTriggers.add(enabledPrefix + alias);
newTriggers.add(disabledPrefix + alias);
}
@@ -126,31 +129,29 @@
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)
+ public void processParent(final WriteableCommandLine commandLine,
+ final ListIterator arguments)
throws OptionException {
-
- final String arg = (String)arguments.next();
+ 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, "cli.error.unexpected", arg);
+ } else {
+ throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg);
}
}
@@ -165,38 +166,37 @@
public void validate(WriteableCommandLine commandLine)
throws OptionException {
if (isRequired() && !commandLine.hasOption(this)) {
- throw new OptionException(this,"cli.error.missing.required", getPreferredName());
+ throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED,
+ getPreferredName());
}
super.validate(commandLine);
}
- public void appendUsage(
- final StringBuffer buffer,
- final Set helpSettings,
- final Comparator comp) {
-
+ 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 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);
+ !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);
}
@@ -208,14 +208,16 @@
Collections.sort(list);
for (final Iterator i = list.iterator(); i.hasNext();) {
- final String alias = (String)i.next();
+ final String alias = (String) i.next();
if (enabled) {
buffer.append(enabledPrefix).append(alias);
}
+
if (both) {
buffer.append('|');
}
+
if (disabled) {
buffer.append(disabledPrefix).append(alias);
}
@@ -224,6 +226,7 @@
buffer.append(',');
}
}
+
buffer.append(')');
}
@@ -237,7 +240,7 @@
public String getPreferredName() {
return enabledPrefix + preferredName;
}
-
+
public void defaults(final WriteableCommandLine commandLine) {
commandLine.setDefaultSwitch(this, defaultSwitch);
}
Added: jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties?rev=280462&view=auto
==============================================================================
--- jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties (added)
+++ jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/CLIMessageBundle_en_US.properties Mon Sep 12 19:32:04 2005
@@ -0,0 +1,47 @@
+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
Added: jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/ResourceConstants.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/ResourceConstants.java?rev=280462&view=auto
==============================================================================
--- jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/ResourceConstants.java (added)
+++ jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/ResourceConstants.java Mon Sep 12 19:32:04 2005
@@ -0,0 +1,57 @@
+/*
+ * 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";
+}
Modified: jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/ResourceHelper.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/ResourceHelper.java?rev=280462&r1=280461&r2=280462&view=diff
==============================================================================
--- jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/ResourceHelper.java (original)
+++ jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/resource/ResourceHelper.java Mon Sep 12 19:32:04 2005
@@ -16,8 +16,8 @@
package org.apache.commons.cli2.resource;
import java.text.MessageFormat;
-import java.util.HashMap;
-import java.util.Map;
+
+import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
@@ -27,123 +27,120 @@
* @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;
- /** default bundle name */
- private static final String DEFAULT_BUNDLE = "messages";
-
- /** cache */
- private static Map cache = new HashMap(13);
-
- /**
- * Gets the ResourceHelper appropriate to the specified class.
- * @param clazz the class to get resources for
- * @return a ResourceHelper
- */
- public static ResourceHelper getResourceHelper(final Class clazz) {
-
- if (cache.containsKey(clazz)) {
- return (ResourceHelper)cache.get(clazz);
- }
-
- return new ResourceHelper(clazz);
- }
-
/**
* Create a new ResourceHelper for the specified class.
- *
+ *
* @param clazz the Class that requires some resources
*/
- private ResourceHelper(final Class clazz) {
+ private ResourceHelper() {
+ String bundleName = System.getProperty(PROP_LOCALE);
+
+ if (bundleName == null) {
+ bundleName = DEFAULT_BUNDLE;
+ }
- // get the name of the class
- final String className = clazz.getName();
+ int firstUnderscore = bundleName.indexOf('_');
+ int secondUnderscore = bundleName.indexOf('_', firstUnderscore + 1);
- // discover the package name
- final String packageName =
- className.substring(0, className.lastIndexOf(".") + 1);
+ String language = bundleName.substring(firstUnderscore + 1, secondUnderscore);
+ String country = bundleName.substring(secondUnderscore + 1);
- final String bundleName = packageName + DEFAULT_BUNDLE;
+ Locale locale = new Locale(language, country);
// initialize the bundle
try {
- bundle = ResourceBundle.getBundle(bundleName);
+ bundle = ResourceBundle.getBundle(bundleName, locale);
+ } catch (MissingResourceException exp) {
+ bundle = ResourceBundle.getBundle(DEFAULT_BUNDLE, locale);
}
- catch (MissingResourceException e) {
- //TODO Handle missing resources nicely
- bundle = null;
+ }
+
+ /**
+ * Gets the ResourceHelper appropriate to the specified class.
+ * @param clazz the class to get resources for
+ * @return a ResourceHelper
+ */
+ public static ResourceHelper getResourceHelper() {
+ if (helper == null) {
+ helper = new ResourceHelper();
}
- // cache bundle
- cache.put(bundleName, bundle);
+ 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[] {});
+ 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) {
+ 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) {
-
+ 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) {
-
+ 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) {
+ public String getMessage(final String key,
+ final Object[] values) {
final String msgFormatStr = bundle.getString(key);
final MessageFormat msgFormat = new MessageFormat(msgFormatStr);
Modified: jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/util/HelpFormatter.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/util/HelpFormatter.java?rev=280462&r1=280461&r2=280462&view=diff
==============================================================================
--- jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/util/HelpFormatter.java (original)
+++ jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/util/HelpFormatter.java Mon Sep 12 19:32:04 2005
@@ -1,5 +1,5 @@
-/**
- * Copyright 2003-2004 The Apache Software Foundation
+/*
+ * 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.
@@ -18,6 +18,7 @@
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@@ -31,12 +32,13 @@
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
*/
@@ -46,12 +48,12 @@
* 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
*/
@@ -60,22 +62,22 @@
/**
* 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
+ * 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
+ * body of help
*/
public static final Set DEFAULT_DISPLAY_USAGE_SETTINGS;
@@ -93,8 +95,7 @@
final Set displayUsage = new HashSet(DisplaySetting.ALL);
displayUsage.remove(DisplaySetting.DISPLAY_PARENT_ARGUMENT);
- DEFAULT_DISPLAY_USAGE_SETTINGS =
- Collections.unmodifiableSet(displayUsage);
+ DEFAULT_DISPLAY_USAGE_SETTINGS = Collections.unmodifiableSet(displayUsage);
}
private Set fullUsageSettings = new HashSet(DEFAULT_FULL_USAGE_SETTINGS);
@@ -103,32 +104,23 @@
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?
+ //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);
+ this(DEFAULT_GUTTER_LEFT, DEFAULT_GUTTER_CENTER, DEFAULT_GUTTER_RIGHT, DEFAULT_FULL_WIDTH);
}
/**
@@ -138,12 +130,10 @@
* @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) {
-
+ 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;
@@ -155,21 +145,21 @@
// 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(
- "The gutter strings leave no space for output! "
- + "Supply shorter gutters or more width.");
+ 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.
* @throws IOException if an error occurs
*/
- public void print() throws IOException {
+ public void print()
+ throws IOException {
printHeader();
printException();
printUsage();
@@ -179,10 +169,11 @@
}
/**
- * Prints any error message.
+ * Prints any error message.
* @throws IOException if an error occurs
*/
- public void printException() throws IOException {
+ public void printException()
+ throws IOException {
if (exception != null) {
printDivider();
printWrapped(exception.getMessage());
@@ -190,80 +181,84 @@
}
/**
- * Prints detailed help per option.
+ * Prints detailed help per option.
* @throws IOException if an error occurs
*/
- public void printHelp() throws IOException {
+ public void printHelp()
+ throws IOException {
printDivider();
final Option option;
- if (exception != null && exception.getOption() != null) {
+
+ if ((exception != null) && (exception.getOption() != null)) {
option = exception.getOption();
- }
- else {
+ } 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 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);
-
+ 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();
-
+ final HelpLine helpLine = (HelpLine) i.next();
+
// wrap the description
- final List descList =
- wrap(helpLine.getDescription(), descriptionWidth);
+ 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);
+ 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);
+ pad((String) descriptionIterator.next(), descriptionWidth, out);
printGutterRight();
out.println();
}
}
+
printDivider();
}
/**
- * Prints a single line of usage information (wrapping if necessary)
+ * Prints a single line of usage information (wrapping if necessary)
* @throws IOException if an error occurs
*/
- public void printUsage() throws IOException {
+ public void printUsage()
+ throws IOException {
printDivider();
+
final StringBuffer buffer = new StringBuffer("Usage:\n");
buffer.append(shellCommand).append(' ');
group.appendUsage(buffer, fullUsageSettings, comparator, " ");
@@ -271,10 +266,11 @@
}
/**
- * Prints a header string if necessary
+ * Prints a header string if necessary
* @throws IOException if an error occurs
*/
- public void printHeader() throws IOException {
+ public void printHeader()
+ throws IOException {
if (header != null) {
printDivider();
printWrapped(header);
@@ -282,10 +278,11 @@
}
/**
- * Prints a footer string if necessary
+ * Prints a footer string if necessary
* @throws IOException if an error occurs
*/
- public void printFooter() throws IOException {
+ public void printFooter()
+ throws IOException {
if (footer != null) {
printWrapped(footer);
printDivider();
@@ -294,23 +291,21 @@
/**
* Prints a string wrapped if necessary
- * @param text the string to wrap
+ * @param text the string to wrap
* @throws IOException if an error occurs
*/
protected void printWrapped(final String text)
throws IOException {
- for (final Iterator i = wrap(text, pageWidth).iterator();
- i.hasNext();
- ) {
+ for (final Iterator i = wrap(text, pageWidth).iterator(); i.hasNext();) {
printGutterLeft();
- pad((String)i.next(), pageWidth, out);
+ pad((String) i.next(), pageWidth, out);
printGutterRight();
out.println();
}
}
/**
- * Prints the left gutter string
+ * Prints the left gutter string
*/
public void printGutterLeft() {
if (gutterLeft != null) {
@@ -319,7 +314,7 @@
}
/**
- * Prints the right gutter string
+ * Prints the right gutter string
*/
public void printGutterRight() {
if (gutterRight != null) {
@@ -336,18 +331,16 @@
}
}
- protected static void pad(
- final String text,
- final int width,
- final Writer writer)
+ protected static void pad(final String text,
+ final int width,
+ final Writer writer)
throws IOException {
final int left;
-
+
// write the text and record how many characters written
if (text == null) {
left = 0;
- }
- else {
+ } else {
writer.write(text);
left = text.length();
}
@@ -358,13 +351,16 @@
}
}
- protected static List wrap(final String text, final int width) {
-
+ protected static List wrap(final String text,
+ final int width) {
// check for valid width
- if(width<1){
- throw new IllegalArgumentException("width must be positive");
+ 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("");
@@ -378,42 +374,45 @@
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) {
+ while ((right < chars.length) && (chars[right] != '\n') &&
+ (right < (left + width + 1))) {
right++;
}
-
+
// if a newline was found
- if (right<chars.length && chars[right] == '\n') {
+ 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;
-
+ 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);
+ 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] != ' ') {
+ while ((right >= left) && (chars[right] != ' ')) {
right--;
}
@@ -422,28 +421,30 @@
// 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] == ' ') {
+ 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] == ' ') {
+ while ((right < chars.length) && (chars[right] == ' ')) {
right++;
}
+
left = right;
}
@@ -457,11 +458,11 @@
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
*/
@@ -476,7 +477,7 @@
public void setDivider(String divider) {
this.divider = divider;
}
-
+
/**
* Sets the exception to document
* @param exception the exception that occured
@@ -495,7 +496,7 @@
/**
* The DisplaySettings used to select the elements to display in the
- * displayed line of full usage information.
+ * displayed line of full usage information.
* @see DisplaySetting
* @param fullUsageSettings
*/
@@ -520,7 +521,7 @@
}
/**
- * Sets the DisplaySettings used to select elements in the per helpline
+ * Sets the DisplaySettings used to select elements in the per helpline
* usage strings.
* @see DisplaySetting
* @param lineUsageSettings the DisplaySettings to use
@@ -629,7 +630,7 @@
}
/**
- * @return the command used to execute the application
+ * @return the command used to execute the application
*/
public String getShellCommand() {
return shellCommand;
Modified: jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/validation/ClassValidator.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/validation/ClassValidator.java?rev=280462&r1=280461&r2=280462&view=diff
==============================================================================
--- jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/validation/ClassValidator.java (original)
+++ jakarta/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/validation/ClassValidator.java Mon Sep 12 19:32:04 2005
@@ -18,6 +18,7 @@
import java.util.List;
import java.util.ListIterator;
+import org.apache.commons.cli2.resource.ResourceConstants;
import org.apache.commons.cli2.resource.ResourceHelper;
/**
@@ -33,22 +34,20 @@
* validator.setInstance(true);
*
* ArgumentBuilder builder = new ArgumentBuilder();
- * Argument logger =
+ * Argument logger =
* builder.withName("logger");
* .withValidator(validator);
* </pre>
- *
+ *
* @author John Keyes
*/
public class ClassValidator implements Validator {
-
/** i18n */
- private static final ResourceHelper resources =
- ResourceHelper.getResourceHelper(ClassValidator.class);
+ 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;
@@ -58,53 +57,42 @@
/**
* 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 {
-
+ public void validate(final List values)
+ throws InvalidArgumentException {
for (final ListIterator i = values.listIterator(); i.hasNext();) {
- final String name = (String)i.next();
+ final String name = (String) i.next();
if (!isPotentialClassName(name)) {
- throw new InvalidArgumentException(
- resources.getMessage(
- "ClassValidator.error.bad.classname",
- 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 {
+ } else {
i.set(clazz);
}
- }
- catch (final ClassNotFoundException exp) {
- throw new InvalidArgumentException(
- resources.getMessage(
- "ClassValidator.error.class.notfound",
- name));
- }
- catch (final IllegalAccessException exp) {
- throw new InvalidArgumentException(
- resources.getMessage(
- "ClassValidator.error.class.access",
- name,
- exp.getMessage()));
- }
- catch (final InstantiationException exp) {
- throw new InvalidArgumentException(
- resources.getMessage(
- "ClassValidator.error.class.create",
- name));
+ } 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));
}
}
}
@@ -125,7 +113,7 @@
* Specifies whether the argument value must represent a
* class that is loadable.
*
- * @param loadable whether the argument value must
+ * @param loadable whether the argument value must
* represent a class that is loadable.
*/
public void setLoadable(boolean loadable) {
@@ -143,7 +131,7 @@
if (loader == null) {
loader = getClass().getClassLoader();
}
-
+
return loader;
}
@@ -173,7 +161,7 @@
* Specifies whether the argument value must represent a
* class that can be instantiated.
*
- * @param instance whether the argument value must
+ * @param instance whether the argument value must
* represent a class that can be instantiated.
*/
public void setInstance(boolean instance) {
@@ -191,22 +179,22 @@
for (int i = 0; i < chars.length; ++i) {
final char c = chars[i];
+
if (expectingStart) {
if (!Character.isJavaIdentifierStart(c)) {
return false;
}
+
expectingStart = false;
- }
- else {
+ } else {
if (c == '.') {
expectingStart = true;
- }
- else if (!Character.isJavaIdentifierPart(c)) {
+ } else if (!Character.isJavaIdentifierPart(c)) {
return false;
}
}
}
+
return !expectingStart;
}
-
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org