cec8ebe34eeb9ac6a4e7b723d6998065fe372270
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / server / spi / DefaultNormalizedNodeWriter.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.server.spi;
9
10 import com.google.common.collect.Iterables;
11 import java.io.IOException;
12 import java.util.List;
13 import java.util.Map.Entry;
14 import java.util.Set;
15 import javax.xml.transform.dom.DOMSource;
16 import org.opendaylight.restconf.api.query.DepthParam;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.schema.AnydataNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
37  * the opposite of a {@link javax.xml.stream.XMLStreamReader} -- unlike instantiating an iterator over
38  * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
39  * us to write multiple nodes.
40  */
41 // FIXME: this is a copy&paste from yangtools' NormalizedNodeWriter then adapted for filtering
42 sealed class DefaultNormalizedNodeWriter extends NormalizedNodeWriter {
43     private static final QName ROOT_DATA_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "data");
44
45     private final Integer maxDepth;
46     private final List<Set<QName>> fields;
47
48     int currentDepth = 0;
49
50     DefaultNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParam depth,
51             final List<Set<QName>> fields) {
52         super(writer);
53         maxDepth = depth == null ? null : depth.value();
54         this.fields = fields;
55     }
56
57     @Override
58     protected void writeAnydata(final AnydataNode<?> node) throws IOException {
59         final var objectModel = node.bodyObjectModel();
60         if (writer.startAnydataNode(node.name(), objectModel)) {
61             writer.scalarValue(node.body());
62             writer.endNode();
63         }
64     }
65
66     @Override
67     protected void writeAnyxml(final AnyxmlNode<?> node) throws IOException {
68         final var objectModel = node.bodyObjectModel();
69         if (writer.startAnyxmlNode(node.name(), objectModel)) {
70             if (DOMSource.class.isAssignableFrom(objectModel)) {
71                 writer.domSourceValue((DOMSource) node.body());
72             } else {
73                 writer.scalarValue(node.body());
74             }
75             writer.endNode();
76         }
77     }
78
79     @Override
80     protected void writeChoice(final ChoiceNode node) throws IOException {
81         writer.startChoiceNode(node.name(), node.size());
82         writeChildren(node.body(), true);
83     }
84
85     @Override
86     protected void writeContainer(final ContainerNode node) throws IOException {
87         if (!node.name().getNodeType().withoutRevision().equals(ROOT_DATA_QNAME)) {
88             writer.startContainerNode(node.name(), node.size());
89             currentDepth++;
90             writeChildren(node.body(), false);
91             currentDepth--;
92         } else {
93             // write child nodes of data root container
94             for (var child : node.body()) {
95                 currentDepth++;
96                 if (selectedByParameters(child, false)) {
97                     write(child);
98                 }
99                 currentDepth--;
100             }
101         }
102     }
103
104     @Override
105     protected void writeLeaf(final LeafNode<?> node) throws IOException {
106         writer.startLeafNode(node.name());
107         writer.scalarValue(node.body());
108         writer.endNode();
109     }
110
111     @Override
112     protected void writeLeafSet(final LeafSetNode<?> node) throws IOException {
113         final var ordering = node.ordering();
114         switch (ordering) {
115             case SYSTEM -> writer.startLeafSet(node.name(), node.size());
116             case USER -> writer.startOrderedLeafSet(node.name(), node.size());
117             default -> throw new IOException("Unsupported ordering " + ordering.argument());
118         }
119
120         currentDepth++;
121         writeChildren(node.body(), true);
122         currentDepth--;
123     }
124
125     @Override
126     protected void writeLeafSetEntry(final LeafSetEntryNode<?> node) throws IOException {
127         if (selectedByParameters(node, false)) {
128             writer.startLeafSetEntryNode(node.name());
129             writer.scalarValue(node.body());
130             writer.endNode();
131         }
132     }
133
134     @Override
135     protected void writeMap(final MapNode node) throws IOException {
136         final var ordering = node.ordering();
137         switch (ordering) {
138             case SYSTEM -> writer.startMapNode(node.name(), node.size());
139             case USER -> writer.startOrderedMapNode(node.name(), node.size());
140             default -> throw new IOException("Unsupported ordering " + ordering.argument());
141         }
142         writeChildren(node.body(), true);
143     }
144
145     @Override
146     protected void writeMapEntry(final MapEntryNode node) throws IOException {
147         writer.startMapEntryNode(node.name(), node.size());
148         currentDepth++;
149         writeMapEntryChildren(node);
150         currentDepth--;
151     }
152
153     @Override
154     protected void writeUnkeyedList(final UnkeyedListNode node) throws IOException {
155         writer.startUnkeyedList(node.name(), node.size());
156         writeChildren(node.body(), false);
157     }
158
159     @Override
160     protected void writeUnkeyedListEntry(final UnkeyedListEntryNode node) throws IOException {
161         writer.startUnkeyedListItem(node.name(), node.size());
162         currentDepth++;
163         writeChildren(node.body(), false);
164         currentDepth--;
165     }
166
167     /**
168      * Check if node should be written according to parameters fields and depth.
169      * See <a href="https://tools.ietf.org/html/draft-ietf-netconf-restconf-18#page-49">Restconf draft</a>.
170      * @param node Node to be written
171      * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
172      * @return {@code true} if node will be written, {@code false} otherwise
173      */
174     protected boolean selectedByParameters(final NormalizedNode node, final boolean mixinParent) {
175         // nodes to be written are not limited by fields, only by depth
176         if (fields == null) {
177             return maxDepth == null || currentDepth < maxDepth;
178         }
179
180         // children of mixin nodes are never selected in fields but must be written if they are first in selected target
181         if (mixinParent && currentDepth == 0) {
182             return true;
183         }
184
185         // write only selected nodes
186         if (currentDepth > 0 && currentDepth <= fields.size()) {
187             return fields.get(currentDepth - 1).contains(node.name().getNodeType());
188         }
189
190         // after this depth only depth parameter is used to determine when to write node
191         return maxDepth == null || currentDepth < maxDepth;
192     }
193
194     /**
195      * Emit events for all children and then emit an endNode() event.
196      *
197      * @param children Child iterable
198      * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
199      * @throws IOException when the writer reports it
200      */
201     protected final void writeChildren(final Iterable<? extends NormalizedNode> children, final boolean mixinParent)
202             throws IOException {
203         for (var child : children) {
204             if (selectedByParameters(child, mixinParent)) {
205                 write(child);
206             }
207         }
208         writer.endNode();
209     }
210
211     private void writeMapEntryChildren(final MapEntryNode mapEntryNode) throws IOException {
212         if (selectedByParameters(mapEntryNode, false)) {
213             writeChildren(mapEntryNode.body(), false);
214         } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
215             writeOnlyKeys(mapEntryNode.name().entrySet());
216         }
217     }
218
219     private void writeOnlyKeys(final Set<Entry<QName, Object>> entries) throws IOException {
220         for (var entry : entries) {
221             writer.startLeafNode(new NodeIdentifier(entry.getKey()));
222             writer.scalarValue(entry.getValue());
223             writer.endNode();
224         }
225         writer.endNode();
226     }
227
228     static final class OrderedRestconfNormalizedNodeWriter extends DefaultNormalizedNodeWriter {
229         private static final Logger LOG = LoggerFactory.getLogger(OrderedRestconfNormalizedNodeWriter.class);
230
231         OrderedRestconfNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParam depth,
232                 final List<Set<QName>> fields) {
233             super(writer, depth, fields);
234         }
235
236         @Override
237         protected void writeMapEntry(final MapEntryNode node) throws IOException {
238             writer.startMapEntryNode(node.name(), node.size());
239
240             final var qnames = node.name().keySet();
241             // Write out all the key children
242             currentDepth++;
243             for (var qname : qnames) {
244                 final var child = node.childByArg(new NodeIdentifier(qname));
245                 if (child != null) {
246                     if (selectedByParameters(child, false)) {
247                         write(child);
248                     }
249                 } else {
250                     LOG.info("No child for key element {} found", qname);
251                 }
252             }
253
254             // Write all the rest
255             writeChildren(Iterables.filter(node.body(), input -> {
256                 if (!qnames.contains(input.name().getNodeType())) {
257                     return true;
258                 }
259
260                 LOG.debug("Skipping key child {}", input);
261                 return false;
262             }), false);
263             currentDepth--;
264         }
265     }
266 }