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