View Javadoc

    1   /*
    2    * Licensed to the Apache Software Foundation (ASF) under one or more
    3    * contributor license agreements.  See the NOTICE file distributed with
    4    * this work for additional information regarding copyright ownership.
    5    * The ASF licenses this file to You under the Apache License, Version 2.0
    6    * (the "License"); you may not use this file except in compliance with
    7    * the License.  You may obtain a copy of the License at
    8    *
    9    *      http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  package org.apache.commons.validator.routines;
    18
    19  import java.text.DecimalFormat;
    20  import java.text.Format;
    21  import java.math.BigDecimal;
    22
    23  /***
    24   * <p><b>Percentage Validation</b> and Conversion routines (<code>java.math.BigDecimal</code>).</p>
    25   *
    26   * <p>This is one implementation of a percent validator that has the following features:</p>
    27   *    <ul>
    28   *       <li>It is <i>lenient</i> about the the presence of the <i>percent symbol</i></li>
    29   *       <li>It converts the percent to a <code>java.math.BigDecimal</code></li>
    30   *    </ul>
    31   *
    32   * <p>However any of the <i>number</i> validators can be used for <i>percent</i> validation.
    33   *    For example, if you wanted a <i>percent</i> validator that converts to a
    34   *    <code>java.lang.Float</code> then you can simply instantiate an
    35   *    <code>FloatValidator</code> with the appropriate <i>format type</i>:</p>
    36   *
    37   *    <p><code>... = new FloatValidator(false, FloatValidator.PERCENT_FORMAT);</code></p>
    38   *
    39   * <p>Pick the appropriate validator, depending on the type (i.e Float, Double or BigDecimal)
    40   *    you want the percent converted to. Please note, it makes no sense to use
    41   *    one of the validators that doesn't handle fractions (i.e. byte, short, integer, long
    42   *    and BigInteger) since percentages are converted to fractions (i.e <code>50%</code> is
    43   *    converted to <code>0.5</code>).</p>
    44   *
    45   * @version $Revision: 478334 $ $Date: 2006-11-22 21:31:54 +0000 (Wed, 22 Nov 2006) $
    46   * @since Validator 1.3.0
    47   */
    48  public class PercentValidator extends BigDecimalValidator {
    49
    50      private static final PercentValidator VALIDATOR = new PercentValidator();
    51
    52      /*** DecimalFormat's percent (thousand multiplier) symbol */
    53      private static final char PERCENT_SYMBOL = '%';
    54
    55      private static final BigDecimal POINT_ZERO_ONE = new BigDecimal("0.01");
    56
    57      /***
    58       * Return a singleton instance of this validator.
    59       * @return A singleton instance of the PercentValidator.
    60       */
    61      public static BigDecimalValidator getInstance() {
    62          return VALIDATOR;
    63      }
    64
    65      /***
    66       * Construct a <i>strict</i> instance.
    67       */
    68      public PercentValidator() {
    69          this(true);
    70      }
    71
    72      /***
    73       * Construct an instance with the specified strict setting.
    74       *
    75       * @param strict <code>true</code> if strict
    76       *        <code>Format</code> parsing should be used.
    77       */
    78      public PercentValidator(boolean strict) {
    79          super(strict, PERCENT_FORMAT, true);
    80      }
    81
    82      /***
    83       * <p>Parse the value with the specified <code>Format</code>.</p>
    84       *
    85       * <p>This implementation is lenient whether the currency symbol
    86       *    is present or not. The default <code>NumberFormat</code>
    87       *    behaviour is for the parsing to "fail" if the currency
    88       *    symbol is missing. This method re-parses with a format
    89       *    without the currency symbol if it fails initially.</p>
    90       *
    91       * @param value The value to be parsed.
    92       * @param formatter The Format to parse the value with.
    93       * @return The parsed value if valid or <code>null</code> if invalid.
    94       */
    95      protected Object parse(String value, Format formatter) {
    96
    97          // Initial parse of the value
    98          BigDecimal parsedValue = (BigDecimal)super.parse(value, formatter);
    99          if (parsedValue != null || !(formatter instanceof DecimalFormat)) {
    100             return parsedValue;
    101         }
    102
    103         // Re-parse using a pattern without the percent symbol
    104         DecimalFormat decimalFormat = (DecimalFormat)formatter;
    105         String pattern = decimalFormat.toPattern();
    106         if (pattern.indexOf(PERCENT_SYMBOL) >= 0) {
    107             StringBuffer buffer = new StringBuffer(pattern.length());
    108             for (int i = 0; i < pattern.length(); i++) {
    109                 if (pattern.charAt(i) != PERCENT_SYMBOL) {
    110                     buffer.append(pattern.charAt(i));
    111                 }
    112             }
    113             decimalFormat.applyPattern(buffer.toString());
    114             parsedValue = (BigDecimal)super.parse(value, decimalFormat);
    115
    116             // If parsed OK, divide by 100 to get percent
    117             if (parsedValue != null) {
    118                 parsedValue = parsedValue.multiply(POINT_ZERO_ONE);
    119             }
    120
    121         }
    122         return parsedValue;
    123     }
    124 }