Merge branch 'master' of ../controller
[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 com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.collect.Iterables;
16 import java.io.Closeable;
17 import java.io.Flushable;
18 import java.io.IOException;
19 import java.util.Collection;
20 import java.util.Optional;
21 import java.util.Set;
22 import javax.xml.stream.XMLStreamReader;
23 import javax.xml.transform.dom.DOMSource;
24 import org.eclipse.jdt.annotation.NonNull;
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.AnydataNode;
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.OrderedLeafSetNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.YangModeledAnyXmlNode;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
48  * the opposite of a {@link XMLStreamReader} -- unlike instantiating an iterator over
49  * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
50  * us to write multiple nodes.
51  */
52 @Beta
53 public class NormalizedNodeWriter implements Closeable, Flushable {
54     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeWriter.class);
55
56     private final @NonNull NormalizedNodeStreamWriter writer;
57
58     protected NormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
59         this.writer = requireNonNull(writer);
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 NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer) {
73         return forStreamWriter(writer, true);
74     }
75
76     /**
77      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
78      * {@link #forStreamWriter(NormalizedNodeStreamWriter)} method, this allows the caller to switch off RFC6020 XML
79      * compliance, providing better throughput. The reason is that the XML mapping rules in RFC6020 require
80      * the encoding to emit leaf nodes which participate in a list's key first and in the order in which they are
81      * defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any way we
82      * see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we need
83      * to check whether it was already emitted.
84      *
85      * @param writer Back-end writer
86      * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
87      * @return A new instance.
88      */
89     public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
90             final boolean orderKeyLeaves) {
91         return orderKeyLeaves ? new OrderedNormalizedNodeWriter(writer) : new NormalizedNodeWriter(writer);
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 NormalizedNodeWriter this
100      * @throws IOException when thrown from the backing writer.
101      */
102     public 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     protected static int childSizeHint(final Iterable<?> children) {
134         return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
135     }
136
137     protected boolean wasProcessAsSimpleNode(final NormalizedNode<?, ?> node) throws IOException {
138         if (node instanceof LeafSetEntryNode) {
139             final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>)node;
140             writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
141             writer.scalarValue(nodeAsLeafList.getValue());
142             writer.endNode();
143             return true;
144         } else if (node instanceof LeafNode) {
145             final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
146             writer.startLeafNode(nodeAsLeaf.getIdentifier());
147             writer.scalarValue(nodeAsLeaf.getValue());
148             writer.endNode();
149             return true;
150         } else if (node instanceof AnyxmlNode) {
151             final AnyxmlNode<?> anyxmlNode = (AnyxmlNode<?>)node;
152             final Class<?> model = anyxmlNode.getValueObjectModel();
153             if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), model)) {
154                 final Object value = node.getValue();
155                 if (DOMSource.class.isAssignableFrom(model)) {
156                     verify(value instanceof DOMSource, "Inconsistent anyxml node %s", anyxmlNode);
157                     writer.domSourceValue((DOMSource) value);
158                 } else {
159                     writer.scalarValue(value);
160                 }
161                 writer.endNode();
162                 return true;
163             }
164
165             LOG.debug("Ignoring unhandled anyxml node {}", anyxmlNode);
166         } else if (node instanceof AnydataNode) {
167             final AnydataNode<?> anydata = (AnydataNode<?>) node;
168             final Class<?> model = anydata.getValueObjectModel();
169             if (writer.startAnydataNode(anydata.getIdentifier(), model)) {
170                 writer.scalarValue(anydata.getValue());
171                 writer.endNode();
172                 return true;
173             }
174
175             LOG.debug("Writer {} does not support anydata in form of {}", writer, model);
176         }
177
178         return false;
179     }
180
181     /**
182      * Emit events for all children and then emit an endNode() event.
183      *
184      * @param children Child iterable
185      * @return True
186      * @throws IOException when the writer reports it
187      */
188     protected boolean writeChildren(final Iterable<? extends NormalizedNode<?, ?>> children) throws IOException {
189         for (final NormalizedNode<?, ?> child : children) {
190             write(child);
191         }
192
193         writer.endNode();
194         return true;
195     }
196
197     protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
198         writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
199         return writeChildren(node.getValue());
200     }
201
202     protected boolean wasProcessedAsCompositeNode(final NormalizedNode<?, ?> node) throws IOException {
203         if (node instanceof ContainerNode) {
204             final ContainerNode n = (ContainerNode) node;
205             writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
206             return writeChildren(n.getValue());
207         }
208         if (node instanceof YangModeledAnyXmlNode) {
209             final YangModeledAnyXmlNode n = (YangModeledAnyXmlNode) node;
210             writer.startYangModeledAnyXmlNode(n.getIdentifier(), childSizeHint(n.getValue()));
211             return writeChildren(n.getValue());
212         }
213         if (node instanceof MapEntryNode) {
214             return writeMapEntryNode((MapEntryNode) node);
215         }
216         if (node instanceof UnkeyedListEntryNode) {
217             final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
218             writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.getValue()));
219             return writeChildren(n.getValue());
220         }
221         if (node instanceof ChoiceNode) {
222             final ChoiceNode n = (ChoiceNode) node;
223             writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.getValue()));
224             return writeChildren(n.getValue());
225         }
226         if (node instanceof AugmentationNode) {
227             final AugmentationNode n = (AugmentationNode) node;
228             writer.startAugmentationNode(n.getIdentifier());
229             return writeChildren(n.getValue());
230         }
231         if (node instanceof UnkeyedListNode) {
232             final UnkeyedListNode n = (UnkeyedListNode) node;
233             writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.getValue()));
234             return writeChildren(n.getValue());
235         }
236         if (node instanceof OrderedMapNode) {
237             final OrderedMapNode n = (OrderedMapNode) node;
238             writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
239             return writeChildren(n.getValue());
240         }
241         if (node instanceof MapNode) {
242             final MapNode n = (MapNode) node;
243             writer.startMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
244             return writeChildren(n.getValue());
245         }
246         if (node instanceof OrderedLeafSetNode) {
247             final LeafSetNode<?> n = (LeafSetNode<?>) node;
248             writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
249             return writeChildren(n.getValue());
250         }
251         if (node instanceof LeafSetNode) {
252             final LeafSetNode<?> n = (LeafSetNode<?>) node;
253             writer.startLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
254             return writeChildren(n.getValue());
255         }
256
257         return false;
258     }
259
260     private static final class OrderedNormalizedNodeWriter extends NormalizedNodeWriter {
261         private static final Logger LOG = LoggerFactory.getLogger(OrderedNormalizedNodeWriter.class);
262
263         OrderedNormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
264             super(writer);
265         }
266
267         @Override
268         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
269             final NormalizedNodeStreamWriter nnWriter = getWriter();
270             nnWriter.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
271
272             final Set<QName> qnames = node.getIdentifier().keySet();
273             // Write out all the key children
274             for (final QName qname : qnames) {
275                 final Optional<? extends NormalizedNode<?, ?>> child = node.getChild(new NodeIdentifier(qname));
276                 if (child.isPresent()) {
277                     write(child.get());
278                 } else {
279                     LOG.info("No child for key element {} found", qname);
280                 }
281             }
282
283             // Write all the rest
284             return writeChildren(Iterables.filter(node.getValue(), input -> {
285                 if (input instanceof AugmentationNode) {
286                     return true;
287                 }
288                 if (!qnames.contains(input.getNodeType())) {
289                     return true;
290                 }
291
292                 LOG.debug("Skipping key child {}", input);
293                 return false;
294             }));
295         }
296     }
297 }