01: /*
02:
03: This software is OSI Certified Open Source Software.
04: OSI Certified is a certification mark of the Open Source Initiative.
05:
06: The license (Mozilla version 1.0) can be read at the MMBase site.
07: See http://www.MMBase.org/license
08:
09: */
10: package org.mmbase.util.transformers;
11:
12: import java.util.*;
13: import java.io.*;
14:
15: import org.mmbase.util.logging.*;
16: import org.mmbase.util.functions.*;
17:
18: /**
19: * Factories new chartransformer based on {@link java.util.ResourceBundle}. The result transformers
20: * are based on {@link ChunkedTransformer}, so using the 'mode' argument it can be controlled what
21: * excactly must correspond to the resource bundle keys (e.g. words, lines, or the entire
22: * string). Defaults to words.
23: *
24: * @author Michiel Meeuwissen
25: * @since MMBase-1.8
26: * @version $Id: ResourceBundleReplacerFactory.java,v 1.7 2008/02/03 17:33:56 nklasens Exp $
27: */
28:
29: public class ResourceBundleReplacerFactory implements
30: ParameterizedTransformerFactory<CharTransformer> {
31: private static final Logger log = Logging
32: .getLoggerInstance(ResourceBundleReplacerFactory.class);
33:
34: protected static final Parameter[] PARAMS = new Parameter[] {
35: new Parameter<String>("basename", String.class, true),
36: new Parameter<String>("mode", String.class),
37: Parameter.LOCALE };
38:
39: public Parameters createParameters() {
40: return new Parameters(PARAMS);
41: }
42:
43: /**
44: * Creates a parameterized transformer.
45: */
46: public CharTransformer createTransformer(final Parameters parameters) {
47: parameters.checkRequiredParameters();
48: if (log.isDebugEnabled()) {
49: log.debug("Creating transformer, with " + parameters);
50: }
51: String baseName = (String) parameters.get("basename");
52: final ResourceBundle bundle = ResourceBundle.getBundle(
53: baseName, parameters.get(Parameter.LOCALE));
54: return new ResourceBundleReplacer(1, bundle, baseName);
55: }
56:
57: }
58:
59: class ResourceBundleReplacer extends ChunkedTransformer {
60: private final ResourceBundle bundle;
61: private final String name;
62:
63: ResourceBundleReplacer(int mode, ResourceBundle bundle, String name) {
64: super (mode);
65: this .bundle = bundle;
66: this .name = name;
67: }
68:
69: protected boolean replace(final String word, final Writer w,
70: final Status status) throws IOException {
71: if (replaceFirstAll && status.used.contains(word)) {
72: w.write(word);
73: return false;
74: }
75: try {
76: w.write("" + bundle.getObject(word));
77: status.replaced++;
78: if (replaceFirstAll)
79: status.used.add(word);
80: return true;
81: } catch (MissingResourceException mre) {
82: w.write(word);
83: return false;
84: }
85: }
86:
87: protected String base() {
88: return name;
89: }
90: };
|