commons-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From bay...@apache.org
Subject svn commit: r639943 [4/17] - in /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/resource/ jav...
Date Sat, 22 Mar 2008 03:08:35 GMT
Modified: commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/Command.java
URL: http://svn.apache.org/viewvc/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/Command.java?rev=639943&r1=639942&r2=639943&view=diff
==============================================================================
--- commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/Command.java (original)
+++ commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/Command.java Fri Mar 21 20:08:23 2008
@@ -1 +1,175 @@
-/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.  See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import 
 java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * Represents a cvs "update" style command line option. * * Like all Parents, Commands can have child options and can be part of * Arguments */public class Command    extends ParentImpl {    /** The display name for the command */    private final String preferredName;    /** The aliases for this command */    private final Set aliases;    /** All the names for this command */    private final Set triggers;    /**     * Creates a new Command instance.     *     * @param preferredName     *            The name normally used to refer to the Command     * @param description     *            A descriptio
 n of the Command     * @param aliases     *            Alternative names for the Command     * @param required     *            Whether the Command is required     * @param argument     *            An Argument that the command takes     * @param children     *            The Group of child options for this Command     * @param id     *            A unique id for the Command     *     * @see ParentImpl#ParentImpl(Argument, Group, String, int, boolean)     */    public Command(final String preferredName,                   final String description,                   final Set aliases,                   final boolean required,                   final Argument argument,                   final Group children,                   final int id) {        super(argument, children, description, id, required);        // check the preferred name is valid        if ((preferredName == null) || (preferredName.length() < 1)) {            throw new IllegalArgumentException(ResourceHelper.getR
 esourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT));        }        this.preferredName = preferredName;        // gracefully and defensively handle aliases        this.aliases =            (aliases == null) ? Collections.EMPTY_SET                              : Collections.unmodifiableSet(new HashSet(aliases));        // populate the triggers Set        final Set newTriggers = new HashSet();        newTriggers.add(preferredName);        newTriggers.addAll(this.aliases);        this.triggers = Collections.unmodifiableSet(newTriggers);    }    public void processParent(final WriteableCommandLine commandLine,                              final ListIterator arguments)        throws OptionException {        // grab the argument to process        final String arg = (String) arguments.next();        // if we can process it        if (canProcess(commandLine, arg)) {            // then note the option            commandLine.addOption(this);            // 
 normalise the argument list            arguments.set(preferredName);        } else {            throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg);        }    }    public Set getTriggers() {        return triggers;    }    public void validate(WriteableCommandLine commandLine)        throws OptionException {        if (isRequired() && !commandLine.hasOption(this)) {            throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED,                                      getPreferredName());        }        super.validate(commandLine);    }    public void appendUsage(final StringBuffer buffer,                            final Set helpSettings,                            final Comparator comp) {        // do we display optionality        final boolean optional =            !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL);        final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES);  
       if (optional) {            buffer.append('[');        }        buffer.append(preferredName);        if (displayAliases && !aliases.isEmpty()) {            buffer.append(" (");            final List list = new ArrayList(aliases);            Collections.sort(list);            for (final Iterator i = list.iterator(); i.hasNext();) {                final String alias = (String) i.next();                buffer.append(alias);                if (i.hasNext()) {                    buffer.append(',');                }            }            buffer.append(')');        }        super.appendUsage(buffer, helpSettings, comp);        if (optional) {            buffer.append(']');        }    }    public String getPreferredName() {        return preferredName;    }}
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.cli2.option;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Set;
+
+import org.apache.commons.cli2.Argument;
+import org.apache.commons.cli2.DisplaySetting;
+import org.apache.commons.cli2.Group;
+import org.apache.commons.cli2.OptionException;
+import org.apache.commons.cli2.WriteableCommandLine;
+import org.apache.commons.cli2.resource.ResourceConstants;
+import org.apache.commons.cli2.resource.ResourceHelper;
+
+/**
+ * Represents a cvs "update" style command line option.
+ *
+ * Like all Parents, Commands can have child options and can be part of
+ * Arguments
+ */
+public class Command
+    extends ParentImpl {
+    /** The display name for the command */
+    private final String preferredName;
+
+    /** The aliases for this command */
+    private final Set aliases;
+
+    /** All the names for this command */
+    private final Set triggers;
+
+    /**
+     * Creates a new Command instance.
+     *
+     * @param preferredName
+     *            The name normally used to refer to the Command
+     * @param description
+     *            A description of the Command
+     * @param aliases
+     *            Alternative names for the Command
+     * @param required
+     *            Whether the Command is required
+     * @param argument
+     *            An Argument that the command takes
+     * @param children
+     *            The Group of child options for this Command
+     * @param id
+     *            A unique id for the Command
+     *
+     * @see ParentImpl#ParentImpl(Argument, Group, String, int, boolean)
+     */
+    public Command(final String preferredName,
+                   final String description,
+                   final Set aliases,
+                   final boolean required,
+                   final Argument argument,
+                   final Group children,
+                   final int id) {
+        super(argument, children, description, id, required);
+
+        // check the preferred name is valid
+        if ((preferredName == null) || (preferredName.length() < 1)) {
+            throw new IllegalArgumentException(ResourceHelper.getResourceHelper().getMessage(ResourceConstants.COMMAND_PREFERRED_NAME_TOO_SHORT));
+        }
+
+        this.preferredName = preferredName;
+
+        // gracefully and defensively handle aliases
+        this.aliases =
+            (aliases == null) ? Collections.EMPTY_SET
+                              : Collections.unmodifiableSet(new HashSet(aliases));
+
+        // populate the triggers Set
+        final Set newTriggers = new HashSet();
+        newTriggers.add(preferredName);
+        newTriggers.addAll(this.aliases);
+        this.triggers = Collections.unmodifiableSet(newTriggers);
+    }
+
+    public void processParent(final WriteableCommandLine commandLine,
+                              final ListIterator arguments)
+        throws OptionException {
+        // grab the argument to process
+        final String arg = (String) arguments.next();
+
+        // if we can process it
+        if (canProcess(commandLine, arg)) {
+            // then note the option
+            commandLine.addOption(this);
+
+            // normalise the argument list
+            arguments.set(preferredName);
+        } else {
+            throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, arg);
+        }
+    }
+
+    public Set getTriggers() {
+        return triggers;
+    }
+
+    public void validate(WriteableCommandLine commandLine)
+        throws OptionException {
+        if (isRequired() && !commandLine.hasOption(this)) {
+            throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED,
+                                      getPreferredName());
+        }
+
+        super.validate(commandLine);
+    }
+
+    public void appendUsage(final StringBuffer buffer,
+                            final Set helpSettings,
+                            final Comparator comp) {
+        // do we display optionality
+        final boolean optional =
+            !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL);
+        final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES);
+
+        if (optional) {
+            buffer.append('[');
+        }
+
+        buffer.append(preferredName);
+
+        if (displayAliases && !aliases.isEmpty()) {
+            buffer.append(" (");
+
+            final List list = new ArrayList(aliases);
+            Collections.sort(list);
+
+            for (final Iterator i = list.iterator(); i.hasNext();) {
+                final String alias = (String) i.next();
+                buffer.append(alias);
+
+                if (i.hasNext()) {
+                    buffer.append(',');
+                }
+            }
+
+            buffer.append(')');
+        }
+
+        super.appendUsage(buffer, helpSettings, comp);
+
+        if (optional) {
+            buffer.append(']');
+        }
+    }
+
+    public String getPreferredName() {
+        return preferredName;
+    }
+}

