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.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;
16 import java.util.Map.Entry;
18 import java.util.concurrent.ConcurrentHashMap;
19 import javax.annotation.Nonnull;
20 import javax.annotation.Nullable;
21 import javax.xml.XMLConstants;
22 import javax.xml.namespace.NamespaceContext;
23 import javax.xml.stream.XMLStreamException;
24 import javax.xml.stream.XMLStreamWriter;
25 import javax.xml.transform.OutputKeys;
26 import javax.xml.transform.Transformer;
27 import javax.xml.transform.TransformerException;
28 import javax.xml.transform.TransformerFactory;
29 import javax.xml.transform.TransformerFactoryConfigurationError;
30 import javax.xml.transform.dom.DOMSource;
31 import javax.xml.transform.stax.StAXResult;
32 import javax.xml.transform.stream.StreamResult;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
37 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamAttributeWriter;
38 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Element;
46 * A {@link NormalizedNodeStreamWriter} which translates the events into an {@link XMLStreamWriter},
47 * resulting in a RFC 6020 XML encoding. There are 2 versions of this class, one that takes a
48 * SchemaContext and encodes values appropriately according to the yang schema. The other is
49 * schema-less and merely outputs values using toString. The latter is intended for debugging
50 * where doesn't have a SchemaContext available and isn't meant for production use.
52 public abstract class XMLStreamNormalizedNodeStreamWriter<T> implements NormalizedNodeStreamAttributeWriter {
53 private static final Logger LOG = LoggerFactory.getLogger(XMLStreamNormalizedNodeStreamWriter.class);
54 private static final String COM_SUN_TRANSFORMER =
55 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
57 private static final TransformerFactory TRANSFORMER_FACTORY;
60 TransformerFactory fa = TransformerFactory.newInstance();
61 if (!fa.getFeature(StAXResult.FEATURE)) {
62 LOG.warn("Platform-default TransformerFactory {} does not support StAXResult, attempting fallback to {}",
63 fa, COM_SUN_TRANSFORMER);
64 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
65 if (!fa.getFeature(StAXResult.FEATURE)) {
66 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
70 TRANSFORMER_FACTORY = fa;
73 private static final Set<String> BROKEN_NAMESPACES = ConcurrentHashMap.newKeySet();
75 private final RandomPrefix prefixes;
76 final XMLStreamWriter writer;
78 XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
79 this.writer = Preconditions.checkNotNull(writer);
80 this.prefixes = new RandomPrefix(writer.getNamespaceContext());
84 * Create a new writer with the specified context as its root.
86 * @param writer Output {@link XMLStreamWriter}
87 * @param context Associated {@link SchemaContext}.
88 * @return A new {@link NormalizedNodeStreamWriter}
90 public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context) {
91 return create(writer, context, SchemaPath.ROOT);
95 * Create a new writer with the specified context and rooted in the specified schema path.
97 * @param writer Output {@link XMLStreamWriter}
98 * @param context Associated {@link SchemaContext}.
101 * @return A new {@link NormalizedNodeStreamWriter}
103 public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
104 final SchemaPath path) {
105 return SchemaAwareXMLStreamNormalizedNodeStreamWriter.newInstance(writer, context, path);
109 * Create a new schema-less writer. Note that this version is intended for debugging
110 * where doesn't have a SchemaContext available and isn't meant for production use.
112 * @param writer Output {@link XMLStreamWriter}
114 * @return A new {@link NormalizedNodeStreamWriter}
116 public static NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
117 return SchemalessXMLStreamNormalizedNodeStreamWriter.newInstance(writer);
120 abstract void writeValue(XMLStreamWriter xmlWriter, QName qname, @Nonnull Object value, T context)
121 throws IOException, XMLStreamException;
123 abstract void startList(NodeIdentifier name);
125 abstract void startListItem(PathArgument name) throws IOException;
127 private void writeAttributes(@Nonnull final Map<QName, String> attributes) throws IOException {
128 for (final Entry<QName, String> entry : attributes.entrySet()) {
130 final QName qname = entry.getKey();
131 final String namespace = qname.getNamespace().toString();
133 if (!Strings.isNullOrEmpty(namespace)) {
134 final String prefix = getPrefix(qname.getNamespace(), namespace);
135 writer.writeAttribute(prefix, namespace, qname.getLocalName(), entry.getValue());
137 writer.writeAttribute(qname.getLocalName(), entry.getValue());
139 } catch (final XMLStreamException e) {
140 throw new IOException("Unable to emit attribute " + entry, e);
145 private String getPrefix(final URI uri, final String str) throws XMLStreamException {
146 final String prefix = writer.getPrefix(str);
147 if (prefix != null) {
151 // This is needed to recover from attributes emitted while the namespace was not declared. Ordinarily
152 // attribute namespaces would be bound in the writer, so the resulting XML is efficient, but we cannot rely
153 // on that having been done.
154 if (BROKEN_NAMESPACES.add(str)) {
155 LOG.info("Namespace {} was not bound, please fix the caller", str, new Throwable());
158 return prefixes.encodePrefix(uri);
161 private void writeStartElement(final QName qname) throws XMLStreamException {
162 String ns = qname.getNamespace().toString();
163 writer.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, qname.getLocalName(), ns);
164 if (writer.getNamespaceContext() != null) {
165 String parentNs = writer.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX);
166 if (!ns.equals(parentNs)) {
167 writer.writeDefaultNamespace(ns);
172 void writeElement(final QName qname, final Object value, @Nullable final Map<QName, String> attributes,
173 final T context) throws IOException {
175 writeStartElement(qname);
177 writeAttributes(attributes);
179 writeValue(writer, qname, value, context);
181 writer.writeEndElement();
182 } catch (XMLStreamException e) {
183 throw new IOException("Failed to emit element", e);
187 void startElement(final QName qname) throws IOException {
189 writeStartElement(qname);
190 } catch (XMLStreamException e) {
191 throw new IOException("Failed to start element", e);
195 void anyxmlNode(final QName qname, final Object value) throws IOException {
197 Preconditions.checkArgument(value instanceof DOMSource, "AnyXML value must be DOMSource, not %s", value);
198 final DOMSource domSource = (DOMSource) value;
199 Preconditions.checkNotNull(domSource.getNode());
200 Preconditions.checkArgument(domSource.getNode().getNodeName().equals(qname.getLocalName()));
201 Preconditions.checkArgument(domSource.getNode().getNamespaceURI().equals(qname.getNamespace().toString()));
203 // TODO can the transformer be a constant ? is it thread safe ?
204 final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
205 // Writer has to be wrapped in a wrapper that ignores endDocument event
206 // EndDocument event forbids any other modification to the writer so a nested anyXml breaks
208 transformer.transform(domSource, new StAXResult(new DelegateWriterNoEndDoc(writer)));
209 } catch (final TransformerException e) {
210 throw new IOException("Unable to transform anyXml(" + qname + ") value: " + value, e);
216 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint,
217 final Map<QName, String> attributes) throws IOException {
218 startContainerNode(name, childSizeHint);
219 writeAttributes(attributes);
223 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint,
224 final Map<QName, String> attributes) throws IOException {
225 startYangModeledAnyXmlNode(name, childSizeHint);
226 writeAttributes(attributes);
230 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint,
231 final Map<QName, String> attributes) throws IOException {
232 startUnkeyedListItem(name, childSizeHint);
233 writeAttributes(attributes);
237 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
242 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint,
243 final Map<QName, String> attributes) throws IOException {
244 startMapEntryNode(identifier, childSizeHint);
245 writeAttributes(attributes);
249 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
251 startListItem(identifier);
255 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
260 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
265 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
269 public static String toString(final Element xml) {
271 final Transformer transformer = TransformerFactory.newInstance().newTransformer();
272 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
274 final StreamResult result = new StreamResult(new StringWriter());
275 final DOMSource source = new DOMSource(xml);
276 transformer.transform(source, result);
278 return result.getWriter().toString();
279 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
280 throw new RuntimeException("Unable to serialize xml element " + xml, e);
284 abstract void endNode(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException;
287 public final void endNode() throws IOException {
290 } catch (XMLStreamException e) {
291 throw new IOException("Failed to end element", e);
296 public final void close() throws IOException {
299 } catch (XMLStreamException e) {
300 throw new IOException("Failed to close writer", e);
305 public final void flush() throws IOException {
308 } catch (XMLStreamException e) {
309 throw new IOException("Failed to flush writer", e);
314 * Delegate writer that ignores writeEndDocument event. Used for AnyXml serialization.
316 private static final class DelegateWriterNoEndDoc implements XMLStreamWriter {
317 private final XMLStreamWriter writer;
319 DelegateWriterNoEndDoc(final XMLStreamWriter writer) {
320 this.writer = writer;
324 public void writeStartElement(final String localName) throws XMLStreamException {
325 writer.writeStartElement(localName);
329 public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
330 writer.writeStartElement(namespaceURI, localName);
334 public void writeStartElement(final String prefix, final String localName, final String namespaceURI)
335 throws XMLStreamException {
336 writer.writeStartElement(prefix, localName, namespaceURI);
340 public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
341 writer.writeEmptyElement(namespaceURI, localName);
345 public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI)
346 throws XMLStreamException {
347 writer.writeEmptyElement(prefix, localName, namespaceURI);
351 public void writeEmptyElement(final String localName) throws XMLStreamException {
352 writer.writeEmptyElement(localName);
356 public void writeEndElement() throws XMLStreamException {
357 writer.writeEndElement();
362 public void writeEndDocument() throws XMLStreamException {
363 // End document is disabled
367 public void close() throws XMLStreamException {
372 public void flush() throws XMLStreamException {
377 public void writeAttribute(final String localName, final String value) throws XMLStreamException {
378 writer.writeAttribute(localName, value);
382 public void writeAttribute(final String prefix, final String namespaceURI, final String localName,
383 final String value) throws XMLStreamException {
384 writer.writeAttribute(prefix, namespaceURI, localName, value);
388 public void writeAttribute(final String namespaceURI, final String localName, final String value)
389 throws XMLStreamException {
390 writer.writeAttribute(namespaceURI, localName, value);
394 public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
395 // Workaround for default namespace
396 // If a namespace is not prefixed, it is is still treated as prefix namespace.
397 // This results in the NamespaceSupport class ignoring the namespace since xmlns is not a valid prefix
398 // Write the namespace at least as an attribute
399 // TODO this is a hotfix, the transformer itself should write namespaces passing the namespace
400 // in writeStartElement method
401 if (prefix.equals("xml") || prefix.equals("xmlns")) {
402 writer.writeAttribute(prefix, namespaceURI);
404 writer.writeNamespace(prefix, namespaceURI);
409 public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
410 writer.writeDefaultNamespace(namespaceURI);
414 public void writeComment(final String data) throws XMLStreamException {
415 writer.writeComment(data);
419 public void writeProcessingInstruction(final String target) throws XMLStreamException {
420 writer.writeProcessingInstruction(target);
424 public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
425 writer.writeProcessingInstruction(target, data);
429 public void writeCData(final String data) throws XMLStreamException {
430 writer.writeCData(data);
434 public void writeDTD(final String dtd) throws XMLStreamException {
435 writer.writeDTD(dtd);
439 public void writeEntityRef(final String name) throws XMLStreamException {
440 writer.writeEntityRef(name);
444 public void writeStartDocument() throws XMLStreamException {
448 public void writeStartDocument(final String version) throws XMLStreamException {
452 public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
456 public void writeCharacters(final String text) throws XMLStreamException {
457 writer.writeCharacters(text);
461 public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
462 writer.writeCharacters(text, start, len);
466 public String getPrefix(final String uri) throws XMLStreamException {
467 return writer.getPrefix(uri);
471 public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
472 // Disabled since it causes exceptions in the underlying writer
476 public void setDefaultNamespace(final String uri) throws XMLStreamException {
477 writer.setDefaultNamespace(uri);
481 public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
482 writer.setNamespaceContext(context);
486 public NamespaceContext getNamespaceContext() {
487 return writer.getNamespaceContext();
491 public Object getProperty(final String name) {
492 return writer.getProperty(name);