    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.text.DecimalFormat;
    020import java.text.Format;
    021
    022/**
    023 * <p><strong>Currency Validation</strong> and Conversion routines ({@code java.math.BigDecimal}).</p>
    024 *
    025 * <p>This is one implementation of a currency validator that has the following features:</p>
    026 *    <ul>
    027 *       <li>It is <em>lenient</em> about the presence of the <em>currency symbol</em></li>
    028 *       <li>It converts the currency to a {@code java.math.BigDecimal}</li>
    029 *    </ul>
    030 *
    031 * <p>However any of the <em>number</em> validators can be used for <em>currency</em> validation.
    032 *    For example, if you wanted a <em>currency</em> validator that converts to a
    033 *    {@code java.lang.Integer} then you can simply instantiate an
    034 *    {@code IntegerValidator} with the appropriate <em>format type</em>:</p>
    035 *
    036 *    <p>{@code ... = new IntegerValidator(false, IntegerValidator.CURRENCY_FORMAT);}</p>
    037 *
    038 * <p>Pick the appropriate validator, depending on the type (for example, Float, Double, Integer, Long and so on)
    039 *    you want the currency converted to. One thing to note - only the CurrencyValidator
    040 *    implements <em>lenient</em> behavior regarding the currency symbol.</p>
    041 *
    042 * @since 1.3.0
    043 */
    044public class CurrencyValidator extends BigDecimalValidator {
    045
    046    private static final long serialVersionUID = -4201640771171486514L;
    047
    048    private static final CurrencyValidator VALIDATOR = new CurrencyValidator();
    049
    050    /** DecimalFormat's currency symbol */
    051    private static final char CURRENCY_SYMBOL = '\u00A4';
    052
    053    /**
    054     * Gets the singleton instance of this validator.
    055     * @return A singleton instance of the CurrencyValidator.
    056     */
    057    public static BigDecimalValidator getInstance() {
    058        return VALIDATOR;
    059    }
    060
    061    /**
    062     * Constructs a <em>strict</em> instance.
    063     */
    064    public CurrencyValidator() {
    065        this(true, true);
    066    }
    067
    068    /**
    069     * Constructs an instance with the specified strict setting.
    070     *
    071     * @param strict {@code true} if strict
    072     *        {@code Format} parsing should be used.
    073     * @param allowFractions {@code true} if fractions are
    074     *        allowed or {@code false} if integers only.
    075     */
    076    public CurrencyValidator(final boolean strict, final boolean allowFractions) {
    077        super(strict, CURRENCY_FORMAT, allowFractions);
    078    }
    079
    080    /**
    081     * <p>Parse the value with the specified {@code Format}.</p>
    082     *
    083     * <p>This implementation is lenient whether the currency symbol
    084     *    is present or not. The default {@code NumberFormat}
    085     *    behavior is for the parsing to "fail" if the currency
    086     *    symbol is missing. This method re-parses with a format
    087     *    without the currency symbol if it fails initially.</p>
    088     *
    089     * @param value The value to be parsed.
    090     * @param formatter The Format to parse the value with.
    091     * @return The parsed value if valid or {@code null} if invalid.
    092     */
    093    @Override
    094    protected Object parse(final String value, final Format formatter) {
    095
    096        // Initial parse of the value
    097        Object parsedValue = super.parse(value, formatter);
    098        if (parsedValue != null || !(formatter instanceof DecimalFormat)) {
    099            return parsedValue;
    100        }
    101
    102        // Re-parse using a pattern without the currency symbol
    103        final DecimalFormat decimalFormat = (DecimalFormat) formatter;
    104        final String pattern = decimalFormat.toPattern();
    105        if (pattern.indexOf(CURRENCY_SYMBOL) >= 0) {
    106            final StringBuilder buffer = new StringBuilder(pattern.length());
    107            for (int i = 0; i < pattern.length(); i++) {
    108                if (pattern.charAt(i) != CURRENCY_SYMBOL) {
    109                    buffer.append(pattern.charAt(i));
    110                }
    111            }
    112            decimalFormat.applyPattern(buffer.toString());
    113            parsedValue = super.parse(value, decimalFormat);
    114        }
    115        return parsedValue;
    116    }
    117}