Modified: commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/DefaultOption.java
URL: http://svn.apache.org/viewvc/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/DefaultOption.java?rev=639943&r1=639942&r2=639943&view=diff
==============================================================================
--- commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/DefaultOption.java (original)
+++ commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/DefaultOption.java Fri Mar 21 20:08:23 2008
@@ -1 +1,221 @@
-/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.  See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;import java.util.List;import 
 java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;/** * A Parent implementation representing normal options. */public class DefaultOption    extends ParentImpl {    /**     * The default token used to prefix a short option     */    public static final String DEFAULT_SHORT_PREFIX = "-";    /**     * The default token used to prefix a long option     */    public static final String DEFAULT_LONG_PREFIX = "--";    /**     * The default value for the burstEnabled constructor parameter     */    public static final boolean DEFAULT_BURST_ENABLED = true;    private final String preferredName;    private final Set aliases;    private final Set burstAliases;    private final Set triggers;    private final Set pref
 ixes;    private final String shortPrefix;    private final boolean burstEnabled;    private final int burstLength;    /**     * Creates a new DefaultOption     *     * @param shortPrefix the prefix used for short options     * @param longPrefix the prefix used for long options     * @param burstEnabled should option bursting be enabled     * @param preferredName the preferred name for this Option, this should begin with either shortPrefix or longPrefix     * @param description a description of this Option     * @param aliases the alternative names for this Option     * @param burstAliases the aliases that can be burst     * @param required whether the Option is strictly required     * @param argument the Argument belonging to this Parent, or null     * @param children the Group children belonging to this Parent, ot null     * @param id the unique identifier for this Option     * @throws IllegalArgumentException if the preferredName or an alias isn't     *     prefixed with 
 shortPrefix or longPrefix     */    public DefaultOption(final String shortPrefix,                         final String longPrefix,                         final boolean burstEnabled,                         final String preferredName,                         final String description,                         final Set aliases,                         final Set burstAliases,                         final boolean required,                         final Argument argument,                         final Group children,                         final int id) {        super(argument, children, description, id, required);        this.shortPrefix = shortPrefix;        this.burstEnabled = burstEnabled;        this.burstLength = shortPrefix.length() + 1;        this.preferredName = preferredName;        this.aliases =            (aliases == null) ? Collections.EMPTY_SET                              : Collections.unmodifiableSet(new HashSet(aliases));        this.burstAliases =          
   (burstAliases == null) ? Collections.EMPTY_SET                                   : Collections.unmodifiableSet(new HashSet(burstAliases));        final Set newTriggers = new HashSet();        newTriggers.add(preferredName);        newTriggers.addAll(this.aliases);        newTriggers.addAll(this.burstAliases);        this.triggers = Collections.unmodifiableSet(newTriggers);        final Set newPrefixes = new HashSet(super.getPrefixes());        newPrefixes.add(shortPrefix);        newPrefixes.add(longPrefix);        this.prefixes = Collections.unmodifiableSet(newPrefixes);        checkPrefixes(newPrefixes);    }    public boolean canProcess(final WriteableCommandLine commandLine,                              final String argument) {        return (argument != null) &&               (super.canProcess(commandLine, argument) ||               ((argument.length() >= burstLength) &&               burstAliases.contains(argument.substring(0, burstLength))));    }    public void pro
 cessParent(WriteableCommandLine commandLine,                              ListIterator arguments)        throws OptionException {        final String argument = (String) arguments.next();        if (triggers.contains(argument)) {            commandLine.addOption(this);            arguments.set(preferredName);        } else if (burstEnabled && (argument.length() >= burstLength)) {            final String burst = argument.substring(0, burstLength);            if (burstAliases.contains(burst)) {                commandLine.addOption(this);                //HMM test bursting all vs bursting one by one.                arguments.set(preferredName);                if (getArgument() == null) {                    arguments.add(shortPrefix + argument.substring(burstLength));                } else {                    arguments.add(argument.substring(burstLength));                }                arguments.previous();            } else {                throw new OptionException(this, Re
 sourceConstants.CANNOT_BURST, argument);            }        } else {            throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, argument);        }    }    public Set getTriggers() {        return triggers;    }    public Set getPrefixes() {        return prefixes;    }    public void validate(WriteableCommandLine commandLine)        throws OptionException {        if (isRequired() && !commandLine.hasOption(this)) {            throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED,                                      getPreferredName());        }        super.validate(commandLine);    }    public void appendUsage(final StringBuffer buffer,                            final Set helpSettings,                            final Comparator comp) {        // do we display optionality        final boolean optional =            !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL);        final boolean displayAliases = helpSet
 tings.contains(DisplaySetting.DISPLAY_ALIASES);        if (optional) {            buffer.append('[');        }        buffer.append(preferredName);        if (displayAliases && !aliases.isEmpty()) {            buffer.append(" (");            final List list = new ArrayList(aliases);            Collections.sort(list);            for (final Iterator i = list.iterator(); i.hasNext();) {                final String alias = (String) i.next();                buffer.append(alias);                if (i.hasNext()) {                    buffer.append(',');                }            }            buffer.append(')');        }        super.appendUsage(buffer, helpSettings, comp);        if (optional) {            buffer.append(']');        }    }    public String getPreferredName() {        return preferredName;    }}
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.cli2.option;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Set;
+
+import org.apache.commons.cli2.Argument;
+import org.apache.commons.cli2.DisplaySetting;
+import org.apache.commons.cli2.Group;
+import org.apache.commons.cli2.OptionException;
+import org.apache.commons.cli2.WriteableCommandLine;
+import org.apache.commons.cli2.resource.ResourceConstants;
+
+/**
+ * A Parent implementation representing normal options.
+ */
+public class DefaultOption
+    extends ParentImpl {
+    /**
+     * The default token used to prefix a short option
+     */
+    public static final String DEFAULT_SHORT_PREFIX = "-";
+
+    /**
+     * The default token used to prefix a long option
+     */
+    public static final String DEFAULT_LONG_PREFIX = "--";
+
+    /**
+     * The default value for the burstEnabled constructor parameter
+     */
+    public static final boolean DEFAULT_BURST_ENABLED = true;
+    private final String preferredName;
+    private final Set aliases;
+    private final Set burstAliases;
+    private final Set triggers;
+    private final Set prefixes;
+    private final String shortPrefix;
+    private final boolean burstEnabled;
+    private final int burstLength;
+
+    /**
+     * Creates a new DefaultOption
+     *
+     * @param shortPrefix the prefix used for short options
+     * @param longPrefix the prefix used for long options
+     * @param burstEnabled should option bursting be enabled
+     * @param preferredName the preferred name for this Option, this should begin with either shortPrefix or longPrefix
+     * @param description a description of this Option
+     * @param aliases the alternative names for this Option
+     * @param burstAliases the aliases that can be burst
+     * @param required whether the Option is strictly required
+     * @param argument the Argument belonging to this Parent, or null
+     * @param children the Group children belonging to this Parent, ot null
+     * @param id the unique identifier for this Option
+     * @throws IllegalArgumentException if the preferredName or an alias isn't
+     *     prefixed with shortPrefix or longPrefix
+     */
+    public DefaultOption(final String shortPrefix,
+                         final String longPrefix,
+                         final boolean burstEnabled,
+                         final String preferredName,
+                         final String description,
+                         final Set aliases,
+                         final Set burstAliases,
+                         final boolean required,
+                         final Argument argument,
+                         final Group children,
+                         final int id) {
+        super(argument, children, description, id, required);
+
+        this.shortPrefix = shortPrefix;
+        this.burstEnabled = burstEnabled;
+
+        this.burstLength = shortPrefix.length() + 1;
+
+        this.preferredName = preferredName;
+        this.aliases =
+            (aliases == null) ? Collections.EMPTY_SET
+                              : Collections.unmodifiableSet(new HashSet(aliases));
+
+        this.burstAliases =
+            (burstAliases == null) ? Collections.EMPTY_SET
+                                   : Collections.unmodifiableSet(new HashSet(burstAliases));
+
+        final Set newTriggers = new HashSet();
+        newTriggers.add(preferredName);
+        newTriggers.addAll(this.aliases);
+        newTriggers.addAll(this.burstAliases);
+        this.triggers = Collections.unmodifiableSet(newTriggers);
+
+        final Set newPrefixes = new HashSet(super.getPrefixes());
+        newPrefixes.add(shortPrefix);
+        newPrefixes.add(longPrefix);
+        this.prefixes = Collections.unmodifiableSet(newPrefixes);
+
+        checkPrefixes(newPrefixes);
+    }
+
+    public boolean canProcess(final WriteableCommandLine commandLine,
+                              final String argument) {
+        return (argument != null) &&
+               (super.canProcess(commandLine, argument) ||
+               ((argument.length() >= burstLength) &&
+               burstAliases.contains(argument.substring(0, burstLength))));
+    }
+
+    public void processParent(WriteableCommandLine commandLine,
+                              ListIterator arguments)
+        throws OptionException {
+        final String argument = (String) arguments.next();
+
+        if (triggers.contains(argument)) {
+            commandLine.addOption(this);
+            arguments.set(preferredName);
+        } else if (burstEnabled && (argument.length() >= burstLength)) {
+            final String burst = argument.substring(0, burstLength);
+
+            if (burstAliases.contains(burst)) {
+                commandLine.addOption(this);
+
+                //HMM test bursting all vs bursting one by one.
+                arguments.set(preferredName);
+
+                if (getArgument() == null) {
+                    arguments.add(shortPrefix + argument.substring(burstLength));
+                } else {
+                    arguments.add(argument.substring(burstLength));
+                }
+
+                arguments.previous();
+            } else {
+                throw new OptionException(this, ResourceConstants.CANNOT_BURST, argument);
+            }
+        } else {
+            throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, argument);
+        }
+    }
+
+    public Set getTriggers() {
+        return triggers;
+    }
+
+    public Set getPrefixes() {
+        return prefixes;
+    }
+
+    public void validate(WriteableCommandLine commandLine)
+        throws OptionException {
+        if (isRequired() && !commandLine.hasOption(this)) {
+            throw new OptionException(this, ResourceConstants.OPTION_MISSING_REQUIRED,
+                                      getPreferredName());
+        }
+
+        super.validate(commandLine);
+    }
+
+    public void appendUsage(final StringBuffer buffer,
+                            final Set helpSettings,
+                            final Comparator comp) {
+        // do we display optionality
+        final boolean optional =
+            !isRequired() && helpSettings.contains(DisplaySetting.DISPLAY_OPTIONAL);
+        final boolean displayAliases = helpSettings.contains(DisplaySetting.DISPLAY_ALIASES);
+
+        if (optional) {
+            buffer.append('[');
+        }
+
+        buffer.append(preferredName);
+
+        if (displayAliases && !aliases.isEmpty()) {
+            buffer.append(" (");
+
+            final List list = new ArrayList(aliases);
+            Collections.sort(list);
+
+            for (final Iterator i = list.iterator(); i.hasNext();) {
+                final String alias = (String) i.next();
+                buffer.append(alias);
+
+                if (i.hasNext()) {
+                    buffer.append(',');
+                }
+            }
+
+            buffer.append(')');
+        }
+
+        super.appendUsage(buffer, helpSettings, comp);
+
+        if (optional) {
+            buffer.append(']');
+        }
+    }
+
+    public String getPreferredName() {
+        return preferredName;
+    }
+}

