velocity-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From nbu...@apache.org
Subject svn commit: r545420 - in /velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools: generic/DateTool.java generic/MathTool.java generic/NumberTool.java generic/ValueParser.java view/ParameterTool.java
Date Fri, 08 Jun 2007 05:21:53 GMT
Author: nbubna
Date: Thu Jun  7 22:21:52 2007
New Revision: 545420

URL: http://svn.apache.org/viewvc?view=rev&rev=545420
Log:
update to use new config base classes and ConversionUtils (which both got most of their code
from these anyway)

Modified:
    velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/DateTool.java
    velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/MathTool.java
    velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/NumberTool.java
    velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/ValueParser.java
    velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/view/ParameterTool.java

Modified: velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/DateTool.java
URL: http://svn.apache.org/viewvc/velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/DateTool.java?view=diff&rev=545420&r1=545419&r2=545420
==============================================================================
--- velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/DateTool.java
(original)
+++ velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/DateTool.java
Thu Jun  7 22:21:52 2007
@@ -27,6 +27,7 @@
 import java.util.Locale;
 import java.util.Map;
 import java.util.TimeZone;
+import org.apache.velocity.tools.ConversionUtils;
 import org.apache.velocity.tools.config.DefaultKey;
 
 /**
@@ -67,75 +68,13 @@
  * @version $Revision$ $Date$
  */
 @DefaultKey("date")
