aboutsummaryrefslogtreecommitdiffstats
path: root/fop-util/src/main/java/org/apache/fop/utils/XMLResourceBundle.java
blob: 747284ec4ada59212cfe22aca92436e06b735a4c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

package org.apache.fop.utils;

import java.io.IOException;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Stack;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamSource;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import org.apache.xmlgraphics.util.QName;

/**
 * This class is a ResourceBundle that loads its contents from XML files instead of properties
 * files (like PropertiesResourceBundle).
 * <p>
 * The XML format for this resource bundle implementation is the following
 * (the same as Apache Cocoon's XMLResourceBundle):
 * <pre>
 * &lt;catalogue xml:lang="en"&gt;
 *   &lt;message key="key1"&gt;Message &lt;br/&gt; Value 1&lt;/message&gt;
 *   &lt;message key="key2"&gt;Message &lt;br/&gt; Value 1&lt;/message&gt;
 *   ...
 * &lt;/catalogue&gt;
 * </pre>
 */
public class XMLResourceBundle extends ResourceBundle {

    //Note: Some code here has been copied and adapted from Apache Harmony!

    private Properties resources = new Properties();

    private Locale locale;

    private static SAXTransformerFactory tFactory
        = (SAXTransformerFactory)SAXTransformerFactory.newInstance();

    /**
     * Creates a resource bundle from an InputStream.
     * @param in the stream to read from
     * @throws IOException if an I/O error occurs
     */
    public XMLResourceBundle(InputStream in) throws IOException {
        try {
            Transformer transformer = tFactory.newTransformer();
            StreamSource src = new StreamSource(in);
            SAXResult res = new SAXResult(new CatalogueHandler());
            transformer.transform(src, res);
        } catch (TransformerException e) {
            throw new IOException("Error while parsing XML resource bundle: " + e.getMessage());
        }
    }

    /**
     * Gets a resource bundle using the specified base name, default locale, and class loader.
     * @param baseName the base name of the resource bundle, a fully qualified class name
     * @param loader the class loader from which to load the resource bundle
     * @return a resource bundle for the given base name and the default locale
     * @throws MissingResourceException if no resource bundle for the specified base name can be
     *                                          found
     * @see java.util.ResourceBundle#getBundle(String)
     */
    public static ResourceBundle getXMLBundle(String baseName, ClassLoader loader)
                throws MissingResourceException {
        return getXMLBundle(baseName, Locale.getDefault(), loader);
    }

    /**
     * Gets a resource bundle using the specified base name, locale, and class loader.
     * @param baseName the base name of the resource bundle, a fully qualified class name
     * @param locale the locale for which a resource bundle is desired
     * @param loader the class loader from which to load the resource bundle
     * @return a resource bundle for the given base name and locale
     * @throws MissingResourceException if no resource bundle for the specified base name can be
     *                                          found
     * @see java.util.ResourceBundle#getBundle(String, Locale, ClassLoader)
     */
    public static ResourceBundle getXMLBundle(String baseName, Locale locale, ClassLoader loader)
                throws MissingResourceException {
        if (loader == null) {
            throw new NullPointerException("loader must not be null");
        }
        if (baseName == null) {
            throw new NullPointerException("baseName must not be null");
        }
        assert locale != null;
        ResourceBundle bundle;
        if (!locale.equals(Locale.getDefault())) {
            bundle = handleGetXMLBundle(baseName, "_" + locale, false, loader);
            if (bundle != null) {
                return bundle;
            }
        }
        bundle = handleGetXMLBundle(baseName, "_" + Locale.getDefault(), true, loader);
        if (bundle != null) {
            return bundle;
        }
        throw new MissingResourceException(
                baseName + " (" + locale + ")", baseName + '_' + locale, null);
    }

    static class MissingBundle extends ResourceBundle {
        public Enumeration getKeys() {
            return null;
        }

        public Object handleGetObject(String name) {
            return null;
        }
    }

    private static final ResourceBundle MISSING = new MissingBundle();
    private static final ResourceBundle MISSINGBASE = new MissingBundle();

    private static Map cache = new java.util.WeakHashMap();
    //<Object, Hashtable<String, ResourceBundle>>

