Bump yangtools to 3.0.0
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / DepthAwareNormalizedNodeWriter.java
1 /*
2  * Copyright (c) 2015 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.netconf.sal.rest.impl;
9
10 import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
11
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Iterables;
14 import java.io.IOException;
15 import java.util.Collection;
16 import java.util.Map;
17 import java.util.Optional;
18 import java.util.Set;
19 import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * This is an experimental iterator over a {@link NormalizedNode}. This is essentially the opposite of a
42  * {@link javax.xml.stream.XMLStreamReader} -- unlike instantiating an iterator over the backing data, this
43  * encapsulates a {@link NormalizedNodeStreamWriter} and allows us to write multiple nodes.
44  *
45  * @deprecated This class will be replaced by ParameterAwareNormalizedNodeWriter in restconf-nb-rfc8040
46  */
47 @Deprecated
48 public class DepthAwareNormalizedNodeWriter implements RestconfNormalizedNodeWriter {
49     private final NormalizedNodeStreamWriter writer;
50     protected int currentDepth = 0;
51     protected final int maxDepth;
52
53     private DepthAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final int maxDepth) {
54         this.writer = Preconditions.checkNotNull(writer);
55         this.maxDepth = maxDepth;
56     }
57
58     protected final NormalizedNodeStreamWriter getWriter() {
59         return writer;
60     }
61
62     /**
63      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
64      *
65      * @param writer Back-end writer
66      * @return A new instance.
67      */
68     public static DepthAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
69                                                                  final int maxDepth) {
70         return forStreamWriter(writer, true,  maxDepth);
71     }
72
73     /**
74      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
75      * Unlike the simple {@link #forStreamWriter(NormalizedNodeStreamWriter, int)}
76      * method, this allows the caller to switch off RFC6020 XML compliance, providing better
77      * throughput. The reason is that the XML mapping rules in RFC6020 require the encoding
78      * to emit leaf nodes which participate in a list's key first and in the order in which
79      * they are defined in the key. For JSON, this requirement is completely relaxed and leaves
80      * can be ordered in any way we see fit. The former requires a bit of work: first a lookup
81      * for each key and then for each emitted node we need to check whether it was already
82      * emitted.
83      *
84      * @param writer Back-end writer
85      * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
86      * @return A new instance.
87      */
88     public static DepthAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
89                                                                  final boolean orderKeyLeaves, final int maxDepth) {
90         return orderKeyLeaves ? new OrderedDepthAwareNormalizedNodeWriter(writer, maxDepth)
91                 : new DepthAwareNormalizedNodeWriter(writer, maxDepth);
92     }
93
94     /**
95      * Iterate over the provided {@link NormalizedNode} and emit write
96      * events to the encapsulated {@link NormalizedNodeStreamWriter}.
97      *
98      * @param node Node
99      * @return DepthAwareNormalizedNodeWriter
100      * @throws IOException when thrown from the backing writer.
101      */
102     @Override
103     public final DepthAwareNormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException {
104         if (wasProcessedAsCompositeNode(node)) {
105             return this;
106         }
107
108         if (wasProcessAsSimpleNode(node)) {
109             return this;
110         }
111
112         throw new IllegalStateException("It wasn't possible to serialize node " + node);
113     }
114
115     @Override
116     public void flush() throws IOException {
117         writer.flush();
118     }
119
120     @Override
121     public void close() throws IOException {
122         writer.flush();
123         writer.close();
124     }
125
126     /**
127      * Emit a best guess of a hint for a particular set of children. It evaluates the
128      * iterable to see if the size can be easily gotten to. If it is, we hint at the
129      * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
130      *
131      * @param children Child nodes
132      * @return Best estimate of the collection size required to hold all the children.
133      */
134     static final int childSizeHint(final Iterable<?> children) {
135         return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
136     }
137
138     private boolean wasProcessAsSimpleNode(final NormalizedNode<?, ?> node) throws IOException {
139         if (node instanceof LeafSetEntryNode) {
140             if (currentDepth < maxDepth) {
141                 final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>) node;
142                 writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
143                 writer.scalarValue(nodeAsLeafList.getValue());
144                 writer.endNode();
145             }
146             return true;
147         } else if (node instanceof LeafNode) {
148             final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
149             writer.startLeafNode(nodeAsLeaf.getIdentifier());
150             writer.scalarValue(nodeAsLeaf.getValue());
151             writer.endNode();
152             return true;
153         } else if (node instanceof AnyXmlNode) {
154             final AnyXmlNode anyXmlNode = (AnyXmlNode)node;
155             writer.startAnyxmlNode(anyXmlNode.getIdentifier());
156             writer.domSourceValue(anyXmlNode.getValue());
157             writer.endNode();
158             return true;
159         }
160
161         return false;
162     }
163
164     /**
165      * Emit events for all children and then emit an endNode() event.
166      *
167      * @param children Child iterable
168      * @return True
169      * @throws IOException when the writer reports it
170      */
171     protected final boolean writeChildren(final Iterable<? extends NormalizedNode<?, ?>> children) throws IOException {
172         if (currentDepth < maxDepth) {
173             for (final NormalizedNode<?, ?> child : children) {
174                 write(child);
175             }
176         }
177         writer.endNode();
178         return true;
179     }
180
181     protected boolean writeMapEntryChildren(final MapEntryNode mapEntryNode) throws IOException {
182         if (currentDepth < maxDepth) {
183             writeChildren(mapEntryNode.getValue());
184         } else if (currentDepth == maxDepth) {
185             writeOnlyKeys(mapEntryNode.getIdentifier().getKeyValues());
186         }
187         return true;
188     }
189
190     private void writeOnlyKeys(final Map<QName, Object> keyValues) throws IllegalArgumentException, IOException {
191         for (final Map.Entry<QName, Object> entry : keyValues.entrySet()) {
192             writer.startLeafNode(new NodeIdentifier(entry.getKey()));
193             writer.scalarValue(entry.getValue());
194             writer.endNode();
195         }
196         writer.endNode();
197
198     }
199
200     protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
201         writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
202         currentDepth++;
203         writeMapEntryChildren(node);
204         currentDepth--;
205         return true;
206     }
207
208     private boolean wasProcessedAsCompositeNode(final NormalizedNode<?, ?> node) throws IOException {
209         boolean processedAsCompositeNode = false;
210         if (node instanceof ContainerNode) {
211             final ContainerNode n = (ContainerNode) node;
212             writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
213             currentDepth++;
214             processedAsCompositeNode = writeChildren(n.getValue());
215             currentDepth--;
216         } else if (node instanceof MapEntryNode) {
217             processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
218         } else if (node instanceof UnkeyedListEntryNode) {
219             final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
220             writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.getValue()));
221             currentDepth++;
222             processedAsCompositeNode = writeChildren(n.getValue());
223             currentDepth--;
224         } else if (node instanceof ChoiceNode) {
225             final ChoiceNode n = (ChoiceNode) node;
226             writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.getValue()));
227             processedAsCompositeNode = writeChildren(n.getValue());
228         } else if (node instanceof AugmentationNode) {
229             final AugmentationNode n = (AugmentationNode) node;
230             writer.startAugmentationNode(n.getIdentifier());
231             processedAsCompositeNode = writeChildren(n.getValue());
232         } else if (node instanceof UnkeyedListNode) {
233             final UnkeyedListNode n = (UnkeyedListNode) node;
234             writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.getValue()));
235             processedAsCompositeNode = writeChildren(n.getValue());
236         } else if (node instanceof OrderedMapNode) {
237             final OrderedMapNode n = (OrderedMapNode) node;
238             writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
239             processedAsCompositeNode = writeChildren(n.getValue());
240         } else if (node instanceof MapNode) {
241             final MapNode n = (MapNode) node;
242             writer.startMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
243             processedAsCompositeNode = writeChildren(n.getValue());
244         } else if (node instanceof LeafSetNode) {
245             final LeafSetNode<?> n = (LeafSetNode<?>) node;
246             if (node instanceof OrderedLeafSetNode) {
247                 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
248             } else {
249                 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
250             }
251             currentDepth++;
252             processedAsCompositeNode = writeChildren(n.getValue());
253             currentDepth--;
254         }
255
256         return processedAsCompositeNode;
257     }
258
259     private static final class OrderedDepthAwareNormalizedNodeWriter extends DepthAwareNormalizedNodeWriter {
260         private static final Logger LOG = LoggerFactory.getLogger(OrderedDepthAwareNormalizedNodeWriter.class);
261
262         OrderedDepthAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final int maxDepth) {
263             super(writer, maxDepth);
264         }
265
266         @Override
267         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
268             final NormalizedNodeStreamWriter writer = getWriter();
269             writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
270
271             final Set<QName> qnames = node.getIdentifier().getKeyValues().keySet();
272             // Write out all the key children
273             for (final QName qname : qnames) {
274                 final Optional<? extends NormalizedNode<?, ?>> child = node.getChild(new NodeIdentifier(qname));
275                 if (child.isPresent()) {
276                     write(child.get());
277                 } else {
278                     LOG.info("No child for key element {} found", qname);
279                 }
280             }
281
282             // Write all the rest
283             currentDepth++;
284             final boolean result = writeChildren(Iterables.filter(node.getValue(), input -> {
285                 if (input instanceof AugmentationNode) {
286                     return true;
287                 }
288                 if (!qnames.contains(input.getNodeType())) {
289                     return true;
290                 }
291
292                 LOG.debug("Skipping key child {}", input);
293                 return false;
294             }));
295             currentDepth--;
296             return result;
297         }
298     }
299 }