    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.beanutils2.locale.converters;
    019
    020import java.math.BigDecimal;
    021import java.math.BigInteger;
    022import java.text.DecimalFormat;
    023import java.text.NumberFormat;
    024import java.text.ParseException;
    025import java.text.SimpleDateFormat;
    026import java.util.Date;
    027import java.util.Locale;
    028
    029import org.apache.commons.beanutils2.ConversionException;
    030import org.apache.commons.beanutils2.locale.BaseLocaleConverter;
    031import org.apache.commons.beanutils2.locale.LocaleConverter;
    032import org.apache.commons.logging.Log;
    033import org.apache.commons.logging.LogFactory;
    034
    035/**
    036 * Standard {@link org.apache.commons.beanutils2.locale.LocaleConverter} implementation that converts an incoming locale-sensitive object into a {@link String}
    037 * object, optionally using a default value or throwing a {@link org.apache.commons.beanutils2.ConversionException} if a conversion error occurs.
    038 */
    039public class StringLocaleConverter extends BaseLocaleConverter<String> {
    040
    041    /**
    042     * Builds instances of {@link StringLocaleConverter}.
    043     */
    044    public static class Builder extends BaseLocaleConverter.Builder<Builder, String> {
    045
    046        /**
    047         * Constructs a new instance.
    048         */
    049        public Builder() {
    050            // empty
    051        }
    052
    053        /**
    054         * Gets a new instance.
    055         * <p>
    056         * Defaults construct a {@link LocaleConverter} that will throw a {@link ConversionException} if a conversion error occurs. The locale is the default
    057         * locale for this instance of the Java Virtual Machine and an unlocalized pattern is used for the conversion.
    058         * </p>
    059         *
    060         * @return a new instance.
    061         */
    062        @Override
    063        public StringLocaleConverter get() {
    064            return new StringLocaleConverter(defaultValue, locale, pattern, useDefault || defaultValue != null, localizedPattern);
    065        }
    066
    067    }
    068
    069    /** All logging goes through this logger */
    070    private static final Log LOG = LogFactory.getLog(StringLocaleConverter.class);
    071
    072    /**
    073     * Constructs a new builder.
    074     *
    075     * @return a new builder.
    076     */
    077    public static Builder builder() {
    078        return new Builder();
    079    }
    080
    081    private StringLocaleConverter(final String defaultValue, final Locale locale, final String pattern, final boolean useDefault, final boolean locPattern) {
    082        super(defaultValue, locale, pattern, useDefault, locPattern);
    083    }
    084
    085    /**
    086     * Gets an instance of DecimalFormat.
    087     *
    088     * @param locale  The locale
    089     * @param pattern The pattern is used for the conversion
    090     * @return The format for the locale and pattern
    091     * @throws ConversionException      if conversion cannot be performed successfully
    092     * @throws IllegalArgumentException if an error occurs parsing a String to a Number
    093     */
    094    private DecimalFormat getDecimalFormat(final Locale locale, final String pattern) {
    095        final DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(locale);
    096
    097        // if some constructors default pattern to null, it makes only sense to handle null pattern gracefully
    098        if (pattern != null) {
    099            if (localizedPattern) {
    100                numberFormat.applyLocalizedPattern(pattern);
    101            } else {
    102                numberFormat.applyPattern(pattern);
    103            }
    104        } else {
    105            LOG.debug("No pattern provided, using default.");
    106        }
    107
    108        return numberFormat;
    109    }
    110
    111    /**
    112     * Parses the specified locale-sensitive input object into an output object of the specified type.
    113     *
    114     * @param value   The input object to be converted
    115     * @param pattern The pattern is used for the conversion
    116     * @return The converted value
    117     * @throws ConversionException if conversion cannot be performed successfully
    118     * @throws ParseException      if an error occurs
    119     */
    120    @Override
    121    protected String parse(final Object value, final String pattern) throws ParseException {
    122        String result = null;
    123
    124        if (value instanceof Integer || value instanceof Long || value instanceof BigInteger || value instanceof Byte || value instanceof Short) {
    125            result = getDecimalFormat(locale, pattern).format(((Number) value).longValue());
    126        } else if (value instanceof Double || value instanceof BigDecimal || value instanceof Float) {
    127            result = getDecimalFormat(locale, pattern).format(((Number) value).doubleValue());
    128        } else if (value instanceof Date) { // java.util.Date, java.sql.Date, java.sql.Time, java.sql.Timestamp
    129            result = new SimpleDateFormat(pattern, locale).format(value);
    130        } else {
    131            result = value.toString();
    132        }
    133
    134        return result;
    135    }
    136}