001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 * $Id: I18NUtils.java 19046 2007-05-21 13:03:50Z sfermigier $
020 */
021
022package org.nuxeo.common.utils.i18n;
023
024import java.text.MessageFormat;
025import java.util.Locale;
026import java.util.MissingResourceException;
027import java.util.ResourceBundle;
028
029/**
030 * Utility methods for translations.
031 */
032public final class I18NUtils {
033
034    // Utility class.
035    private I18NUtils() {
036    }
037
038    static ClassLoader getCurrentClassLoader(Object defaultObject) {
039        ClassLoader loader = Thread.currentThread().getContextClassLoader();
040        if (loader == null) {
041            loader = defaultObject.getClass().getClassLoader();
042        }
043        return loader;
044    }
045
046    public static String getMessageString(String bundleName, String key, Object[] params, Locale locale)
047            throws MissingResourceException {
048
049        String text;
050
051        ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale, getCurrentClassLoader(params));
052
053        try {
054            text = bundle.getString(key);
055        } catch (MissingResourceException e) {
056            text = key;
057        }
058
059        if (params != null && params.length != 0) {
060            MessageFormat mf = new MessageFormat(text, locale);
061            text = mf.format(params, new StringBuffer(), null).toString();
062        }
063
064        return text;
065    }
066
067}