com.feilong.commons.core.configure.ResourceBundleUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.feilong.commons.core.configure.ResourceBundleUtil.java

Source

/*
 * Copyright (C) 2008 feilong (venusdrogon@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.feilong.commons.core.configure;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.feilong.commons.core.io.FileUtil;
import com.feilong.commons.core.io.UncheckedIOException;
import com.feilong.commons.core.text.MessageFormatUtil;
import com.feilong.commons.core.util.StringUtil;
import com.feilong.commons.core.util.Validator;

/**
 * {@link ResourceBundle} .
 * 
 * @author <a href="mailto:venusdrogon@163.com"></a>
 * @version 1.0 2011-11-11 ?10:24:25
 * @see MessageFormatUtil#format(String, Object...)
 * @see java.util.ResourceBundle
 * @see java.util.PropertyResourceBundle
 * @since 1.0.0
 */
public final class ResourceBundleUtil implements BaseConfigure {

    /** The Constant log. */
    private static final Logger log = LoggerFactory.getLogger(ResourceBundleUtil.class);

    /** Don't let anyone instantiate this class. */
    private ResourceBundleUtil() {
        //AssertionError?. ?????. ???.
        //see Effective Java 2nd
        throw new AssertionError("No " + getClass().getName() + " instances for you!");
    }

    /**
     * ?Properties?,typeClass .
     * 
     * @param <T>
     *            the generic type
     * @param baseName
     *            ?+??(??),the base name of the resource bundle, a fully qualified class name
     * @param key
     *            the key
     * @param typeClass
     *            ,<br>
     *            String.class,String <br>
     *            Integer.class,Integer
     * @return the value
     * @see #getValue(String, String)
     * @see com.feilong.commons.core.util.StringUtil#toT(String, Class)
     */
    @SuppressWarnings("unchecked")
    public static <T> T getValue(String baseName, String key, Class<?> typeClass) {
        String value = getValue(baseName, key);
        return (T) StringUtil.toT(value, typeClass);
    }

    /**
     * ?Properties?,typeClass .
     * 
     * @param <T>
     *            the generic type
     * @param resourceBundle
     *            the resource bundle
     * @param key
     *            the key
     * @param typeClass
     *            ,<br>
     *            String.class,String <br>
     *            Integer.class,Integer
     * @return the value
     * @see #getValue(ResourceBundle, String)
     * @see com.feilong.commons.core.util.StringUtil#toT(String, Class)
     */
    @SuppressWarnings("unchecked")
    public static <T> T getValue(ResourceBundle resourceBundle, String key, Class<?> typeClass) {
        String value = getValue(resourceBundle, key);
        return (T) StringUtil.toT(value, typeClass);
    }

    /**
     * ?Properties? ,java.util.ResourceBundlegetBundle()??
     *
     * @param baseName
     *            ?+??(??),the base name of the resource bundle, a fully qualified class name
     * @param key
     *            Properties???
     * @return 
     * @see #getResourceBundle(String)
     * @see #getValue(ResourceBundle, String)
     * @since 1.0
     */
    public static String getValue(String baseName, String key) {
        ResourceBundle resourceBundle = getResourceBundle(baseName);
        return getValue(resourceBundle, key);
    }

    /**
     * ?Properties? ,java.util.ResourceBundlegetBundle()??
     *
     * @param baseName
     *            ?+??(??),the base name of the resource bundle, a fully qualified class name
     * @param key
     *            Properties???
     * @param locale
     *            the locale
     * @return 
     * @see #getResourceBundle(String, Locale)
     * @see #getValue(ResourceBundle, String)
     * @since 1.0.5
     */
    public static String getValue(String baseName, String key, Locale locale) {
        ResourceBundle resourceBundle = getResourceBundle(baseName, locale);
        return getValue(resourceBundle, key);
    }

    /**
     * ? ?<br>
     * ?:name={0}.
     * 
     * @param baseName
     *            ?+??(??),the base name of the resource bundle, a fully qualified class name
     * @param key
     *            the key
     * @param locale
     *            the locale
     * @param arguments
     *            ?Object[]?
     * @return the value with arguments
     * @see #getResourceBundle(String, Locale)
     * @see #getValueWithArguments(ResourceBundle, String, Object...)
     */
    public static String getValueWithArguments(String baseName, String key, Locale locale, Object... arguments) {
        ResourceBundle resourceBundle = getResourceBundle(baseName, locale);
        return getValueWithArguments(resourceBundle, key, arguments);
    }

