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