1 16 package org.apache.cocoon.transformation.helpers; 17 18 import java.util.Map ; 19 import java.util.StringTokenizer ; 20 21 import org.apache.avalon.framework.configuration.SAXConfigurationHandler; 22 import org.xml.sax.Attributes ; 23 import org.xml.sax.SAXException ; 24 import org.xml.sax.helpers.AttributesImpl ; 25 26 34 public class InterpolatingConfigurationHandler extends SAXConfigurationHandler { 35 final private Map vars; 36 final private String location; 37 38 41 public InterpolatingConfigurationHandler(Map vars) { 42 this.vars = vars; 43 this.location = "Unknown"; 44 } 45 46 50 public InterpolatingConfigurationHandler(Map vars, String location) { 51 this.vars = vars; 52 this.location = location; 53 } 54 55 56 public void startElement(String uri, String localName, String qName, Attributes attr) throws SAXException { 57 AttributesImpl newAttr = new AttributesImpl (attr); 58 for (int i=0; i<attr.getLength(); i++) { 59 newAttr.setValue(i, interp(attr.getValue(i))); 60 } 61 super.startElement(uri, localName, qName, newAttr); 62 } 63 64 65 public void characters( final char[] ch, int start, int len ) 66 throws SAXException 67 { 68 StringBuffer buf = new StringBuffer (); 69 if (start!=0) buf.append(ch, 0, start-1); 70 String newVal = interp(new String (ch,start, len)); 71 buf.append(newVal); 72 buf.append(ch, start+len, ch.length-(start+len)); 73 super.characters(buf.toString().toCharArray(), start, newVal.length()); 74 } 75 76 protected String getLocationString() { 77 return this.location; 78 } 79 80 81 88 private String interp(String str) { 89 StringBuffer buf = new StringBuffer (str.length()*2); 90 StringTokenizer tok = new StringTokenizer (str, "{}", true); 91 int state = 0; while (tok.hasMoreTokens()) { 93 String token = tok.nextToken(); 94 if (state == 0 && "{".equals(token)) { 95 state = 1; 96 } else if (state == 1 && "}".equals(token)) { 97 state = 0; 98 } else if (state == 0) { 99 buf.append(token); 100 } else if (state == 1) { 101 String val = (String )vars.get(token); 103 if (val == null) { 104 buf.append("{").append(token).append("}"); 105 } else{ buf.append(val); } 106 } 107 } 108 return buf.toString(); 109 } 110 111 } 112 | Popular Tags |