2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Strings;
12 import java.io.IOException;
13 import java.io.StringWriter;
15 import javax.xml.XMLConstants;
16 import java.io.StringWriter;
17 import javax.xml.namespace.NamespaceContext;
18 import javax.xml.stream.XMLStreamException;
19 import javax.xml.stream.XMLStreamWriter;
20 import javax.xml.transform.OutputKeys;
21 import javax.xml.transform.Transformer;
22 import javax.xml.transform.TransformerException;
23 import javax.xml.transform.TransformerFactory;
24 import javax.xml.transform.TransformerFactoryConfigurationError;
25 import javax.xml.transform.dom.DOMSource;
26 import javax.xml.transform.stax.StAXResult;
27 import javax.xml.transform.stream.StreamResult;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamAttributeWriter;
34 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
35 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
36 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
44 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
45 import org.w3c.dom.Element;
48 * A {@link NormalizedNodeStreamWriter} which translates the events into an
49 * {@link XMLStreamWriter}, resulting in a RFC 6020 XML encoding.
51 public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNodeStreamAttributeWriter {
53 private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
55 private final XMLStreamWriter writer;
56 private final SchemaTracker tracker;
57 private final XmlStreamUtils streamUtils;
58 private RandomPrefix randomPrefix;
60 private XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer, final SchemaContext context, final SchemaPath path) {
61 this.writer = Preconditions.checkNotNull(writer);
62 this.tracker = SchemaTracker.create(context, path);
63 this.streamUtils = XmlStreamUtils.create(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, context);
64 randomPrefix = new RandomPrefix();
68 * Create a new writer with the specified context as its root.
70 * @param writer Output {@link XMLStreamWriter}
71 * @param context Associated {@link SchemaContext}.
72 * @return A new {@link NormalizedNodeStreamWriter}
74 public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context) {
75 return create( writer, context, SchemaPath.ROOT);
79 * Create a new writer with the specified context and rooted in the specified schema path
81 * @param writer Output {@link XMLStreamWriter}
82 * @param context Associated {@link SchemaContext}.
84 * @return A new {@link NormalizedNodeStreamWriter}
86 public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context, final SchemaPath path) {
87 return new XMLStreamNormalizedNodeStreamWriter(writer, context, path);
90 private void writeStartElement( QName qname) throws XMLStreamException {
91 String ns = qname.getNamespace().toString();
92 writer.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, qname.getLocalName(), ns);
93 if(writer.getNamespaceContext() != null) {
94 String parentNs = writer.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX);
95 if (!ns.equals(parentNs)) {
96 writer.writeDefaultNamespace(ns);
101 private void writeElement(final QName qname, final TypeDefinition<?> type, final Object value) throws IOException {
103 writeStartElement(qname);
105 streamUtils.writeValue(writer, type, value);
107 writer.writeEndElement();
108 } catch (XMLStreamException e) {
109 throw new IOException("Failed to emit element", e);
113 private void writeElement(final QName qname, final SchemaNode schemaNode, final Object value) throws IOException {
115 writeStartElement(qname);
117 streamUtils.writeValue(writer, schemaNode, value);
119 writer.writeEndElement();
120 } catch (XMLStreamException e) {
121 throw new IOException("Failed to emit element", e);
125 private void writeElement(final QName qname, final SchemaNode schemaNode, final Object value, final Map<QName, String> attributes) throws IOException {
127 writeStartElement(qname);
128 writeAttributes(attributes);
130 streamUtils.writeValue(writer, schemaNode, value);
132 writer.writeEndElement();
133 } catch (XMLStreamException e) {
134 throw new IOException("Failed to emit element", e);
138 private void startElement(final QName qname) throws IOException {
140 writeStartElement(qname);
141 } catch (XMLStreamException e) {
142 throw new IOException("Failed to start element", e);
146 private void startList(final NodeIdentifier name) {
147 tracker.startList(name);
150 private void startListItem(final PathArgument name) throws IOException {
151 tracker.startListItem(name);
152 startElement(name.getNodeType());
156 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
157 final LeafSchemaNode schema = tracker.leafNode(name);
158 writeElement(schema.getQName(), schema, value);
162 public void leafNode(final NodeIdentifier name, final Object value, final Map<QName, String> attributes) throws IOException {
163 final LeafSchemaNode schema = tracker.leafNode(name);
164 writeElement(schema.getQName(), schema, value, attributes);
168 public void leafSetEntryNode(final Object value, final Map<QName, String> attributes) throws IOException, IllegalArgumentException {
169 final LeafListSchemaNode schema = tracker.leafSetEntryNode();
170 writeElement(schema.getQName(), schema, value, attributes);
174 public void startContainerNode(final NodeIdentifier name, final int childSizeHint, final Map<QName, String> attributes) throws IOException, IllegalArgumentException {
175 startContainerNode(name, childSizeHint);
176 writeAttributes(attributes);
180 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint, final Map<QName, String> attributes) throws IOException, IllegalStateException {
181 startUnkeyedListItem(name, childSizeHint);
182 writeAttributes(attributes);
186 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint, final Map<QName, String> attributes) throws IOException, IllegalArgumentException {
187 startMapEntryNode(identifier, childSizeHint);
188 writeAttributes(attributes);
191 private void writeAttributes(final Map<QName, String> attributes) throws IOException {
192 for (final Map.Entry<QName, String> qNameStringEntry : attributes.entrySet()) {
194 final String namespace = qNameStringEntry.getKey().getNamespace().toString();
195 if(Strings.isNullOrEmpty(namespace)) {
196 writer.writeAttribute(qNameStringEntry.getKey().getLocalName(), qNameStringEntry.getValue());
198 final String prefix = randomPrefix.encodePrefix(qNameStringEntry.getKey().getNamespace());
199 writer.writeAttribute(prefix, namespace, qNameStringEntry.getKey().getLocalName(), qNameStringEntry.getValue());
201 } catch (final XMLStreamException e) {
202 throw new IOException("Unable to emit attribute " + qNameStringEntry, e);
208 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) {
209 tracker.startLeafSet(name);
213 public void leafSetEntryNode(final Object value) throws IOException {
214 final LeafListSchemaNode schema = tracker.leafSetEntryNode();
215 writeElement(schema.getQName(), schema, value);
219 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
220 final SchemaNode schema = tracker.startContainerNode(name);
221 startElement(schema.getQName());
225 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
230 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
235 public void startMapNode(final NodeIdentifier name, final int childSizeHint) {
240 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint) throws IOException {
241 startListItem(identifier);
245 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
250 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
251 tracker.startChoiceNode(name);
255 public void startAugmentationNode(final AugmentationIdentifier identifier) {
256 tracker.startAugmentationNode(identifier);
260 public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
261 final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
263 Preconditions.checkArgument(value instanceof DOMSource, "AnyXML value must be DOMSource, not %s", value);
264 final QName qname = schema.getQName();
265 final DOMSource domSource = (DOMSource) value;
266 Preconditions.checkNotNull(domSource.getNode());
267 Preconditions.checkArgument(domSource.getNode().getNodeName().equals(qname.getLocalName()));
268 Preconditions.checkArgument(domSource.getNode().getNamespaceURI().equals(qname.getNamespace().toString()));
270 // TODO can the transformer be a constant ? is it thread safe ?
271 final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
272 // Writer has to be wrapped in a wrapper that ignores endDocument event
273 // EndDocument event forbids any other modification to the writer so a nested anyXml breaks serialization
274 transformer.transform(domSource, new StAXResult(new DelegateWriterNoEndDoc(writer)));
275 } catch (final TransformerException e) {
276 throw new IOException("Unable to transform anyXml(" + name + ") value: " + value, e);
281 public static String toString(final Element xml) {
283 final Transformer transformer = TransformerFactory.newInstance().newTransformer();
284 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
286 final StreamResult result = new StreamResult(new StringWriter());
287 final DOMSource source = new DOMSource(xml);
288 transformer.transform(source, result);
290 return result.getWriter().toString();
291 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
292 throw new RuntimeException("Unable to serialize xml element " + xml, e);
297 public void endNode() throws IOException {
298 final Object schema = tracker.endNode();
301 if (schema instanceof ListSchemaNode) {
302 // For lists, we only emit end element on the inner frame
303 final Object parent = tracker.getParent();
304 if (parent == schema) {
305 writer.writeEndElement();
307 } else if (schema instanceof ContainerSchemaNode) {
308 // Emit container end element
309 writer.writeEndElement();
311 } catch (XMLStreamException e) {
312 throw new IOException("Failed to end element", e);
317 public void close() throws IOException {
320 } catch (XMLStreamException e) {
321 throw new IOException("Failed to close writer", e);
326 public void flush() throws IOException {
329 } catch (XMLStreamException e) {
330 throw new IOException("Failed to flush writer", e);
335 * Delegate writer that ignores writeEndDocument event. Used for AnyXml serialization.
337 private static final class DelegateWriterNoEndDoc implements XMLStreamWriter {
338 private final XMLStreamWriter writer;
340 public DelegateWriterNoEndDoc(final XMLStreamWriter writer) {
341 this.writer = writer;
345 public void writeStartElement(final String localName) throws XMLStreamException {
346 writer.writeStartElement(localName);
350 public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
351 writer.writeStartElement(namespaceURI, localName);
355 public void writeStartElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
356 writer.writeStartElement(prefix, localName, namespaceURI);
360 public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
361 writer.writeEmptyElement(namespaceURI, localName);
365 public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
366 writer.writeEmptyElement(prefix, localName, namespaceURI);
370 public void writeEmptyElement(final String localName) throws XMLStreamException {
371 writer.writeEmptyElement(localName);
375 public void writeEndElement() throws XMLStreamException {
376 writer.writeEndElement();
381 public void writeEndDocument() throws XMLStreamException {
382 // End document is disabled
386 public void close() throws XMLStreamException {
391 public void flush() throws XMLStreamException {
396 public void writeAttribute(final String localName, final String value) throws XMLStreamException {
397 writer.writeAttribute(localName, value);
401 public void writeAttribute(final String prefix, final String namespaceURI, final String localName, final String value) throws XMLStreamException {
402 writer.writeAttribute(prefix, namespaceURI, localName, value);
406 public void writeAttribute(final String namespaceURI, final String localName, final String value) throws XMLStreamException {
407 writer.writeAttribute(namespaceURI, localName, value);
411 public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
412 // Workaround for default namespace
413 // If a namespace is not prefixed, it is is still treated as prefix namespace. This results in the NamespaceSupport class ignoring the namespace since xmlns is not a valid prefix
414 // Write the namespace at least as an attribute
415 // TODO this is a hotfix, the transformer itself should write namespaces passing the namespace in writeStartElement method
416 if (prefix.equals("xml") || prefix.equals("xmlns")) {
417 writer.writeAttribute(prefix, namespaceURI);
419 writer.writeNamespace(prefix, namespaceURI);
424 public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
425 writer.writeDefaultNamespace(namespaceURI);
429 public void writeComment(final String data) throws XMLStreamException {
430 writer.writeComment(data);
434 public void writeProcessingInstruction(final String target) throws XMLStreamException {
435 writer.writeProcessingInstruction(target);
439 public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
440 writer.writeProcessingInstruction(target, data);
444 public void writeCData(final String data) throws XMLStreamException {
445 writer.writeCData(data);
449 public void writeDTD(final String dtd) throws XMLStreamException {
450 writer.writeDTD(dtd);
454 public void writeEntityRef(final String name) throws XMLStreamException {
455 writer.writeEntityRef(name);
459 public void writeStartDocument() throws XMLStreamException {
463 public void writeStartDocument(final String version) throws XMLStreamException {
467 public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
471 public void writeCharacters(final String text) throws XMLStreamException {
472 writer.writeCharacters(text);
476 public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
477 writer.writeCharacters(text, start, len);
481 public String getPrefix(final String uri) throws XMLStreamException {
482 return writer.getPrefix(uri);
486 public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
487 // Disabled since it causes exceptions in the underlying writer
491 public void setDefaultNamespace(final String uri) throws XMLStreamException {
492 writer.setDefaultNamespace(uri);
496 public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
497 writer.setNamespaceContext(context);
501 public NamespaceContext getNamespaceContext() {
502 return writer.getNamespaceContext();
506 public Object getProperty(final String name) throws IllegalArgumentException {
507 return writer.getProperty(name);