Bump MRI upstreams
[netconf.git] / restconf / restconf-nb-rfc8040 / 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 import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.collect.Iterables;
15 import java.io.IOException;
16 import java.util.Collection;
17 import java.util.List;
18 import java.util.Map.Entry;
19 import java.util.Optional;
20 import java.util.Set;
21 import javax.xml.transform.dom.DOMSource;
22 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.api.RestconfNormalizedNodeWriter;
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.AnyxmlNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
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.LeafNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
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 Integer maxDepth,
59                                                final List<Set<QName>> fields) {
60         this.writer = requireNonNull(writer);
61         this.maxDepth = maxDepth;
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 ParameterAwareNormalizedNodeWriter forStreamWriter(
78             final NormalizedNodeStreamWriter writer, final Integer 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, Integer, List)}
85      * method, this allows the caller to switch off RFC6020 XML compliance, providing better
86      * throughput. The reason is that the XML mapping rules in RFC6020 require the encoding
87      * to emit leaf nodes which participate in a list's key first and in the order in which
88      * they are defined in the key. For JSON, this requirement is completely relaxed and leaves
89      * can be ordered in any way we see fit. The former requires a bit of work: first a lookup
90      * for each key and then for each emitted node we need to check whether it was already
91      * emitted.
92      *
93      * @param writer Back-end writer
94      * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
95      * @param maxDepth Maximal depth to write
96      * @param fields Selected child nodes to write
97      * @return A new instance.
98      */
99     public static ParameterAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
100                                                                      final boolean orderKeyLeaves,
101                                                                      final Integer maxDepth,
102                                                                      final List<Set<QName>> fields) {
103         return orderKeyLeaves ? new OrderedParameterAwareNormalizedNodeWriter(writer, maxDepth, fields)
104                 : new ParameterAwareNormalizedNodeWriter(writer, maxDepth, fields);
105     }
106
107     /**
108      * Iterate over the provided {@link NormalizedNode} and emit write
109      * events to the encapsulated {@link NormalizedNodeStreamWriter}.
110      *
111      * @param node Node
112      * @return {@code ParameterAwareNormalizedNodeWriter}
113      * @throws IOException when thrown from the backing writer.
114      */
115     @Override
116     public final ParameterAwareNormalizedNodeWriter write(final NormalizedNode node) throws IOException {
117         if (wasProcessedAsCompositeNode(node)) {
118             return this;
119         }
120
121         if (wasProcessAsSimpleNode(node)) {
122             return this;
123         }
124
125         throw new IllegalStateException("It wasn't possible to serialize node " + node);
126     }
127
128     @Override
129     public void flush() throws IOException {
130         writer.flush();
131     }
132
133     @Override
134     public void close() throws IOException {
135         writer.flush();
136         writer.close();
137     }
138
139     /**
140      * Emit a best guess of a hint for a particular set of children. It evaluates the
141      * iterable to see if the size can be easily gotten to. If it is, we hint at the
142      * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
143      *
144      * @param children Child nodes
145      * @return Best estimate of the collection size required to hold all the children.
146      */
147     static final int childSizeHint(final Iterable<?> children) {
148         return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
149     }
150
151     private boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
152         if (node instanceof LeafSetEntryNode) {
153             if (selectedByParameters(node, false)) {
154                 final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>) node;
155                 writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
156                 writer.scalarValue(nodeAsLeafList.body());
157                 writer.endNode();
158             }
159             return true;
160         } else if (node instanceof LeafNode) {
161             final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
162             writer.startLeafNode(nodeAsLeaf.getIdentifier());
163             writer.scalarValue(nodeAsLeaf.body());
164             writer.endNode();
165             return true;
166         } else if (node instanceof AnyxmlNode) {
167             final AnyxmlNode<?> anyxmlNode = (AnyxmlNode<?>)node;
168             final Class<?> objectModel = anyxmlNode.bodyObjectModel();
169             if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), objectModel)) {
170                 if (DOMSource.class.isAssignableFrom(objectModel)) {
171                     writer.domSourceValue((DOMSource) anyxmlNode.body());
172                 } else {
173                     writer.scalarValue(anyxmlNode.body());
174                 }
175                 writer.endNode();
176             }
177             return true;
178         }
179
180         return false;
181     }
182
183     /**
184      * Check if node should be written according to parameters fields and depth.
185      * See <a href="https://tools.ietf.org/html/draft-ietf-netconf-restconf-18#page-49">Restconf draft</a>.
186      * @param node Node to be written
187      * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
188      * @return {@code true} if node will be written, {@code false} otherwise
189      */
190     protected boolean selectedByParameters(final NormalizedNode node, final boolean mixinParent) {
191         // nodes to be written are not limited by fields, only by depth
192         if (fields == null) {
193             return maxDepth == null || currentDepth < maxDepth;
194         }
195
196         // children of mixin nodes are never selected in fields but must be written if they are first in selected target
197         if (mixinParent && currentDepth == 0) {
198             return true;
199         }
200
201         // always write augmentation nodes
202         if (node instanceof AugmentationNode) {
203             return true;
204         }
205
206         // write only selected nodes
207         if (currentDepth > 0 && currentDepth <= fields.size()) {
208             return fields.get(currentDepth - 1).contains(node.getIdentifier().getNodeType());
209         }
210
211         // after this depth only depth parameter is used to determine when to write node
212         return maxDepth == null || currentDepth < maxDepth;
213     }
214
215     /**
216      * Emit events for all children and then emit an endNode() event.
217      *
218      * @param children Child iterable
219      * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
220      * @return True
221      * @throws IOException when the writer reports it
222      */
223     protected final boolean writeChildren(final Iterable<? extends NormalizedNode> children,
224                                           final boolean mixinParent) throws IOException {
225         for (final NormalizedNode child : children) {
226             if (selectedByParameters(child, mixinParent)) {
227                 write(child);
228             }
229         }
230         writer.endNode();
231         return true;
232     }
233
234     protected boolean writeMapEntryChildren(final MapEntryNode mapEntryNode) throws IOException {
235         if (selectedByParameters(mapEntryNode, false)) {
236             writeChildren(mapEntryNode.body(), false);
237         } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
238             writeOnlyKeys(mapEntryNode.getIdentifier().entrySet());
239         }
240         return true;
241     }
242
243     private void writeOnlyKeys(final Set<Entry<QName, Object>> entries) throws IOException {
244         for (final Entry<QName, Object> entry : entries) {
245             writer.startLeafNode(new NodeIdentifier(entry.getKey()));
246             writer.scalarValue(entry.getValue());
247             writer.endNode();
248         }
249         writer.endNode();
250     }
251
252     protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
253         writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
254         currentDepth++;
255         writeMapEntryChildren(node);
256         currentDepth--;
257         return true;
258     }
259
260     private boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
261         boolean processedAsCompositeNode = false;
262         if (node instanceof ContainerNode) {
263             final ContainerNode n = (ContainerNode) node;
264             if (!n.getIdentifier().getNodeType().withoutRevision().equals(ROOT_DATA_QNAME)) {
265                 writer.startContainerNode(n.getIdentifier(), childSizeHint(n.body()));
266                 currentDepth++;
267                 processedAsCompositeNode = writeChildren(n.body(), false);
268                 currentDepth--;
269             } else {
270                 // write child nodes of data root container
271                 for (final NormalizedNode child : n.body()) {
272                     currentDepth++;
273                     if (selectedByParameters(child, false)) {
274                         write(child);
275                     }
276                     currentDepth--;
277                     processedAsCompositeNode = true;
278                 }
279             }
280         } else if (node instanceof MapEntryNode) {
281             processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
282         } else if (node instanceof UnkeyedListEntryNode) {
283             final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
284             writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.body()));
285             currentDepth++;
286             processedAsCompositeNode = writeChildren(n.body(), false);
287             currentDepth--;
288         } else if (node instanceof ChoiceNode) {
289             final ChoiceNode n = (ChoiceNode) node;
290             writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.body()));
291             processedAsCompositeNode = writeChildren(n.body(), true);
292         } else if (node instanceof AugmentationNode) {
293             final AugmentationNode n = (AugmentationNode) node;
294             writer.startAugmentationNode(n.getIdentifier());
295             processedAsCompositeNode = writeChildren(n.body(), true);
296         } else if (node instanceof UnkeyedListNode) {
297             final UnkeyedListNode n = (UnkeyedListNode) node;
298             writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.body()));
299             processedAsCompositeNode = writeChildren(n.body(), false);
300         } else if (node instanceof UserMapNode) {
301             final UserMapNode n = (UserMapNode) node;
302             writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.body()));
303             processedAsCompositeNode = writeChildren(n.body(), true);
304         } else if (node instanceof MapNode) {
305             final MapNode n = (MapNode) node;
306             writer.startMapNode(n.getIdentifier(), childSizeHint(n.body()));
307             processedAsCompositeNode = writeChildren(n.body(), true);
308         } else if (node instanceof LeafSetNode) {
309             final LeafSetNode<?> n = (LeafSetNode<?>) node;
310             if (node instanceof UserLeafSetNode) {
311                 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.body()));
312             } else {
313                 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.body()));
314             }
315             currentDepth++;
316             processedAsCompositeNode = writeChildren(n.body(), true);
317             currentDepth--;
318         }
319
320         return processedAsCompositeNode;
321     }
322
323     private static final class OrderedParameterAwareNormalizedNodeWriter extends ParameterAwareNormalizedNodeWriter {
324         private static final Logger LOG = LoggerFactory.getLogger(OrderedParameterAwareNormalizedNodeWriter.class);
325
326         OrderedParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final Integer maxDepth,
327                                                   final List<Set<QName>> fields) {
328             super(writer, maxDepth, fields);
329         }
330
331         @Override
332         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
333             final NormalizedNodeStreamWriter writer = getWriter();
334             writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
335
336             final Set<QName> qnames = node.getIdentifier().keySet();
337             // Write out all the key children
338             currentDepth++;
339             for (final QName qname : qnames) {
340                 final Optional<? extends NormalizedNode> child = node.findChildByArg(new NodeIdentifier(qname));
341                 if (child.isPresent()) {
342                     if (selectedByParameters(child.get(), false)) {
343                         write(child.get());
344                     }
345                 } else {
346                     LOG.info("No child for key element {} found", qname);
347                 }
348             }
349             currentDepth--;
350
351             currentDepth++;
352             // Write all the rest
353             final boolean result =
354                     writeChildren(Iterables.filter(node.body(), input -> {
355                         if (input instanceof AugmentationNode) {
356                             return true;
357                         }
358                         if (!qnames.contains(input.getIdentifier().getNodeType())) {
359                             return true;
360                         }
361
362                         LOG.debug("Skipping key child {}", input);
363                         return false;
364                     }), false);
365             currentDepth--;
366             return result;
367         }
368     }
369 }