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.model.api.SchemaContext;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.w3c.dom.Element;
48 * A {@link NormalizedNodeStreamWriter} which translates the events into an {@link XMLStreamWriter},
49 * resulting in a RFC 6020 XML encoding. There are 2 versions of this class, one that takes a
50 * SchemaContext and encodes values appropriately according to the yang schema. The other is
51 * schema-less and merely outputs values using toString. The latter is intended for debugging
52 * where doesn't have a SchemaContext available and isn't meant for production use.
54 public abstract class XMLStreamNormalizedNodeStreamWriter<T> implements NormalizedNodeStreamAttributeWriter {
55 private static final Logger LOG = LoggerFactory.getLogger(XMLStreamNormalizedNodeStreamWriter.class);
56 private static final String COM_SUN_TRANSFORMER =
57 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
59 static final TransformerFactory TRANSFORMER_FACTORY;
62 TransformerFactory fa = TransformerFactory.newInstance();
63 if (!fa.getFeature(StAXResult.FEATURE)) {
64 LOG.warn("Platform-default TransformerFactory {} does not support StAXResult, attempting fallback to {}",
65 fa, COM_SUN_TRANSFORMER);
66 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
67 if (!fa.getFeature(StAXResult.FEATURE)) {
68 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
72 TRANSFORMER_FACTORY = fa;
75 private static final Set<String> BROKEN_NAMESPACES = ConcurrentHashMap.newKeySet();
77 private final @NonNull XMLStreamWriter writer;
78 private final RandomPrefix prefixes;
80 XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
81 this.writer = requireNonNull(writer);
82 this.prefixes = new RandomPrefix(writer.getNamespaceContext());
86 * Create a new writer with the specified context as its root.
88 * @param writer Output {@link XMLStreamWriter}
89 * @param context Associated {@link SchemaContext}.
90 * @return A new {@link NormalizedNodeStreamWriter}
92 public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context) {
93 return create(writer, context, SchemaPath.ROOT);
97 * Create a new writer with the specified context and rooted in the specified schema path.
99 * @param writer Output {@link XMLStreamWriter}
100 * @param context Associated {@link SchemaContext}.
103 * @return A new {@link NormalizedNodeStreamWriter}
105 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
106 final SchemaPath path) {
107 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, path);
111 * Create a new schema-less writer. Note that this version is intended for debugging
112 * where doesn't have a SchemaContext available and isn't meant for production use.
114 * @param writer Output {@link XMLStreamWriter}
116 * @return A new {@link NormalizedNodeStreamWriter}
118 public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
119 return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
122 abstract void writeValue(@NonNull XMLStreamWriter xmlWriter, QName qname, @NonNull Object value, T context)
123 throws IOException, XMLStreamException;
125 abstract void startList(NodeIdentifier name);
127 abstract void startListItem(PathArgument name) throws IOException;
129 private void writeAttributes(final @NonNull Map<QName, String> attributes) throws IOException {
130 for (final Entry<QName, String> entry : attributes.entrySet()) {
132 final QName qname = entry.getKey();
133 final String namespace = qname.getNamespace().toString();
135 if (!Strings.isNullOrEmpty(namespace)) {
136 final String prefix = getPrefix(qname.getNamespace(), namespace);
137 writer.writeAttribute(prefix, namespace, qname.getLocalName(), entry.getValue());
139 writer.writeAttribute(qname.getLocalName(), entry.getValue());
141 } catch (final XMLStreamException e) {
142 throw new IOException("Unable to emit attribute " + entry, e);
147 private String getPrefix(final URI uri, final String str) throws XMLStreamException {
148 final String prefix = writer.getPrefix(str);
149 if (prefix != null) {
153 // This is needed to recover from attributes emitted while the namespace was not declared. Ordinarily
154 // attribute namespaces would be bound in the writer, so the resulting XML is efficient, but we cannot rely
155 // on that having been done.
156 if (BROKEN_NAMESPACES.add(str)) {
157 LOG.info("Namespace {} was not bound, please fix the caller", str, new Throwable());
160 return prefixes.encodePrefix(uri);
163 private void writeStartElement(final QName qname) throws XMLStreamException {
164 final String ns = qname.getNamespace().toString();
165 final NamespaceContext context = writer.getNamespaceContext();
166 final boolean needDefaultNs;
167 if (context != null) {
168 final String parentNs = context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX);
169 needDefaultNs = !ns.equals(parentNs);
171 needDefaultNs = false;
174 writer.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, qname.getLocalName(), ns);
176 writer.writeDefaultNamespace(ns);
180 final void writeElement(final QName qname, final Object value, final @Nullable Map<QName, String> attributes,
181 final T context) throws IOException {
183 writeStartElement(qname);
185 if (attributes != null) {
186 writeAttributes(attributes);
189 writeValue(writer, qname, value, context);
191 writer.writeEndElement();
192 } catch (XMLStreamException e) {
193 throw new IOException("Failed to emit element", e);
197 final void startElement(final QName qname) throws IOException {
199 writeStartElement(qname);
200 } catch (XMLStreamException e) {
201 throw new IOException("Failed to start element", e);
205 final void endElement() throws IOException {
207 writer.writeEndElement();
208 } catch (XMLStreamException e) {
209 throw new IOException("Failed to end element", e);
213 final void anyxmlNode(final QName qname, final Object value) throws IOException {
215 checkArgument(value instanceof DOMSource, "AnyXML value must be DOMSource, not %s", value);
216 final DOMSource domSource = (DOMSource) value;
217 requireNonNull(domSource.getNode());
218 checkArgument(domSource.getNode().getNodeName().equals(qname.getLocalName()));
219 checkArgument(domSource.getNode().getNamespaceURI().equals(qname.getNamespace().toString()));
221 // TODO can the transformer be a constant ? is it thread safe ?
222 final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
223 // Writer has to be wrapped in a wrapper that ignores endDocument event
224 // EndDocument event forbids any other modification to the writer so a nested anyXml breaks
226 transformer.transform(domSource, new StAXResult(new DelegateWriterNoEndDoc(writer)));
227 } catch (final TransformerException e) {
228 throw new IOException("Unable to transform anyXml(" + qname + ") value: " + value, e);
234 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint,
235 final Map<QName, String> attributes) throws IOException {
236 startContainerNode(name, childSizeHint);
237 writeAttributes(attributes);
241 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint,
242 final Map<QName, String> attributes) throws IOException {
243 startYangModeledAnyXmlNode(name, childSizeHint);
244 writeAttributes(attributes);
248 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint,
249 final Map<QName, String> attributes) throws IOException {
250 startUnkeyedListItem(name, childSizeHint);
251 writeAttributes(attributes);
255 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
260 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint,
261 final Map<QName, String> attributes) throws IOException {
262 startMapEntryNode(identifier, childSizeHint);
263 writeAttributes(attributes);
267 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
269 startListItem(identifier);
273 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
278 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
283 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
287 public static String toString(final Element xml) {
289 final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
290 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
292 final StreamResult result = new StreamResult(new StringWriter());
293 final DOMSource source = new DOMSource(xml);
294 transformer.transform(source, result);
296 return result.getWriter().toString();
297 } catch (IllegalArgumentException | TransformerException e) {
298 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
303 public final void close() throws IOException {
306 } catch (XMLStreamException e) {
307 throw new IOException("Failed to close writer", e);
312 public final void flush() throws IOException {
315 } catch (XMLStreamException e) {
316 throw new IOException("Failed to flush writer", e);
321 * Delegate writer that ignores writeEndDocument event. Used for AnyXml serialization.
323 private static final class DelegateWriterNoEndDoc implements XMLStreamWriter {
324 private final XMLStreamWriter writer;
326 DelegateWriterNoEndDoc(final XMLStreamWriter writer) {
327 this.writer = writer;
331 public void writeStartElement(final String localName) throws XMLStreamException {
332 writer.writeStartElement(localName);
336 public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
337 writer.writeStartElement(namespaceURI, localName);
341 public void writeStartElement(final String prefix, final String localName, final String namespaceURI)
342 throws XMLStreamException {
343 writer.writeStartElement(prefix, localName, namespaceURI);
347 public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
348 writer.writeEmptyElement(namespaceURI, localName);
352 public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI)
353 throws XMLStreamException {
354 writer.writeEmptyElement(prefix, localName, namespaceURI);
358 public void writeEmptyElement(final String localName) throws XMLStreamException {
359 writer.writeEmptyElement(localName);
363 public void writeEndElement() throws XMLStreamException {
364 writer.writeEndElement();
369 public void writeEndDocument() throws XMLStreamException {
370 // End document is disabled
374 public void close() throws XMLStreamException {
379 public void flush() throws XMLStreamException {
384 public void writeAttribute(final String localName, final String value) throws XMLStreamException {
385 writer.writeAttribute(localName, value);
389 public void writeAttribute(final String prefix, final String namespaceURI, final String localName,
390 final String value) throws XMLStreamException {
391 writer.writeAttribute(prefix, namespaceURI, localName, value);
395 public void writeAttribute(final String namespaceURI, final String localName, final String value)
396 throws XMLStreamException {
397 writer.writeAttribute(namespaceURI, localName, value);
401 public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
402 // Workaround for default namespace
403 // If a namespace is not prefixed, it is is still treated as prefix namespace.
404 // This results in the NamespaceSupport class ignoring the namespace since xmlns is not a valid prefix
405 // Write the namespace at least as an attribute
406 // TODO this is a hotfix, the transformer itself should write namespaces passing the namespace
407 // in writeStartElement method
408 if (prefix.equals("xml") || prefix.equals("xmlns")) {
409 writer.writeAttribute(prefix, namespaceURI);
411 writer.writeNamespace(prefix, namespaceURI);
416 public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
417 writer.writeDefaultNamespace(namespaceURI);
421 public void writeComment(final String data) throws XMLStreamException {
422 writer.writeComment(data);
426 public void writeProcessingInstruction(final String target) throws XMLStreamException {
427 writer.writeProcessingInstruction(target);
431 public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
432 writer.writeProcessingInstruction(target, data);
436 public void writeCData(final String data) throws XMLStreamException {
437 writer.writeCData(data);
441 public void writeDTD(final String dtd) throws XMLStreamException {
442 writer.writeDTD(dtd);
446 public void writeEntityRef(final String name) throws XMLStreamException {
447 writer.writeEntityRef(name);
451 public void writeStartDocument() throws XMLStreamException {
455 public void writeStartDocument(final String version) throws XMLStreamException {
459 public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
463 public void writeCharacters(final String text) throws XMLStreamException {
464 writer.writeCharacters(text);
468 public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
469 writer.writeCharacters(text, start, len);
473 public String getPrefix(final String uri) throws XMLStreamException {
474 return writer.getPrefix(uri);
478 public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
479 // Disabled since it causes exceptions in the underlying writer
483 public void setDefaultNamespace(final String uri) throws XMLStreamException {
484 writer.setDefaultNamespace(uri);
488 public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
489 writer.setNamespaceContext(context);
493 public NamespaceContext getNamespaceContext() {
494 return writer.getNamespaceContext();
498 public Object getProperty(final String name) {
499 return writer.getProperty(name);