View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.resources.impl;
19  
20  import java.io.FileNotFoundException;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.util.HashMap;
24  import java.util.Locale;
25  import java.util.Map;
26  
27  import javax.servlet.ServletContext;
28  
29  import org.apache.commons.digester.Digester;
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.xml.sax.SAXException;
33  
34  /**
35   * <p>Concrete implementation of
36   * {@link org.apache.commons.resources.Resources} that wraps a family
37   * (one per <code>Locale</code> of XML documents that share a base
38   * context-relative path for servlet context resources, and have
39   * name suffixes reflecting the <code>Locale</code> for which
40   * the document's messages apply.  Resources are looked up in a hierarchy
41   * of properties files in a manner identical to that performed by
42   * <code>java.util.ResourceBundle.getBundle().</code>.</p>
43   *
44   * <p>The base resource path passed to our constructor must contain the
45   * context-relative base name of the properties file family.
46   * For example, if the base path is passed as
47   * <code>http://localhost/foo/Bar</code>, the resources for the
48   * <code>en_US</code> Locale would be stored under URL
49   * <code>http://localhost/foo/Bar_en_US.xml</code>, and the default
50   * resources would be stored in
51   * <code>http://localhost/foo/Bar.xml</code>.</p>
52   */
53  public class WebappXMLResources extends CollectionResourcesBase {
54  
55      /**
56       * <p>The <code>Log</code> instance for this class.</p>
57       */
58      private transient Log log = LogFactory.getLog(WebappXMLResources.class);
59  
60      /**
61       * <p>Create a new {@link org.apache.commons.resources.Resources} instance with the specified
62       * logical name and base resource URL.</p>
63       *
64       * @param name Logical name of the new instance
65       * @param base Base URL of the family of properties files that contain
66       *  the resource keys and values
67       * @param servletContext the <code>ServletContext</code> instance
68       *  to use for resolving resource references
69       */
70      public WebappXMLResources(String name, String base,
71                                     ServletContext servletContext) {
72  
73          super(name, base);
74          this.servletContext = servletContext;
75  
76      }
77  
78  
79      // ----------------------------------------------------- Instance Variables
80  
81      /**
82       * <p>The <code>ServletContext</code> instance for resolving
83       * our resources references.</p>
84       */
85      private ServletContext servletContext = null;
86  
87  
88      // ------------------------------------------------------ Protected Methods
89  
90  
91      /**
92       * <p>Return a <code>Map</code> containing the name-value mappings for
93       * the specified base URL and requested <code>Locale</code>, if there
94       * are any.  If there are no defined mappings for the specified
95       * <code>Locale</code>, return an empty <code>Map</code> instead.</p>
96       *
97       * <p>Concrete subclasses must override this method to perform the
98       * appropriate lookup.  A typical implementation will construct an
99       * 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 }