Eliminate NormalizedNodePayload
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / server / spi / NormalizedNodeWriter.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.server.spi;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.Iterables;
14 import java.io.Closeable;
15 import java.io.Flushable;
16 import java.io.IOException;
17 import java.util.List;
18 import java.util.Map.Entry;
19 import java.util.Set;
20 import javax.xml.transform.dom.DOMSource;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.opendaylight.restconf.api.query.DepthParam;
24 import org.opendaylight.yangtools.yang.common.Ordering;
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.ChoiceNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
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.SystemMapNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
46  * the opposite of a {@link javax.xml.stream.XMLStreamReader} -- unlike instantiating an iterator over
47  * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
48  * us to write multiple nodes.
49  */
50 // FIXME: this is a copy&paste from yangtools' NormalizedNodeWriter then adapted for filtering
51 @Beta
52 public sealed class NormalizedNodeWriter implements Flushable, Closeable {
53     private static final QName ROOT_DATA_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "data");
54
55     final @NonNull NormalizedNodeStreamWriter writer;
56     private final Integer maxDepth;
57     private final List<Set<QName>> fields;
58
59     int currentDepth = 0;
60
61     private NormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParam depth,
62             final List<Set<QName>> fields) {
63         this.writer = requireNonNull(writer);
64         maxDepth = depth == null ? null : depth.value();
65         this.fields = fields;
66     }
67
68     /**
69      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
70      *
71      * @param writer Back-end writer
72      * @param maxDepth Maximal depth to write
73      * @return A new instance.
74      */
75     public static @NonNull NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
76             final @Nullable DepthParam maxDepth) {
77         return forStreamWriter(writer, true,  maxDepth, null);
78     }
79
80     /**
81      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
82      *
83      * @param writer Back-end writer
84      * @param maxDepth Maximal depth to write
85      * @param fields Selected child nodes to write
86      * @return A new instance.
87      */
88     public static @NonNull NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
89             final @Nullable DepthParam maxDepth, final @Nullable List<Set<QName>> fields) {
90         return forStreamWriter(writer, true,  maxDepth, fields);
91     }
92
93     /**
94      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
95      * {@link #forStreamWriter(NormalizedNodeStreamWriter, DepthParam, List)} method, this allows the caller to
96      * switch off RFC6020 XML compliance, providing better throughput. The reason is that the XML mapping rules in
97      * RFC6020 require the encoding to emit leaf nodes which participate in a list's key first and in the order in which
98      * they are defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any
99      * way we see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we
100      * need to check whether it was already emitted.
101      *
102      * @param writer Back-end writer
103      * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
104      * @param depth Maximal depth to write
105      * @param fields Selected child nodes to write
106      * @return A new instance.
107      */
108     public static @NonNull NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
109             final boolean orderKeyLeaves, final DepthParam depth, final List<Set<QName>> fields) {
110         return orderKeyLeaves ? new OrderedRestconfNormalizedNodeWriter(writer, depth, fields)
111                 : new NormalizedNodeWriter(writer, depth, fields);
112     }
113
114     /**
115      * Iterate over the provided {@link NormalizedNode} and emit write events to the encapsulated
116      * {@link NormalizedNodeStreamWriter}.
117      *
118      * @param node Node
119      * @return {@code ParameterAwareNormalizedNodeWriter}
120      * @throws IOException when thrown from the backing writer.
121      */
122     public final NormalizedNodeWriter write(final NormalizedNode node) throws IOException {
123         if (wasProcessedAsCompositeNode(node) || wasProcessAsSimpleNode(node)) {
124             return this;
125         }
126         throw new IllegalStateException("It wasn't possible to serialize node " + node);
127     }
128
129     @Override
130     public final void flush() throws IOException {
131         writer.flush();
132     }
133
134     @Override
135     public final void close() throws IOException {
136         writer.flush();
137         writer.close();
138     }
139
140     private boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
141         if (node instanceof LeafSetEntryNode<?> nodeAsLeafList) {
142             if (selectedByParameters(node, false)) {
143                 writer.startLeafSetEntryNode(nodeAsLeafList.name());
144                 writer.scalarValue(nodeAsLeafList.body());
145                 writer.endNode();
146             }
147         } else if (node instanceof LeafNode<?> nodeAsLeaf) {
148             writer.startLeafNode(nodeAsLeaf.name());
149             writer.scalarValue(nodeAsLeaf.body());
150             writer.endNode();
151         } else if (node instanceof AnyxmlNode<?> anyxmlNode) {
152             final var objectModel = anyxmlNode.bodyObjectModel();
153             if (writer.startAnyxmlNode(anyxmlNode.name(), objectModel)) {
154                 if (DOMSource.class.isAssignableFrom(objectModel)) {
155                     writer.domSourceValue((DOMSource) anyxmlNode.body());
156                 } else {
157                     writer.scalarValue(anyxmlNode.body());
158                 }
159                 writer.endNode();
160             }
161         } else if (node instanceof AnydataNode<?> anydataNode) {
162             final var objectModel = anydataNode.bodyObjectModel();
163             if (writer.startAnydataNode(anydataNode.name(), objectModel)) {
164                 writer.scalarValue(anydataNode.body());
165                 writer.endNode();
166             }
167         } else {
168             return false;
169         }
170         return true;
171     }
172
173     /**
174      * Check if node should be written according to parameters fields and depth.
175      * See <a href="https://tools.ietf.org/html/draft-ietf-netconf-restconf-18#page-49">Restconf draft</a>.
176      * @param node Node to be written
177      * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
178      * @return {@code true} if node will be written, {@code false} otherwise
179      */
180     protected boolean selectedByParameters(final NormalizedNode node, final boolean mixinParent) {
181         // nodes to be written are not limited by fields, only by depth
182         if (fields == null) {
183             return maxDepth == null || currentDepth < maxDepth;
184         }
185
186         // children of mixin nodes are never selected in fields but must be written if they are first in selected target
187         if (mixinParent && currentDepth == 0) {
188             return true;
189         }
190
191         // write only selected nodes
192         if (currentDepth > 0 && currentDepth <= fields.size()) {
193             return fields.get(currentDepth - 1).contains(node.name().getNodeType());
194         }
195
196         // after this depth only depth parameter is used to determine when to write node
197         return maxDepth == null || currentDepth < maxDepth;
198     }
199
200     /**
201      * Emit events for all children and then emit an endNode() event.
202      *
203      * @param children Child iterable
204      * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
205      * @return True
206      * @throws IOException when the writer reports it
207      */
208     protected final boolean writeChildren(final Iterable<? extends NormalizedNode> children, final boolean mixinParent)
209             throws IOException {
210         for (var child : children) {
211             if (selectedByParameters(child, mixinParent)) {
212                 write(child);
213             }
214         }
215         writer.endNode();
216         return true;
217     }
218
219     private boolean writeMapEntryChildren(final MapEntryNode mapEntryNode) throws IOException {
220         if (selectedByParameters(mapEntryNode, false)) {
221             writeChildren(mapEntryNode.body(), false);
222         } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
223             writeOnlyKeys(mapEntryNode.name().entrySet());
224         }
225         return true;
226     }
227
228     private void writeOnlyKeys(final Set<Entry<QName, Object>> entries) throws IOException {
229         for (final Entry<QName, Object> entry : entries) {
230             writer.startLeafNode(new NodeIdentifier(entry.getKey()));
231             writer.scalarValue(entry.getValue());
232             writer.endNode();
233         }
234         writer.endNode();
235     }
236
237     boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
238         writer.startMapEntryNode(node.name(), node.size());
239         currentDepth++;
240         writeMapEntryChildren(node);
241         currentDepth--;
242         return true;
243     }
244
245     private boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
246         boolean processedAsCompositeNode = false;
247         if (node instanceof ContainerNode n) {
248             if (!n.name().getNodeType().withoutRevision().equals(ROOT_DATA_QNAME)) {
249                 writer.startContainerNode(n.name(), n.size());
250                 currentDepth++;
251                 processedAsCompositeNode = writeChildren(n.body(), false);
252                 currentDepth--;
253             } else {
254                 // write child nodes of data root container
255                 for (final NormalizedNode child : n.body()) {
256                     currentDepth++;
257                     if (selectedByParameters(child, false)) {
258                         write(child);
259                     }
260                     currentDepth--;
261                 }
262                 processedAsCompositeNode = true;
263             }
264         } else if (node instanceof MapEntryNode n) {
265             processedAsCompositeNode = writeMapEntryNode(n);
266         } else if (node instanceof UnkeyedListEntryNode n) {
267             writer.startUnkeyedListItem(n.name(), n.size());
268             currentDepth++;
269             processedAsCompositeNode = writeChildren(n.body(), false);
270             currentDepth--;
271         } else if (node instanceof ChoiceNode n) {
272             writer.startChoiceNode(n.name(), n.size());
273             processedAsCompositeNode = writeChildren(n.body(), true);
274         } else if (node instanceof UnkeyedListNode n) {
275             writer.startUnkeyedList(n.name(), n.size());
276             processedAsCompositeNode = writeChildren(n.body(), false);
277         } else if (node instanceof UserMapNode n) {
278             writer.startOrderedMapNode(n.name(), n.size());
279             processedAsCompositeNode = writeChildren(n.body(), true);
280         } else if (node instanceof SystemMapNode n) {
281             writer.startMapNode(n.name(), n.size());
282             processedAsCompositeNode = writeChildren(n.body(), true);
283         } else if (node instanceof LeafSetNode<?> n) {
284             if (n.ordering() == Ordering.USER) {
285                 writer.startOrderedLeafSet(n.name(), n.size());
286             } else {
287                 writer.startLeafSet(n.name(), n.size());
288             }
289             currentDepth++;
290             processedAsCompositeNode = writeChildren(n.body(), true);
291             currentDepth--;
292         }
293
294         return processedAsCompositeNode;
295     }
296
297     private static final class OrderedRestconfNormalizedNodeWriter extends NormalizedNodeWriter {
298         private static final Logger LOG = LoggerFactory.getLogger(OrderedRestconfNormalizedNodeWriter.class);
299
300         OrderedRestconfNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParam depth,
301                 final List<Set<QName>> fields) {
302             super(writer, depth, fields);
303         }
304
305         @Override
306         boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
307             writer.startMapEntryNode(node.name(), node.size());
308
309             final var qnames = node.name().keySet();
310             // Write out all the key children
311             currentDepth++;
312             for (var qname : qnames) {
313                 final var child = node.childByArg(new NodeIdentifier(qname));
314                 if (child != null) {
315                     if (selectedByParameters(child, false)) {
316                         write(child);
317                     }
318                 } else {
319                     LOG.info("No child for key element {} found", qname);
320                 }
321             }
322
323             // Write all the rest
324             final boolean result = writeChildren(Iterables.filter(node.body(), input -> {
325                 if (!qnames.contains(input.name().getNodeType())) {
326                     return true;
327                 }
328
329                 LOG.debug("Skipping key child {}", input);
330                 return false;
331             }), false);
332             currentDepth--;
333             return result;
334         }
335     }
336 }