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 static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.Strings;
14 import java.io.IOException;
15 import java.io.StringWriter;
18 import java.util.Map.Entry;
20 import java.util.concurrent.ConcurrentHashMap;
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.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
39 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamAttributeWriter;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
42 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.w3c.dom.Element;
50 * A {@link NormalizedNodeStreamWriter} which translates the events into an {@link XMLStreamWriter},
51 * resulting in a RFC 6020 XML encoding. There are 2 versions of this class, one that takes a
52 * SchemaContext and encodes values appropriately according to the yang schema. The other is
53 * schema-less and merely outputs values using toString. The latter is intended for debugging
54 * where doesn't have a SchemaContext available and isn't meant for production use.
56 public abstract class XMLStreamNormalizedNodeStreamWriter<T> implements NormalizedNodeStreamAttributeWriter {
57 private static final Logger LOG = LoggerFactory.getLogger(XMLStreamNormalizedNodeStreamWriter.class);
58 private static final String COM_SUN_TRANSFORMER =
59 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
61 static final TransformerFactory TRANSFORMER_FACTORY;
64 TransformerFactory fa = TransformerFactory.newInstance();
65 if (!fa.getFeature(StAXResult.FEATURE)) {
66 LOG.warn("Platform-default TransformerFactory {} does not support StAXResult, attempting fallback to {}",
67 fa, COM_SUN_TRANSFORMER);
68 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
69 if (!fa.getFeature(StAXResult.FEATURE)) {
70 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
74 TRANSFORMER_FACTORY = fa;
77 private static final Set<String> BROKEN_NAMESPACES = ConcurrentHashMap.newKeySet();
79 private final @NonNull XMLStreamWriter writer;
80 private final RandomPrefix prefixes;
82 XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
83 this.writer = requireNonNull(writer);
84 this.prefixes = new RandomPrefix(writer.getNamespaceContext());
88 * Create a new writer with the specified context as its root.
90 * @param writer Output {@link XMLStreamWriter}
91 * @param context Associated {@link SchemaContext}.
92 * @return A new {@link NormalizedNodeStreamWriter}
94 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
95 final SchemaContext context) {
96 return create(writer, context, context);
100 * Create a new writer with the specified context and rooted at the specified node.
102 * @param writer Output {@link XMLStreamWriter}
103 * @param context Associated {@link SchemaContext}.
104 * @param rootNode Root node
105 * @return A new {@link NormalizedNodeStreamWriter}
107 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
108 final DataNodeContainer rootNode) {
109 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, SchemaTracker.create(rootNode));
113 * Create a new writer with the specified context and rooted in the specified schema path.
115 * @param writer Output {@link XMLStreamWriter}
116 * @param context Associated {@link SchemaContext}.
118 * @return A new {@link NormalizedNodeStreamWriter}
120 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
121 final SchemaPath path) {
122 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, SchemaTracker.create(context, path));
126 * Create a new schema-less writer. Note that this version is intended for debugging
127 * where doesn't have a SchemaContext available and isn't meant for production use.
129 * @param writer Output {@link XMLStreamWriter}
131 * @return A new {@link NormalizedNodeStreamWriter}
133 public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
134 return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
137 abstract void writeValue(@NonNull XMLStreamWriter xmlWriter, QName qname, @NonNull Object value, T context)
138 throws IOException, XMLStreamException;
140 abstract void startList(NodeIdentifier name);
142 abstract void startListItem(PathArgument name) throws IOException;
144 private void writeAttributes(final @NonNull Map<QName, String> attributes) throws IOException {
145 for (final Entry<QName, String> entry : attributes.entrySet()) {
147 final QName qname = entry.getKey();
148 final String namespace = qname.getNamespace().toString();
150 if (!Strings.isNullOrEmpty(namespace)) {
151 final String prefix = getPrefix(qname.getNamespace(), namespace);
152 writer.writeAttribute(prefix, namespace, qname.getLocalName(), entry.getValue());
154 writer.writeAttribute(qname.getLocalName(), entry.getValue());
156 } catch (final XMLStreamException e) {
157 throw new IOException("Unable to emit attribute " + entry, e);
162 private String getPrefix(final URI uri, final String str) throws XMLStreamException {
163 final String prefix = writer.getPrefix(str);
164 if (prefix != null) {
168 // This is needed to recover from attributes emitted while the namespace was not declared. Ordinarily
169 // attribute namespaces would be bound in the writer, so the resulting XML is efficient, but we cannot rely
170 // on that having been done.
171 if (BROKEN_NAMESPACES.add(str)) {
172 LOG.info("Namespace {} was not bound, please fix the caller", str, new Throwable());
175 return prefixes.encodePrefix(uri);
178 private void writeStartElement(final QName qname) throws XMLStreamException {
179 final String ns = qname.getNamespace().toString();
180 final NamespaceContext context = writer.getNamespaceContext();
181 final boolean needDefaultNs;
182 if (context != null) {
183 final String parentNs = context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX);
184 needDefaultNs = !ns.equals(parentNs);
186 needDefaultNs = false;
189 writer.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, qname.getLocalName(), ns);
191 writer.writeDefaultNamespace(ns);
195 final void writeElement(final QName qname, final Object value, final @Nullable Map<QName, String> attributes,
196 final T context) throws IOException {
198 writeStartElement(qname);
200 if (attributes != null) {
201 writeAttributes(attributes);
204 writeValue(writer, qname, value, context);
206 writer.writeEndElement();
207 } catch (XMLStreamException e) {
208 throw new IOException("Failed to emit element", e);
212 final void startElement(final QName qname) throws IOException {
214 writeStartElement(qname);
215 } catch (XMLStreamException e) {
216 throw new IOException("Failed to start element", e);
220 final void endElement() throws IOException {
222 writer.writeEndElement();
223 } catch (XMLStreamException e) {
224 throw new IOException("Failed to end element", e);
228 final void anyxmlNode(final QName qname, final Object value) throws IOException {
230 checkArgument(value instanceof DOMSource, "AnyXML value must be DOMSource, not %s", value);
231 final DOMSource domSource = (DOMSource) value;
232 requireNonNull(domSource.getNode());
233 checkArgument(domSource.getNode().getNodeName().equals(qname.getLocalName()));
234 checkArgument(domSource.getNode().getNamespaceURI().equals(qname.getNamespace().toString()));
236 // TODO can the transformer be a constant ? is it thread safe ?
237 final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
238 // Writer has to be wrapped in a wrapper that ignores endDocument event
239 // EndDocument event forbids any other modification to the writer so a nested anyXml breaks
241 transformer.transform(domSource, new StAXResult(new DelegateWriterNoEndDoc(writer)));
242 } catch (final TransformerException e) {
243 throw new IOException("Unable to transform anyXml(" + qname + ") value: " + value, e);
249 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint,
250 final Map<QName, String> attributes) throws IOException {
251 startContainerNode(name, childSizeHint);
252 writeAttributes(attributes);
256 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint,
257 final Map<QName, String> attributes) throws IOException {
258 startYangModeledAnyXmlNode(name, childSizeHint);
259 writeAttributes(attributes);
263 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint,
264 final Map<QName, String> attributes) throws IOException {
265 startUnkeyedListItem(name, childSizeHint);
266 writeAttributes(attributes);
270 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
275 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint,
276 final Map<QName, String> attributes) throws IOException {
277 startMapEntryNode(identifier, childSizeHint);
278 writeAttributes(attributes);
282 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
284 startListItem(identifier);
288 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
293 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
298 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
302 public static String toString(final Element xml) {
304 final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
305 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
307 final StreamResult result = new StreamResult(new StringWriter());
308 final DOMSource source = new DOMSource(xml);
309 transformer.transform(source, result);
311 return result.getWriter().toString();
312 } catch (IllegalArgumentException | TransformerException e) {
313 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
318 public final void close() throws IOException {
321 } catch (XMLStreamException e) {
322 throw new IOException("Failed to close writer", e);
327 public final void flush() throws IOException {
330 } catch (XMLStreamException e) {
331 throw new IOException("Failed to flush writer", e);
336 * Delegate writer that ignores writeEndDocument event. Used for AnyXml serialization.
338 private static final class DelegateWriterNoEndDoc implements XMLStreamWriter {
339 private final XMLStreamWriter writer;
341 DelegateWriterNoEndDoc(final XMLStreamWriter writer) {
342 this.writer = writer;
346 public void writeStartElement(final String localName) throws XMLStreamException {
347 writer.writeStartElement(localName);
351 public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
352 writer.writeStartElement(namespaceURI, localName);
356 public void writeStartElement(final String prefix, final String localName, final String namespaceURI)
357 throws XMLStreamException {
358 writer.writeStartElement(prefix, localName, namespaceURI);
362 public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
363 writer.writeEmptyElement(namespaceURI, localName);
367 public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI)
368 throws XMLStreamException {
369 writer.writeEmptyElement(prefix, localName, namespaceURI);
373 public void writeEmptyElement(final String localName) throws XMLStreamException {
374 writer.writeEmptyElement(localName);
378 public void writeEndElement() throws XMLStreamException {
379 writer.writeEndElement();
384 public void writeEndDocument() throws XMLStreamException {
385 // End document is disabled
389 public void close() throws XMLStreamException {
394 public void flush() throws XMLStreamException {
399 public void writeAttribute(final String localName, final String value) throws XMLStreamException {
400 writer.writeAttribute(localName, value);
404 public void writeAttribute(final String prefix, final String namespaceURI, final String localName,
405 final String value) throws XMLStreamException {
406 writer.writeAttribute(prefix, namespaceURI, localName, value);
410 public void writeAttribute(final String namespaceURI, final String localName, final String value)
411 throws XMLStreamException {
412 writer.writeAttribute(namespaceURI, localName, value);
416 public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
417 // Workaround for default namespace
418 // If a namespace is not prefixed, it is is still treated as prefix namespace.
419 // This results in the NamespaceSupport class ignoring the namespace since xmlns is not a valid prefix
420 // Write the namespace at least as an attribute
421 // TODO this is a hotfix, the transformer itself should write namespaces passing the namespace
422 // in writeStartElement method
423 if (prefix.equals("xml") || prefix.equals("xmlns")) {
424 writer.writeAttribute(prefix, namespaceURI);
426 writer.writeNamespace(prefix, namespaceURI);
431 public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
432 writer.writeDefaultNamespace(namespaceURI);
436 public void writeComment(final String data) throws XMLStreamException {
437 writer.writeComment(data);
441 public void writeProcessingInstruction(final String target) throws XMLStreamException {
442 writer.writeProcessingInstruction(target);
446 public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
447 writer.writeProcessingInstruction(target, data);
451 public void writeCData(final String data) throws XMLStreamException {
452 writer.writeCData(data);
456 public void writeDTD(final String dtd) throws XMLStreamException {
457 writer.writeDTD(dtd);
461 public void writeEntityRef(final String name) throws XMLStreamException {
462 writer.writeEntityRef(name);
466 public void writeStartDocument() throws XMLStreamException {
470 public void writeStartDocument(final String version) throws XMLStreamException {
474 public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
478 public void writeCharacters(final String text) throws XMLStreamException {
479 writer.writeCharacters(text);
483 public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
484 writer.writeCharacters(text, start, len);
488 public String getPrefix(final String uri) throws XMLStreamException {
489 return writer.getPrefix(uri);
493 public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
494 // Disabled since it causes exceptions in the underlying writer
498 public void setDefaultNamespace(final String uri) throws XMLStreamException {
499 writer.setDefaultNamespace(uri);
503 public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
504 writer.setNamespaceContext(context);
508 public NamespaceContext getNamespaceContext() {
509 return writer.getNamespaceContext();
513 public Object getProperty(final String name) {
514 return writer.getProperty(name);