001/* 
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     <a href="mailto:stan@nuxeo.com">Sun Seng David TAN</a>
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.platform.rendering.fm.i18n;
016
017import java.util.Enumeration;
018import java.util.HashMap;
019import java.util.Locale;
020import java.util.Map;
021import java.util.ResourceBundle;
022
023/**
024 * A resource bundle for Nuxeo Rendering that holds a map of locals, allows developers to change it from its api
025 * (setLocale) and that will delegate its method to the correct resource bundle according to the local chosen.
026 *
027 * @author <a href="mailto:stan@nuxeo.com">Sun Seng David TAN</a>
028 */
029public class ResourceComposite extends ResourceBundle {
030
031    final Map<Locale, ResourceBundle> map = new HashMap<Locale, ResourceBundle>();
032
033    final ClassLoader cl;
034
035    ResourceBundle current;
036
037    public ResourceComposite() {
038        cl = null;
039    }
040
041    public ResourceComposite(ClassLoader cl) {
042        this.cl = cl;
043    }
044
045    /**
046     * Set the locale to be used.
047     *
048     * @param locale
049     */
050    public void setLocale(Locale locale) {
051        current = map.get(locale);
052        if (current == null) {
053            if (cl == null) {
054                current = ResourceBundle.getBundle("messages", locale);
055            } else {
056                current = ResourceBundle.getBundle("messages", locale, cl);
057            }
058            map.put(locale, current);
059        }
060    }
061
062    @Override
063    public Enumeration<String> getKeys() {
064        if (current == null) {
065            setLocale(Locale.getDefault());
066        }
067        return current.getKeys();
068    }
069
070    @Override
071    protected Object handleGetObject(String key) {
072        if (current == null) {
073            setLocale(Locale.getDefault());
074        }
075        return current.getObject(key);
076    }
077
078    /**
079     * Delegates getString using the resource bundle corresponding to the local (create one if it doesn't exist).
080     *
081     * @param key
082     * @param locale
083     * @return
084     */
085    public String getString(String key, Locale locale) {
086        ResourceBundle bundle = map.get(locale);
087        if (bundle == null) {
088            if (cl == null) {
089                bundle = ResourceBundle.getBundle("messages", locale);
090            } else {
091                bundle = ResourceBundle.getBundle("messages", locale, cl);
092            }
093            map.put(locale, bundle);
094        }
095        return bundle.getString(key);
096    }
097
098}