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    *      https://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.math.BigDecimal;
20  import java.text.DecimalFormat;
21  import java.text.Format;
22  
23  /**
24   * <p><strong>Percentage Validation</strong> and Conversion routines ({@code java.math.BigDecimal}).</p>
25   *
26   * <p>This is one implementation of a percent validator that has the following features:</p>
27   *    <ul>
28   *       <li>It is <em>lenient</em> about the presence of the <em>percent symbol</em></li>
29   *       <li>It converts the percent to a {@code java.math.BigDecimal}</li>
30   *    </ul>
31   *
32   * <p>However any of the <em>number</em> validators can be used for <em>percent</em> validation.
33   *    For example, if you wanted a <em>percent</em> validator that converts to a
34   *    {@code java.lang.Float} then you can simply instantiate an
35   *    {@code FloatValidator} with the appropriate <em>format type</em>:</p>
36   *
37   *    <p>{@code ... = new FloatValidator(false, FloatValidator.PERCENT_FORMAT);}</p>
38   *
39   * <p>Pick the appropriate validator, depending on the type (that is, 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 (such as byte, short, integer, long
42   *    and BigInteger) since percentages are converted to fractions (for example, {@code 50%} is
43   *    converted to {@code 0.5}).</p>
44   *
45   * @since 1.3.0
46   */
47  public class PercentValidator extends BigDecimalValidator {
48  
49      private static final long serialVersionUID = -3508241924961535772L;
50  
51      private static final PercentValidator VALIDATOR = new PercentValidator();
52  
53      /** DecimalFormat's percent (thousand multiplier) symbol */
54      private static final char PERCENT_SYMBOL = '%';
55  
56      private static final BigDecimal POINT_ZERO_ONE = new BigDecimal("0.01");
57  
58      /**
59       * Gets the singleton instance of this validator.
60       * @return A singleton instance of the PercentValidator.
61       */
62      public static BigDecimalValidator getInstance() {
63          return VALIDATOR;
64      }
65  
66      /**
67       * Constructs a <em>strict</em> instance.
68       */
69      public PercentValidator() {
70          this(true);
71      }
72  
73      /**
74       * Constructs an instance with the specified strict setting.
75       *
76       * @param strict {@code true} if strict
77       *        {@code Format} parsing should be used.
78       */
79      public PercentValidator(final boolean strict) {
80          super(strict, PERCENT_FORMAT, true);
81      }
82  
83      /**
84       * <p>Parse the value with the specified {@code Format}.</p>
85       *
86       * <p>This implementation is lenient whether the currency symbol
87       *    is present or not. The default {@code NumberFormat}
88       *    behavior is for the parsing to "fail" if the currency
89       *    symbol is missing. This method re-parses with a format
90       *    without the currency symbol if it fails initially.</p>
91       *
92       * @param value The value to be parsed.
93       * @param formatter The Format to parse the value with.
94       * @return The parsed value if valid or {@code null} if invalid.
95       */
96      @Override
97      protected Object parse(final String value, final Format formatter) {
98  
99          // Initial parse of the value
100         BigDecimal parsedValue = (BigDecimal) super.parse(value, formatter);
101         if (parsedValue != null || !(formatter instanceof DecimalFormat)) {
102             return parsedValue;
103         }
104 
105         // Re-parse using a pattern without the percent symbol
106         final DecimalFormat decimalFormat = (DecimalFormat) formatter;
107         final String pattern = decimalFormat.toPattern();
108         if (pattern.indexOf(PERCENT_SYMBOL) >= 0) {
109             final StringBuilder buffer = new StringBuilder(pattern.length());
110             for (int i = 0; i < pattern.length(); i++) {
111                 if (pattern.charAt(i) != PERCENT_SYMBOL) {
112                     buffer.append(pattern.charAt(i));
113                 }
114             }
115             decimalFormat.applyPattern(buffer.toString());
116             parsedValue = (BigDecimal) super.parse(value, decimalFormat);
117 
118             // If parsed OK, divide by 100 to get percent
119             if (parsedValue != null) {
120                 parsedValue = parsedValue.multiply(POINT_ZERO_ONE);
121             }
122 
123         }
124         return parsedValue;
125     }
126 }