1 17 package org.apache.geronimo.kernel.config.xstream; 18 19 import javax.xml.parsers.DocumentBuilderFactory ; 20 import javax.xml.parsers.DocumentBuilder ; 21 import javax.xml.parsers.ParserConfigurationException ; 22 23 import com.thoughtworks.xstream.converters.Converter; 24 import com.thoughtworks.xstream.converters.MarshallingContext; 25 import com.thoughtworks.xstream.converters.UnmarshallingContext; 26 import com.thoughtworks.xstream.converters.ConversionException; 27 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 28 import com.thoughtworks.xstream.io.HierarchicalStreamReader; 29 import com.thoughtworks.xstream.io.xml.DomReader; 30 import com.thoughtworks.xstream.io.xml.DomWriter; 31 import org.w3c.dom.Document ; 32 import org.w3c.dom.Element ; 33 import org.apache.geronimo.kernel.util.XmlUtil; 34 35 38 public class DomConverter implements Converter { 39 public boolean canConvert(Class clazz) { 40 return Document .class.isAssignableFrom(clazz) || Element .class.isAssignableFrom(clazz); 41 } 42 43 public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) { 44 DomReader reader; 45 if (object instanceof Document ) { 46 Document doc = (Document ) object; 47 reader = new DomReader(doc); 48 } else { 49 Element element = (Element ) object; 50 reader = new DomReader(element); 51 } 52 53 copy(reader, writer); 54 } 55 56 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext unmarshallingContext) { 57 DocumentBuilderFactory documentBuilderFactory = XmlUtil.newDocumentBuilderFactory(); 58 DocumentBuilder documentBuilder = null; 59 try { 60 documentBuilder = documentBuilderFactory.newDocumentBuilder(); 61 } catch (ParserConfigurationException e) { 62 throw new ConversionException("Cannot instantiate " + Document .class.getName(), e); 63 } 64 Document document = documentBuilder.newDocument(); 65 DomWriter writer = new DomWriter(document); 66 67 copy(reader, writer); 68 69 if (Document .class.isAssignableFrom(unmarshallingContext.getRequiredType())) { 70 return document; 71 } else { 72 return document.getDocumentElement(); 73 } 74 } 75 76 public static void copy(HierarchicalStreamReader reader, HierarchicalStreamWriter writer) { 77 writer.startNode(reader.getNodeName()); 78 79 int attributeCount = reader.getAttributeCount(); 81 for (int i = 0; i < attributeCount; i++) { 82 String attributeName = reader.getAttributeName(i); 83 String attributeValue = reader.getAttribute(i); 84 writer.addAttribute(attributeName, attributeValue); 85 } 86 87 while (reader.hasMoreChildren()) { 89 reader.moveDown(); 90 copy(reader, writer); 91 reader.moveUp(); 92 } 93 94 String value = reader.getValue(); 96 if (value != null && value.trim().length() > 0) { 97 writer.setValue(value); 98 } 99 100 writer.endNode(); 101 } 102 } 103 | Popular Tags |