Source code
Description: source: package: org.apache.commons.validator.routines, class: BigIntegerValidator

    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 */
    017
    018package org.apache.commons.validator.routines;
    019
    020import java.math.BigDecimal;
    021import java.math.BigInteger;
    022import java.text.DecimalFormat;
    023import java.text.Format;
    024import java.text.NumberFormat;
    025import java.util.Locale;
    026
    027/**
    028 * <strong>BigInteger Validation</strong> and Conversion routines ({@code java.math.BigInteger}).
    029 *
    030 * <p>
    031 * This validator provides a number of methods for validating/converting a {@link String} value to a {@code BigInteger} using {@link NumberFormat} to parse
    032 * either:
    033 * </p>
    034 * <ul>
    035 * <li>using the default format for the default {@link Locale}</li>
    036 * <li>using a specified pattern with the default {@link Locale}</li>
    037 * <li>using the default format for a specified {@link Locale}</li>
    038 * <li>using a specified pattern with a specified {@link Locale}</li>
    039 * </ul>
    040 *
    041 * <p>
    042 * Use one of the {@code isValid()} methods to just validate or one of the {@code validate()} methods to validate and receive a <em>converted</em>
    043 * {@code BigInteger} value.
    044 * </p>
    045 *
    046 * <p>
    047 * Once a value has been successfully converted the following methods can be used to perform minimum, maximum and range checks:
    048 * </p>
    049 * <ul>
    050 * <li>{@code minValue()} checks whether the value is greater than or equal to a specified minimum.</li>
    051 * <li>{@code maxValue()} checks whether the value is less than or equal to a specified maximum.</li>
    052 * <li>{@code isInRange()} checks whether the value is within a specified range of values.</li>
    053 * </ul>
    054 *
    055 * <p>
    056 * So that the same mechanism used for parsing an <em>input</em> value for validation can be used to format <em>output</em>, corresponding {@code format()}
    057 * methods are also provided. That is you can format either:
    058 * </p>
    059 * <ul>
    060 * <li>using the default format for the default {@link Locale}</li>
    061 * <li>using a specified pattern with the default {@link Locale}</li>
    062 * <li>using the default format for a specified {@link Locale}</li>
    063 * <li>using a specified pattern with a specified {@link Locale}</li>
    064 * </ul>
    065 *
    066 * @since 1.3.0
    067 */
    068public class BigIntegerValidator extends AbstractNumberValidator {
    069
    070    private static final long serialVersionUID = 6713144356347139988L;
    071    private static final BigIntegerValidator VALIDATOR = new BigIntegerValidator();
    072
    073    /**
    074     * Gets the singleton instance of this validator.
    075     *
    076     * @return A singleton instance of the BigIntegerValidator.
    077     */
    078    public static BigIntegerValidator getInstance() {
    079        return VALIDATOR;
    080    }
    081
    082    /**
    083     * Constructs a <em>strict</em> instance.
    084     */
    085    public BigIntegerValidator() {
    086        this(true, STANDARD_FORMAT);
    087    }
    088
    089    /**
    090     * Construct an instance with the specified strict setting and format type.
    091     *
    092     * <p>
    093     * The {@code formatType} specified what type of {@code NumberFormat} is created - valid types are:
    094     * </p>
    095     * <ul>
    096     * <li>AbstractNumberValidator.STANDARD_FORMAT -to create <em>standard</em> number formats (the default).</li>
    097     * <li>AbstractNumberValidator.CURRENCY_FORMAT -to create <em>currency</em> number formats.</li>
    098     * <li>AbstractNumberValidator.PERCENT_FORMAT -to create <em>percent</em> number formats (the default).</li>
    099     * </ul>
    100     *
    101     * @param strict     {@code true} if strict {@code Format} parsing should be used.
    102     * @param formatType The {@code NumberFormat} type to create for validation, default is STANDARD_FORMAT.
    103     */
    104    public BigIntegerValidator(final boolean strict, final int formatType) {
    105        super(strict, formatType, false);
    106    }
    107
    108    /**
    109     * Returns a {@code Format} that parses to a {@code BigDecimal} so the exact value of the input is preserved.
    110     *
    111     * <p>
    112     * The superclass leaves {@link DecimalFormat} in its default mode, where {@code parse} yields a {@code Double} for a
    113     * value outside the {@code long} range and so rounds an integer carrying more significant digits than a {@code double}
    114     * can hold. Enabling {@link DecimalFormat#setParseBigDecimal(boolean)} keeps the full magnitude through parsing before
    115     * it is converted to a {@code BigInteger}.
    116     * </p>
    117     *
    118     * @param pattern The pattern used to validate the value against or {@code null} to use the default for the {@link Locale}.
    119     * @param locale  The locale to use for the format, system default if null.
    120     * @return The {@code Format} to use.
    121     */
    122    @Override
    123    protected Format getFormat(final String pattern, final Locale locale) {
    124        return setParseBigDecimal(super.getFormat(pattern, locale));
    125    }
    126
    127    /**
    128     * Tests if the value is within a specified range.
    129     *
    130     * @param value The {@code Number} value to check.
    131     * @param min   The minimum value of the range.
    132     * @param max   The maximum value of the range.
    133     * @return {@code true} if the value is within the specified range.
    134     */
    135    public boolean isInRange(final BigInteger value, final long min, final long max) {
    136        return minValue(value, min) && maxValue(value, max);
    137    }
    138
    139    /**
    140     * Tests if the value is less than or equal to a maximum.
    141     *
    142     * @param value The value validation is being performed on.
    143     * @param max   The maximum value.
    144     * @return {@code true} if the value is less than or equal to the maximum.
    145     */
    146    public boolean maxValue(final BigInteger value, final long max) {
    147        return value.compareTo(BigInteger.valueOf(max)) <= 0;
    148    }
    149
    150    /**
    151     * Tests if the value is less than or equal to a maximum, comparing the exact values.
    152     *
    153     * <p>
    154     * This overrides the {@link Number} overload inherited from the superclass, which narrows the value to a {@code long} before comparing and so loses
    155     * magnitude for a {@code BigInteger} outside the long range. The operands are compared as {@code BigDecimal} so a non-integer bound keeps its fractional
    156     * part instead of being truncated towards zero. A non-finite {@link Double} or {@link Float} operand keeps the {@code doubleValue()} comparison, since
    157     * {@code BigDecimal} cannot represent {@code NaN} or an infinity.
    158     * </p>
    159     *
    160     * @param value The value validation is being performed on.
    161     * @param max   The maximum value.
    162     * @return {@code true} if the value is less than or equal to the maximum.
    163     */
    164    @Override
    165    public boolean maxValue(final Number value, final Number max) {
    166        return isFinite(value) && isFinite(max) ? compareTo(value, max) <= 0 : value.doubleValue() <= max.doubleValue();
    167    }
    168
    169    /**
    170     * Tests if the value is greater than or equal to a minimum.
    171     *
    172     * @param value The value validation is being performed on.
    173     * @param min   The minimum value.
    174     * @return {@code true} if the value is greater than or equal to the minimum.
    175     */
    176    public boolean minValue(final BigInteger value, final long min) {
    177        return value.compareTo(BigInteger.valueOf(min)) >= 0;
    178    }
    179
    180    /**
    181     * Tests if the value is greater than or equal to a minimum, comparing the exact values.
    182     *
    183     * <p>
    184     * This overrides the {@link Number} overload inherited from the superclass, which narrows the value to a {@code long} before comparing and so loses
    185     * magnitude for a {@code BigInteger} outside the long range. The operands are compared as {@code BigDecimal} so a non-integer bound keeps its fractional
    186     * part instead of being truncated towards zero. A non-finite {@link Double} or {@link Float} operand keeps the {@code doubleValue()} comparison, since
    187     * {@code BigDecimal} cannot represent {@code NaN} or an infinity.
    188     * </p>
    189     *
    190     * @param value The value validation is being performed on.
    191     * @param min   The minimum value.
    192     * @return {@code true} if the value is greater than or equal to the minimum.
    193     */
    194    @Override
    195    public boolean minValue(final Number value, final Number min) {
    196        return isFinite(value) && isFinite(min) ? compareTo(value, min) >= 0 : value.doubleValue() >= min.doubleValue();
    197    }
    198
    199    /**
    200     * Converts the parsed value to a {@code BigInteger}.
    201     *
    202     * @param value     The parsed {@code Number} object created.
    203     * @param formatter The Format used to parse the value with.
    204     * @return The parsed {@code Number} converted to a {@code BigInteger}.
    205     */
    206    @Override
    207    protected Object processParsedValue(final Object value, final Format formatter) {
    208        final BigDecimal parsed = toBigDecimal(value);
    209        // parseIntegerOnly only stops at the decimal separator, so a fractional value written with a negative exponent and no decimal point (for example
    210        // "15E-1" for 1.5) is consumed in full and, because getFormat enables setParseBigDecimal, arrives here as a fractional BigDecimal. Reject it instead
    211        // of flooring it with toBigInteger, matching ByteValidator, IntegerValidator and LongValidator, which return null for the same input.
    212        if (parsed.signum() != 0 && parsed.stripTrailingZeros().scale() > 0) {
    213            return null;
    214        }
    215        return parsed.toBigInteger();
    216    }
    217
    218    /**
    219     * Validates and converts a {@code BigInteger} using the default {@link Locale}.
    220     *
    221     * @param value The value validation is being performed on.
    222     * @return The parsed {@code BigInteger} if valid or {@code null} if invalid.
    223     */
    224    public BigInteger validate(final String value) {
    225        return (BigInteger) parse(value, (String) null, (Locale) null);
    226    }
    227
    228    /**
    229     * Validates and converts a {@code BigInteger} using the specified {@link Locale}.
    230     *
    231     * @param value  The value validation is being performed on.
    232     * @param locale The locale to use for the number format, system default if null.
    233     * @return The parsed {@code BigInteger} if valid or {@code null} if invalid.
    234     */
    235    public BigInteger validate(final String value, final Locale locale) {
    236        return (BigInteger) parse(value, (String) null, locale);
    237    }
    238
    239    /**
    240     * Validates and converts a {@code BigInteger} using the specified <em>pattern</em>.
    241     *
    242     * @param value   The value validation is being performed on.
    243     * @param pattern The pattern used to validate the value against.
    244     * @return The parsed {@code BigInteger} if valid or {@code null} if invalid.
    245     */
    246    public BigInteger validate(final String value, final String pattern) {
    247        return (BigInteger) parse(value, pattern, (Locale) null);
    248    }
    249
    250    /**
    251     * Validates and converts a {@code BigInteger} using the specified pattern and/ or {@link Locale}.
    252     *
    253     * @param value   The value validation is being performed on.
    254     * @param pattern The pattern used to validate the value against, or the default for the {@link Locale} if {@code null}.
    255     * @param locale  The locale to use for the date format, system default if null.
    256     * @return The parsed {@code BigInteger} if valid or {@code null} if invalid.
    257     */
    258    public BigInteger validate(final String value, final String pattern, final Locale locale) {
    259        return (BigInteger) parse(value, pattern, locale);
    260    }
    261}