Java tutorial
/* * Copyright (C) 2008 feilong * * 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.sunchenbin.store.feilong.core.util; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.Collections; 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.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sunchenbin.store.feilong.core.bean.ConvertUtil; import com.sunchenbin.store.feilong.core.io.FileUtil; import com.sunchenbin.store.feilong.core.io.UncheckedIOException; import com.sunchenbin.store.feilong.core.lang.StringUtil; import com.sunchenbin.store.feilong.core.text.MessageFormatUtil; /** * {@link java.util.ResourceBundle} . * * <h3>??,</h3> * * <blockquote> * <p> * ?Message.properties?Message_zh_CN.properties?Message_zh_ CN.class 3,?<br> * ?,<br> * ?Message_zh_CN.class?Message_zh_CN.properties?Message.properties<br> * </p> * <p> * ??,??:<br> * {@link "java.util.ResourceBundle#loadBundle(CacheKey, List, Control, boolean)"}<br> * {@link java.util.ResourceBundle.Control#newBundle(String, Locale, String, ClassLoader, boolean)} * </p> * </blockquote> * * @author feilong * @see MessageFormatUtil#format(String, Object...) * @see java.util.ResourceBundle * * @see java.util.PropertyResourceBundle * @see java.util.ListResourceBundle * @version 1.4.0 201583 ?3:18:50 * @since 1.4.0 */ public final class ResourceBundleUtil { /** The Constant LOGGER. */ private static final Logger LOGGER = 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 * ?+??<span style="color:red">(??)</span>,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.sunchenbin.store.feilong.core.bean.ConvertUtil#convert(Object, Class) */ @SuppressWarnings("unchecked") public static <T> T getValue(String baseName, String key, Class<?> typeClass) { String value = getValue(baseName, key); return (T) ConvertUtil.convert(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.sunchenbin.store.feilong.core.bean.ConvertUtil#convert(Object, Class) */ @SuppressWarnings("unchecked") public static <T> T getValue(ResourceBundle resourceBundle, String key, Class<?> typeClass) { String value = getValue(resourceBundle, key); return (T) ConvertUtil.convert(value, typeClass); } /** * ?Properties? , {@link java.util.ResourceBundle#getBundle(String)} ??. * * @param baseName * ?+??<span style="color:red">(??)</span>,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? , {@link java.util.ResourceBundle#getBundle(String)} ??. * * @param baseName * ?+??<span style="color:red">(??)</span>,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); } /** * ? ?. * * <p> * ?:name={0}. * </p> * * @param baseName * ?+??<span style="color:red">(??)</span>,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? , {@link java.util.ResourceBundle#getBundle(String)} ??. * * @param resourceBundle * ?+??(??) * @param key * Properties??? * @return <br> * ?, * <ul> * <li>key?,LOGGER.warn ,?null</li> * <li>key,valuenull empty,LOGGER.warn ,?value</li> * </ul> * @see java.util.ResourceBundle#getString(String) */ public static String getValue(ResourceBundle resourceBundle, String key) { if (!resourceBundle.containsKey(key)) { LOGGER.debug("resourceBundle:[{}] don't containsKey:[{}]", resourceBundle, key); return StringUtils.EMPTY; } try { String value = resourceBundle.getString(key); if (Validator.isNullOrEmpty(value)) { LOGGER.debug("resourceBundle has key:[{}],but value is null/empty", key); } return value; } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return StringUtils.EMPTY; } /** * ? ?. * <p> * ?:name={0}. * </p> * * @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 StringUtils.EMPTY; } // ? arguments null, return MessageFormatUtil.format(value, arguments); } // ***************************************************************************** /** * ?,?. * <p> * {@link #getArray(ResourceBundle, String, String, Class)} ? * </p> * * @param baseName * ?+??<span style="color:red">(??)</span>,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); } /** * ?,?. * <p> * {@link #getArray(ResourceBundle, String, String, Class)} ? * </p> * * @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 * ?+??<span style="color:red">(??)</span>,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.sunchenbin.store.feilong.core.lang.StringUtil#tokenizeToStringArray(String, String) */ public static <T> T[] getArray(ResourceBundle resourceBundle, String key, String spliter, Class<T> typeClass) { String value = getValue(resourceBundle, key); String[] array = StringUtil.tokenizeToStringArray(value, spliter); return ConvertUtil.convert(array, typeClass); } // ************************************************************************** /** * Read prefix as map(HashMap). * * @param baseName * ?+??<span style="color:red">(??)</span>,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.isNullOrEmpty(propertyMap)) { return Collections.emptyMap(); } 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; } /** * ??,k/v ?map(HashMap). * * @param baseName * ?+??<span style="color:red">(??)</span>,the base name of the resource bundle, a fully qualified class name * @return baseName key value,null,?,?keyvalue?HashMap * @see #readAllPropertiesToMap(String, Locale) * @since 1.2.1 */ public static Map<String, String> readAllPropertiesToMap(String baseName) { final Locale defaultLocale = Locale.getDefault(); return readAllPropertiesToMap(baseName, defaultLocale); } /** * ??,k/v ?map(HashMap). * * @param baseName * ?+??<span style="color:red">(??)</span>,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 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.isNullOrEmpty(enumeration)) { return Collections.emptyMap(); } 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; } /** * ResourceBundle. * * @param baseName * ?+??<span style="color:red">(??)</span>,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 * ?+??<span style="color:red">(??)</span>,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) { LOGGER.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.sunchenbin.store.feilong.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 { return new PropertyResourceBundle(inputStream); } catch (IOException e) { throw new UncheckedIOException(e); } } /** * resource bundle({@link PropertyResourceBundle}),????(file). * * @param reader * the reader * @return the resource bundle * @see java.util.PropertyResourceBundle#PropertyResourceBundle(Reader) * @since 1.0.9 */ public static ResourceBundle getResourceBundle(Reader reader) { if (Validator.isNullOrEmpty(reader)) { throw new IllegalArgumentException("reader can't be null/empty!"); } try { return new PropertyResourceBundle(reader); } catch (IOException e) { throw new UncheckedIOException(e); } } }