Modified: commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/GroupImpl.java
URL: http://svn.apache.org/viewvc/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/GroupImpl.java?rev=639943&r1=639942&r2=639943&view=diff
==============================================================================
--- commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/GroupImpl.java (original)
+++ commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/GroupImpl.java Fri Mar 21 20:08:23 2008
@@ -1 +1,517 @@
-/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.  See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.Iterator;i
 mport java.util.List;import java.util.ListIterator;import java.util.Map;import java.util.Set;import java.util.SortedMap;import java.util.TreeMap;import org.apache.commons.cli2.Argument;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Group;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;import org.apache.commons.cli2.OptionException;import org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;/** * An implementation of Group */public class GroupImpl    extends OptionImpl implements Group {    private final String name;    private final String description;    private final List options;    private final int minimum;    private final int maximum;    private final List anonymous;    private final SortedMap optionMap;    private final Set prefixes;    /**     * Creates a new GroupImpl using the specified parameters.     *     * @param options the Options and Arguments that 
 make up the Group     * @param name the name of this Group, or null     * @param description a description of this Group     * @param minimum the minimum number of Options for a valid CommandLine     * @param maximum the maximum number of Options for a valid CommandLine     */    public GroupImpl(final List options,                     final String name,                     final String description,                     final int minimum,                     final int maximum) {        super(0, false);        this.name = name;        this.description = description;        this.minimum = minimum;        this.maximum = maximum;        // store a copy of the options to be used by the        // help methods        this.options = Collections.unmodifiableList(options);        // anonymous Argument temporary storage        final List newAnonymous = new ArrayList();        // map (key=trigger & value=Option) temporary storage        final SortedMap newOptionMap = new TreeMap(ReverseS
 tringComparator.getInstance());        // prefixes temporary storage        final Set newPrefixes = new HashSet();        // process the options        for (final Iterator i = options.iterator(); i.hasNext();) {            final Option option = (Option) i.next();            if (option instanceof Argument) {                i.remove();                newAnonymous.add(option);            } else {                final Set triggers = option.getTriggers();                for (Iterator j = triggers.iterator(); j.hasNext();) {                    newOptionMap.put(j.next(), option);                }                // store the prefixes                newPrefixes.addAll(option.getPrefixes());            }        }        this.anonymous = Collections.unmodifiableList(newAnonymous);        this.optionMap = Collections.unmodifiableSortedMap(newOptionMap);        this.prefixes = Collections.unmodifiableSet(newPrefixes);    }    public boolean canProcess(final WriteableCommandLine commandLi
 ne,                              final String arg) {        if (arg == null) {            return false;        }        // if arg does not require bursting        if (optionMap.containsKey(arg)) {            return true;        }        // filter        final Map tailMap = optionMap.tailMap(arg);        // check if bursting is required        for (final Iterator iter = tailMap.values().iterator(); iter.hasNext();) {            final Option option = (Option) iter.next();            if (option.canProcess(commandLine, arg)) {                return true;            }        }        if (commandLine.looksLikeOption(arg)) {            return false;        }        // anonymous argument(s) means we can process it        if (anonymous.size() > 0) {            return true;        }        return false;    }    public Set getPrefixes() {        return prefixes;    }    public Set getTriggers() {        return optionMap.keySet();    }    public void process(final WriteableCommandLine c
 ommandLine,                        final ListIterator arguments)        throws OptionException {        String previous = null;        // [START process each command line token        while (arguments.hasNext()) {            // grab the next argument            final String arg = (String) arguments.next();            // if we have just tried to process this instance            if (arg == previous) {                // rollback and abort                arguments.previous();                break;            }            // remember last processed instance            previous = arg;            final Option opt = (Option) optionMap.get(arg);            // option found            if (opt != null) {                arguments.previous();                opt.process(commandLine, arguments);            }            // [START option NOT found            else {                // it might be an anonymous argument continue search                // [START argument may be anonymous           
      if (commandLine.looksLikeOption(arg)) {                    // narrow the search                    final Collection values = optionMap.tailMap(arg).values();                    boolean foundMemberOption = false;                    for (Iterator i = values.iterator(); i.hasNext() && !foundMemberOption;) {                        final Option option = (Option) i.next();                        if (option.canProcess(commandLine, arg)) {                            foundMemberOption = true;                            arguments.previous();                            option.process(commandLine, arguments);                        }                    }                    // back track and abort this group if necessary                    if (!foundMemberOption) {                        arguments.previous();                        return;                    }                } // [END argument may be anonymous                // [START argument is NOT anonymous                else { 
                    // move iterator back, current value not used                    arguments.previous();                    // if there are no anonymous arguments then this group can't                    // process the argument                    if (anonymous.isEmpty()) {                        break;                    }                    // TODO: why do we iterate over all anonymous arguments?                    // canProcess will always return true?                    for (final Iterator i = anonymous.iterator(); i.hasNext();) {                        final Argument argument = (Argument) i.next();                        if (argument.canProcess(commandLine, arguments)) {                            argument.process(commandLine, arguments);                        }                    }                } // [END argument is NOT anonymous            } // [END option NOT found        } // [END process each command line token    }    public void validate(final WriteableCommand
 Line commandLine)        throws OptionException {        // number of options found        int present = 0;        // reference to first unexpected option        Option unexpected = null;        for (final Iterator i = options.iterator(); i.hasNext();) {            final Option option = (Option) i.next();            // if the child option is required then validate it            if (option.isRequired()) {                option.validate(commandLine);            }            if (option instanceof Group) {                option.validate(commandLine);            }            // if the child option is present then validate it            if (commandLine.hasOption(option)) {                if (++present > maximum) {                    unexpected = option;                    break;                }                option.validate(commandLine);            }        }        // too many options        if (unexpected != null) {            throw new OptionException(this, ResourceConstants.
 UNEXPECTED_TOKEN,                                      unexpected.getPreferredName());        }        // too few option        if (present < minimum) {            throw new OptionException(this, ResourceConstants.MISSING_OPTION);        }        // validate each anonymous argument        for (final Iterator i = anonymous.iterator(); i.hasNext();) {            final Option option = (Option) i.next();            option.validate(commandLine);        }    }    public String getPreferredName() {        return name;    }    public String getDescription() {        return description;    }    public void appendUsage(final StringBuffer buffer,                            final Set helpSettings,                            final Comparator comp) {        appendUsage(buffer, helpSettings, comp, "|");    }    public void appendUsage(final StringBuffer buffer,                            final Set helpSettings,                            final Comparator comp,                            fi
 nal String separator) {        final Set helpSettingsCopy = new HashSet(helpSettings);        final boolean optional =            (minimum == 0) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_OPTIONAL);        final boolean expanded =            (name == null) || helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED);        final boolean named =            !expanded ||            ((name != null) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_NAME));        final boolean arguments = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT);        final boolean outer = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_OUTER);        helpSettingsCopy.remove(DisplaySetting.DISPLAY_GROUP_OUTER);        final boolean both = named && expanded;        if (optional) {            buffer.append('[');        }        if (named) {            buffer.append(name);        }        if (both) {            buffer.append(" (");        }        if (expande
 d) {            final Set childSettings;            if (!helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) {                childSettings = DisplaySetting.NONE;            } else {                childSettings = new HashSet(helpSettingsCopy);                childSettings.remove(DisplaySetting.DISPLAY_OPTIONAL);            }            // grab a list of the group's options.            final List list;            if (comp == null) {                // default to using the initial order                list = options;            } else {                // sort options if comparator is supplied                list = new ArrayList(options);                Collections.sort(list, comp);            }            // for each option.            for (final Iterator i = list.iterator(); i.hasNext();) {                final Option option = (Option) i.next();                // append usage information                option.appendUsage(buffer, childSettings, comp);            
     // add separators as needed                if (i.hasNext()) {                    buffer.append(separator);                }            }        }        if (both) {            buffer.append(')');        }        if (optional && outer) {            buffer.append(']');        }        if (arguments) {            for (final Iterator i = anonymous.iterator(); i.hasNext();) {                buffer.append(' ');                final Option option = (Option) i.next();                option.appendUsage(buffer, helpSettingsCopy, comp);            }        }        if (optional && !outer) {            buffer.append(']');        }    }    public List helpLines(final int depth,                          final Set helpSettings,                          final Comparator comp) {        final List helpLines = new ArrayList();        if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_NAME)) {            final HelpLine helpLine = new HelpLineImpl(this, depth);            helpLines.add(h
 elpLine);        }        if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) {            // grab a list of the group's options.            final List list;            if (comp == null) {                // default to using the initial order                list = options;            } else {                // sort options if comparator is supplied                list = new ArrayList(options);                Collections.sort(list, comp);            }            // for each option            for (final Iterator i = list.iterator(); i.hasNext();) {                final Option option = (Option) i.next();                helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp));            }        }        if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT)) {            for (final Iterator i = anonymous.iterator(); i.hasNext();) {                final Option option = (Option) i.next();                helpLines.addAll(option.helpLines(depth + 1,
  helpSettings, comp));            }        }        return helpLines;    }    /**     * Gets the member Options of thie Group.     * Note this does not include any Arguments     * @return only the non Argument Options of the Group     */    public List getOptions() {        return options;    }    /**     * Gets the anonymous Arguments of this Group.     * @return the Argument options of this Group     */    public List getAnonymous() {        return anonymous;    }    public Option findOption(final String trigger) {        final Iterator i = getOptions().iterator();        while (i.hasNext()) {            final Option option = (Option) i.next();            final Option found = option.findOption(trigger);            if (found != null) {                return found;            }        }        return null;    }    public int getMinimum() {        return minimum;    }    public int getMaximum() {        return maximum;    }    public boolean isRequired() {        return getMi
 nimum() > 0;    }    public void defaults(final WriteableCommandLine commandLine) {        super.defaults(commandLine);        for (final Iterator i = options.iterator(); i.hasNext();) {            final Option option = (Option) i.next();            option.defaults(commandLine);        }        for (final Iterator i = anonymous.iterator(); i.hasNext();) {            final Option option = (Option) i.next();            option.defaults(commandLine);        }    }}class ReverseStringComparator implements Comparator {    private static final Comparator instance = new ReverseStringComparator();    private ReverseStringComparator() {        // just making sure nobody else creates one    }    /**     * Gets a singleton instance of a ReverseStringComparator     * @return the singleton instance     */    public static final Comparator getInstance() {        return instance;    }    public int compare(final Object o1,                       final Object o2) {        final String s1 = (S
 tring) o1;        final String s2 = (String) o2;        return -s1.compareTo(s2);    }}
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.cli2.option;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+import org.apache.commons.cli2.Argument;
+import org.apache.commons.cli2.DisplaySetting;
+import org.apache.commons.cli2.Group;
+import org.apache.commons.cli2.HelpLine;
+import org.apache.commons.cli2.Option;
+import org.apache.commons.cli2.OptionException;
+import org.apache.commons.cli2.WriteableCommandLine;
+import org.apache.commons.cli2.resource.ResourceConstants;
+
+/**
+ * An implementation of Group
+ */
+public class GroupImpl
+    extends OptionImpl implements Group {
+    private final String name;
+    private final String description;
+    private final List options;
+    private final int minimum;
+    private final int maximum;
+    private final List anonymous;
+    private final SortedMap optionMap;
+    private final Set prefixes;
+
+    /**
+     * Creates a new GroupImpl using the specified parameters.
+     *
+     * @param options the Options and Arguments that make up the Group
+     * @param name the name of this Group, or null
+     * @param description a description of this Group
+     * @param minimum the minimum number of Options for a valid CommandLine
+     * @param maximum the maximum number of Options for a valid CommandLine
+     */
+    public GroupImpl(final List options,
+                     final String name,
+                     final String description,
+                     final int minimum,
+                     final int maximum) {
+        super(0, false);
+
+        this.name = name;
+        this.description = description;
+        this.minimum = minimum;
+        this.maximum = maximum;
+
+        // store a copy of the options to be used by the 
+        // help methods
+        this.options = Collections.unmodifiableList(options);
+
+        // anonymous Argument temporary storage
+        final List newAnonymous = new ArrayList();
+
+        // map (key=trigger & value=Option) temporary storage
+        final SortedMap newOptionMap = new TreeMap(ReverseStringComparator.getInstance());
+
+        // prefixes temporary storage
+        final Set newPrefixes = new HashSet();
+
+        // process the options
+        for (final Iterator i = options.iterator(); i.hasNext();) {
+            final Option option = (Option) i.next();
+
+            if (option instanceof Argument) {
+                i.remove();
+                newAnonymous.add(option);
+            } else {
+                final Set triggers = option.getTriggers();
+
+                for (Iterator j = triggers.iterator(); j.hasNext();) {
+                    newOptionMap.put(j.next(), option);
+                }
+
+                // store the prefixes
+                newPrefixes.addAll(option.getPrefixes());
+            }
+        }
+
+        this.anonymous = Collections.unmodifiableList(newAnonymous);
+        this.optionMap = Collections.unmodifiableSortedMap(newOptionMap);
+        this.prefixes = Collections.unmodifiableSet(newPrefixes);
+    }
+
+    public boolean canProcess(final WriteableCommandLine commandLine,
+                              final String arg) {
+        if (arg == null) {
+            return false;
+        }
+
+        // if arg does not require bursting
+        if (optionMap.containsKey(arg)) {
+            return true;
+        }
+
+        // filter
+        final Map tailMap = optionMap.tailMap(arg);
+
+        // check if bursting is required
+        for (final Iterator iter = tailMap.values().iterator(); iter.hasNext();) {
+            final Option option = (Option) iter.next();
+
+            if (option.canProcess(commandLine, arg)) {
+                return true;
+            }
+        }
+
+        if (commandLine.looksLikeOption(arg)) {
+            return false;
+        }
+
+        // anonymous argument(s) means we can process it
+        if (anonymous.size() > 0) {
+            return true;
+        }
+
+        return false;
+    }
+
+    public Set getPrefixes() {
+        return prefixes;
+    }
+
+    public Set getTriggers() {
+        return optionMap.keySet();
+    }
+
+    public void process(final WriteableCommandLine commandLine,
+                        final ListIterator arguments)
+        throws OptionException {
+        String previous = null;
+
+        // [START process each command line token
+        while (arguments.hasNext()) {
+            // grab the next argument
+            final String arg = (String) arguments.next();
+
+            // if we have just tried to process this instance
+            if (arg == previous) {
+                // rollback and abort
+                arguments.previous();
+
+                break;
+            }
+
+            // remember last processed instance
+            previous = arg;
+
+            final Option opt = (Option) optionMap.get(arg);
+
+            // option found
+            if (opt != null) {
+                arguments.previous();
+                opt.process(commandLine, arguments);
+            }
+            // [START option NOT found
+            else {
+                // it might be an anonymous argument continue search
+                // [START argument may be anonymous
+                if (commandLine.looksLikeOption(arg)) {
+                    // narrow the search
+                    final Collection values = optionMap.tailMap(arg).values();
+
+                    boolean foundMemberOption = false;
+
+                    for (Iterator i = values.iterator(); i.hasNext() && !foundMemberOption;) {
+                        final Option option = (Option) i.next();
+
+                        if (option.canProcess(commandLine, arg)) {
+                            foundMemberOption = true;
+                            arguments.previous();
+                            option.process(commandLine, arguments);
+                        }
+                    }
+
+                    // back track and abort this group if necessary
+                    if (!foundMemberOption) {
+                        arguments.previous();
+
+                        return;
+                    }
+                } // [END argument may be anonymous
+
+                // [START argument is NOT anonymous
+                else {
+                    // move iterator back, current value not used
+                    arguments.previous();
+
+                    // if there are no anonymous arguments then this group can't
+                    // process the argument
+                    if (anonymous.isEmpty()) {
+                        break;
+                    }
+
+                    // TODO: why do we iterate over all anonymous arguments?
+                    // canProcess will always return true?
+                    for (final Iterator i = anonymous.iterator(); i.hasNext();) {
+                        final Argument argument = (Argument) i.next();
+
+                        if (argument.canProcess(commandLine, arguments)) {
+                            argument.process(commandLine, arguments);
+                        }
+                    }
+                } // [END argument is NOT anonymous
+            } // [END option NOT found
+        } // [END process each command line token
+    }
+
+    public void validate(final WriteableCommandLine commandLine)
+        throws OptionException {
+        // number of options found
+        int present = 0;
+
+        // reference to first unexpected option
+        Option unexpected = null;
+
+        for (final Iterator i = options.iterator(); i.hasNext();) {
+            final Option option = (Option) i.next();
+
+            // if the child option is required then validate it
+            if (option.isRequired()) {
+                option.validate(commandLine);
+            }
+
+            if (option instanceof Group) {
+                option.validate(commandLine);
+            }
+
+            // if the child option is present then validate it
+            if (commandLine.hasOption(option)) {
+                if (++present > maximum) {
+                    unexpected = option;
+
+                    break;
+                }
+
+                option.validate(commandLine);
+            }
+        }
+
+        // too many options
+        if (unexpected != null) {
+            throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN,
+                                      unexpected.getPreferredName());
+        }
+
+        // too few option
+        if (present < minimum) {
+            throw new OptionException(this, ResourceConstants.MISSING_OPTION);
+        }
+
+        // validate each anonymous argument
+        for (final Iterator i = anonymous.iterator(); i.hasNext();) {
+            final Option option = (Option) i.next();
+            option.validate(commandLine);
+        }
+    }
+
+    public String getPreferredName() {
+        return name;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void appendUsage(final StringBuffer buffer,
+                            final Set helpSettings,
+                            final Comparator comp) {
+        appendUsage(buffer, helpSettings, comp, "|");
+    }
+
+    public void appendUsage(final StringBuffer buffer,
+                            final Set helpSettings,
+                            final Comparator comp,
+                            final String separator) {
+        final Set helpSettingsCopy = new HashSet(helpSettings);
+
+        final boolean optional =
+            (minimum == 0) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_OPTIONAL);
+
+        final boolean expanded =
+            (name == null) || helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED);
+
+        final boolean named =
+            !expanded ||
+            ((name != null) && helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_NAME));
+
+        final boolean arguments = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT);
+
+        final boolean outer = helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_OUTER);
+
+        helpSettingsCopy.remove(DisplaySetting.DISPLAY_GROUP_OUTER);
+
+        final boolean both = named && expanded;
+
+        if (optional) {
+            buffer.append('[');
+        }
+
+        if (named) {
+            buffer.append(name);
+        }
+
+        if (both) {
+            buffer.append(" (");
+        }
+
+        if (expanded) {
+            final Set childSettings;
+
+            if (!helpSettingsCopy.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) {
+                childSettings = DisplaySetting.NONE;
+            } else {
+                childSettings = new HashSet(helpSettingsCopy);
+                childSettings.remove(DisplaySetting.DISPLAY_OPTIONAL);
+            }
+
+            // grab a list of the group's options.
+            final List list;
+
+            if (comp == null) {
+                // default to using the initial order
+                list = options;
+            } else {
+                // sort options if comparator is supplied
+                list = new ArrayList(options);
+                Collections.sort(list, comp);
+            }
+
+            // for each option.
+            for (final Iterator i = list.iterator(); i.hasNext();) {
+                final Option option = (Option) i.next();
+
+                // append usage information
+                option.appendUsage(buffer, childSettings, comp);
+
+                // add separators as needed
+                if (i.hasNext()) {
+                    buffer.append(separator);
+                }
+            }
+        }
+
+        if (both) {
+            buffer.append(')');
+        }
+
+        if (optional && outer) {
+            buffer.append(']');
+        }
+
+        if (arguments) {
+            for (final Iterator i = anonymous.iterator(); i.hasNext();) {
+                buffer.append(' ');
+
+                final Option option = (Option) i.next();
+                option.appendUsage(buffer, helpSettingsCopy, comp);
+            }
+        }
+
+        if (optional && !outer) {
+            buffer.append(']');
+        }
+    }
+
+    public List helpLines(final int depth,
+                          final Set helpSettings,
+                          final Comparator comp) {
+        final List helpLines = new ArrayList();
+
+        if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_NAME)) {
+            final HelpLine helpLine = new HelpLineImpl(this, depth);
+            helpLines.add(helpLine);
+        }
+
+        if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_EXPANDED)) {
+            // grab a list of the group's options.
+            final List list;
+
+            if (comp == null) {
+                // default to using the initial order
+                list = options;
+            } else {
+                // sort options if comparator is supplied
+                list = new ArrayList(options);
+                Collections.sort(list, comp);
+            }
+
+            // for each option
+            for (final Iterator i = list.iterator(); i.hasNext();) {
+                final Option option = (Option) i.next();
+                helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp));
+            }
+        }
+
+        if (helpSettings.contains(DisplaySetting.DISPLAY_GROUP_ARGUMENT)) {
+            for (final Iterator i = anonymous.iterator(); i.hasNext();) {
+                final Option option = (Option) i.next();
+                helpLines.addAll(option.helpLines(depth + 1, helpSettings, comp));
+            }
+        }
+
+        return helpLines;
+    }
+
+    /**
+     * Gets the member Options of thie Group.
+     * Note this does not include any Arguments
+     * @return only the non Argument Options of the Group
+     */
+    public List getOptions() {
+        return options;
+    }
+
+    /**
+     * Gets the anonymous Arguments of this Group.
+     * @return the Argument options of this Group
+     */
+    public List getAnonymous() {
+        return anonymous;
+    }
+
+    public Option findOption(final String trigger) {
+        final Iterator i = getOptions().iterator();
+
+        while (i.hasNext()) {
+            final Option option = (Option) i.next();
+            final Option found = option.findOption(trigger);
+
+            if (found != null) {
+                return found;
+            }
+        }
+
+        return null;
+    }
+
+    public int getMinimum() {
+        return minimum;
+    }
+
+    public int getMaximum() {
+        return maximum;
+    }
+
+    public boolean isRequired() {
+        return getMinimum() > 0;
+    }
+
+    public void defaults(final WriteableCommandLine commandLine) {
+        super.defaults(commandLine);
+
+        for (final Iterator i = options.iterator(); i.hasNext();) {
+            final Option option = (Option) i.next();
+            option.defaults(commandLine);
+        }
+
+        for (final Iterator i = anonymous.iterator(); i.hasNext();) {
+            final Option option = (Option) i.next();
+            option.defaults(commandLine);
+        }
+    }
+}
+
+
+class ReverseStringComparator implements Comparator {
+    private static final Comparator instance = new ReverseStringComparator();
+
+    private ReverseStringComparator() {
+        // just making sure nobody else creates one
+    }
+
+    /**
+     * Gets a singleton instance of a ReverseStringComparator
+     * @return the singleton instance
+     */
+    public static final Comparator getInstance() {
+        return instance;
+    }
+
+    public int compare(final Object o1,
+                       final Object o2) {
+        final String s1 = (String) o1;
+        final String s2 = (String) o2;
+
+        return -s1.compareTo(s2);
+    }
+}