-public class DateTool
+public class DateTool extends FormatConfig
 {
+    @Deprecated
+    public static final String DEFAULT_FORMAT_KEY = FORMAT_KEY;
 
-    /**
-     * The default format to be used when none is specified.
-     * @since VelocityTools 1.1
-     */
-    public static final String DEFAULT_FORMAT = "default";
-
-    /**
-     * The key used for specifying a default format via toolbox params.
-     * @since VelocityTools 1.3
-     */
-    public static final String DEFAULT_FORMAT_KEY = "format";
-
-    /**
-     * The key used for specifying a default locale via toolbox params.
-     * @since VelocityTools 1.4
-     */
-    public static final String DEFAULT_LOCALE_KEY = "locale";
-
-    /**
-     * The key used for specifying whether or not to prevent templates
-     * from reconfiguring this tool.  The default is true.
-     * @since VelocityTools 1.4
-     */
-    public static final String LOCK_CONFIG_KEY = "lock-config";
-
-    private String format = DEFAULT_FORMAT;
-    private Locale locale = Locale.getDefault();
-    private boolean configLocked = false;
-
-    /**
-     * Looks for configuration values in the given params.
-     * @since VelocityTools 1.3
-     */
-    public void configure(Map params)
-    {
-        if (!configLocked)
-        {
-            ValueParser values = new ValueParser(params);
-            configure(values);
-
-            // by default, lock down this method after use
-            // to prevent templates from re-configuring this instance
-            configLocked = values.getBoolean(LOCK_CONFIG_KEY, true);
-        }
-    }
-
-    /**
-     * Does the actual configuration. This is protected, so
-     * subclasses may share the same ValueParser and call configure
-     * at any time, while preventing templates from doing so when 
-     * configure(Map) is locked.
-     * @since VelocityTools 1.4
-     */
-    protected void configure(ValueParser values)
-    {
-        String format = values.getString(DEFAULT_FORMAT_KEY);
-        if (format != null)
-        {
-            setFormat(format);
-        }
-        Locale locale = values.getLocale(DEFAULT_LOCALE_KEY);
-        if (locale != null)
-        {
-            setLocale(locale);
-        }
-    }
+    @Deprecated
+    public static final String DEFAULT_LOCALE_KEY = LOCALE_KEY;
 
 
     // ------------------------- system date access ------------------
@@ -170,31 +109,6 @@
     // ------------------------- default parameter access ----------------
 
     /**
-     * This implementation returns the configured default locale. Subclasses
-     * may override this to return alternate locales. Please note that
-     * doing so will affect all formatting methods where no locale is
-     * specified in the parameters.
-     *
-     * @return the default {@link Locale}
-     */
-    public Locale getLocale()
-    {
-        return this.locale;
-    }
-
-    /**
-     * Sets the default locale for this instance. This is protected,
-     * because templates ought not to be using it; that would not
-     * be threadsafe so far as templates are concerned.
-     *
-     * @since VelocityTools 1.4
-     */
-    protected void setLocale(Locale locale)
-    {
-        this.locale = locale;
-    }
-
-    /**
      * This implementation returns the default TimeZone. Subclasses
      * may override this to return alternate timezones. Please note that
      * doing so will affect all formatting methods where no timezone is
@@ -238,34 +152,6 @@
         return Calendar.getInstance(getTimeZone(), getLocale());
     }
 
-    /**
-     * Return the pattern or style to be used for formatting dates when none
-     * is specified. This implementation gives a 'default' date-time format.
-     * Subclasses may override this to provide a different default format.
-     *
-     * <p>This can now be configured via the toolbox definition.
-     * Add a <code>&lt;parameter name="format" value="short"/&gt;<code>
-     * to your date tool configuration.</p>
-     *
-     * @since VelocityTools 1.1
-     */
-    public String getFormat()
-    {
-        return format;
-    }
-
-    /**
-     * Sets the default format for this instance. This is protected,
-     * because templates ought not to be using it; that would not
-     * be threadsafe so far as templates are concerned.
-     *
-     * @since VelocityTools 1.3
-     */
-    protected void setFormat(String format)
-    {
-        this.format = format;
-    }
-
     // ------------------------- date value access ---------------------------
 
     /**
@@ -643,43 +529,7 @@
     public DateFormat getDateFormat(String format, Locale locale,
                                     TimeZone timezone)
     {
-        if (format == null)
-        {
-            return null;
-        }
-
-        DateFormat df = null;
-        // do they want a date instance
-        if (format.endsWith("_date"))
-        {
-            String fmt = format.substring(0, format.length() - 5);
-            int style = getStyleAsInt(fmt);
-            df = getDateFormat(style, -1, locale, timezone);
-        }
-        // do they want a time instance?
-        else if (format.endsWith("_time"))
-        {
-            String fmt = format.substring(0, format.length() - 5);
-            int style = getStyleAsInt(fmt);
-            df = getDateFormat(-1, style, locale, timezone);
-        }
-        // ok, they either want a custom or date-time instance
-        else
-        {
-            int style = getStyleAsInt(format);
-            if (style < 0)
-            {
-                // we have a custom format
-                df = new SimpleDateFormat(format, locale);
-                df.setTimeZone(timezone);
-            }
-            else
-            {
-                // they want a date-time instance
-                df = getDateFormat(style, style, locale, timezone);
-            }
-        }
-        return df;
+        return ConversionUtils.getDateFormat(format, locale, timezone);
     }
 
     /**
@@ -697,9 +547,7 @@
     public DateFormat getDateFormat(String dateStyle, String timeStyle,
                                     Locale locale, TimeZone timezone)
     {
-        int ds = getStyleAsInt(dateStyle);
-        int ts = getStyleAsInt(timeStyle);
-        return getDateFormat(ds, ts, locale, timezone);
+        return ConversionUtils.getDateFormat(dateStyle, timeStyle, locale, timezone);
     }
 
     /**
@@ -717,40 +565,11 @@
      *         parameters
      * @since VelocityTools 1.1
      */
+    @Deprecated
     protected DateFormat getDateFormat(int dateStyle, int timeStyle,
                                        Locale locale, TimeZone timezone)
     {
-        try
-        {
-            DateFormat df;
-            if (dateStyle < 0 && timeStyle < 0)
-            {
-                // no style was specified, use default instance
-                df = DateFormat.getInstance();
-            }
-            else if (timeStyle < 0)
-            {
-                // only a date style was specified
-                df = DateFormat.getDateInstance(dateStyle, locale);
-            }
-            else if (dateStyle < 0)
-            {
-                // only a time style was specified
-                df = DateFormat.getTimeInstance(timeStyle, locale);
-            }
-            else
-            {
-                df = DateFormat.getDateTimeInstance(dateStyle, timeStyle,
-                                                    locale);
-            }
-            df.setTimeZone(timezone);
-            return df;
-        }
-        catch (Exception suppressed)
-        {
-            // let it go...
-            return null;
-        }
+        return ConversionUtils.getDateFormat(dateStyle, timeStyle, locale, timezone);
     }
 
     /**
@@ -764,34 +583,10 @@
      * @return the int identifying the style pattern
      * @since VelocityTools 1.1
      */
+    @Deprecated
     protected int getStyleAsInt(String style)
     {
-        // avoid needlessly running through all the string comparisons
-        if (style == null || style.length() < 4 || style.length() > 7) {
-            return -1;
-        }
-        if (style.equalsIgnoreCase("full"))
-        {
-            return DateFormat.FULL;
-        }
-        if (style.equalsIgnoreCase("long"))
-        {
-            return DateFormat.LONG;
-        }
-        if (style.equalsIgnoreCase("medium"))
-        {
-            return DateFormat.MEDIUM;
-        }
-        if (style.equalsIgnoreCase("short"))
-        {
-            return DateFormat.SHORT;
-        }
-        if (style.equalsIgnoreCase("default"))
-        {
-            return DateFormat.DEFAULT;
-        }
-        // ok, it's not any of the standard patterns
-        return -1;
+        return ConversionUtils.getStyleAsInt(style);
     }
 
 
@@ -865,34 +660,7 @@
     public Date toDate(String format, Object obj,
                        Locale locale, TimeZone timezone)
     {
-        if (obj == null)
-        {
-            return null;
-        }
-        if (obj instanceof Date)
-        {
-            return (Date)obj;
-        }
-        if (obj instanceof Calendar)
-        {
-            return ((Calendar)obj).getTime();
-        }
-        if (obj instanceof Number)
-        {
-            Date d = new Date();
-            d.setTime(((Number)obj).longValue());
-            return d;
-        }
-        try
-        {
-            //try parsing w/a customized SimpleDateFormat
-            DateFormat parser = getDateFormat(format, locale, timezone);
-            return parser.parse(String.valueOf(obj));
-        }
-        catch (Exception e)
-        {
-            return null;
-        }
+        return ConversionUtils.toDate(obj, format, locale, timezone);
     }
 
     /**
@@ -935,13 +703,14 @@
             return null;
         }
 
+        // if the locale is null, do as the javadoc claims
+        if (locale == null)
+        {
+            locale = getLocale();
+        }
+
         //convert the date to a calendar
-        Calendar cal = Calendar.getInstance(locale);
-        cal.setTime(date);
-        // HACK: Force all fields to update. see link for explanation of this.
-        //http://java.sun.com/j2se/1.4/docs/api/java/util/Calendar.html
-        cal.getTime();
-        return cal;
+        return ConversionUtils.toCalendar(date, locale);
     }
 
 

Modified: velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/MathTool.java
URL: http://svn.apache.org/viewvc/velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/MathTool.java?view=diff&rev=545420&r1=545419&r2=545420
==============================================================================
--- velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/MathTool.java
(original)
+++ velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/MathTool.java
Thu Jun  7 22:21:52 2007
@@ -22,7 +22,10 @@
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Iterator;
+import java.util.Locale;
+import java.util.Map;
 import org.apache.commons.beanutils.PropertyUtils;
+import org.apache.velocity.tools.ConversionUtils;
 import org.apache.velocity.tools.config.DefaultKey;
 
 /**
@@ -41,7 +44,7 @@
  * literally. (e.g. $math.div(1, 0) renders as '$math.div(1, 0)')</li>
  * </ul>
  * <p><pre>
- * Example tools.xml config (if you want to use this with VelocityView):
+ * Example tools.xml config:
  * &lt;tools&gt;
  *   &lt;toolbox scope="application"&gt;
  *     &lt;tool class="org.apache.velocity.tools.generic.MathTool"/&gt;
@@ -54,7 +57,7 @@
  * @version $Revision$ $Date$
  */
 @DefaultKey("math")
-public class MathTool
+public class MathTool extends FormatConfig
 {
     /**
      * @param num1 the first number
@@ -456,22 +459,7 @@
      */
     public Number toNumber(Object num)
     {
-        if (num == null)
-        {
-            return null;
-        }
-        if (num instanceof Number)
-        {
-            return (Number)num;
-        }
-        try
-        {
-            return parseNumber(String.valueOf(num));
-        }
-        catch (NumberFormatException nfe)
-        {
-            return null;
-        }
+        return ConversionUtils.toNumber(num, getFormat(), getLocale());
     }
 
 
@@ -534,17 +522,8 @@
         }
     }
 
