001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    
018    package org.apache.commons.resources.impl;
019    
020    import java.io.FileNotFoundException;
021    import java.io.IOException;
022    import java.io.InputStream;
023    import java.net.URL;
024    import java.util.Locale;
025    import java.util.Map;
026    import java.util.Properties;
027    
028    import org.apache.commons.logging.Log;
029    import org.apache.commons.logging.LogFactory;
030    
031    /**
032     * <p>Concrete implementation of
033     * {@link org.apache.commons.resources.Resources} that wraps a family
034     * (one per <code>Locale</code>) of properties files that share a base URL
035     * and have name suffixes reflecting the <code>Locale</code> for which
036     * the document's messages apply.  Resources are looked up in a hierarchy
037     * of properties files in a manner identical to that performed by
038     * <code>java.util.ResourceBundle.getBundle().</code>.</p>
039     *
040     * <p>The base URL passed to our constructor must contain the base name
041     * of the properties file family.
042     * For example, if the configuration URL is passed as
043     * <code>http://localhost/foo/Bar</code>, the resources for the
044     * <code>en_US</code> Locale would be stored under URL
045     * <code>http://localhost/foo/Bar_en_US.properties</code>, and the default
046     * resources would be stored in
047     * <code>http://localhost/foo/Bar.properties</code>.</p>
048     */
049    public class PropertyResources extends CollectionResourcesBase {
050    
051        /**
052         * <p>The <code>Log</code> instance for this class.</p>
053         */
054        private transient Log log = LogFactory.getLog(PropertyResources.class);
055    
056        // ----------------------------------------------------------- Constructors
057    
058        /**
059         * <p>Create a new
060         * {@link org.apache.commons.resources.Resources} instance with the specified
061         * logical name and base resource URL.</p>
062         *
063         * @param name Logical name of the new instance
064         * @param base Base URL of the family of properties files that contain
065         *  the resource keys and values
066         */
067        public PropertyResources(String name, String base) {
068            super(name, base);
069        }
070    
071    
072        // ------------------------------------------------------ Protected Methods
073    
074    
075        /**
076         * <p>Return a <code>Map</code> containing the name-value mappings for
077         * the specified base URL and requested <code>Locale</code>, if there
078         * are any.  If there are no defined mappings for the specified
079         * <code>Locale</code>, return an empty <code>Map</code> instead.</p>
080         *
081         * <p>Concrete subclasses must override this method to perform the
082         * appropriate lookup.  A typical implementation will construct an
083         * absolute URL based on the specified base URL and <code>Locale</code>,
084         * retrieve the specified resource file (if any), and parse it into
085         * a <code>Map</code> structure.</p>
086         *
087         * <p>Caching of previously retrieved <code>Map</code>s (if any) should
088         * be performed by callers of this method.  Therefore, this method should
089         * always attempt to retrieve the specified resource and load it
090         * appropriately.</p>
091         *
092         * @param baseUrl Base URL of the resource files for this
093         * {@link org.apache.commons.resources.Resources} instance
094         * @param locale <code>Locale</code> for which name-value mappings
095         *  are requested
096         * @return A name-value Map for the specified URL and locale.
097         */
098        protected Map getLocaleMap(String baseUrl, Locale locale) {
099    
100            if (getLog().isDebugEnabled()) {
101                getLog().debug("Loading locale '" + locale + "' resources from base '" +
102                        baseUrl + "'");
103            }
104    
105            Properties props = new Properties();
106            String name = baseUrl + getLocaleSuffix(locale) + ".properties";
107            InputStream stream = null;
108    
109            try {
110    
111                // Open an input stream to the URL for this locale (if any)
112                if (getLog().isTraceEnabled()) {
113                    getLog().trace("Absolute URL is '" + name + "'");
114                }
115                URL url = new URL(name);
116                stream = url.openStream();
117    
118                // Parse the input stream and populate the name-value mappings map
119                if (getLog().isTraceEnabled()) {
120                    getLog().trace("Parsing input resource");
121                }
122                props.load(stream);
123    
124            } catch (FileNotFoundException e) {
125    
126                // Log and swallow this exception
127                if (getLog().isDebugEnabled()) {
128                    getLog().debug("No resources for locale '" + locale +
129                              "' from base '" + baseUrl + "'");
130                }
131                props.clear();
132    
133            } catch (IOException e) {
134    
135                getLog().warn("IOException loading locale '" + locale +
136                         "' from base '" + baseUrl + "'", e);
137                props.clear();
138    
139            } finally {
140    
141                // Close the input stream that was opened earlier
142                if (stream != null) {
143                    try {
144                        stream.close();
145                    } catch (IOException e) {
146                        getLog().error("Error closing stream.", e);
147                    }
148                    stream = null;
149                }
150    
151            }
152    
153            // Return the populated (or empty) properties
154            return (props);
155    
156        }
157    
158    
159        /**
160         * Accessor method for Log instance.
161         *
162         * The Log instance variable is transient and
163         * accessing it through this method ensures it
164         * is re-initialized when this instance is
165         * de-serialized.
166         *
167         * @return The Log instance.
168         */
169        private Log getLog() {
170            if (log == null) {
171                log =  LogFactory.getLog(PropertyResources.class);
172            }
173            return log;
174        }
175    
176    }