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.HashMap;
025    import java.util.Locale;
026    import java.util.Map;
027    
028    import org.apache.commons.digester.Digester;
029    import org.apache.commons.logging.Log;
030    import org.apache.commons.logging.LogFactory;
031    import org.xml.sax.SAXException;
032    
033    /**
034     * <p>Concrete implementation of
035     * {@link org.apache.commons.resources.Resources} that wraps a family
036     * (one per <code>Locale</code> of XML documents that share a base URL
037     * and have name suffixes reflecting the <code>Locale</code> for which
038     * the document's messages apply.  Resources are looked up in a hierarchy
039     * XML documents in a manner identical to that performed by
040     * <code>java.util.ResourceBundle.getBundle().</code>.</p>
041     *
042     * <p>The base URL passed to our constructor must contain the base name
043     * of the XML document family.
044     * For example, if the configuration URL is passed as
045     * <code>http://localhost/foo/Bar</code>, the resources for the
046     * <code>en_US</code> Locale would be stored under URL
047     * <code>http://localhost/foo/Bar_en_US.xml</code>, and the default
048     * resources would be stored in
049     * <code>http://localhost/foo/Bar.xml</code>.</p>
050     *
051     * <p>The required structure of the XML documents is very simple:</p>
052     * <ul>
053     * <li>The top level element must be <code>&lt;resources&gt;</code>.</li>
054     * <li>Each name-value pair is represented by a nested
055     *     <code>&lt;resource&gt;</code> element.</li>
056     * <li>For each <code>&lt;resource&gt;</code> element, the <code>id</code>
057     *     attribute contains the resource key, and the body contains a
058     *     string representation of the value.</li>
059     * </ul>
060     */
061    public class XMLResources extends CollectionResourcesBase {
062    
063        /**
064         * <p>The <code>Log</code> instance for this class.</p>
065         */
066        private transient Log log = LogFactory.getLog(XMLResources.class);
067    
068        // ----------------------------------------------------------- Constructors
069    
070    
071        /**
072         * <p>Create a new {@link org.apache.commons.resources.Resources} instance with the specified
073         * logical name and base resource URL.</p>
074         *
075         * @param name Logical name of the new instance
076         * @param base Base URL of the family of properties files that contain
077         *  the resource keys and values
078         */
079        public XMLResources(String name, String base) {
080            super(name, base);
081        }
082    
083    
084        // ------------------------------------------------------ Protected Methods
085    
086    
087        /**
088         * <p>Return a <code>Map</code> containing the name-value mappings for
089         * the specified base URL and requested <code>Locale</code>, if there
090         * are any.  If there are no defined mappings for the specified
091         * <code>Locale</code>, return an empty <code>Map</code> instead.</p>
092         *
093         * <p>Concrete subclasses must override this method to perform the
094         * appropriate lookup.  A typical implementation will construct an
095         * absolute URL based on the specified base URL and <code>Locale</code>,
096         * retrieve the specified resource file (if any), and parse it into
097         * a <code>Map</code> structure.</p>
098         *
099         * <p>Caching of previously retrieved <code>Map</code>s (if any) should
100         * be performed by callers of this method.  Therefore, this method should
101         * always attempt to retrieve the specified resource and load it
102         * appropriately.</p>
103         *
104         * @param baseUrl Base URL of the resource files for this {@link org.apache.commons.resources.Resources}
105         *  instance
106         * @param locale <code>Locale</code> for which name-value mappings
107         *  are requested
108         * @return A name-value Map for the specified URL and locale.
109         */
110        protected Map getLocaleMap(String baseUrl, Locale locale) {
111    
112            if (getLog().isDebugEnabled()) {
113                getLog().debug("Loading locale '" + locale + "' resources from base '" +
114                        baseUrl + "'");
115            }
116    
117            Map map = new HashMap();
118            String name = baseUrl + getLocaleSuffix(locale) + ".xml";
119            InputStream stream = null;
120    
121            try {
122    
123                // Open an input stream to the URL for this locale (if any)
124                if (getLog().isTraceEnabled()) {
125                    getLog().trace("Absolute URL is '" + name + "'");
126                }
127                URL url = new URL(name);
128                stream = url.openStream();
129    
130                // Create and configure a new Digester instance
131                if (getLog().isTraceEnabled()) {
132                    getLog().trace("Creating Digester instance");
133                }
134                Digester digester = new Digester();
135                digester.setNamespaceAware(false);
136                digester.setValidating(false);
137                digester.push(map);
138                digester.addCallMethod("resources/resource", "put", 2,
139                                       new String[] { "java.lang.Object",
140                                                      "java.lang.Object" });
141                digester.addCallParam("resources/resource", 0, "id");
142                digester.addCallParam("resources/resource", 1);
143    
144                // Parse the input stream and populate the name-value mappings map
145                if (getLog().isTraceEnabled()) {
146                    getLog().trace("Parsing input resource");
147                }
148                digester.parse(stream);
149    
150            } catch (FileNotFoundException e) {
151    
152                // Log and swallow this exception
153                if (getLog().isDebugEnabled()) {
154                    getLog().debug("No resources for locale '" + locale +
155                              "' from base '" + baseUrl + "'");
156                }
157                map.clear();
158    
159            } catch (IOException e) {
160    
161                // Log and swallow this exception
162                getLog().warn("IOException loading locale '" + locale +
163                         "' from base '" + baseUrl + "'", e);
164                map.clear();
165    
166            } catch (SAXException e) {
167    
168                // Log and swallow this exception
169                getLog().warn("SAXException loading locale '" + locale +
170                         "' from base '" + baseUrl + "'", e);
171                map.clear();
172    
173            } finally {
174    
175                // Close the input stream that was opened earlier
176                if (stream != null) {
177                    try {
178                        stream.close();
179                    } catch (IOException e) {
180                        getLog().error("Error closing stream.", e);
181                    }
182                    stream = null;
183                }
184    
185            }
186    
187            // Return the populated (or empty) map
188            return (map);
189    
190        }
191    
192        /**
193         * Accessor method for Log instance.
194         *
195         * The Log instance variable is transient and
196         * accessing it through this method ensures it
197         * is re-initialized when this instance is
198         * de-serialized.
199         *
200         * @return The Log instance.
201         */
202        private Log getLog() {
203            if (log == null) {
204                log =  LogFactory.getLog(XMLResources.class);
205            }
206            return log;
207        }
208    
209    }