-
-    /**
-     * Converts an object into a {@link Number} (if it can)
-     * This is used as the base for all numeric parsing methods. So,
-     * sub-classes can override to allow for customized number parsing.
-     * (e.g. for i18n, fractions, compound numbers, bigger numbers, etc.)
-     *
-     * @param value the string to be parsed
-     * @return the value as a {@link Number}
-     */
-    protected Number parseNumber(String value) throws NumberFormatException
+    @Deprecated
+    protected Number parseNumber(String value)
     {
         // check for the floating point
         if (value.indexOf('.') < 0)

Modified: velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/NumberTool.java
URL: http://svn.apache.org/viewvc/velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/NumberTool.java?view=diff&rev=545420&r1=545419&r2=545420
==============================================================================
--- velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/NumberTool.java
(original)
+++ velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/NumberTool.java
Thu Jun  7 22:21:52 2007
@@ -24,6 +24,7 @@
 import java.text.NumberFormat;
 import java.util.Locale;
 import java.util.Map;
+import org.apache.velocity.tools.ConversionUtils;
 import org.apache.velocity.tools.config.DefaultKey;
 
 /**
@@ -59,128 +60,13 @@
  * @version $Id$
  */
 @DefaultKey("number")
-public class NumberTool
+public class NumberTool extends FormatConfig
 {
-    /**
-     * The default format to be used when none is specified.
-     */
-    public static final String DEFAULT_FORMAT = "default";
-
-    /**
-     * The key used for specifying a default format via toolbox params.
-     * @since VelocityTools 1.4
-     */
-    public static final String DEFAULT_FORMAT_KEY = "format";
-
-    /**
-     * The key used for specifying a default locale via toolbox params.
-     * @since VelocityTools 1.4
-     */
-    public static final String DEFAULT_LOCALE_KEY = "locale";
-
-    /**
-     * The key used for specifying whether or not to prevent templates
-     * from reconfiguring this tool.  The default is true.
-     * @since VelocityTools 1.4
-     */
-    public static final String LOCK_CONFIG_KEY = "lock-config";
-
-    private static final int STYLE_NUMBER       = 0;
-    private static final int STYLE_CURRENCY     = 1;
-    private static final int STYLE_PERCENT      = 2;
-    //NOTE: '3' belongs to a non-public "scientific" style
-    private static final int STYLE_INTEGER      = 4;
-
-    private String format = DEFAULT_FORMAT;
-    private Locale locale = Locale.getDefault();
-    private boolean configLocked = false;
-
-    /**
-     * Looks for configuration values in the given params.
-     * @since VelocityTools 1.4
-     */
-    public void configure(Map params)
-    {
-        if (!configLocked)
-        {
-            ValueParser values = new ValueParser(params);
-            configure(values);
-
-            // by default, lock down this method after use
-            // to prevent templates from re-configuring this instance
-            configLocked = values.getBoolean(LOCK_CONFIG_KEY, true);
-        }
-    }
-
-    /**
-     * Does the actual configuration. This is protected, so
-     * subclasses may share the same ValueParser and call configure
-     * at any time, while preventing templates from doing so when 
-     * configure(Map) is locked.
-     * @since VelocityTools 1.4
-     */
-    protected void configure(ValueParser values)
-    {
-        String format = values.getString(DEFAULT_FORMAT_KEY);
-        if (format != null)
-        {
-            setFormat(format);
-        }
-        Locale locale = values.getLocale(DEFAULT_LOCALE_KEY);
-        if (locale != null)
-        {
-            setLocale(locale);
-        }
-    }
-
-    // ------------------------- default parameter access ----------------
-
-    /**
-     * This implementation returns the configured default locale. Subclasses
-     * may override this to return alternate locales. Please note that
-     * doing so will affect all formatting methods where no locale is
-     * specified in the parameters.
-     *
-     * @return the default {@link Locale}
-     */
-    public Locale getLocale()
-    {
-        return this.locale;
-    }
-
-    /**
-     * Sets the default locale for this instance. This is protected,
-     * because templates ought not to be using it; that would not
-     * be threadsafe so far as templates are concerned.
-     *
-     * @since VelocityTools 1.4
-     */
-    protected void setLocale(Locale locale)
-    {
-        this.locale = locale;
-    }
-
-    /**
-     * Return the pattern or style to be used for formatting numbers when none
-     * is specified. This implementation gives a 'default' number format.
-     * Subclasses may override this to provide a different default format.
-     */
-    public String getFormat()
-    {
-        return this.format;
-    }
+    @Deprecated
+    public static final String DEFAULT_FORMAT_KEY = FORMAT_KEY;
 
-    /**
-     * Sets the default format for this instance. This is protected,
-     * because templates ought not to be using it; that would not
-     * be threadsafe so far as templates are concerned.
-     *
-     * @since VelocityTools 1.4
-     */
-    protected void setFormat(String format)
-    {
-        this.format = format;
-    }
+    @Deprecated
+    public static final String DEFAULT_LOCALE_KEY = LOCALE_KEY;
 
 
     // ------------------------- formatting methods ---------------------------
@@ -289,24 +175,7 @@
      */
     public NumberFormat getNumberFormat(String format, Locale locale)
     {
-        if (format == null)
-        {
-            return null;
-        }
-
-        NumberFormat nf = null;
-        int style = getStyleAsInt(format);
-        if (style < 0)
-        {
-            // we have a custom format
-            nf = new DecimalFormat(format, new DecimalFormatSymbols(locale));
-        }
-        else
-        {
-            // we have a standard format
-            nf = getNumberFormat(style, locale);
-        }
-        return nf;
+        return ConversionUtils.getNumberFormat(format, locale);
     }
 
     /**
@@ -320,54 +189,10 @@
      *         if an instance cannot be constructed with the given
      *         parameters
      */
+    @Deprecated
     protected NumberFormat getNumberFormat(int numberStyle, Locale locale)
     {
-        try
-        {
-            NumberFormat nf;
-            switch (numberStyle)
-            {
-                case STYLE_NUMBER:
-                    nf = NumberFormat.getNumberInstance(locale);
-                    break;
-                case STYLE_CURRENCY:
-                    nf = NumberFormat.getCurrencyInstance(locale);
-                    break;
-                case STYLE_PERCENT:
-                    nf = NumberFormat.getPercentInstance(locale);
-                    break;
-                case STYLE_INTEGER:
-                    nf = getIntegerInstance(locale);
-                    break;
-                default:
-                    // invalid style was specified, return null
-                    nf = null;
-            }
-            return nf;
-        }
-        catch (Exception suppressed)
-        {
-            // let it go...
-            return null;
-        }
-    }
-
-    /**
-     * Since we wish to continue supporting Java 1.3,
-     * for the present we cannot use Java 1.4's
-     * NumberFormat.getIntegerInstance(Locale) method.
-     * This method mimics that method (at least as of JDK1.4.2_01).
-     * It is private so that it can be removed later
-     * without a deprecation period.
-     */
-    private NumberFormat getIntegerInstance(Locale locale)
-    {
-        DecimalFormat format =
-            (DecimalFormat)NumberFormat.getNumberInstance(locale);
-        format.setMaximumFractionDigits(0);
-        format.setDecimalSeparatorAlwaysShown(false);
-        format.setParseIntegerOnly(true);
-        return format;
+        return ConversionUtils.getNumberFormat(numberStyle, locale);
     }
 
     /**
@@ -381,36 +206,10 @@
      * @param style the string to be checked
      * @return the int identifying the style pattern
      */
+    @Deprecated
     protected int getStyleAsInt(String style)
     {
-        // avoid needlessly running through all the string comparisons
-        if (style == null || style.length() < 6 || style.length() > 8) {
-            return -1;
-        }
-        if (style.equalsIgnoreCase("default"))
-        {
-            //NOTE: java.text.NumberFormat returns "number" instances
-            //      as the default (at least in Java 1.3 and 1.4).
-            return STYLE_NUMBER;
-        }
-        if (style.equalsIgnoreCase("number"))
-        {
-            return STYLE_NUMBER;
-        }
-        if (style.equalsIgnoreCase("currency"))
-        {
-            return STYLE_CURRENCY;
-        }
-        if (style.equalsIgnoreCase("percent"))
-        {
-            return STYLE_PERCENT;
-        }
-        if (style.equalsIgnoreCase("integer"))
-        {
-            return STYLE_INTEGER;
-        }
-        // ok, it's not any of the standard patterns
-        return -1;
+        return ConversionUtils.getNumberStyleAsInt(style);
     }
 
 
@@ -462,23 +261,7 @@
      */
     public Number toNumber(String format, Object obj, Locale locale)
     {
-        if (obj == null)
-        {
-            return null;
-        }
-        if (obj instanceof Number)
-        {
-            return (Number)obj;
-        }
-        try
-        {
-            NumberFormat parser = getNumberFormat(format, locale);
-            return parser.parse(String.valueOf(obj));
-        }
-        catch (Exception e)
-        {
-            return null;
-        }
+        return ConversionUtils.toNumber(obj, format, locale);
     }
 
 }

Modified: velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/ValueParser.java
URL: http://svn.apache.org/viewvc/velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/ValueParser.java?view=diff&rev=545420&r1=545419&r2=545420
==============================================================================
--- velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/ValueParser.java
(original)
+++ velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/generic/ValueParser.java
Thu Jun  7 22:21:52 2007
@@ -33,15 +33,17 @@
  *
  * <p>This comes in very handy when parsing parameters.</p>
  *
+ * TODO: someone doing java configuration ought to be able to put a source Map
+ *       in the tool properties, allowing this to be used like other tools
+ *
  * @author Nathan Bubna
  * @version $Revision$ $Date$
  * @since VelocityTools 1.2
  */
 @DefaultKey("parser")
-public class ValueParser
+public class ValueParser extends ConversionTool
 {
     private Map source = null;
-    private String delimiter = ",";
 
     public ValueParser() {}
 
@@ -64,30 +66,6 @@
         return this.source;
     }
 
-    /**
-     * Sets the delimiter used for separating values in a single String value.
-     * The default delimiter is a comma.
-     *
-     * @since VelocityTools 1.3
-     * @see #parseStringList
-     */
-    protected final void setStringsDelimiter(String delimiter)
-    {
-        this.delimiter = delimiter;
-    }
-
-    /**
-     * Returns the delimiter used for separating values in a single String value.
-     * The default delimiter is a comma.
-     *
-     * @since VelocityTools 1.3
-     * @see #parseStringList
-     */
-    protected final String getStringsDelimiter()
-    {
-        return this.delimiter;
-    }
-
     // ----------------- public parsing methods --------------------------
 
     /**
@@ -99,7 +77,7 @@
      */
     public boolean exists(String key)
     {
-        return (getString(key) != null);
+        return (getValue(key) != null);
     }
 
     /**
@@ -115,41 +93,41 @@
      */
     public Object get(String key)
     {
-        return getString(key);
+        return getValue(key);
     }
 
-    /**
-     * @param key the parameter's key
-     * @return parameter matching the specified key or
-     *         <code>null</code> if there is no matching
-     *         parameter
-     */
-    public String getString(String key)
+    public Object getValue(String key)
     {
-        Object value = getSource().get(key);
+        return getSource().get(key);
+    }
+
+    public Object[] getValues(String key)
+    {
+        Object value = getValue(key);
         if (value == null)
         {
             return null;
         }
-
-        if (value instanceof Collection)
+        if (value instanceof String)
         {
-            Collection values = (Collection)value;
-            if (!values.isEmpty())
-            {
-                // take the next available value
-                value = values.iterator().next();
-            }
+            return parseStringList((String)value);
         }
-        else if (value.getClass().isArray())
+        if (value instanceof Object[])
         {
-            if (Array.getLength(value) > 0)
-            {
-                // take the first value
-                value = Array.get(value, 0);
-            }
+            return (Object[])value;
         }
-        return String.valueOf(value);
+        return new Object[] { value };
+    }
+
+    /**
+     * @param key the parameter's key
+     * @return parameter matching the specified key or
+     *         <code>null</code> if there is no matching
+     *         parameter
+     */
+    public String getString(String key)
+    {
+        return toString(getValue(key));
     }
 
     /**
@@ -172,8 +150,7 @@
      */
     public Boolean getBoolean(String key)
     {
-        String s = getString(key);
-        return (s != null) ? parseBoolean(s) : null;
+        return toBoolean(getValue(key));
     }
 
     /**
@@ -207,12 +184,7 @@
      */
     public Integer getInteger(String key)
     {
-        Number num = getNumber(key);
-        if (num == null || num instanceof Integer)
-        {
-            return (Integer)num;
-        }
-        return new Integer(num.intValue());
+        return toInteger(getValue(key));
     }
 
     /**
@@ -238,12 +210,7 @@
      */
     public Double getDouble(String key)
     {
-        Number num = getNumber(key);
-        if (num == null || num instanceof Double)
-        {
-            return (Double)num;
-        }
-        return new Double(num.intValue());
+        return toDouble(getValue(key));
     }
 
     /**
@@ -269,20 +236,7 @@
      */
     public Number getNumber(String key)
     {
-        String s = getString(key);
-        if (s == null || s.length() == 0)
-        {
-            return null;
-        }
-        try
-        {
-            return parseNumber(s);
-        }
-        catch (Exception e)
-        {
-            //there is no Number with that key
-            return null;
-        }
+        return toNumber(getValue(key));
     }
 
     /**
@@ -292,12 +246,7 @@
      */
     public Locale getLocale(String key)
     {
-        String s = getString(key);
-        if (s == null || s.length() == 0)
-        {
-            return null;
-        }
-        return parseLocale(s);
+        return toLocale(getValue(key));
     }
 
     /**
@@ -357,39 +306,7 @@
      */
     public String[] getStrings(String key)
     {
-        Object value = getSource().get(key);
-        if (value == null)
-        {
-            return null;
-        }
-
-        String[] strings = null;
-        if (value instanceof Collection)
-        {
-            Collection values = (Collection)value;
-            if (!values.isEmpty())
-            {
-                strings = new String[values.size()];
-                int index = 0;
-                for (Iterator i = values.iterator(); i.hasNext(); )
-                {
-                    strings[index++] = String.valueOf(i.next());
-                }
-            }
-        }
-        else if (value.getClass().isArray())
-        {
-            strings = new String[Array.getLength(value)];
-            for (int i=0; i < strings.length; i++)
-            {
-                strings[i] = String.valueOf(Array.get(value, i));
-            }
-        }
-        else
-        {
-            strings = parseStringList(String.valueOf(value));
-        }
-        return strings;
+        return toStrings(getValues(key));
     }
 
 
@@ -399,21 +316,7 @@
      */
     public Boolean[] getBooleans(String key)
     {
-        String[] strings = getStrings(key);
-        if (strings == null)
-        {
-            return null;
-        }
-
-        Boolean[] bools = new Boolean[strings.length];
-        for (int i=0; i<strings.length; i++)
-        {
-            if (strings[i] != null && strings[i].length() > 0)
-            {
-                bools[i] = parseBoolean(strings[i]);
-            }
-        }
-        return bools;
+        return toBooleans(getValues(key));
     }
 
     /**
@@ -423,28 +326,7 @@
      */
     public Number[] getNumbers(String key)
     {
-        String[] strings = getStrings(key);
-        if (strings == null)
-        {
-            return null;
-        }
-
-        Number[] nums = new Number[strings.length];
-        try
-        {
-            for (int i=0; i<nums.length; i++)
-            {
-                if (strings[i] != null && strings[i].length() > 0)
-                {
-                    nums[i] = parseNumber(strings[i]);
-                }
-            }
-        }
-        catch (NumberFormatException nfe)
-        {
-            return null;
-        }
-        return nums;
+        return toNumbers(getValues(key));
     }
 
     /**
@@ -454,28 +336,7 @@
      */
     public int[] getInts(String key)
     {
-        String[] strings = getStrings(key);
-        if (strings == null)
-        {
-            return null;
-        }
-
-        int[] ints = new int[strings.length];
-        try
-        {
-            for (int i=0; i<ints.length; i++)
-            {
-                if (strings[i] != null && strings[i].length() > 0)
-                {
-                    ints[i] = parseNumber(strings[i]).intValue();
-                }
-            }
-        }
-        catch (NumberFormatException nfe)
-        {
-            return null;
-        }
-        return ints;
+        return toInts(getValues(key));
     }
 
     /**
@@ -485,28 +346,7 @@
      */
     public double[] getDoubles(String key)
     {
-        String[] strings = getStrings(key);
-        if (strings == null)
-        {
-            return null;
-        }
-
-        double[] doubles = new double[strings.length];
-        try
-        {
-            for (int i=0; i<doubles.length; i++)
-            {
-                if (strings[i] != null && strings[i].length() > 0)
-                {
-                    doubles[i] = parseNumber(strings[i]).doubleValue();
-                }
-            }
-        }
-        catch (NumberFormatException nfe)
-        {
-            return null;
-        }
-        return doubles;
+        return toDoubles(getValues(key));
     }
 
     /**
@@ -516,98 +356,7 @@
      */
     public Locale[] getLocales(String key)
     {
-        String[] strings = getStrings(key);
-        if (strings == null)
-        {
-            return null;
-        }
-
-        Locale[] locs = new Locale[strings.length];
-        for (int i=0; i<locs.length; i++)
-        {
-            if (strings[i] != null && strings[i].length() > 0)
-            {
-                locs[i] = parseLocale(strings[i]);
-            }
-        }
-        return locs;
-    }
-
-
-    // --------------------------- protected methods ------------------
-
-    /**
-     * Converts a parameter value into a {@link Number}
-     * This is used as the base for all numeric parsing methods. So,
-     * sub-classes can override to allow for customized number parsing.
-     * (e.g. to handle fractions, compound numbers, etc.)
-     *
-     * @param value the string to be parsed
-     * @return the value as a {@link Number}
-     */
-    protected Number parseNumber(String value) throws NumberFormatException
-    {
-        if (value.indexOf('.') >= 0)
-        {
-            return new Double(value);
-        }
-        return new Long(value);
-    }
-
-    /**
-     * Converts a parameter value into a {@link Boolean}
-     * Sub-classes can override to allow for customized boolean parsing.
-     * (e.g. to handle "Yes/No" or "T/F")
-     *
-     * @param value the string to be parsed
-     * @return the value as a {@link Boolean}
-     */
-    protected Boolean parseBoolean(String value)
-    {
-        return Boolean.valueOf(value);
-    }
-
-    /**
-     * Converts a single String value into an array of Strings by splitting
-     * it on the tool's set delimiter.  The default delimiter is a comma.
-     *
-     * @since VelocityTools 1.3
-     */
-    protected String[] parseStringList(String value)
-    {
-        if (value.indexOf(this.delimiter) < 0)
-        {
-            return new String[] { value };
-        }
-        return value.split(this.delimiter);
-    }
-
-    /**
-     * Converts a String value into a Locale.
-     *
-     * @since VelocityTools 1.3
-     */
-    protected Locale parseLocale(String value)
-    {
-        if (value.indexOf("_") < 0)
-        {
-            return new Locale(value);
-        }
-
-        String[] params = value.split("_");
-        if (params.length == 2)
-        {
-            return new Locale(params[0], params[1]);
-        }
-        else if (params.length == 3)
-        {
-            return new Locale(params[0], params[1], params[2]);
-        }
-        else
-        {
-            // there's only 3 possible params, so this must be invalid
-            return null;
-        }
+        return toLocales(getValues(key));
     }
 
 }

