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.net.URL;
24  import java.util.HashMap;
25  import java.util.Locale;
26  import java.util.Map;
27  
28  import org.apache.commons.digester.Digester;
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.xml.sax.SAXException;
32  
33  /**
34   * <p>Concrete implementation of
35   * {@link org.apache.commons.resources.Resources} that wraps a family
36   * (one per <code>Locale</code> of XML documents that share a base URL
37   * and have name suffixes reflecting the <code>Locale</code> for which
38   * the document's messages apply.  Resources are looked up in a hierarchy
39   * XML documents in a manner identical to that performed by
40   * <code>java.util.ResourceBundle.getBundle().</code>.</p>
41   *
42   * <p>The base URL passed to our constructor must contain the base name
43   * of the XML document family.
44   * For example, if the configuration URL is passed as
45   * <code>http://localhost/foo/Bar</code>, the resources for the
46   * <code>en_US</code> Locale would be stored under URL
47   * <code>http://localhost/foo/Bar_en_US.xml</code>, and the default
48   * resources would be stored in
49   * <code>http://localhost/foo/Bar.xml</code>.</p>
50   *
51   * <p>The required structure of the XML documents is very simple:</p>
52   * <ul>
53   * <li>The top level element must be <code>&lt;resources&gt;</code>.</li>
54   * <li>Each name-value pair is represented by a nested
55   *     <code>&lt;resource&gt;</code> element.</li>
56   * <li>For each <code>&lt;resource&gt;</code> element, the <code>id</code>
57   *     attribute contains the resource key, and the body contains a
58   *     string representation of the value.</li>
59   * </ul>
60   */
61  public class XMLResources extends CollectionResourcesBase {
62  
63      /**
64       * <p>The <code>Log</code> instance for this class.</p>
65       */
66      private transient Log log = LogFactory.getLog(XMLResources.class);
67  
68      // ----------------------------------------------------------- Constructors
69  
70  
71      /**
72       * <p>Create a new {@link org.apache.commons.resources.Resources} instance with the specified
73       * logical name and base resource URL.</p>
74       *
75       * @param name Logical name of the new instance
76       * @param base Base URL of the family of properties files that contain
77       *  the resource keys and values
78       */
79      public XMLResources(String name, String base) {
80          super(name, base);
81      }
82  
83  
84      // ------------------------------------------------------ Protected Methods
85  
86  
87      /**
88       * <p>Return a <code>Map</code> containing the name-value mappings for
89       * the specified base URL and requested <code>Locale</code>, if there
90       * are any.  If there are no defined mappings for the specified
91       * <code>Locale</code>, return an empty <code>Map</code> instead.</p>
92       *
93       * <p>Concrete subclasses must override this method to perform the
94       * appropriate lookup.  A typical implementation will construct an
95       * absolute URL based on the specified base URL and <code>Locale</code>,
96       * retrieve the specified resource file (if any), and parse it into
97       * a <code>Map</code> structure.</p>
98       *
99       * <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 }