1 29 30 package com.caucho.jaxb; 31 import com.caucho.jaxb.adapters.BeanAdapter; 32 import com.caucho.jaxb.skeleton.ClassSkeleton; 33 34 import javax.xml.bind.JAXBException; 35 import javax.xml.bind.Marshaller; 36 import javax.xml.bind.annotation.XmlRootElement; 37 import javax.xml.bind.annotation.XmlType; 38 import javax.xml.bind.annotation.adapters.XmlAdapter; 39 import javax.xml.bind.helpers.AbstractMarshallerImpl; 40 import javax.xml.namespace.QName ; 41 import javax.xml.stream.XMLEventWriter; 42 import javax.xml.stream.XMLOutputFactory; 43 import javax.xml.stream.XMLStreamException; 44 import javax.xml.stream.XMLStreamWriter; 45 import javax.xml.transform.Result ; 46 47 public class MarshallerImpl extends AbstractMarshallerImpl { 48 49 private JAXBContextImpl _context; 50 private Listener _listener; 51 52 53 MarshallerImpl(JAXBContextImpl context) 54 { 55 this._context = context; 56 } 57 58 61 public void marshal(Object jaxbElement, XMLStreamWriter writer) 62 throws JAXBException 63 { 64 ClassSkeleton skeleton = _context.findSkeletonForObject(jaxbElement); 65 Class c = skeleton.getType(); 66 67 72 73 String name = null; 74 String namespace = null; 75 76 XmlType xmlTypeAnnotation = (XmlType) c.getAnnotation(XmlType.class); 78 79 if (name == null) { 80 name = 81 (xmlTypeAnnotation == null ? c.getName() : xmlTypeAnnotation.name()); 82 } 83 84 XmlRootElement xre = (XmlRootElement) c.getAnnotation(XmlRootElement.class); 85 86 if (xre != null) { 87 name = xre.name(); 88 } 89 90 String encoding = getEncoding(); 91 if (encoding == null) 92 encoding = "utf-8"; 93 94 try { 95 if (!isFragment()) 96 writer.writeStartDocument(encoding, "1.0"); 97 98 107 108 109 skeleton.write(this, writer, jaxbElement, null); 110 } 111 catch (Exception e) { 112 throw new JAXBException(e); 113 } 114 } 115 116 public Listener getListener() 117 { 118 return _listener; 119 } 120 121 public void setListener(Marshaller.Listener listener) 122 { 123 _listener = listener; 124 } 125 126 public void marshal(Object obj, XMLEventWriter writer) throws JAXBException 127 { 128 throw new UnsupportedOperationException (); 129 } 130 131 public void marshal(Object obj, Result result) throws JAXBException 132 { 133 try { 134 XMLOutputFactory factory = XMLOutputFactory.newInstance(); 135 XMLStreamWriter out = factory.createXMLStreamWriter(result); 136 137 marshal(obj, out); 138 } 139 catch (XMLStreamException e) { 140 throw new JAXBException(e); 141 } 142 } 143 144 public <A extends XmlAdapter> A getAdapter(Class <A> type) 145 { 146 A a = super.getAdapter(type); 147 148 if (a == null) 149 return (A)new BeanAdapter(); 150 151 return a; 152 } 153 } 154 155 | Popular Tags |