    /**
     * ?Properties? ,java.util.ResourceBundlegetBundle()??
     * 
     * @param resourceBundle
     *            ?+??(??)
     * @param key
     *            Properties???
     * @return <br>
     *         ?,
     *         <ul>
     *         <li>key?,log.warn ,?null</li>
     *         <li>key,valuenull  empty,log.warn ,?value</li>
     *         </ul>
     * @see java.util.ResourceBundle#getString(String)
     */
    public static String getValue(ResourceBundle resourceBundle, String key) {
        if (!resourceBundle.containsKey(key)) {
            log.warn("resourceBundle don't containsKey:[{}]", key);
        } else {
            try {
                String value = resourceBundle.getString(key);
                if (Validator.isNullOrEmpty(value)) {
                    log.warn("resourceBundle has key:[{}],but value is null/empty", key);
                }
                return value;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    /**
     * ? ?<br>
     * ?:name={0}.
     * 
     * @param resourceBundle
     *            the resource bundle
     * @param key
     *            ? name
     * @param arguments
     *            ?Object[]?
     * @return ? arguments null,
     * @see MessageFormatUtil
     * @see MessageFormatUtil#format(String, Object...)
     */
    public static String getValueWithArguments(ResourceBundle resourceBundle, String key, Object... arguments) {
        String value = getValue(resourceBundle, key);
        if (Validator.isNullOrEmpty(value)) {
            return null;
        }
        // ? arguments null,
        return MessageFormatUtil.format(value, arguments);
    }

    // *****************************************************************************
    /**
     * ?,?,<br>
     *  getArray(baseName, key, spliter, String.class) ?
     * 
     * @param baseName
     *            ?+??(??),the base name of the resource bundle, a fully qualified class name
     * @param key
     *            the key
     * @param spliter
     *            
     * @return value.split(spliter), ??,null
     * @see #getArray(ResourceBundle, String, String, Class)
     */
    public static String[] getArray(String baseName, String key, String spliter) {
        return getArray(baseName, key, spliter, String.class);
    }

    /**
     * ?,?,<br>
     *  getArray(resourceBundle, key, spliter, String.class) ?
     * 
     * @param resourceBundle
     *            the resource bundle
     * @param key
     *            the key
     * @param spliter
     *            
     * @return value.split(spliter), ??,null
     * @see #getArray(ResourceBundle, String, String, Class)
     */
    public static String[] getArray(ResourceBundle resourceBundle, String key, String spliter) {
        return getArray(resourceBundle, key, spliter, String.class);
    }

    /**
     * ?,?.
     * 
     * @param <T>
     *            the generic type
     * @param baseName
     *            ?+??(??),the base name of the resource bundle, a fully qualified class name
     * @param key
     *            the key
     * @param spliter
     *            
     * @param typeClass
     *            ,<br>
     *            String.class,String []<br>
     *            Integer.class,Integer [] 
     * @return value.split(spliter), ??,null
     * @see #getResourceBundle(String)
     * @see #getArray(ResourceBundle, String, String, Class)
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] getArray(String baseName, String key, String spliter, Class<?> typeClass) {
        ResourceBundle resourceBundle = getResourceBundle(baseName);
        return (T[]) getArray(resourceBundle, key, spliter, typeClass);
    }

    /**
     * ?,?.
     * 
     * @param <T>
     *            the generic type
     * @param resourceBundle
     *            the resource bundle
     * @param key
     *            the key
     * @param spliter
     *            
     * @param typeClass
     *            ,<br>
     *            String.class,String []<br>
     *            Integer.class,Integer [] 
     * @return value.split(spliter), ??,null
     * @see #getValue(ResourceBundle, String)
     * @see com.feilong.commons.core.util.StringUtil#splitToTArray(String, String, Class)
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] getArray(ResourceBundle resourceBundle, String key, String spliter, Class<?> typeClass) {
        String value = getValue(resourceBundle, key);
        return (T[]) StringUtil.splitToTArray(value, spliter, typeClass);
    }

    // **************************************************************************
    /**
     * Read prefix as map(HashMap).
     * 
     * @param baseName
     *            ?+??(??),the base name of the resource bundle, a fully qualified class name
     * @param prefix
     *            ?
     * @param spliter
     *            the spliter
     * @param locale
     *            the locale
     * @return  baseName key value,null,?,?keyvalue?HashMap
     * @see #readAllPropertiesToMap(String, Locale)
     */
    public static Map<String, String> readPrefixAsMap(String baseName, String prefix, String spliter,
            Locale locale) {
        Map<String, String> propertyMap = readAllPropertiesToMap(baseName, locale);
        if (Validator.isNotNullOrEmpty(propertyMap)) {
            Map<String, String> result = new HashMap<String, String>();
            for (Map.Entry<String, String> entry : propertyMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                //  prefix 
                if (key.startsWith(prefix)) {
                    // 
                    String[] values = key.split(spliter);
                    if (values.length >= 2) {
                        result.put(values[1], value);
                    }
                }
            }
            return result;
        }
        return null;
    }

    /**
     * ??,k/v ?map(HashMap).
     * 
     * @param baseName
     *            ?+??(??),the base name of the resource bundle, a fully qualified class name
     * @param locale
     *            the locale ?
     * @return  baseName key value,null,?,?keyvalue?HashMap
     * @see #getResourceBundle(String, Locale)
     * @see java.util.ResourceBundle#getKeys()
     * @see org.apache.commons.collections.MapUtils#toMap(ResourceBundle)
     */
    public static Map<String, String> readAllPropertiesToMap(String baseName, Locale locale) {
        ResourceBundle resourceBundle = getResourceBundle(baseName, locale);
        Enumeration<String> enumeration = resourceBundle.getKeys();
        if (Validator.isNotNullOrEmpty(enumeration)) {
            Map<String, String> propertyMap = new HashMap<String, String>();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = resourceBundle.getString(key);
                propertyMap.put(key, value);
            }
            return propertyMap;
        }
        return null;
    }

    /**
     * ResourceBundle.
     * 
     * @param baseName
     *            the base name of the resource bundle, a fully qualified class name
     * @return the resource bundle
     * @see java.util.Locale#getDefault()
     * @see #getResourceBundle(String, Locale)
     */
    public static ResourceBundle getResourceBundle(String baseName) {
        // Locale enLoc = new Locale("en", "US"); // 
        return getResourceBundle(baseName, Locale.getDefault());
    }

    /**
     * ResourceBundle.
     * 
     * @param baseName
     *            ?+??(??),the base name of the resource bundle, a fully qualified class name
     * @param locale
     *            the locale for which a resource bundle is desired
     * @return the resource bundle,may be null
     * @see java.util.ResourceBundle#getBundle(String, Locale)
     */
    public static ResourceBundle getResourceBundle(String baseName, Locale locale) {
        if (Validator.isNullOrEmpty(baseName)) {
            throw new IllegalArgumentException("baseName can't be null/empty!");
        }
        if (Validator.isNullOrEmpty(locale)) {
            throw new IllegalArgumentException("locale can't be null/empty!");
        }
        ResourceBundle resourceBundle = ResourceBundle.getBundle(baseName, locale);
        if (null == resourceBundle) {
            log.warn("resourceBundle is null,baseName:{},locale:{}", resourceBundle, baseName, locale);
        }
        return resourceBundle;
    }

    /**
     * ResourceBundle({@link PropertyResourceBundle}),????(file).
     *
     * @param fileName
     *            the file name
     * @return the resource bundle,may be null
     * @see com.feilong.commons.core.io.FileUtil#getFileInputStream(String)
     * @see java.util.PropertyResourceBundle#PropertyResourceBundle(InputStream)
     * @see #ResourceBundleUtil.getResourceBundle(InputStream)
     * @since 1.0.9
     */
    public static ResourceBundle getResourceBundleByFileName(String fileName) {
        if (Validator.isNullOrEmpty(fileName)) {
            throw new IllegalArgumentException("fileName can't be null/empty!");
        }
        InputStream inputStream = FileUtil.getFileInputStream(fileName);
        return getResourceBundle(inputStream);
    }

    /**
     * ResourceBundle({@link PropertyResourceBundle}),????(file).
     *
     * @param inputStream
     *            the input stream
     * @return the resource bundle,may be null
     * @see java.util.PropertyResourceBundle#PropertyResourceBundle(InputStream)
     * @since 1.0.9
     */
    public static ResourceBundle getResourceBundle(InputStream inputStream) {
        if (Validator.isNullOrEmpty(inputStream)) {
            throw new IllegalArgumentException("inputStream can't be null/empty!");
        }
        try {
            ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
            return resourceBundle;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    /**
     *  resource bundle({@link PropertyResourceBundle}),????(file).
     *
     * @param reader
     *            the reader
     * @return the resource bundle
     * @throws UncheckedIOException
     *             the unchecked io exception
     * @see java.util.PropertyResourceBundle#PropertyResourceBundle(Reader)
     * @since 1.0.9
     */
    public static ResourceBundle getResourceBundle(Reader reader) throws UncheckedIOException {
        if (Validator.isNullOrEmpty(reader)) {
            throw new IllegalArgumentException("reader can't be null/empty!");
        }
        try {
            ResourceBundle resourceBundle = new PropertyResourceBundle(reader);
            return resourceBundle;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}