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;
20 import java.util.Optional;
22 import javax.xml.stream.XMLStreamReader;
23 import javax.xml.transform.dom.DOMSource;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.schema.AnydataNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
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.LeafSetNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.YangModeledAnyXmlNode;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
48 * the opposite of a {@link XMLStreamReader} -- unlike instantiating an iterator over
49 * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
50 * us to write multiple nodes.
53 public class NormalizedNodeWriter implements Closeable, Flushable {
54 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeWriter.class);
56 private final @NonNull NormalizedNodeStreamWriter writer;
58 protected NormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
59 this.writer = requireNonNull(writer);
62 protected final NormalizedNodeStreamWriter getWriter() {
67 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
69 * @param writer Back-end writer
70 * @return A new instance.
72 public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer) {
73 return forStreamWriter(writer, true);
77 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
78 * {@link #forStreamWriter(NormalizedNodeStreamWriter)} method, this allows the caller to switch off RFC6020 XML
79 * compliance, providing better throughput. The reason is that the XML mapping rules in RFC6020 require
80 * the encoding to emit leaf nodes which participate in a list's key first and in the order in which they are
81 * defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any way we
82 * see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we need
83 * to check whether it was already emitted.
85 * @param writer Back-end writer
86 * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
87 * @return A new instance.
89 public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
90 final boolean orderKeyLeaves) {
91 return orderKeyLeaves ? new OrderedNormalizedNodeWriter(writer) : new NormalizedNodeWriter(writer);
95 * Iterate over the provided {@link NormalizedNode} and emit write
96 * events to the encapsulated {@link NormalizedNodeStreamWriter}.
99 * @return NormalizedNodeWriter this
100 * @throws IOException when thrown from the backing writer.
102 public NormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException {
103 if (wasProcessedAsCompositeNode(node)) {
107 if (wasProcessAsSimpleNode(node)) {
111 throw new IllegalStateException("It wasn't possible to serialize node " + node);
115 public void flush() throws IOException {
120 public void close() throws IOException {
126 * Emit a best guess of a hint for a particular set of children. It evaluates the
127 * iterable to see if the size can be easily gotten to. If it is, we hint at the
128 * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
130 * @param children Child nodes
131 * @return Best estimate of the collection size required to hold all the children.
133 protected static int childSizeHint(final Iterable<?> children) {
134 return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
137 protected boolean wasProcessAsSimpleNode(final NormalizedNode<?, ?> node) throws IOException {
138 if (node instanceof LeafSetEntryNode) {
139 final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>)node;
140 writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
141 writer.scalarValue(nodeAsLeafList.getValue());
144 } else if (node instanceof LeafNode) {
145 final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
146 writer.startLeafNode(nodeAsLeaf.getIdentifier());
147 writer.scalarValue(nodeAsLeaf.getValue());
150 } else if (node instanceof AnyxmlNode) {
151 final AnyxmlNode<?> anyxmlNode = (AnyxmlNode<?>)node;
152 final Class<?> model = anyxmlNode.getValueObjectModel();
153 if (DOMSource.class.isAssignableFrom(model)) {
154 final Object value = node.getValue();
155 verify(value instanceof DOMSource, "Inconsistent anyxml node %s", anyxmlNode);
156 writer.startAnyxmlNode(anyxmlNode.getIdentifier());
157 writer.domSourceValue((DOMSource) value);
162 LOG.debug("Ignoring unhandled anyxml node {}", anyxmlNode);
163 } else if (node instanceof AnydataNode) {
164 final AnydataExtension ext = writer.getExtensions().getInstance(AnydataExtension.class);
166 final AnydataNode<?> anydata = (AnydataNode<?>) node;
167 final Class<?> model = anydata.getValueObjectModel();
168 if (ext.startAnydataNode(anydata.getIdentifier(), model)) {
169 writer.scalarValue(anydata.getValue());
174 LOG.debug("Writer {} does not support anydata in form of {}", writer, model);
176 LOG.debug("Writer {} does not support anydata", writer);
184 * Emit events for all children and then emit an endNode() event.
186 * @param children Child iterable
188 * @throws IOException when the writer reports it
190 protected boolean writeChildren(final Iterable<? extends NormalizedNode<?, ?>> children) throws IOException {
191 for (final NormalizedNode<?, ?> child : children) {
199 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
200 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
201 return writeChildren(node.getValue());
204 protected boolean wasProcessedAsCompositeNode(final NormalizedNode<?, ?> node) throws IOException {
205 if (node instanceof ContainerNode) {
206 final ContainerNode n = (ContainerNode) node;
207 writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
208 return writeChildren(n.getValue());
210 if (node instanceof YangModeledAnyXmlNode) {
211 final YangModeledAnyXmlNode n = (YangModeledAnyXmlNode) node;
212 writer.startYangModeledAnyXmlNode(n.getIdentifier(), childSizeHint(n.getValue()));
213 return writeChildren(n.getValue());
215 if (node instanceof MapEntryNode) {
216 return writeMapEntryNode((MapEntryNode) node);
218 if (node instanceof UnkeyedListEntryNode) {
219 final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
220 writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.getValue()));
221 return writeChildren(n.getValue());
223 if (node instanceof ChoiceNode) {
224 final ChoiceNode n = (ChoiceNode) node;
225 writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.getValue()));
226 return writeChildren(n.getValue());
228 if (node instanceof AugmentationNode) {
229 final AugmentationNode n = (AugmentationNode) node;
230 writer.startAugmentationNode(n.getIdentifier());
231 return writeChildren(n.getValue());
233 if (node instanceof UnkeyedListNode) {
234 final UnkeyedListNode n = (UnkeyedListNode) node;
235 writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.getValue()));
236 return writeChildren(n.getValue());
238 if (node instanceof OrderedMapNode) {
239 final OrderedMapNode n = (OrderedMapNode) node;
240 writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
241 return writeChildren(n.getValue());
243 if (node instanceof MapNode) {
244 final MapNode n = (MapNode) node;
245 writer.startMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
246 return writeChildren(n.getValue());
248 if (node instanceof OrderedLeafSetNode) {
249 final LeafSetNode<?> n = (LeafSetNode<?>) node;
250 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
251 return writeChildren(n.getValue());
253 if (node instanceof LeafSetNode) {
254 final LeafSetNode<?> n = (LeafSetNode<?>) node;
255 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
256 return writeChildren(n.getValue());
262 private static final class OrderedNormalizedNodeWriter extends NormalizedNodeWriter {
263 private static final Logger LOG = LoggerFactory.getLogger(OrderedNormalizedNodeWriter.class);
265 OrderedNormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
270 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
271 final NormalizedNodeStreamWriter nnWriter = getWriter();
272 nnWriter.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
274 final Set<QName> qnames = node.getIdentifier().keySet();
275 // Write out all the key children
276 for (final QName qname : qnames) {
277 final Optional<? extends NormalizedNode<?, ?>> child = node.getChild(new NodeIdentifier(qname));
278 if (child.isPresent()) {
281 LOG.info("No child for key element {} found", qname);
285 // Write all the rest
286 return writeChildren(Iterables.filter(node.getValue(), input -> {
287 if (input instanceof AugmentationNode) {
290 if (!qnames.contains(input.getNodeType())) {
294 LOG.debug("Skipping key child {}", input);