1 13 package com.tonbeller.wcf.utils; 14 15 import java.util.MissingResourceException ; 16 import java.util.ResourceBundle ; 17 18 import org.w3c.dom.Attr ; 19 import org.w3c.dom.Element ; 20 import org.w3c.dom.NamedNodeMap ; 21 import org.w3c.dom.Node ; 22 import org.w3c.dom.NodeList ; 23 import org.w3c.dom.Text ; 24 25 26 34 public abstract class I18nReplacer { 35 36 public static final String PREFIX = "fmt:"; 37 38 public static I18nReplacer instance(final ResourceBundle resb) { 39 return new I18nReplacer() { 40 protected String internalReplace(String key) { 41 try { 42 return resb.getString(key); 43 } catch (MissingResourceException e) { 44 return "???" + key + "???"; 45 } 46 } 47 48 }; 49 } 50 51 public static I18nReplacer instance(final com.tonbeller.tbutils.res.Resources res) { 52 return new I18nReplacer() { 53 protected String internalReplace(String key) { 54 try { 55 return res.getString(key); 56 } catch (MissingResourceException e) { 57 return "???" + key + "???"; 58 } 59 } 60 }; 61 } 62 63 protected abstract String internalReplace(String key); 64 65 public String replace(String value) { 66 if (value.startsWith(PREFIX)) { 67 return internalReplace(value.substring(4)); 68 } 69 return value; 70 } 71 72 public void replaceAll(Node root) { 73 if (root.getNodeType() == Node.ELEMENT_NODE) { 74 Element e = (Element ) root; 75 NamedNodeMap atts = e.getAttributes(); 76 final int N = atts.getLength(); 77 for (int i = 0; i < N; i++) { 78 Attr attr = (Attr ) atts.item(i); 79 String value = attr.getValue(); 80 if (value.startsWith(PREFIX)) { 81 value = internalReplace(value.substring(4)); 82 attr.setValue(value); 83 } 84 } 85 } 86 if (root.getNodeType() == Node.TEXT_NODE) { 87 Text text = (Text ) root; 88 String data = text.getData(); 89 if (data.startsWith(PREFIX)) { 90 data = internalReplace(data.substring(4)); 91 text.setData(data); 92 } 93 } 94 NodeList list = root.getChildNodes(); 95 int N = list.getLength(); 96 for (int i = 0; i < N; i++) 97 replaceAll(list.item(i)); 98 } 99 } 100 | Popular Tags |