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