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