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