All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.tkit.jee.base.resource.ResourceManager Maven / Gradle / Ivy

There is a newer version: 0.8.0
Show newest version
/*
 * Copyright (c) 2011, 1000kit.org, and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.tkit.jee.base.resource;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * This class load the resources or the resource key from the class-path.
 *
 * @author Andrej Petras
 */
public final class ResourceManager {

    /**
     * The default constructor.
     */
    private ResourceManager() {
        // empty private constructor
    }

    /**
     * Loads the bundle from class-path.
     *
     * @param bundleName the name of bundle.
     * @param locale the local for the bundle file.
     * @param loader the loader of class.
     * @return the resource bundle.
     */
    private static ResourceBundle lookupBundle(final String bundleName, final Locale locale, final ClassLoader loader) {
        ResourceBundle bundle;
        if (loader != null && locale != null) {
            bundle = ResourceBundle.getBundle(bundleName, locale, loader);
        } else if (locale != null) {
            bundle = ResourceBundle.getBundle(bundleName, locale);
        } else {
            bundle = ResourceBundle.getBundle(bundleName);
        }
        return bundle;
    }

    /**
     * Gets the text for the resource key from the resource file specified by locale.
     *
     * @param key the key of resource.
     * @param locale the locale for text.
     * @return the text from the resource.
     */
    public static String getString(final Enum key, final Locale locale) {
        return getString(key, locale, null);
    }

    /**
     * Gets the text for the resource key from the resource file specified by locale and class loader.
     *
     * @param key the key of resource.
     * @param locale the locale for text.
     * @param loader the loader of class.
     * @return the text from the resource.
     */
    public static String getString(final Enum key, final Locale locale, final ClassLoader loader) {
        return getMessage(key, locale, loader);
    }


    /**
     * Gets the message for the resource key specified by locale and arguments.
     *
     * @param key the key of resource.
     * @param locale the locale of resource (text).
     * @param arguments the arguments for the message.
     * @return the message of the resource key.
     */
    public static String getMessage(final Enum key, final Locale locale, final Object... arguments) {
        return getMessage(key, locale, null, arguments);
    }

    /**
     * Gets the message for the resource key specified by locale and arguments.
     *
     * @param key the key of resource.
     * @param locale the locale of resource (text).
     * @param arguments the arguments for the message.
     * @param loader the loader of class.
     * @return the message of the resource key.
     */
    public static String getMessage(final Enum key, final Locale locale, final ClassLoader loader, final Object... arguments) {
        String result;

        Object[] params = createParameters(arguments);

        try {
            ClassLoader classLoader = loader;
            if (classLoader == null) {
                classLoader = key.getClass().getClassLoader();
            }

            String value = getKeyString(key, locale, classLoader);

            if (params != null) {
                MessageFormat msgFormat;
                if (locale != null) {
                    msgFormat = new MessageFormat(value, locale);
                } else {
                    msgFormat = new MessageFormat(value);
                }
                StringBuffer bf = msgFormat.format(params, new StringBuffer(), null);
                result = bf.toString();
            } else {
                result = value;
            }
        } catch (MissingResourceException e) {
            // missing translation 
            // create the result string: ENUM_NAME[param1,param2,..]
            StringBuilder sb = new StringBuilder();
            sb.append(key.name());
            sb.append('[');
            if (params != null) {
                boolean first = false;
                for (Object param : params) {
                    if (first) {
                        sb.append(',');
                    }
                    sb.append(param);
                    first = true;
                }
            }
            sb.append(']');
            result = sb.toString();
        }
        return result;
    }

    /**
     * Gets the string from the key by locale and class-loader.
     *
     * @param key the key.
     * @param locale the locale.
     * @param classLoader the class loader.
     * @return the string corresponding to the key.
     */
    private static String getKeyString(final Enum key, Locale locale, ClassLoader classLoader) {
        String keyPrefix = key.getClass().getSimpleName();
        ResourceBundle bundle = lookupBundle(key.getClass().getName(), locale, classLoader);
        StringBuilder sb = new StringBuilder();
        sb.append(keyPrefix).append('.').append(key.name());
        String value = null;
        try {
            value = bundle.getString(sb.toString());
        } catch (MissingResourceException ex) {
            // to be removed after migrated all old projects to new standard
            // deprecated - camel case
            String tmp = convertConstantToCamelCase(key.name());
            sb = new StringBuilder();
            sb.append(keyPrefix).append('.').append(tmp);
            value = bundle.getString(sb.toString());
        }
        return value;
    }

    /**
     * Creates the list of parameters for the message.
     *
     * @param arguments the arguments.
     * @return the list of parameters.
     */
    private static Object[] createParameters(Object... arguments) {
        Object[] params = null;
        if (arguments != null && arguments.length > 0) {

            params = new Object[arguments.length];

            for (int i = 0; i < arguments.length; i++) {
                Object item = arguments[i];
                if (item == null) {
                    params[i] = item;
                } else if (item instanceof ResourceList) {
                    StringBuilder sb = new StringBuilder();
                    ResourceList list = (ResourceList) item;

                    boolean first = false;
                    for (Object var : list.getValues()) {
                        if (first) {
                            sb.append(',');
                        }
                        sb.append(var);
                        first = true;
                    }
                    params[i] = sb.toString();
                } else {
                    params[i] = item;
                }
            }
        }
        return params;
    }

    /**
     * Transforms an (enumeration) constant name into a Java property-like String with camel case notation.. Concretely, it
     * transforms the provided name name into lowercase and characters following a single underscore (_) into
     * uppercase again.
     * 

* Example: A constant name of COMPLAINT_NR will be transformed to a property String of * complaintNr. *

* * @deprecated * @param constantName The constant name to be transformed. * @return The resulting String in camel case notation. */ private static String convertConstantToCamelCase(final String constantName) { String property = constantName.replace("__", ".").toLowerCase(); int index = property.indexOf('_'); while (index != -1 && index < property.length() - 1) { String prefix = property.substring(0, index); String character = property.substring(index + 1, index + 2).toUpperCase(); String postfix = property.substring(index + 2); property = prefix + character + postfix; index = property.indexOf('_'); } return property; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy