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) {
138 final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>)node;
139 writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
140 writer.scalarValue(nodeAsLeafList.body());
143 } else if (node instanceof LeafNode) {
144 final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
145 writer.startLeafNode(nodeAsLeaf.getIdentifier());
146 writer.scalarValue(nodeAsLeaf.body());
149 } else if (node instanceof AnyxmlNode) {
150 final AnyxmlNode<?> anyxmlNode = (AnyxmlNode<?>)node;
151 final Class<?> model = anyxmlNode.bodyObjectModel();
152 if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), model)) {
153 final Object value = node.body();
154 if (DOMSource.class.isAssignableFrom(model)) {
155 verify(value instanceof DOMSource, "Inconsistent anyxml node %s", anyxmlNode);
156 writer.domSourceValue((DOMSource) value);
158 writer.scalarValue(value);
164 LOG.debug("Ignoring unhandled anyxml node {}", anyxmlNode);
165 } else if (node instanceof AnydataNode) {
166 final AnydataNode<?> anydata = (AnydataNode<?>) node;
167 final Class<?> model = anydata.bodyObjectModel();
168 if (writer.startAnydataNode(anydata.getIdentifier(), model)) {
169 writer.scalarValue(anydata.body());
174 LOG.debug("Writer {} does not support anydata in form of {}", writer, model);
181 * Emit events for all children and then emit an endNode() event.
183 * @param children Child iterable
185 * @throws IOException when the writer reports it
187 protected boolean writeChildren(final Iterable<? extends NormalizedNode> children) throws IOException {
188 for (final NormalizedNode child : children) {
196 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
197 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
198 return writeChildren(node.body());
201 protected boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
202 if (node instanceof ContainerNode) {
203 final ContainerNode n = (ContainerNode) node;
204 writer.startContainerNode(n.getIdentifier(), childSizeHint(n.body()));
205 return writeChildren(n.body());
207 if (node instanceof MapEntryNode) {
208 return writeMapEntryNode((MapEntryNode) node);
210 if (node instanceof UnkeyedListEntryNode) {
211 final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
212 writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.body()));
213 return writeChildren(n.body());
215 if (node instanceof ChoiceNode) {
216 final ChoiceNode n = (ChoiceNode) node;
217 writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.body()));
218 return writeChildren(n.body());
220 if (node instanceof AugmentationNode) {
221 final AugmentationNode n = (AugmentationNode) node;
222 writer.startAugmentationNode(n.getIdentifier());
223 return writeChildren(n.body());
225 if (node instanceof UnkeyedListNode) {
226 final UnkeyedListNode n = (UnkeyedListNode) node;
227 writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.body()));
228 return writeChildren(n.body());
230 if (node instanceof UserMapNode) {
231 final UserMapNode n = (UserMapNode) node;
232 writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.body()));
233 return writeChildren(n.body());
235 if (node instanceof SystemMapNode) {
236 final SystemMapNode n = (SystemMapNode) node;
237 writer.startMapNode(n.getIdentifier(), childSizeHint(n.body()));
238 return writeChildren(n.body());
240 if (node instanceof UserLeafSetNode) {
241 final UserLeafSetNode<?> n = (UserLeafSetNode<?>) node;
242 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.body()));
243 return writeChildren(n.body());
245 if (node instanceof SystemLeafSetNode) {
246 final SystemLeafSetNode<?> n = (SystemLeafSetNode<?>) node;
247 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.body()));
248 return writeChildren(n.body());
254 private static final class OrderedNormalizedNodeWriter extends NormalizedNodeWriter {
255 private static final Logger LOG = LoggerFactory.getLogger(OrderedNormalizedNodeWriter.class);
257 OrderedNormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
262 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
263 final NormalizedNodeStreamWriter nnWriter = getWriter();
264 nnWriter.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
266 final Set<QName> qnames = node.getIdentifier().keySet();
267 // Write out all the key children
268 for (final QName qname : qnames) {
269 final DataContainerChild child = node.childByArg(new NodeIdentifier(qname));
273 LOG.info("No child for key element {} found", qname);
277 // Write all the rest
278 return writeChildren(Iterables.filter(node.body(), input -> {
279 if (input instanceof AugmentationNode) {
282 if (!qnames.contains(input.getIdentifier().getNodeType())) {
286 LOG.debug("Skipping key child {}", input);