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