    private static ResourceBundle handleGetXMLBundle(String base, String locale,
            boolean loadBase, final ClassLoader loader) {
        XMLResourceBundle bundle = null;
        String bundleName = base + locale;
        Object cacheKey = loader != null ? (Object) loader : (Object) "null";
        Hashtable loaderCache; //<String, ResourceBundle>
        synchronized (cache) {
            loaderCache = (Hashtable)cache.get(cacheKey);
            if (loaderCache == null) {
                loaderCache = new Hashtable();
                cache.put(cacheKey, loaderCache);
            }
        }
        ResourceBundle result = (ResourceBundle)loaderCache.get(bundleName);
        if (result != null) {
            if (result == MISSINGBASE) {
                return null;
            }
            if (result == MISSING) {
                if (!loadBase) {
                    return null;
                }
                String extension = strip(locale);
                if (extension == null) {
                    return null;
                }
                return handleGetXMLBundle(base, extension, loadBase, loader);
            }
            return result;
        }

        final String fileName = bundleName.replace('.', '/') + ".xml";
        InputStream stream = (InputStream)AccessController
                .doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return loader == null
                            ? ClassLoader.getSystemResourceAsStream(fileName)
                            : loader.getResourceAsStream(fileName);
                    }
                });
        if (stream != null) {
            try {
                try {
                    bundle = new XMLResourceBundle(stream);
                } finally {
                    stream.close();
                }
                bundle.setLocale(locale);
            } catch (IOException e) {
                throw new MissingResourceException(e.getMessage(), base, null);
            }
        }

        String extension = strip(locale);
        if (bundle != null) {
            if (extension != null) {
                ResourceBundle parent = handleGetXMLBundle(base, extension, true,
                        loader);
                if (parent != null) {
                    bundle.setParent(parent);
                }
            }
            loaderCache.put(bundleName, bundle);
            return bundle;
        }

        if (extension != null) {
            ResourceBundle fallback = handleGetXMLBundle(base, extension, loadBase, loader);
            if (fallback != null) {
                loaderCache.put(bundleName, fallback);
                return fallback;
            }
        }
        loaderCache.put(bundleName, loadBase ? MISSINGBASE : MISSING);
        return null;
    }

    private void setLocale(String name) {
        String language = "";
        String country = "";
        String variant = "";
        if (name.length() > 1) {
            int nextIndex = name.indexOf('_', 1);
            if (nextIndex == -1) {
                nextIndex = name.length();
            }
            language = name.substring(1, nextIndex);
            if (nextIndex + 1 < name.length()) {
                int index = nextIndex;
                nextIndex = name.indexOf('_', nextIndex + 1);
                if (nextIndex == -1) {
                    nextIndex = name.length();
                }
                country = name.substring(index + 1, nextIndex);
                if (nextIndex + 1 < name.length()) {
                    variant = name.substring(nextIndex + 1, name.length());
                }
            }
        }
        this.locale = new Locale(language, country, variant);
    }

    private static String strip(String name) {
        int index = name.lastIndexOf('_');
        if (index != -1) {
            return name.substring(0, index);
        }
        return null;
    }

    private Enumeration getLocalKeys() {
        return (Enumeration)resources.propertyNames();
    }

    /** {@inheritDoc} */
    public Locale getLocale() {
        return this.locale;
    }

    /** {@inheritDoc} */
    public Enumeration getKeys() {
        if (parent == null) {
            return getLocalKeys();
        }
        return new Enumeration() {
            private Enumeration local = getLocalKeys();
            private Enumeration pEnum = parent.getKeys();

            private Object nextElement;

            private boolean findNext() {
                if (nextElement != null) {
                    return true;
                }
                while (pEnum.hasMoreElements()) {
                    Object next = pEnum.nextElement();
                    if (!resources.containsKey(next)) {
                        nextElement = next;
                        return true;
                    }
                }
                return false;
            }

            public boolean hasMoreElements() {
                if (local.hasMoreElements()) {
                    return true;
                }
                return findNext();
            }

            public Object nextElement() {
                if (local.hasMoreElements()) {
                    return local.nextElement();
                }
                if (findNext()) {
                    Object result = nextElement;
                    nextElement = null;
                    return result;
                }
                // Cause an exception
                return pEnum.nextElement();
            }
        };
    }

    /** {@inheritDoc} */
    protected Object handleGetObject(String key) {
        if (key == null) {
            throw new NullPointerException("key must not be null");
        }
        return resources.get(key);
    }

    /** {@inheritDoc} */
    public String toString() {
        return "XMLResourceBundle: " + getLocale();
    }

    private class CatalogueHandler extends DefaultHandler {

        private static final String CATALOGUE = "catalogue";
        private static final String MESSAGE = "message";

        private StringBuffer valueBuffer = new StringBuffer();
        private Stack elementStack = new Stack();
        private String currentKey;

        private boolean isOwnNamespace(String uri) {
            return ("".equals(uri));
        }

        private QName getParentElementName() {
            return (QName)elementStack.peek();
        }

        /** {@inheritDoc} */
        public void startElement(String uri, String localName, String qName,
                Attributes atts) throws SAXException {
            super.startElement(uri, localName, qName, atts);
            QName elementName = new QName(uri, qName);
            if (isOwnNamespace(uri)) {
                if (CATALOGUE.equals(localName)) {
                    //nop
                } else if (MESSAGE.equals(localName)) {
                    if (!CATALOGUE.equals(getParentElementName().getLocalName())) {
                        throw new SAXException(MESSAGE + " must be a child of " + CATALOGUE);
                    }
                    this.currentKey = atts.getValue("key");
                } else {
                    throw new SAXException("Invalid element name: " + elementName);
                }
            } else {
                //ignore
            }
            this.valueBuffer.setLength(0);
            elementStack.push(elementName);
        }

        /** {@inheritDoc} */
        public void endElement(String uri, String localName, String qName) throws SAXException {
            super.endElement(uri, localName, qName);
            elementStack.pop();
            if (isOwnNamespace(uri)) {
                if (CATALOGUE.equals(localName)) {
                    //nop
                } else if (MESSAGE.equals(localName)) {
                    if (this.currentKey == null) {
                        throw new SAXException(
                                "current key is null (attribute 'key' might be mistyped)");
                    }
                    resources.put(this.currentKey, this.valueBuffer.toString());
                    this.currentKey = null;
                }
            } else {
                //ignore
            }
            this.valueBuffer.setLength(0);
        }

        /** {@inheritDoc} */
        public void characters(char[] ch, int start, int length) throws SAXException {
            super.characters(ch, start, length);
            valueBuffer.append(ch, start, length);
        }

    }

}