1 15 package org.apache.hivemind.lib.groovy; 16 17 import java.util.HashMap ; 18 import java.util.Map ; 19 20 import groovy.xml.SAXBuilder; 21 22 import org.xml.sax.Attributes ; 23 import org.xml.sax.ContentHandler ; 24 import org.xml.sax.Locator ; 25 import org.xml.sax.helpers.AttributesImpl ; 26 27 41 public class HiveMindBuilder extends SAXBuilder 42 { 43 public static final Locator GROOVY_LOCATOR = new GroovyLocator(); 44 45 private static final Map CAMEL_TO_HYPHEN_MAP = new HashMap (); 46 47 public HiveMindBuilder(ContentHandler parser) 48 { 49 super(parser); 50 51 parser.setDocumentLocator(GROOVY_LOCATOR); 52 } 53 54 protected void nodeCompleted(Object parent, Object node) 55 { 56 super.nodeCompleted(parent, getHyphenatedName(node.toString())); 57 } 58 59 protected void doStartElement(Object name, Attributes attributes) 60 { 61 super.doStartElement( 62 getHyphenatedName(name.toString()), 63 getHyphenatedAttributes(attributes)); 64 } 65 66 private String getHyphenatedName(String name) 67 { 68 String hyphenatedName = (String ) CAMEL_TO_HYPHEN_MAP.get(name); 69 70 if (hyphenatedName == null) 71 { 72 char[] chars = name.toCharArray(); 73 74 StringBuffer hyphenated = new StringBuffer (); 75 76 for (int i = 0; i < name.length(); i++) 77 { 78 if (Character.isUpperCase(chars[i])) 79 hyphenated.append('-').append(Character.toLowerCase(chars[i])); 80 else 81 hyphenated.append(chars[i]); 82 } 83 84 hyphenatedName = hyphenated.toString(); 85 86 CAMEL_TO_HYPHEN_MAP.put(name, hyphenatedName); 87 } 88 89 return hyphenatedName; 90 } 91 92 private Attributes getHyphenatedAttributes(Attributes attributes) 93 { 94 AttributesImpl result = (AttributesImpl ) attributes; 95 96 for (int i = 0; i < result.getLength(); i++) 97 { 98 result.setLocalName(i, getHyphenatedName(result.getLocalName(i))); 99 } 100 101 return result; 102 } 103 104 private static class GroovyLocator implements Locator 105 { 106 public String getPublicId() 107 { 108 return null; 109 } 110 111 public String getSystemId() 112 { 113 return null; 114 } 115 116 public int getLineNumber() 117 { 118 try 119 { 120 throw new Throwable (); 121 } 122 catch (Throwable t) 123 { 124 StackTraceElement [] trace = t.getStackTrace(); 125 126 for (int i = 0; i < trace.length; i++) 127 if (trace[i].getFileName().endsWith(".groovy")) 128 return trace[i].getLineNumber(); 129 } 130 131 return -1; 132 } 133 134 public int getColumnNumber() 135 { 136 return -1; 137 } 138 } 139 } | Popular Tags |