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.annotation.Nonnull;
22 import javax.annotation.Nullable;
23 import javax.xml.XMLConstants;
24 import javax.xml.namespace.NamespaceContext;
25 import javax.xml.stream.XMLStreamException;
26 import javax.xml.stream.XMLStreamWriter;
27 import javax.xml.transform.OutputKeys;
28 import javax.xml.transform.Transformer;
29 import javax.xml.transform.TransformerException;
30 import javax.xml.transform.TransformerFactory;
31 import javax.xml.transform.TransformerFactoryConfigurationError;
32 import javax.xml.transform.dom.DOMSource;
33 import javax.xml.transform.stax.StAXResult;
34 import javax.xml.transform.stream.StreamResult;
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 RandomPrefix prefixes;
78 final XMLStreamWriter writer;
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 NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
106 final SchemaPath path) {
107 return SchemaAwareXMLStreamNormalizedNodeStreamWriter.newInstance(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 NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
119 return SchemalessXMLStreamNormalizedNodeStreamWriter.newInstance(writer);
122 abstract void writeValue(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(@Nonnull final 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 void writeElement(final QName qname, final Object value, @Nullable final Map<QName, String> attributes,
181 final T context) throws IOException {
183 writeStartElement(qname);
185 writeAttributes(attributes);
187 writeValue(writer, qname, value, context);
189 writer.writeEndElement();
190 } catch (XMLStreamException e) {
191 throw new IOException("Failed to emit element", e);
195 void startElement(final QName qname) throws IOException {
197 writeStartElement(qname);
198 } catch (XMLStreamException e) {
199 throw new IOException("Failed to start element", e);
203 void anyxmlNode(final QName qname, final Object value) throws IOException {
205 checkArgument(value instanceof DOMSource, "AnyXML value must be DOMSource, not %s", value);
206 final DOMSource domSource = (DOMSource) value;
207 requireNonNull(domSource.getNode());
208 checkArgument(domSource.getNode().getNodeName().equals(qname.getLocalName()));
209 checkArgument(domSource.getNode().getNamespaceURI().equals(qname.getNamespace().toString()));
211 // TODO can the transformer be a constant ? is it thread safe ?
212 final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
213 // Writer has to be wrapped in a wrapper that ignores endDocument event
214 // EndDocument event forbids any other modification to the writer so a nested anyXml breaks
216 transformer.transform(domSource, new StAXResult(new DelegateWriterNoEndDoc(writer)));
217 } catch (final TransformerException e) {
218 throw new IOException("Unable to transform anyXml(" + qname + ") value: " + value, e);
224 public final void startContainerNode(final NodeIdentifier name, final int childSizeHint,
225 final Map<QName, String> attributes) throws IOException {
226 startContainerNode(name, childSizeHint);
227 writeAttributes(attributes);
231 public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint,
232 final Map<QName, String> attributes) throws IOException {
233 startYangModeledAnyXmlNode(name, childSizeHint);
234 writeAttributes(attributes);
238 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint,
239 final Map<QName, String> attributes) throws IOException {
240 startUnkeyedListItem(name, childSizeHint);
241 writeAttributes(attributes);
245 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
250 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint,
251 final Map<QName, String> attributes) throws IOException {
252 startMapEntryNode(identifier, childSizeHint);
253 writeAttributes(attributes);
257 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
259 startListItem(identifier);
263 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
268 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
273 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
277 public static String toString(final Element xml) {
279 final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
280 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
282 final StreamResult result = new StreamResult(new StringWriter());
283 final DOMSource source = new DOMSource(xml);
284 transformer.transform(source, result);
286 return result.getWriter().toString();
287 } catch (IllegalArgumentException | TransformerException e) {
288 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
292 abstract void endNode(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException;
295 public final void endNode() throws IOException {
298 } catch (XMLStreamException e) {
299 throw new IOException("Failed to end element", e);
304 public final void close() throws IOException {
307 } catch (XMLStreamException e) {
308 throw new IOException("Failed to close writer", e);
313 public final void flush() throws IOException {
316 } catch (XMLStreamException e) {
317 throw new IOException("Failed to flush writer", e);
322 * Delegate writer that ignores writeEndDocument event. Used for AnyXml serialization.
324 private static final class DelegateWriterNoEndDoc implements XMLStreamWriter {
325 private final XMLStreamWriter writer;
327 DelegateWriterNoEndDoc(final XMLStreamWriter writer) {
328 this.writer = writer;
332 public void writeStartElement(final String localName) throws XMLStreamException {
333 writer.writeStartElement(localName);
337 public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
338 writer.writeStartElement(namespaceURI, localName);
342 public void writeStartElement(final String prefix, final String localName, final String namespaceURI)
343 throws XMLStreamException {
344 writer.writeStartElement(prefix, localName, namespaceURI);
348 public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
349 writer.writeEmptyElement(namespaceURI, localName);
353 public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI)
354 throws XMLStreamException {
355 writer.writeEmptyElement(prefix, localName, namespaceURI);
359 public void writeEmptyElement(final String localName) throws XMLStreamException {
360 writer.writeEmptyElement(localName);
364 public void writeEndElement() throws XMLStreamException {
365 writer.writeEndElement();
370 public void writeEndDocument() throws XMLStreamException {
371 // End document is disabled
375 public void close() throws XMLStreamException {
380 public void flush() throws XMLStreamException {
385 public void writeAttribute(final String localName, final String value) throws XMLStreamException {
386 writer.writeAttribute(localName, value);
390 public void writeAttribute(final String prefix, final String namespaceURI, final String localName,
391 final String value) throws XMLStreamException {
392 writer.writeAttribute(prefix, namespaceURI, localName, value);
396 public void writeAttribute(final String namespaceURI, final String localName, final String value)
397 throws XMLStreamException {
398 writer.writeAttribute(namespaceURI, localName, value);
402 public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
403 // Workaround for default namespace
404 // If a namespace is not prefixed, it is is still treated as prefix namespace.
405 // This results in the NamespaceSupport class ignoring the namespace since xmlns is not a valid prefix
406 // Write the namespace at least as an attribute
407 // TODO this is a hotfix, the transformer itself should write namespaces passing the namespace
408 // in writeStartElement method
409 if (prefix.equals("xml") || prefix.equals("xmlns")) {
410 writer.writeAttribute(prefix, namespaceURI);
412 writer.writeNamespace(prefix, namespaceURI);
417 public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
418 writer.writeDefaultNamespace(namespaceURI);
422 public void writeComment(final String data) throws XMLStreamException {
423 writer.writeComment(data);
427 public void writeProcessingInstruction(final String target) throws XMLStreamException {
428 writer.writeProcessingInstruction(target);
432 public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
433 writer.writeProcessingInstruction(target, data);
437 public void writeCData(final String data) throws XMLStreamException {
438 writer.writeCData(data);
442 public void writeDTD(final String dtd) throws XMLStreamException {
443 writer.writeDTD(dtd);
447 public void writeEntityRef(final String name) throws XMLStreamException {
448 writer.writeEntityRef(name);
452 public void writeStartDocument() throws XMLStreamException {
456 public void writeStartDocument(final String version) throws XMLStreamException {
460 public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
464 public void writeCharacters(final String text) throws XMLStreamException {
465 writer.writeCharacters(text);
469 public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
470 writer.writeCharacters(text, start, len);
474 public String getPrefix(final String uri) throws XMLStreamException {
475 return writer.getPrefix(uri);
479 public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
480 // Disabled since it causes exceptions in the underlying writer
484 public void setDefaultNamespace(final String uri) throws XMLStreamException {
485 writer.setDefaultNamespace(uri);
489 public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
490 writer.setNamespaceContext(context);
494 public NamespaceContext getNamespaceContext() {
495 return writer.getNamespaceContext();
499 public Object getProperty(final String name) {
500 return writer.getProperty(name);