3834137e90448e1689ad846ea6dbf9a86bc0b17e
[netconf.git] /
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.Entry;
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().entrySet());
186         }
187         return true;
188     }
189
190     private void writeOnlyKeys(final Set<Entry<QName, Object>> entries) throws IOException {
191         for (final Entry<QName, Object> entry : entries) {
192             writer.startLeafNode(new NodeIdentifier(entry.getKey()));
193             writer.scalarValue(entry.getValue());
194             writer.endNode();
195         }
196         writer.endNode();
197     }
198
199     protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
200         writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
201         currentDepth++;
202         writeMapEntryChildren(node);
203         currentDepth--;
204         return true;
205     }
206
207     private boolean wasProcessedAsCompositeNode(final NormalizedNode<?, ?> node) throws IOException {
208         boolean processedAsCompositeNode = false;
209         if (node instanceof ContainerNode) {
210             final ContainerNode n = (ContainerNode) node;
211             writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
212             currentDepth++;
213             processedAsCompositeNode = writeChildren(n.getValue());
214             currentDepth--;
215         } else if (node instanceof MapEntryNode) {
216             processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
217         } else if (node instanceof UnkeyedListEntryNode) {
218             final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
219             writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.getValue()));
220             currentDepth++;
221             processedAsCompositeNode = writeChildren(n.getValue());
222             currentDepth--;
223         } else if (node instanceof ChoiceNode) {
224             final ChoiceNode n = (ChoiceNode) node;
225             writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.getValue()));
226             processedAsCompositeNode = writeChildren(n.getValue());
227         } else if (node instanceof AugmentationNode) {
228             final AugmentationNode n = (AugmentationNode) node;
229             writer.startAugmentationNode(n.getIdentifier());
230             processedAsCompositeNode = writeChildren(n.getValue());
231         } else if (node instanceof UnkeyedListNode) {
232             final UnkeyedListNode n = (UnkeyedListNode) node;
233             writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.getValue()));
234             processedAsCompositeNode = writeChildren(n.getValue());
235         } else if (node instanceof OrderedMapNode) {
236             final OrderedMapNode n = (OrderedMapNode) node;
237             writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
238             processedAsCompositeNode = writeChildren(n.getValue());
239         } else if (node instanceof MapNode) {
240             final MapNode n = (MapNode) node;
241             writer.startMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
242             processedAsCompositeNode = writeChildren(n.getValue());
243         } else if (node instanceof LeafSetNode) {
244             final LeafSetNode<?> n = (LeafSetNode<?>) node;
245             if (node instanceof OrderedLeafSetNode) {
246                 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
247             } else {
248                 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
249             }
250             currentDepth++;
251             processedAsCompositeNode = writeChildren(n.getValue());
252             currentDepth--;
253         }
254
255         return processedAsCompositeNode;
256     }
257
258     private static final class OrderedDepthAwareNormalizedNodeWriter extends DepthAwareNormalizedNodeWriter {
259         private static final Logger LOG = LoggerFactory.getLogger(OrderedDepthAwareNormalizedNodeWriter.class);
260
261         OrderedDepthAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final int maxDepth) {
262             super(writer, maxDepth);
263         }
264
265         @Override
266         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
267             final NormalizedNodeStreamWriter writer = getWriter();
268             writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
269
270             final Set<QName> qnames = node.getIdentifier().keySet();
271             // Write out all the key children
272             for (final QName qname : qnames) {
273                 final Optional<? extends NormalizedNode<?, ?>> child = node.getChild(new NodeIdentifier(qname));
274                 if (child.isPresent()) {
275                     write(child.get());
276                 } else {
277                     LOG.info("No child for key element {} found", qname);
278                 }
279             }
280
281             // Write all the rest
282             currentDepth++;
283             final boolean result = writeChildren(Iterables.filter(node.getValue(), input -> {
284                 if (input instanceof AugmentationNode) {
285                     return true;
286                 }
287                 if (!qnames.contains(input.getNodeType())) {
288                     return true;
289                 }
290
291                 LOG.debug("Skipping key child {}", input);
292                 return false;
293             }));
294             currentDepth--;
295             return result;
296         }
297     }
298 }