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