001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (C) Alkacon Software (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.i18n;
029
030import org.opencms.cache.CmsVfsMemoryObjectCache;
031import org.opencms.file.CmsObject;
032import org.opencms.main.CmsLog;
033import org.opencms.main.OpenCms;
034import org.opencms.xml.content.CmsVfsBundleLoaderXml;
035
036import java.util.ArrayList;
037import java.util.Collections;
038import java.util.Enumeration;
039import java.util.Iterator;
040import java.util.List;
041import java.util.Locale;
042import java.util.Map;
043import java.util.ResourceBundle;
044import java.util.Set;
045
046import org.apache.commons.logging.Log;
047
048import com.google.common.collect.Iterators;
049
050/**
051 * Resource bundle which loads its data from a VFS resource.<p>
052 */
053public class CmsVfsResourceBundle extends ResourceBundle implements I_CmsResourceBundle {
054
055    /**
056     * Implementors of this interface are responsible for actually loading the data from the VFS.<p>
057     */
058    public interface I_Loader {
059
060        /**
061         * Loads the data from the VFS.<p>
062         *
063         * @param cms the CMS context to use
064         * @param params the VFS bundle parameters
065         *
066         * @return the message bundle data
067         *
068         * @throws Exception if something goes wrong
069         */
070        Map<Locale, Map<String, String>> loadData(CmsObject cms, CmsVfsBundleParameters params) throws Exception;
071    }
072
073    /** Name constant for the 'properties' vfs bundle type. */
074    public static final String TYPE_PROPERTIES = "properties";
075
076    /** Name constant for the 'xml content' vfs bundle type. */
077    public static final String TYPE_XML = "xml";
078
079    /** The CMS context to use. */
080    protected static CmsObject m_cms;
081
082    /** The logger instance for this class. */
083    private static final Log LOG = CmsLog.getLog(CmsVfsResourceBundle.class);
084
085    /** The cache instance used for caching the resource bundle data. */
086    private static CmsVfsMemoryObjectCache m_cache = new CmsVfsMemoryObjectCache();
087
088    /** The bundle loader instance to use. */
089    protected I_Loader m_loader;
090
091    /** The VFS bundle parameters. */
092    protected CmsVfsBundleParameters m_parameters;
093
094    /**
095     * Creates a new VFS bundle instance.<p>
096     *
097     * @param params the VFS bundle parameters
098     */
099    public CmsVfsResourceBundle(CmsVfsBundleParameters params) {
100
101        m_parameters = params;
102        m_loader = initLoader(params.getType());
103    }
104
105    /**
106     * Sets the CMS context used by this class.<p>
107     *
108     * This can be never called more than once, and is usually called on startup.<p>
109     *
110     * @param cms the CMS context to set
111     */
112    public static void setCmsObject(CmsObject cms) {
113
114        m_cms = cms;
115    }
116
117    /**
118     * Initializes the type given the string value of the type.<p>
119     *
120     * @param type a string representation of the type
121     *
122     * @return the actual type object
123     */
124    private static I_Loader initLoader(String type) {
125
126        if (TYPE_PROPERTIES.equals(type)) {
127            return new CmsVfsBundleLoaderProperties();
128        } else if (TYPE_XML.equals(type)) {
129            return new CmsVfsBundleLoaderXml();
130        } else {
131            return new CmsVfsBundleLoaderXml();
132        }
133    }
134
135    /**
136     * @see org.opencms.i18n.I_CmsResourceBundle#getClone()
137     */
138    public CmsVfsResourceBundle getClone() {
139
140        return new CmsVfsResourceBundle(m_parameters);
141    }
142
143    /**
144     * @see java.util.ResourceBundle#getKeys()
145     */
146    @Override
147    public Enumeration<String> getKeys() {
148
149        Iterator<String> myKeyIter = handleKeySet().iterator();
150        Iterator<String> result = myKeyIter;
151        if (parent != null) {
152            Iterator<String> parentKeyIter = Iterators.forEnumeration(parent.getKeys());
153            result = Iterators.concat(myKeyIter, parentKeyIter);
154        }
155        return Iterators.asEnumeration(result);
156    }
157
158    /**
159     * @see java.util.ResourceBundle#getLocale()
160     */
161    @Override
162    public Locale getLocale() {
163
164        return m_parameters.getLocale();
165    }
166
167    /**
168     * @see org.opencms.i18n.I_CmsResourceBundle#setLocale(java.util.Locale)
169     */
170    public void setLocale(Locale locale) {
171
172        // ignore
173    }
174
175    /**
176     * @see java.util.ResourceBundle#setParent(java.util.ResourceBundle)
177     */
178    @Override
179    public void setParent(ResourceBundle p) {
180
181        super.setParent(p);
182    }
183
184    /**
185     * Returns the path of the file to read the message data from.<p>
186     *
187     * @return the root path of the file containing the message data
188     */
189    protected String getFilePath() {
190
191        return m_parameters.getBasePath();
192    }
193
194    /**
195     * @see java.util.ResourceBundle#handleGetObject(java.lang.String)
196     */
197    @Override
198    protected Object handleGetObject(String key) {
199
200        Map<String, String> messages = getMessagesForLocale();
201        return messages.get(key);
202    }
203
204    /**
205     * @see java.util.ResourceBundle#handleKeySet()
206     */
207    @Override
208    protected Set<String> handleKeySet() {
209
210        Map<String, String> messages = getMessagesForLocale();
211        return messages.keySet();
212    }
213
214    /**
215     * Actually loads the message data from the VFS.<p>
216     *
217     * @return a map from locales to message maps
218     *
219     * @throws Exception if something goes wrong
220     */
221
222    /**
223     * Gets the (possibly already cached) message data.<p>
224     *
225     * @return the message data
226     */
227    private Map<Locale, Map<String, String>> getData() {
228
229        @SuppressWarnings("unchecked")
230        Map<Locale, Map<String, String>> result = (Map<Locale, Map<String, String>>)m_cache.getCachedObject(
231            m_cms,
232            getFilePath());
233        if (result == null) {
234            try {
235                result = m_loader.loadData(m_cms, m_parameters);
236                m_cache.putCachedObject(m_cms, getFilePath(), result);
237            } catch (Exception e) {
238                LOG.error(e.getLocalizedMessage(), e);
239            }
240        }
241        return result;
242    }
243
244    /**
245     * Returns the message data for this bundle's locale.<p>
246     *
247     * @return the message data for this bundle's locale
248     */
249    private Map<String, String> getMessagesForLocale() {
250
251        Map<Locale, Map<String, String>> data = getData();
252        if (data == null) {
253            return Collections.emptyMap();
254        }
255        List<Locale> available = new ArrayList<Locale>(data.keySet());
256        Locale bestMatchingLocale = OpenCms.getLocaleManager().getBestMatchingLocale(
257            getLocale(),
258            OpenCms.getLocaleManager().getDefaultLocales(),
259            available);
260        Map<String, String> bundleForLocale = data.get(bestMatchingLocale);
261        if (bundleForLocale == null) {
262            return Collections.emptyMap();
263        } else {
264            return Collections.unmodifiableMap(bundleForLocale);
265        }
266    }
267}