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