1 16 package org.directwebremoting.convert; 17 18 import java.io.StringReader ; 19 import java.io.StringWriter ; 20 21 import org.directwebremoting.dwrp.SimpleOutboundVariable; 22 import org.directwebremoting.extend.Converter; 23 import org.directwebremoting.extend.InboundContext; 24 import org.directwebremoting.extend.InboundVariable; 25 import org.directwebremoting.extend.MarshallException; 26 import org.directwebremoting.extend.OutboundContext; 27 import org.directwebremoting.extend.OutboundVariable; 28 import org.directwebremoting.extend.EnginePrivate; 29 import org.directwebremoting.util.LocalUtil; 30 import org.dom4j.Document; 31 import org.dom4j.Element; 32 import org.dom4j.Node; 33 import org.dom4j.io.OutputFormat; 34 import org.dom4j.io.SAXReader; 35 import org.dom4j.io.XMLWriter; 36 37 42 public class DOM4JConverter extends BaseV20Converter implements Converter 43 { 44 47 public Object convertInbound(Class paramType, InboundVariable iv, InboundContext inctx) throws MarshallException 48 { 49 String value = LocalUtil.decode(iv.getValue()); 50 51 try 52 { 53 SAXReader xmlReader = new SAXReader(); 54 Document doc = xmlReader.read(new StringReader (value)); 55 56 if (paramType == Document.class) 57 { 58 return doc; 59 } 60 else if (paramType == Element.class) 61 { 62 return doc.getRootElement(); 63 } 64 65 throw new MarshallException(paramType); 66 } 67 catch (MarshallException ex) 68 { 69 throw ex; 70 } 71 catch (Exception ex) 72 { 73 throw new MarshallException(paramType, ex); 74 } 75 } 76 77 80 public OutboundVariable convertOutbound(Object data, OutboundContext outctx) throws MarshallException 81 { 82 try 83 { 84 if (!(data instanceof Node)) 86 { 87 throw new MarshallException(data.getClass()); 88 } 89 90 Node node = (Node) data; 91 92 OutputFormat outformat = OutputFormat.createCompactFormat(); 93 outformat.setEncoding("UTF-8"); 94 95 StringWriter xml = new StringWriter (); 97 98 XMLWriter writer = new XMLWriter(xml, outformat); 99 writer.write(node); 100 writer.flush(); 101 xml.flush(); 102 103 String script = EnginePrivate.xmlStringToJavascriptDom(xml.toString()); 104 OutboundVariable ov = new SimpleOutboundVariable(script, outctx, false); 105 106 outctx.put(data, ov); 107 108 return ov; 109 } 110 catch (MarshallException ex) 111 { 112 throw ex; 113 } 114 catch (Exception ex) 115 { 116 throw new MarshallException(data.getClass(), ex); 117 } 118 } 119 } 120 | Popular Tags |