BUG-1668: make sure MapEntryNodes emit key children first
[yangtools.git] / yang / yang-data-api / src / main / java / org / opendaylight / yangtools / yang / data / api / schema / stream / NormalizedNodeWriter.java
1 /*
2  * Copyright (c) 2014 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.yangtools.yang.data.api.schema.stream;
9
10 import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Predicate;
16 import com.google.common.collect.Iterables;
17
18 import java.io.Closeable;
19 import java.io.Flushable;
20 import java.io.IOException;
21 import java.util.Set;
22
23 import javax.xml.stream.XMLStreamReader;
24
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
45  * the opposite of a {@link XMLStreamReader} -- unlike instantiating an iterator over
46  * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
47  * us to write multiple nodes.
48  */
49 @Beta
50 public class NormalizedNodeWriter implements Closeable, Flushable {
51     private final NormalizedNodeStreamWriter writer;
52
53     private NormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
54         this.writer = Preconditions.checkNotNull(writer);
55     }
56
57     protected final NormalizedNodeStreamWriter getWriter() {
58         return writer;
59     }
60
61     /**
62      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
63      *
64      * @param writer Back-end writer
65      * @return A new instance.
66      */
67     public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer) {
68         return forStreamWriter(writer, true);
69     }
70
71     /**
72      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple {@link #forStreamWriter(NormalizedNodeStreamWriter)}
73      * method, this allows the caller to switch off RFC6020 XML compliance, providing better
74      * throughput. The reason is that the XML mapping rules in RFC6020 require the encoding
75      * to emit leaf nodes which participate in a list's key first and in the order in which
76      * they are defined in the key. For JSON, this requirement is completely relaxed and leaves
77      * can be ordered in any way we see fit. The former requires a bit of work: first a lookup
78      * for each key and then for each emitted node we need to check whether it was already
79      * emitted.
80      *
81      * @param writer Back-end writer
82      * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
83      * @return A new instance.
84      */
85     public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer, final boolean orderKeyLeaves) {
86         if (orderKeyLeaves) {
87             return new OrderedNormalizedNodeWriter(writer);
88         } else {
89             return new NormalizedNodeWriter(writer);
90         }
91     }
92
93     /**
94      * Iterate over the provided {@link NormalizedNode} and emit write
95      * events to the encapsulated {@link NormalizedNodeStreamWriter}.
96      *
97      * @param node Node
98      * @return
99      * @throws IOException when thrown from the backing writer.
100      */
101     public NormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException {
102         if (wasProcessedAsCompositeNode(node)) {
103             return this;
104         }
105
106         if (wasProcessAsSimpleNode(node)) {
107             return this;
108         }
109
110         throw new IllegalStateException("It wasn't possible to serialize node " + node);
111     }
112
113     private boolean wasProcessAsSimpleNode(final NormalizedNode<?, ?> node) throws IOException {
114         if (node instanceof LeafSetEntryNode) {
115             final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>)node;
116             writer.leafSetEntryNode(nodeAsLeafList.getValue());
117             return true;
118         } else if (node instanceof LeafNode) {
119             final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
120             writer.leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue());
121             return true;
122         } else if (node instanceof AnyXmlNode) {
123             final AnyXmlNode anyXmlNode = (AnyXmlNode)node;
124             writer.anyxmlNode(anyXmlNode.getIdentifier(), anyXmlNode.getValue());
125             return true;
126         }
127
128         return false;
129     }
130
131     /**
132      * Emit events for all children and then emit an endNode() event.
133      *
134      * @param children Child iterable
135      * @return True
136      * @throws IOException when the writer reports it
137      */
138     protected boolean writeChildren(final Iterable<? extends NormalizedNode<?, ?>> children) throws IOException {
139         for (NormalizedNode<?, ?> child : children) {
140             write(child);
141         }
142
143         writer.endNode();
144         return true;
145     }
146
147     protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
148         writer.startMapEntryNode(node.getIdentifier(), UNKNOWN_SIZE);
149         return writeChildren(node.getValue());
150     }
151
152     private boolean wasProcessedAsCompositeNode(final NormalizedNode<?, ?> node) throws IOException {
153         if (node instanceof ContainerNode) {
154             final ContainerNode n = (ContainerNode) node;
155             writer.startContainerNode(n.getIdentifier(), UNKNOWN_SIZE);
156             return writeChildren(n.getValue());
157         }
158         if (node instanceof MapEntryNode) {
159             return writeMapEntryNode((MapEntryNode) node);
160         }
161         if (node instanceof UnkeyedListEntryNode) {
162             final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
163             writer.startUnkeyedListItem(n.getIdentifier(), UNKNOWN_SIZE);
164             return writeChildren(n.getValue());
165         }
166         if (node instanceof ChoiceNode) {
167             final ChoiceNode n = (ChoiceNode) node;
168             writer.startChoiceNode(n.getIdentifier(), UNKNOWN_SIZE);
169             return writeChildren(n.getValue());
170         }
171         if (node instanceof AugmentationNode) {
172             final AugmentationNode n = (AugmentationNode) node;
173             writer.startAugmentationNode(n.getIdentifier());
174             return writeChildren(n.getValue());
175         }
176         if (node instanceof UnkeyedListNode) {
177             final UnkeyedListNode n = (UnkeyedListNode) node;
178             writer.startUnkeyedList(n.getIdentifier(), UNKNOWN_SIZE);
179             return writeChildren(n.getValue());
180         }
181         if (node instanceof OrderedMapNode) {
182             final OrderedMapNode n = (OrderedMapNode) node;
183             writer.startOrderedMapNode(n.getIdentifier(), UNKNOWN_SIZE);
184             return writeChildren(n.getValue());
185         }
186         if (node instanceof MapNode) {
187             final MapNode n = (MapNode) node;
188             writer.startMapNode(n.getIdentifier(), UNKNOWN_SIZE);
189             return writeChildren(n.getValue());
190         }
191         if (node instanceof LeafSetNode) {
192             //covers also OrderedLeafSetNode for which doesn't exist start* method
193             final LeafSetNode<?> n = (LeafSetNode<?>) node;
194             writer.startLeafSet(n.getIdentifier(), UNKNOWN_SIZE);
195             return writeChildren(n.getValue());
196         }
197
198         return false;
199     }
200
201     @Override
202     public void flush() throws IOException {
203         writer.flush();
204     }
205
206     @Override
207     public void close() throws IOException {
208         writer.close();
209     }
210
211     private static final class OrderedNormalizedNodeWriter extends NormalizedNodeWriter {
212         private static final Logger LOG = LoggerFactory.getLogger(OrderedNormalizedNodeWriter.class);
213
214         OrderedNormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
215             super(writer);
216         }
217
218         @Override
219         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
220             getWriter().startMapEntryNode(node.getIdentifier(), UNKNOWN_SIZE);
221
222             final Set<QName> qnames = node.getIdentifier().getKeyValues().keySet();
223             // Write out all the key children
224             for (QName qname : qnames) {
225                 final Optional<? extends NormalizedNode<?, ?>> child = node.getChild(new NodeIdentifier(qname));
226                 if (child.isPresent()) {
227                     write(child.get());
228                 } else {
229                     LOG.info("No child for key element {} found", qname);
230                 }
231             }
232
233             // Write all the rest
234             return writeChildren(Iterables.filter(node.getValue(), new Predicate<NormalizedNode<?, ?>>() {
235                 @Override
236                 public boolean apply(final NormalizedNode<?, ?> input) {
237                     if (input instanceof AugmentationNode) {
238                         return true;
239                     }
240                     if (!qnames.contains(input.getNodeType())) {
241                         return true;
242                     }
243
244                     LOG.debug("Skipping key child {}", input);
245                     return false;
246                 }
247             }));
248         }
249     }
250 }