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 javax.xml.namespace.NamespaceContext;
17 import javax.xml.stream.XMLStreamException;
18 import javax.xml.stream.XMLStreamWriter;
19 import javax.xml.transform.OutputKeys;
20 import javax.xml.transform.Transformer;
21 import javax.xml.transform.TransformerException;
22 import javax.xml.transform.TransformerFactory;
23 import javax.xml.transform.TransformerFactoryConfigurationError;
24 import javax.xml.transform.dom.DOMSource;
25 import javax.xml.transform.stax.StAXResult;
26 import javax.xml.transform.stream.StreamResult;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamAttributeWriter;
33 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
34 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
35 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
43 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
44 import org.w3c.dom.Element;
47 * A {@link NormalizedNodeStreamWriter} which translates the events into an
48 * {@link XMLStreamWriter}, resulting in a RFC 6020 XML encoding.
50 public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNodeStreamAttributeWriter {
52 private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
54 private final XMLStreamWriter writer;
55 private final SchemaTracker tracker;
56 private final XmlStreamUtils streamUtils;
57 private final RandomPrefix randomPrefix;
59 private XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer, final SchemaContext context, final SchemaPath path) {
60 this.writer = Preconditions.checkNotNull(writer);
61 this.tracker = SchemaTracker.create(context, path);
62 this.streamUtils = XmlStreamUtils.create(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, context);
63 randomPrefix = new RandomPrefix();
67 * Create a new writer with the specified context as its root.
69 * @param writer Output {@link XMLStreamWriter}
70 * @param context Associated {@link SchemaContext}.
71 * @return A new {@link NormalizedNodeStreamWriter}
73 public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context) {
74 return create( writer, context, SchemaPath.ROOT);
78 * Create a new writer with the specified context and rooted in the specified schema path
80 * @param writer Output {@link XMLStreamWriter}
81 * @param context Associated {@link SchemaContext}.
83 * @return A new {@link NormalizedNodeStreamWriter}
85 public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context, final SchemaPath path) {
86 return new XMLStreamNormalizedNodeStreamWriter(writer, context, path);
89 private void writeStartElement(final QName qname) throws XMLStreamException {
90 String ns = qname.getNamespace().toString();
91 writer.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, qname.getLocalName(), ns);
92 if(writer.getNamespaceContext() != null) {
93 String parentNs = writer.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX);
94 if (!ns.equals(parentNs)) {
95 writer.writeDefaultNamespace(ns);
100 private void writeElement(final QName qname, final TypeDefinition<?> type, final Object value) throws IOException {
102 writeStartElement(qname);
104 streamUtils.writeValue(writer, type, value);
106 writer.writeEndElement();
107 } catch (XMLStreamException e) {
108 throw new IOException("Failed to emit element", e);
112 private void writeElement(final QName qname, final SchemaNode schemaNode, final Object value) throws IOException {
114 writeStartElement(qname);
116 streamUtils.writeValue(writer, schemaNode, value);
118 writer.writeEndElement();
119 } catch (XMLStreamException e) {
120 throw new IOException("Failed to emit element", e);
124 private void writeElement(final QName qname, final SchemaNode schemaNode, final Object value, final Map<QName, String> attributes) throws IOException {
126 writeStartElement(qname);
127 writeAttributes(attributes);
129 streamUtils.writeValue(writer, schemaNode, value);
131 writer.writeEndElement();
132 } catch (XMLStreamException e) {
133 throw new IOException("Failed to emit element", e);
137 private void startElement(final QName qname) throws IOException {
139 writeStartElement(qname);
140 } catch (XMLStreamException e) {
141 throw new IOException("Failed to start element", e);
145 private void startList(final NodeIdentifier name) {
146 tracker.startList(name);
149 private void startListItem(final PathArgument name) throws IOException {
150 tracker.startListItem(name);
151 startElement(name.getNodeType());
155 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
156 final LeafSchemaNode schema = tracker.leafNode(name);
157 writeElement(schema.getQName(), schema, value);
161 public void leafNode(final NodeIdentifier name, final Object value, final Map<QName, String> attributes) throws IOException {
162 final LeafSchemaNode schema = tracker.leafNode(name);
163 writeElement(schema.getQName(), schema, value, attributes);
167 public void leafSetEntryNode(final Object value, final Map<QName, String> attributes) throws IOException {
168 final LeafListSchemaNode schema = tracker.leafSetEntryNode();
169 writeElement(schema.getQName(), schema, value, attributes);
173 public void startContainerNode(final NodeIdentifier name, final int childSizeHint, final Map<QName, String> attributes) throws IOException {
174 startContainerNode(name, childSizeHint);
175 writeAttributes(attributes);
179 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint, final Map<QName, String> attributes) throws IOException {
180 startUnkeyedListItem(name, childSizeHint);
181 writeAttributes(attributes);
185 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint, final Map<QName, String> attributes) throws IOException {
186 startMapEntryNode(identifier, childSizeHint);
187 writeAttributes(attributes);
190 private void writeAttributes(final Map<QName, String> attributes) throws IOException {
191 for (final Map.Entry<QName, String> qNameStringEntry : attributes.entrySet()) {
193 final String namespace = qNameStringEntry.getKey().getNamespace().toString();
194 if(Strings.isNullOrEmpty(namespace)) {
195 writer.writeAttribute(qNameStringEntry.getKey().getLocalName(), qNameStringEntry.getValue());
197 final String prefix = randomPrefix.encodePrefix(qNameStringEntry.getKey().getNamespace());
198 writer.writeAttribute(prefix, namespace, qNameStringEntry.getKey().getLocalName(), qNameStringEntry.getValue());
200 } catch (final XMLStreamException e) {
201 throw new IOException("Unable to emit attribute " + qNameStringEntry, e);
207 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) {
208 tracker.startLeafSet(name);
212 public void leafSetEntryNode(final Object value) throws IOException {
213 final LeafListSchemaNode schema = tracker.leafSetEntryNode();
214 writeElement(schema.getQName(), schema, value);
218 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
219 final SchemaNode schema = tracker.startContainerNode(name);
220 startElement(schema.getQName());
224 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
229 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
234 public void startMapNode(final NodeIdentifier name, final int childSizeHint) {
239 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint) throws IOException {
240 startListItem(identifier);
244 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
249 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
250 tracker.startChoiceNode(name);
254 public void startAugmentationNode(final AugmentationIdentifier identifier) {
255 tracker.startAugmentationNode(identifier);
259 public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
260 final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
262 Preconditions.checkArgument(value instanceof DOMSource, "AnyXML value must be DOMSource, not %s", value);
263 final QName qname = schema.getQName();
264 final DOMSource domSource = (DOMSource) value;
265 Preconditions.checkNotNull(domSource.getNode());
266 Preconditions.checkArgument(domSource.getNode().getNodeName().equals(qname.getLocalName()));
267 Preconditions.checkArgument(domSource.getNode().getNamespaceURI().equals(qname.getNamespace().toString()));
269 // TODO can the transformer be a constant ? is it thread safe ?
270 final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
271 // Writer has to be wrapped in a wrapper that ignores endDocument event
272 // EndDocument event forbids any other modification to the writer so a nested anyXml breaks serialization
273 transformer.transform(domSource, new StAXResult(new DelegateWriterNoEndDoc(writer)));
274 } catch (final TransformerException e) {
275 throw new IOException("Unable to transform anyXml(" + name + ") value: " + value, e);
280 public static String toString(final Element xml) {
282 final Transformer transformer = TransformerFactory.newInstance().newTransformer();
283 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
285 final StreamResult result = new StreamResult(new StringWriter());
286 final DOMSource source = new DOMSource(xml);
287 transformer.transform(source, result);
289 return result.getWriter().toString();
290 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
291 throw new RuntimeException("Unable to serialize xml element " + xml, e);
296 public void endNode() throws IOException {
297 final Object schema = tracker.endNode();
300 if (schema instanceof ListSchemaNode) {
301 // For lists, we only emit end element on the inner frame
302 final Object parent = tracker.getParent();
303 if (parent == schema) {
304 writer.writeEndElement();
306 } else if (schema instanceof ContainerSchemaNode) {
307 // Emit container end element
308 writer.writeEndElement();
310 } catch (XMLStreamException e) {
311 throw new IOException("Failed to end element", e);
316 public void close() throws IOException {
319 } catch (XMLStreamException e) {
320 throw new IOException("Failed to close writer", e);
325 public void flush() throws IOException {
328 } catch (XMLStreamException e) {
329 throw new IOException("Failed to flush writer", e);
334 * Delegate writer that ignores writeEndDocument event. Used for AnyXml serialization.
336 private static final class DelegateWriterNoEndDoc implements XMLStreamWriter {
337 private final XMLStreamWriter writer;
339 public DelegateWriterNoEndDoc(final XMLStreamWriter writer) {
340 this.writer = writer;
344 public void writeStartElement(final String localName) throws XMLStreamException {
345 writer.writeStartElement(localName);
349 public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
350 writer.writeStartElement(namespaceURI, localName);
354 public void writeStartElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
355 writer.writeStartElement(prefix, localName, namespaceURI);
359 public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
360 writer.writeEmptyElement(namespaceURI, localName);
364 public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
365 writer.writeEmptyElement(prefix, localName, namespaceURI);
369 public void writeEmptyElement(final String localName) throws XMLStreamException {
370 writer.writeEmptyElement(localName);
374 public void writeEndElement() throws XMLStreamException {
375 writer.writeEndElement();
380 public void writeEndDocument() throws XMLStreamException {
381 // End document is disabled
385 public void close() throws XMLStreamException {
390 public void flush() throws XMLStreamException {
395 public void writeAttribute(final String localName, final String value) throws XMLStreamException {
396 writer.writeAttribute(localName, value);
400 public void writeAttribute(final String prefix, final String namespaceURI, final String localName, final String value) throws XMLStreamException {
401 writer.writeAttribute(prefix, namespaceURI, localName, value);
405 public void writeAttribute(final String namespaceURI, final String localName, final String value) throws XMLStreamException {
406 writer.writeAttribute(namespaceURI, localName, value);
410 public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
411 // Workaround for default namespace
412 // 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
413 // Write the namespace at least as an attribute
414 // TODO this is a hotfix, the transformer itself should write namespaces passing the namespace in writeStartElement method
415 if (prefix.equals("xml") || prefix.equals("xmlns")) {
416 writer.writeAttribute(prefix, namespaceURI);
418 writer.writeNamespace(prefix, namespaceURI);
423 public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
424 writer.writeDefaultNamespace(namespaceURI);
428 public void writeComment(final String data) throws XMLStreamException {
429 writer.writeComment(data);
433 public void writeProcessingInstruction(final String target) throws XMLStreamException {
434 writer.writeProcessingInstruction(target);
438 public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
439 writer.writeProcessingInstruction(target, data);
443 public void writeCData(final String data) throws XMLStreamException {
444 writer.writeCData(data);
448 public void writeDTD(final String dtd) throws XMLStreamException {
449 writer.writeDTD(dtd);
453 public void writeEntityRef(final String name) throws XMLStreamException {
454 writer.writeEntityRef(name);
458 public void writeStartDocument() throws XMLStreamException {
462 public void writeStartDocument(final String version) throws XMLStreamException {
466 public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
470 public void writeCharacters(final String text) throws XMLStreamException {
471 writer.writeCharacters(text);
475 public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
476 writer.writeCharacters(text, start, len);
480 public String getPrefix(final String uri) throws XMLStreamException {
481 return writer.getPrefix(uri);
485 public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
486 // Disabled since it causes exceptions in the underlying writer
490 public void setDefaultNamespace(final String uri) throws XMLStreamException {
491 writer.setDefaultNamespace(uri);
495 public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
496 writer.setNamespaceContext(context);
500 public NamespaceContext getNamespaceContext() {
501 return writer.getNamespaceContext();
505 public Object getProperty(final String name) {
506 return writer.getProperty(name);