Modified: velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/view/ParameterTool.java
URL: http://svn.apache.org/viewvc/velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/view/ParameterTool.java?view=diff&rev=545420&r1=545419&r2=545420
==============================================================================
--- velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/view/ParameterTool.java
(original)
+++ velocity/tools/branches/2.x/src/main/java/org/apache/velocity/tools/view/ParameterTool.java
Thu Jun  7 22:21:52 2007
@@ -97,22 +97,22 @@
     }
 
     /**
-     * Overrides ValueParser.getString(String key) to retrieve the
-     * String from the ServletRequest instead of an arbitrary Map.
+     * Overrides ValueParser.getValue(String key) to retrieve the
+     * value from the ServletRequest instead of an arbitrary Map.
      *
      * @param key the parameter's key
      * @return parameter matching the specified key or
      *         <code>null</code> if there is no matching
      *         parameter
      */
-    public String getString(String key)
+    public Object getValue(String key)
     {
         return getRequest().getParameter(key);
     }
 
 
     /**
-     * Overrides ValueParser.getString(String key) to retrieve
+     * Overrides ValueParser.getValues(String key) to retrieve
      * Strings from the ServletRequest instead of an arbitrary Map.
      *
      * @param key the key for the desired parameter
@@ -120,9 +120,18 @@
      *         the given request parameter has, or <code>null</code>
      *         if the parameter does not exist
      */
-    public String[] getStrings(String key)
+    public Object[] getValues(String key)
     {
-        return getRequest().getParameterValues(key);
+        String[] strings = getRequest().getParameterValues(key);
+        if (strings == null || strings.length == 0)
+        {
+            return null;
+        }
+        else if (strings.length == 1)
+        {
+            return parseStringList(strings[0]);
+        }
+        return strings;
     }
 
     /**



Mime
View raw message