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.api.schema.stream;
10 import static com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
14 import com.google.common.annotations.Beta;
15 import com.google.common.collect.Iterables;
16 import java.io.Closeable;
17 import java.io.Flushable;
18 import java.io.IOException;
19 import java.util.Collection;
21 import javax.xml.stream.XMLStreamReader;
22 import javax.xml.transform.dom.DOMSource;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.schema.AnydataNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
32 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
47 * the opposite of a {@link XMLStreamReader} -- unlike instantiating an iterator over
48 * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
49 * us to write multiple nodes.
52 public class NormalizedNodeWriter implements Closeable, Flushable {
53 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeWriter.class);
55 private final @NonNull NormalizedNodeStreamWriter writer;
57 protected NormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
58 this.writer = requireNonNull(writer);
61 protected final NormalizedNodeStreamWriter getWriter() {
66 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
68 * @param writer Back-end writer
69 * @return A new instance.
71 public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer) {
72 return forStreamWriter(writer, true);
76 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
77 * {@link #forStreamWriter(NormalizedNodeStreamWriter)} method, this allows the caller to switch off RFC6020 XML
78 * compliance, providing better throughput. The reason is that the XML mapping rules in RFC6020 require
79 * the encoding to emit leaf nodes which participate in a list's key first and in the order in which they are
80 * defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any way we
81 * see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we need
82 * to check whether it was already emitted.
84 * @param writer Back-end writer
85 * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
86 * @return A new instance.
88 public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
89 final boolean orderKeyLeaves) {
90 return orderKeyLeaves ? new OrderedNormalizedNodeWriter(writer) : new NormalizedNodeWriter(writer);
94 * Iterate over the provided {@link NormalizedNode} and emit write
95 * events to the encapsulated {@link NormalizedNodeStreamWriter}.
98 * @return NormalizedNodeWriter this
99 * @throws IOException when thrown from the backing writer.
101 public NormalizedNodeWriter write(final NormalizedNode node) throws IOException {
102 if (wasProcessedAsCompositeNode(node)) {
106 if (wasProcessAsSimpleNode(node)) {
110 throw new IllegalStateException("It wasn't possible to serialize node " + node);
114 public void flush() throws IOException {
119 public void close() throws IOException {
125 * Emit a best guess of a hint for a particular set of children. It evaluates the
126 * iterable to see if the size can be easily gotten to. If it is, we hint at the
127 * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
129 * @param children Child nodes
130 * @return Best estimate of the collection size required to hold all the children.
132 protected static int childSizeHint(final Iterable<?> children) {
133 return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
136 protected boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
137 if (node instanceof LeafSetEntryNode<?> nodeAsLeafList) {
138 writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
139 writer.scalarValue(nodeAsLeafList.body());
142 } else if (node instanceof LeafNode<?> nodeAsLeaf) {
143 writer.startLeafNode(nodeAsLeaf.getIdentifier());
144 writer.scalarValue(nodeAsLeaf.body());
147 } else if (node instanceof AnyxmlNode<?> anyxmlNode) {
148 final Class<?> model = anyxmlNode.bodyObjectModel();
149 if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), model)) {
150 final Object value = node.body();
151 if (DOMSource.class.isAssignableFrom(model)) {
152 verify(value instanceof DOMSource, "Inconsistent anyxml node %s", anyxmlNode);
153 writer.domSourceValue((DOMSource) value);
155 writer.scalarValue(value);
161 LOG.debug("Ignoring unhandled anyxml node {}", anyxmlNode);
162 } else if (node instanceof AnydataNode<?> anydata) {
163 final Class<?> model = anydata.bodyObjectModel();
164 if (writer.startAnydataNode(anydata.getIdentifier(), model)) {
165 writer.scalarValue(anydata.body());
170 LOG.debug("Writer {} does not support anydata in form of {}", writer, model);
177 * Emit events for all children and then emit an endNode() event.
179 * @param children Child iterable
181 * @throws IOException when the writer reports it
183 protected boolean writeChildren(final Iterable<? extends NormalizedNode> children) throws IOException {
184 for (final NormalizedNode child : children) {
192 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
193 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
194 return writeChildren(node.body());
197 protected boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
198 if (node instanceof ContainerNode n) {
199 writer.startContainerNode(n.getIdentifier(), childSizeHint(n.body()));
200 return writeChildren(n.body());
201 } else if (node instanceof MapEntryNode n) {
202 return writeMapEntryNode(n);
203 } else if (node instanceof UnkeyedListEntryNode n) {
204 writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.body()));
205 return writeChildren(n.body());
206 } else if (node instanceof ChoiceNode n) {
207 writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.body()));
208 return writeChildren(n.body());
209 } else if (node instanceof AugmentationNode n) {
210 writer.startAugmentationNode(n.getIdentifier());
211 return writeChildren(n.body());
212 } else if (node instanceof UnkeyedListNode n) {
213 writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.body()));
214 return writeChildren(n.body());
215 } else if (node instanceof UserMapNode n) {
216 writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.body()));
217 return writeChildren(n.body());
218 } else if (node instanceof SystemMapNode n) {
219 writer.startMapNode(n.getIdentifier(), childSizeHint(n.body()));
220 return writeChildren(n.body());
221 } else if (node instanceof UserLeafSetNode<?> n) {
222 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.body()));
223 return writeChildren(n.body());
224 } else if (node instanceof SystemLeafSetNode<?> n) {
225 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.body()));
226 return writeChildren(n.body());
231 private static final class OrderedNormalizedNodeWriter extends NormalizedNodeWriter {
232 private static final Logger LOG = LoggerFactory.getLogger(OrderedNormalizedNodeWriter.class);
234 OrderedNormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
239 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
240 final NormalizedNodeStreamWriter nnWriter = getWriter();
241 nnWriter.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
243 final Set<QName> qnames = node.getIdentifier().keySet();
244 // Write out all the key children
245 for (final QName qname : qnames) {
246 final DataContainerChild child = node.childByArg(new NodeIdentifier(qname));
250 LOG.info("No child for key element {} found", qname);
254 // Write all the rest
255 return writeChildren(Iterables.filter(node.body(), input -> {
256 if (input instanceof AugmentationNode) {
259 if (!qnames.contains(input.getIdentifier().getNodeType())) {
263 LOG.debug("Skipping key child {}", input);