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