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