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