001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.util;
016    
017    import java.text.MessageFormat;
018    
019    import java.util.Locale;
020    import java.util.ResourceBundle;
021    
022    /**
023     * @author Shuyang Zhou
024     * @author Neil Griffin
025     */
026    public class ResourceBundleUtil {
027    
028            public static final String NULL_VALUE = "NULL_VALUE";
029    
030            public static String getString(
031                    ResourceBundle resourceBundle, Locale locale, String key,
032                    Object[] arguments) {
033    
034                    String value = getString(resourceBundle, key);
035    
036                    if (value == null) {
037                            return null;
038                    }
039    
040                    // Get the value associated with the specified key, and substitute any
041                    // arguuments like {0}, {1}, {2}, etc. with the specified argument
042                    // values.
043    
044                    if (ArrayUtil.isNotEmpty(arguments)) {
045                            MessageFormat messageFormat = new MessageFormat(value, locale);
046    
047                            value = messageFormat.format(arguments);
048                    }
049    
050                    return value;
051            }
052    
053            public static String getString(ResourceBundle resourceBundle, String key) {
054                    ResourceBundleThreadLocal.setReplace(true);
055    
056                    String value = null;
057    
058                    try {
059                            value = resourceBundle.getString(key);
060                    }
061                    finally {
062                            ResourceBundleThreadLocal.setReplace(false);
063                    }
064    
065                    if (NULL_VALUE.equals(value)) {
066                            value = null;
067                    }
068    
069                    return value;
070            }
071    
072    }