Modified: commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/HelpLineImpl.java
URL: http://svn.apache.org/viewvc/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/HelpLineImpl.java?rev=639943&r1=639942&r2=639943&view=diff
==============================================================================
--- commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/HelpLineImpl.java (original)
+++ commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/HelpLineImpl.java Fri Mar 21 20:08:23 2008
@@ -1 +1,110 @@
-/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.  See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Comparator;import java.util.Set;import org.apache.commons.cli2.HelpLine;import org.apache.commons.cli2.Option;/** * Represents a line in the help 
 screen. */public class HelpLineImpl implements HelpLine {    /** The option that this HelpLineImpl describes */    private final Option option;    /** The level of indenting for this item */    private final int indent;    /** The help settings used to obtain the previous usage */    private transient Set cachedHelpSettings;    /** The comparator used to obtain the previous usage */    private transient Comparator cachedComparator;    /** The previously obtained usage */    private transient String cachedUsage;    /**     * Creates a new HelpLineImpl to represent a particular Option in the online     * help.     *     * @param option     *            Option that the HelpLineImpl describes     * @param indent     *            Level of indentation for this line     */    public HelpLineImpl(final Option option, final int indent) {        this.option = option;        this.indent = indent;    }    /**     * @return The description of the option     */    public String getDescrip
 tion() {        return option.getDescription();    }    /**     * @return The level of indentation for this line     */    public int getIndent() {        return indent;    }    /**     * @return The Option that the help line relates to     */    public Option getOption() {        return option;    }    /**     * Builds a usage string for the option using the specified settings and     * comparator.     *     *     * @param helpSettings the settings to apply     * @param comparator a comparator to sort options when applicable     * @return the usage string     */    public String usage(final Set helpSettings, final Comparator comparator) {        if (cachedUsage == null            || cachedHelpSettings != helpSettings            || cachedComparator != comparator) {            // cache the arguments to avoid redoing work            cachedHelpSettings = helpSettings;            cachedComparator = comparator;            // build the new buffer            final StringBuffer buff
 er = new StringBuffer();            for (int i = 0; i < indent; ++i) {                buffer.append("  ");            }            option.appendUsage(buffer, helpSettings, comparator);            // cache the usage string            cachedUsage = buffer.toString();        }        return cachedUsage;    }}
\ No newline at end of file
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.cli2.option;
+
+import java.util.Comparator;
+import java.util.Set;
+
+import org.apache.commons.cli2.HelpLine;
+import org.apache.commons.cli2.Option;
+
+/**
+ * Represents a line in the help screen.
+ */
+public class HelpLineImpl implements HelpLine {
+
+    /** The option that this HelpLineImpl describes */
+    private final Option option;
+
+    /** The level of indenting for this item */
+    private final int indent;
+
+    /** The help settings used to obtain the previous usage */
+    private transient Set cachedHelpSettings;
+    
+    /** The comparator used to obtain the previous usage */
+    private transient Comparator cachedComparator;
+    
+    /** The previously obtained usage */
+    private transient String cachedUsage;
+    
+    /**
+     * Creates a new HelpLineImpl to represent a particular Option in the online
+     * help.
+     * 
+     * @param option
+     *            Option that the HelpLineImpl describes
+     * @param indent
+     *            Level of indentation for this line
+     */
+    public HelpLineImpl(final Option option, final int indent) {
+        this.option = option;
+        this.indent = indent;
+    }
+
+    /**
+     * @return The description of the option
+     */
+    public String getDescription() {
+        return option.getDescription();
+    }
+
+    /**
+     * @return The level of indentation for this line
+     */
+    public int getIndent() {
+        return indent;
+    }
+
+    /**
+     * @return The Option that the help line relates to
+     */
+    public Option getOption() {
+        return option;
+    }
+    
+    /**
+     * Builds a usage string for the option using the specified settings and 
+     * comparator.
+     * 
+     *  
+     * @param helpSettings the settings to apply
+     * @param comparator a comparator to sort options when applicable
+     * @return the usage string
+     */
+    public String usage(final Set helpSettings, final Comparator comparator) {
+        if (cachedUsage == null
+            || cachedHelpSettings != helpSettings
+            || cachedComparator != comparator) {
+            
+            // cache the arguments to avoid redoing work
+            cachedHelpSettings = helpSettings;
+            cachedComparator = comparator;
+            
+            // build the new buffer
+            final StringBuffer buffer = new StringBuffer();
+            for (int i = 0; i < indent; ++i) {
+                buffer.append("  ");
+            }
+            option.appendUsage(buffer, helpSettings, comparator);
+            
+            // cache the usage string
+            cachedUsage = buffer.toString();
+        }
+        return cachedUsage;
+    }
+}

Modified: commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/OptionImpl.java
URL: http://svn.apache.org/viewvc/commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/OptionImpl.java?rev=639943&r1=639942&r2=639943&view=diff
==============================================================================
--- commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/OptionImpl.java (original)
+++ commons/proper/cli/trunk/src/java/org/apache/commons/cli2/option/OptionImpl.java Fri Mar 21 20:08:23 2008
@@ -1 +1,159 @@
-/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.  See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.cli2.option;import java.util.Iterator;import java.util.ListIterator;import java.util.Set;import org.apache.commons.cli2.DisplaySetting;import org.apache.commons.cli2.Option;imp
 ort org.apache.commons.cli2.WriteableCommandLine;import org.apache.commons.cli2.resource.ResourceConstants;import org.apache.commons.cli2.resource.ResourceHelper;/** * A base implementation of Option providing limited ground work for further * Option implementations. */public abstract class OptionImpl implements Option {    private final int id;    private final boolean required;    /**     * Creates an OptionImpl with the specified id     * @param id the unique id of this Option     * @param required true iff this Option must be present     */    public OptionImpl(final int id,                      final boolean required) {        this.id = id;        this.required = required;    }    public boolean canProcess(final WriteableCommandLine commandLine,                              final ListIterator arguments) {        if (arguments.hasNext()) {            final String argument = (String) arguments.next();            arguments.previous();            return canProcess(commandLi
 ne, argument);        } else {            return false;        }    }    public String toString() {        final StringBuffer buffer = new StringBuffer();        appendUsage(buffer, DisplaySetting.ALL, null);        return buffer.toString();    }    public int getId() {        return id;    }    public boolean equals(final Object thatObj) {        if (thatObj instanceof OptionImpl) {            final OptionImpl that = (OptionImpl) thatObj;            return (getId() == that.getId()) &&                   equals(getPreferredName(), that.getPreferredName()) &&                   equals(getDescription(), that.getDescription()) &&                   equals(getPrefixes(), that.getPrefixes()) &&                   equals(getTriggers(), that.getTriggers());        } else {            return false;        }    }    private boolean equals(Object left,                           Object right) {        if ((left == null) && (right == null)) {            return true;        } else if ((left 
 == null) || (right == null)) {            return false;        } else {            return left.equals(right);        }    }    public int hashCode() {        int hashCode = getId();        hashCode = (hashCode * 37) + getPreferredName().hashCode();        if (getDescription() != null) {            hashCode = (hashCode * 37) + getDescription().hashCode();        }        hashCode = (hashCode * 37) + getPrefixes().hashCode();        hashCode = (hashCode * 37) + getTriggers().hashCode();        return hashCode;    }    public Option findOption(String trigger) {        if (getTriggers().contains(trigger)) {            return this;        } else {            return null;        }    }    public boolean isRequired() {        return required;    }    public void defaults(final WriteableCommandLine commandLine) {        // nothing to do normally    }    protected void checkPrefixes(final Set prefixes) {        // nothing to do if empty prefix list        if (prefixes.isEmpty()) {   
          return;        }        // check preferred name        checkPrefix(prefixes, getPreferredName());        // check triggers        this.getTriggers();        for (final Iterator i = getTriggers().iterator(); i.hasNext();) {            checkPrefix(prefixes, (String) i.next());        }    }    private void checkPrefix(final Set prefixes,                             final String trigger) {        for (final Iterator i = prefixes.iterator(); i.hasNext();) {            String prefix = (String) i.next();            if (trigger.startsWith(prefix)) {                return;            }        }        final ResourceHelper helper = ResourceHelper.getResourceHelper();        final String message =            helper.getMessage(ResourceConstants.OPTION_TRIGGER_NEEDS_PREFIX, trigger,                              prefixes.toString());        throw new IllegalArgumentException(message);    }}
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.cli2.option;
+
+import java.util.Iterator;
+import java.util.ListIterator;
+import java.util.Set;
+
+import org.apache.commons.cli2.DisplaySetting;
+import org.apache.commons.cli2.Option;
+import org.apache.commons.cli2.WriteableCommandLine;
+import org.apache.commons.cli2.resource.ResourceConstants;
+import org.apache.commons.cli2.resource.ResourceHelper;
+
+/**
+ * A base implementation of Option providing limited ground work for further
+ * Option implementations.
+ */
+public abstract class OptionImpl implements Option {
+    private final int id;
+    private final boolean required;
+
+    /**
+     * Creates an OptionImpl with the specified id
+     * @param id the unique id of this Option
+     * @param required true iff this Option must be present
+     */
+    public OptionImpl(final int id,
+                      final boolean required) {
+        this.id = id;
+        this.required = required;
+    }
+
+    public boolean canProcess(final WriteableCommandLine commandLine,
+                              final ListIterator arguments) {
+        if (arguments.hasNext()) {
+            final String argument = (String) arguments.next();
+            arguments.previous();
+
+            return canProcess(commandLine, argument);
+        } else {
+            return false;
+        }
+    }
+
+    public String toString() {
+        final StringBuffer buffer = new StringBuffer();
+        appendUsage(buffer, DisplaySetting.ALL, null);
+
+        return buffer.toString();
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public boolean equals(final Object thatObj) {
+        if (thatObj instanceof OptionImpl) {
+            final OptionImpl that = (OptionImpl) thatObj;
+
+            return (getId() == that.getId()) &&
+                   equals(getPreferredName(), that.getPreferredName()) &&
+                   equals(getDescription(), that.getDescription()) &&
+                   equals(getPrefixes(), that.getPrefixes()) &&
+                   equals(getTriggers(), that.getTriggers());
+        } else {
+            return false;
+        }
+    }
+
+    private boolean equals(Object left,
+                           Object right) {
+        if ((left == null) && (right == null)) {
+            return true;
+        } else if ((left == null) || (right == null)) {
+            return false;
+        } else {
+            return left.equals(right);
+        }
+    }
+
+    public int hashCode() {
+        int hashCode = getId();
+        hashCode = (hashCode * 37) + getPreferredName().hashCode();
+
+        if (getDescription() != null) {
+            hashCode = (hashCode * 37) + getDescription().hashCode();
+        }
+
+        hashCode = (hashCode * 37) + getPrefixes().hashCode();
+        hashCode = (hashCode * 37) + getTriggers().hashCode();
+
+        return hashCode;
+    }
+
+    public Option findOption(String trigger) {
+        if (getTriggers().contains(trigger)) {
+            return this;
+        } else {
+            return null;
+        }
+    }
+
+    public boolean isRequired() {
+        return required;
+    }
+
+    public void defaults(final WriteableCommandLine commandLine) {
+        // nothing to do normally
+    }
+
+    protected void checkPrefixes(final Set prefixes) {
+        // nothing to do if empty prefix list
+        if (prefixes.isEmpty()) {
+            return;
+        }
+
+        // check preferred name
+        checkPrefix(prefixes, getPreferredName());
+
+        // check triggers
+        this.getTriggers();
+
+        for (final Iterator i = getTriggers().iterator(); i.hasNext();) {
+            checkPrefix(prefixes, (String) i.next());
+        }
+    }
+
+    private void checkPrefix(final Set prefixes,
+                             final String trigger) {
+        for (final Iterator i = prefixes.iterator(); i.hasNext();) {
+            String prefix = (String) i.next();
+
+            if (trigger.startsWith(prefix)) {
+                return;
+            }
+        }
+
+        final ResourceHelper helper = ResourceHelper.getResourceHelper();
+        final String message =
+            helper.getMessage(ResourceConstants.OPTION_TRIGGER_NEEDS_PREFIX, trigger,
+                              prefixes.toString());
+        throw new IllegalArgumentException(message);
+    }
+}



Mime
View raw message