378e9ddda8d38f65c2b0dc399a92d24cf7f56046
[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.DepthParam;
23 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.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.UnkeyedListEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
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 @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 DepthParam depth,
60                                                final List<Set<QName>> fields) {
61         this.writer = requireNonNull(writer);
62         maxDepth = depth == null ? null : depth.value();
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 DepthParam 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, DepthParam, List)} method, this allows the caller to
86      * switch off RFC6020 XML compliance, providing better throughput. The reason is that the XML mapping rules in
87      * RFC6020 require the encoding 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 can be ordered in any
89      * way we see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we
90      * need to check whether it was already emitted.
91      *
92      * @param writer Back-end writer
93      * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
94      * @param depth Maximal depth to write
95      * @param fields Selected child nodes to write
96      * @return A new instance.
97      */
98     public static ParameterAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
99                                                                      final boolean orderKeyLeaves,
100                                                                      final DepthParam depth,
101                                                                      final List<Set<QName>> fields) {
102         return orderKeyLeaves ? new OrderedParameterAwareNormalizedNodeWriter(writer, depth, fields)
103                 : new ParameterAwareNormalizedNodeWriter(writer, depth, fields);
104     }
105
106     /**
107      * Iterate over the provided {@link NormalizedNode} and emit write
108      * events to the encapsulated {@link NormalizedNodeStreamWriter}.
109      *
110      * @param node Node
111      * @return {@code ParameterAwareNormalizedNodeWriter}
112      * @throws IOException when thrown from the backing writer.
113      */
114     @Override
115     public final ParameterAwareNormalizedNodeWriter write(final NormalizedNode node) throws IOException {
116         if (wasProcessedAsCompositeNode(node)) {
117             return this;
118         }
119
120         if (wasProcessAsSimpleNode(node)) {
121             return this;
122         }
123
124         throw new IllegalStateException("It wasn't possible to serialize node " + node);
125     }
126
127     @Override
128     public void flush() throws IOException {
129         writer.flush();
130     }
131
132     @Override
133     public void close() throws IOException {
134         writer.flush();
135         writer.close();
136     }
137
138     /**
139      * Emit a best guess of a hint for a particular set of children. It evaluates the
140      * iterable to see if the size can be easily gotten to. If it is, we hint at the
141      * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
142      *
143      * @param children Child nodes
144      * @return Best estimate of the collection size required to hold all the children.
145      */
146     static final int childSizeHint(final Iterable<?> children) {
147         return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
148     }
149
150     private boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
151         if (node instanceof LeafSetEntryNode) {
152             if (selectedByParameters(node, false)) {
153                 final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>) node;
154                 writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
155                 writer.scalarValue(nodeAsLeafList.body());
156                 writer.endNode();
157             }
158             return true;
159         } else if (node instanceof LeafNode) {
160             final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
161             writer.startLeafNode(nodeAsLeaf.getIdentifier());
162             writer.scalarValue(nodeAsLeaf.body());
163             writer.endNode();
164             return true;
165         } else if (node instanceof AnyxmlNode) {
166             final AnyxmlNode<?> anyxmlNode = (AnyxmlNode<?>)node;
167             final Class<?> objectModel = anyxmlNode.bodyObjectModel();
168             if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), objectModel)) {
169                 if (DOMSource.class.isAssignableFrom(objectModel)) {
170                     writer.domSourceValue((DOMSource) anyxmlNode.body());
171                 } else {
172                     writer.scalarValue(anyxmlNode.body());
173                 }
174                 writer.endNode();
175             }
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.getIdentifier().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.body(), false);
236         } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
237             writeOnlyKeys(mapEntryNode.getIdentifier().entrySet());
238         }
239         return true;
240     }
241
242     private void writeOnlyKeys(final Set<Entry<QName, Object>> entries) throws IOException {
243         for (final Entry<QName, Object> entry : entries) {
244             writer.startLeafNode(new NodeIdentifier(entry.getKey()));
245             writer.scalarValue(entry.getValue());
246             writer.endNode();
247         }
248         writer.endNode();
249     }
250
251     protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
252         writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
253         currentDepth++;
254         writeMapEntryChildren(node);
255         currentDepth--;
256         return true;
257     }
258
259     private boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
260         boolean processedAsCompositeNode = false;
261         if (node instanceof ContainerNode) {
262             final ContainerNode n = (ContainerNode) node;
263             if (!n.getIdentifier().getNodeType().withoutRevision().equals(ROOT_DATA_QNAME)) {
264                 writer.startContainerNode(n.getIdentifier(), childSizeHint(n.body()));
265                 currentDepth++;
266                 processedAsCompositeNode = writeChildren(n.body(), false);
267                 currentDepth--;
268             } else {
269                 // write child nodes of data root container
270                 for (final NormalizedNode child : n.body()) {
271                     currentDepth++;
272                     if (selectedByParameters(child, false)) {
273                         write(child);
274                     }
275                     currentDepth--;
276                 }
277                 processedAsCompositeNode = true;
278             }
279         } else if (node instanceof MapEntryNode) {
280             processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
281         } else if (node instanceof UnkeyedListEntryNode) {
282             final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
283             writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.body()));
284             currentDepth++;
285             processedAsCompositeNode = writeChildren(n.body(), false);
286             currentDepth--;
287         } else if (node instanceof ChoiceNode) {
288             final ChoiceNode n = (ChoiceNode) node;
289             writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.body()));
290             processedAsCompositeNode = writeChildren(n.body(), true);
291         } else if (node instanceof AugmentationNode) {
292             final AugmentationNode n = (AugmentationNode) node;
293             writer.startAugmentationNode(n.getIdentifier());
294             processedAsCompositeNode = writeChildren(n.body(), true);
295         } else if (node instanceof UnkeyedListNode) {
296             final UnkeyedListNode n = (UnkeyedListNode) node;
297             writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.body()));
298             processedAsCompositeNode = writeChildren(n.body(), false);
299         } else if (node instanceof UserMapNode) {
300             final UserMapNode n = (UserMapNode) node;
301             writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.body()));
302             processedAsCompositeNode = writeChildren(n.body(), true);
303         } else if (node instanceof MapNode) {
304             final MapNode n = (MapNode) node;
305             writer.startMapNode(n.getIdentifier(), childSizeHint(n.body()));
306             processedAsCompositeNode = writeChildren(n.body(), true);
307         } else if (node instanceof LeafSetNode) {
308             final LeafSetNode<?> n = (LeafSetNode<?>) node;
309             if (node instanceof UserLeafSetNode) {
310                 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.body()));
311             } else {
312                 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.body()));
313             }
314             currentDepth++;
315             processedAsCompositeNode = writeChildren(n.body(), true);
316             currentDepth--;
317         }
318
319         return processedAsCompositeNode;
320     }
321
322     private static final class OrderedParameterAwareNormalizedNodeWriter extends ParameterAwareNormalizedNodeWriter {
323         private static final Logger LOG = LoggerFactory.getLogger(OrderedParameterAwareNormalizedNodeWriter.class);
324
325         OrderedParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParam depth,
326                                                   final List<Set<QName>> fields) {
327             super(writer, depth, fields);
328         }
329
330         @Override
331         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
332             final NormalizedNodeStreamWriter writer = getWriter();
333             writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
334
335             final Set<QName> qnames = node.getIdentifier().keySet();
336             // Write out all the key children
337             currentDepth++;
338             for (final QName qname : qnames) {
339                 final Optional<? extends NormalizedNode> child = node.findChildByArg(new NodeIdentifier(qname));
340                 if (child.isPresent()) {
341                     if (selectedByParameters(child.get(), false)) {
342                         write(child.get());
343                     }
344                 } else {
345                     LOG.info("No child for key element {} found", qname);
346                 }
347             }
348             currentDepth--;
349
350             currentDepth++;
351             // Write all the rest
352             final boolean result =
353                     writeChildren(Iterables.filter(node.body(), input -> {
354                         if (input instanceof AugmentationNode) {
355                             return true;
356                         }
357                         if (!qnames.contains(input.getIdentifier().getNodeType())) {
358                             return true;
359                         }
360
361                         LOG.debug("Skipping key child {}", input);
362                         return false;
363                     }), false);
364             currentDepth--;
365             return result;
366         }
367     }
368 }