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 = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
56 private static final TransformerFactory TRANSFORMER_FACTORY;
58 TransformerFactory f = TransformerFactory.newInstance();
59 if (!f.getFeature(StAXResult.FEATURE)) {
60 LOG.warn("Platform-default TransformerFactory {} does not support StAXResult, attempting fallback to {}",
61 f, COM_SUN_TRANSFORMER);
62 f = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
63 if (!f.getFeature(StAXResult.FEATURE)) {
64 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
68 TRANSFORMER_FACTORY = f;
71 private static final Set<String> BROKEN_NAMESPACES = ConcurrentHashMap.newKeySet();
73 private final RandomPrefix prefixes;
74 final XMLStreamWriter writer;
76 XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
77 this.writer = Preconditions.checkNotNull(writer);
78 this.prefixes = new RandomPrefix(writer.getNamespaceContext());
82 * Create a new writer with the specified context as its root.
84 * @param writer Output {@link XMLStreamWriter}
85 * @param context Associated {@link SchemaContext}.
86 * @return A new {@link NormalizedNodeStreamWriter}
88 public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context) {
89 return create(writer, context, SchemaPath.ROOT);
93 * Create a new writer with the specified context and rooted in the specified schema path
95 * @param writer Output {@link XMLStreamWriter}
96 * @param context Associated {@link SchemaContext}.
99 * @return A new {@link NormalizedNodeStreamWriter}
101 public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
102 final SchemaPath path) {
103 return SchemaAwareXMLStreamNormalizedNodeStreamWriter.newInstance(writer, context, path);
107 * Create a new schema-less writer. Note that this version is intended for debugging
108 * where doesn't have a SchemaContext available and isn't meant for production use.
110 * @param writer Output {@link XMLStreamWriter}
112 * @return A new {@link NormalizedNodeStreamWriter}
114 public static NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
115 return SchemalessXMLStreamNormalizedNodeStreamWriter.newInstance(writer);
118 abstract void writeValue(final XMLStreamWriter xmlWriter, final QName qname,
119 @Nonnull final Object value, T context) throws IOException, XMLStreamException;
121 abstract void startList(final NodeIdentifier name);
123 abstract void startListItem(final PathArgument name) throws IOException;
125 abstract void endNode(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException;
127 private void writeAttributes(@Nonnull final Map<QName, String> attributes) throws IOException {
128 for (final Entry<QName, String> qNameStringEntry : attributes.entrySet()) {
130 final QName qname = qNameStringEntry.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(), qNameStringEntry.getValue());
137 writer.writeAttribute(qname.getLocalName(), qNameStringEntry.getValue());
139 } catch (final XMLStreamException e) {
140 throw new IOException("Unable to emit attribute " + qNameStringEntry, 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 serialization
207 transformer.transform(domSource, new StAXResult(new DelegateWriterNoEndDoc(writer)));
208 } catch (final TransformerException e) {
209 throw new IOException("Unable to transform anyXml(" + qname + ") value: " + value, e);
215 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint,
216 final Map<QName, String> attributes) throws IOException {
217 startContainerNode(name, childSizeHint);
218 writeAttributes(attributes);
222 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint,
223 final Map<QName, String> attributes) throws IOException {
224 startYangModeledAnyXmlNode(name, childSizeHint);
225 writeAttributes(attributes);
229 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint,
230 final Map<QName, String> attributes) throws IOException {
231 startUnkeyedListItem(name, childSizeHint);
232 writeAttributes(attributes);
236 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint,
237 final Map<QName, String> attributes) throws IOException {
238 startMapEntryNode(identifier, childSizeHint);
239 writeAttributes(attributes);
243 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
248 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
253 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
258 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
260 startListItem(identifier);
264 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
268 public static String toString(final Element xml) {
270 final Transformer transformer = TransformerFactory.newInstance().newTransformer();
271 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
273 final StreamResult result = new StreamResult(new StringWriter());
274 final DOMSource source = new DOMSource(xml);
275 transformer.transform(source, result);
277 return result.getWriter().toString();
278 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
279 throw new RuntimeException("Unable to serialize xml element " + xml, e);
284 public final void endNode() throws IOException {
287 } catch (XMLStreamException e) {
288 throw new IOException("Failed to end element", e);
293 public final void close() throws IOException {
296 } catch (XMLStreamException e) {
297 throw new IOException("Failed to close writer", e);
302 public final void flush() throws IOException {
305 } catch (XMLStreamException e) {
306 throw new IOException("Failed to flush writer", e);
311 * Delegate writer that ignores writeEndDocument event. Used for AnyXml serialization.
313 private static final class DelegateWriterNoEndDoc implements XMLStreamWriter {
314 private final XMLStreamWriter writer;
316 public DelegateWriterNoEndDoc(final XMLStreamWriter writer) {
317 this.writer = writer;
321 public void writeStartElement(final String localName) throws XMLStreamException {
322 writer.writeStartElement(localName);
326 public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
327 writer.writeStartElement(namespaceURI, localName);
331 public void writeStartElement(final String prefix, final String localName, final String namespaceURI)
332 throws XMLStreamException {
333 writer.writeStartElement(prefix, localName, namespaceURI);
337 public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
338 writer.writeEmptyElement(namespaceURI, localName);
342 public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI)
343 throws XMLStreamException {
344 writer.writeEmptyElement(prefix, localName, namespaceURI);
348 public void writeEmptyElement(final String localName) throws XMLStreamException {
349 writer.writeEmptyElement(localName);
353 public void writeEndElement() throws XMLStreamException {
354 writer.writeEndElement();
359 public void writeEndDocument() throws XMLStreamException {
360 // End document is disabled
364 public void close() throws XMLStreamException {
369 public void flush() throws XMLStreamException {
374 public void writeAttribute(final String localName, final String value) throws XMLStreamException {
375 writer.writeAttribute(localName, value);
379 public void writeAttribute(final String prefix, final String namespaceURI, final String localName,
380 final String value) throws XMLStreamException {
381 writer.writeAttribute(prefix, namespaceURI, localName, value);
385 public void writeAttribute(final String namespaceURI, final String localName, final String value)
386 throws XMLStreamException {
387 writer.writeAttribute(namespaceURI, localName, value);
391 public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
392 // Workaround for default namespace
393 // If a namespace is not prefixed, it is is still treated as prefix namespace.
394 // This results in the NamespaceSupport class ignoring the namespace since xmlns is not a valid prefix
395 // Write the namespace at least as an attribute
396 // TODO this is a hotfix, the transformer itself should write namespaces passing the namespace
397 // in writeStartElement method
398 if (prefix.equals("xml") || prefix.equals("xmlns")) {
399 writer.writeAttribute(prefix, namespaceURI);
401 writer.writeNamespace(prefix, namespaceURI);
406 public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
407 writer.writeDefaultNamespace(namespaceURI);
411 public void writeComment(final String data) throws XMLStreamException {
412 writer.writeComment(data);
416 public void writeProcessingInstruction(final String target) throws XMLStreamException {
417 writer.writeProcessingInstruction(target);
421 public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
422 writer.writeProcessingInstruction(target, data);
426 public void writeCData(final String data) throws XMLStreamException {
427 writer.writeCData(data);
431 public void writeDTD(final String dtd) throws XMLStreamException {
432 writer.writeDTD(dtd);
436 public void writeEntityRef(final String name) throws XMLStreamException {
437 writer.writeEntityRef(name);
441 public void writeStartDocument() throws XMLStreamException {
445 public void writeStartDocument(final String version) throws XMLStreamException {
449 public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
453 public void writeCharacters(final String text) throws XMLStreamException {
454 writer.writeCharacters(text);
458 public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
459 writer.writeCharacters(text, start, len);
463 public String getPrefix(final String uri) throws XMLStreamException {
464 return writer.getPrefix(uri);
468 public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
469 // Disabled since it causes exceptions in the underlying writer
473 public void setDefaultNamespace(final String uri) throws XMLStreamException {
474 writer.setDefaultNamespace(uri);
478 public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
479 writer.setNamespaceContext(context);
483 public NamespaceContext getNamespaceContext() {
484 return writer.getNamespaceContext();
488 public Object getProperty(final String name) {
489 return writer.getProperty(name);