    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.validator.routines;
    018
    019import java.math.BigDecimal;
    020import java.text.DecimalFormat;
    021import java.text.Format;
    022
    023/**
    024 * <strong>Percentage Validation</strong> and Conversion routines ({@code java.math.BigDecimal}).
    025 *
    026 * <p>This is one implementation of a percent validator that has the following features:</p>
    027 *    <ul>
    028 *       <li>It is <em>lenient</em> about the presence of the <em>percent symbol</em></li>
    029 *       <li>It converts the percent to a {@code java.math.BigDecimal}</li>
    030 *    </ul>
    031 *
    032 * <p>However any of the <em>number</em> validators can be used for <em>percent</em> validation.
    033 *    For example, if you wanted a <em>percent</em> validator that converts to a
    034 *    {{@link Float} then you can simply instantiate an
    035 *    {@code FloatValidator} with the appropriate <em>format type</em>:</p>
    036 *
    037 *    <p>{@code ... = new FloatValidator(false, FloatValidator.PERCENT_FORMAT);}</p>
    038 *
    039 * <p>Pick the appropriate validator, depending on the type (that is, Float, Double or BigDecimal)
    040 *    you want the percent converted to. Please note, it makes no sense to use
    041 *    one of the validators that doesn't handle fractions (such as byte, short, integer, long
    042 *    and BigInteger) since percentages are converted to fractions (for example, {@code 50%} is
    043 *    converted to {@code 0.5}).</p>
    044 *
    045 * @since 1.3.0
    046 */
    047public class PercentValidator extends BigDecimalValidator {
    048
    049    private static final long serialVersionUID = -3508241924961535772L;
    050
    051    private static final PercentValidator VALIDATOR = new PercentValidator();
    052
    053    /** DecimalFormat's percent (thousand multiplier) symbol */
    054    private static final char PERCENT_SYMBOL = '%';
    055
    056    private static final BigDecimal POINT_ZERO_ONE = new BigDecimal("0.01");
    057
    058    /**
    059     * Gets the singleton instance of this validator.
    060     *
    061     * @return A singleton instance of the PercentValidator.
    062     */
    063    public static BigDecimalValidator getInstance() {
    064        return VALIDATOR;
    065    }
    066
    067    /**
    068     * Constructs a <em>strict</em> instance.
    069     */
    070    public PercentValidator() {
    071        this(true);
    072    }
    073
    074    /**
    075     * Constructs an instance with the specified strict setting.
    076     *
    077     * @param strict {@code true} if strict
    078     *        {@code Format} parsing should be used.
    079     */
    080    public PercentValidator(final boolean strict) {
    081        super(strict, PERCENT_FORMAT, true);
    082    }
    083
    084    /**
    085     * Parse the value with the specified {@code Format}.
    086     *
    087     * <p>This implementation is lenient whether the currency symbol
    088     *    is present or not. The default {@code NumberFormat}
    089     *    behavior is for the parsing to "fail" if the currency
    090     *    symbol is missing. This method re-parses with a format
    091     *    without the currency symbol if it fails initially.</p>
    092     *
    093     * @param value The value to be parsed.
    094     * @param formatter The Format to parse the value with.
    095     * @return The parsed value if valid or {@code null} if invalid.
    096     */
    097    @Override
    098    protected Object parse(final String value, final Format formatter) {
    099
    100        // Initial parse of the value
    101        BigDecimal parsedValue = (BigDecimal) super.parse(value, formatter);
    102        if (parsedValue != null || !(formatter instanceof DecimalFormat)) {
    103            return parsedValue;
    104        }
    105
    106        // Re-parse using a pattern without the percent symbol
    107        final DecimalFormat decimalFormat = (DecimalFormat) formatter;
    108        final String pattern = decimalFormat.toPattern();
    109        if (pattern.indexOf(PERCENT_SYMBOL) >= 0) {
    110            final StringBuilder buffer = new StringBuilder(pattern.length());
    111            for (int i = 0; i < pattern.length(); i++) {
    112                if (pattern.charAt(i) != PERCENT_SYMBOL) {
    113                    buffer.append(pattern.charAt(i));
    114                }
    115            }
    116            decimalFormat.applyPattern(buffer.toString());
    117            parsedValue = (BigDecimal) super.parse(value, decimalFormat);
    118
    119            // If parsed OK, divide by 100 to get percent
    120            if (parsedValue != null) {
    121                parsedValue = parsedValue.multiply(POINT_ZERO_ONE);
    122            }
    123
    124        }
    125        return parsedValue;
    126    }
    127}