13b14435a3a0cf180865c8881ac5cbb42b28291b
[yangtools.git] / data / 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.Set;
21 import javax.xml.stream.XMLStreamReader;
22 import javax.xml.transform.dom.DOMSource;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.schema.AnydataNode;
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.DataContainerChild;
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.MapEntryNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
47  * the opposite of a {@link XMLStreamReader} -- unlike instantiating an iterator over
48  * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
49  * us to write multiple nodes.
50  */
51 @Beta
52 public class NormalizedNodeWriter implements Closeable, Flushable {
53     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeWriter.class);
54
55     private final @NonNull NormalizedNodeStreamWriter writer;
56
57     protected NormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
58         this.writer = requireNonNull(writer);
59     }
60
61     protected final NormalizedNodeStreamWriter getWriter() {
62         return writer;
63     }
64
65     /**
66      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
67      *
68      * @param writer Back-end writer
69      * @return A new instance.
70      */
71     public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer) {
72         return forStreamWriter(writer, true);
73     }
74
75     /**
76      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
77      * {@link #forStreamWriter(NormalizedNodeStreamWriter)} method, this allows the caller to switch off RFC6020 XML
78      * compliance, providing better throughput. The reason is that the XML mapping rules in RFC6020 require
79      * the encoding to emit leaf nodes which participate in a list's key first and in the order in which they are
80      * defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any way we
81      * see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we need
82      * to check whether it was already emitted.
83      *
84      * @param writer Back-end writer
85      * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
86      * @return A new instance.
87      */
88     public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
89             final boolean orderKeyLeaves) {
90         return orderKeyLeaves ? new OrderedNormalizedNodeWriter(writer) : new NormalizedNodeWriter(writer);
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 NormalizedNodeWriter this
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     @Override
114     public void flush() throws IOException {
115         writer.flush();
116     }
117
118     @Override
119     public void close() throws IOException {
120         writer.flush();
121         writer.close();
122     }
123
124     /**
125      * Emit a best guess of a hint for a particular set of children. It evaluates the
126      * iterable to see if the size can be easily gotten to. If it is, we hint at the
127      * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
128      *
129      * @param children Child nodes
130      * @return Best estimate of the collection size required to hold all the children.
131      */
132     protected static int childSizeHint(final Iterable<?> children) {
133         return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
134     }
135
136     protected boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
137         if (node instanceof LeafSetEntryNode) {
138             final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>)node;
139             writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
140             writer.scalarValue(nodeAsLeafList.body());
141             writer.endNode();
142             return true;
143         } else if (node instanceof LeafNode) {
144             final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
145             writer.startLeafNode(nodeAsLeaf.getIdentifier());
146             writer.scalarValue(nodeAsLeaf.body());
147             writer.endNode();
148             return true;
149         } else if (node instanceof AnyxmlNode) {
150             final AnyxmlNode<?> anyxmlNode = (AnyxmlNode<?>)node;
151             final Class<?> model = anyxmlNode.bodyObjectModel();
152             if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), model)) {
153                 final Object value = node.body();
154                 if (DOMSource.class.isAssignableFrom(model)) {
155                     verify(value instanceof DOMSource, "Inconsistent anyxml node %s", anyxmlNode);
156                     writer.domSourceValue((DOMSource) value);
157                 } else {
158                     writer.scalarValue(value);
159                 }
160                 writer.endNode();
161                 return true;
162             }
163
164             LOG.debug("Ignoring unhandled anyxml node {}", anyxmlNode);
165         } else if (node instanceof AnydataNode) {
166             final AnydataNode<?> anydata = (AnydataNode<?>) node;
167             final Class<?> model = anydata.bodyObjectModel();
168             if (writer.startAnydataNode(anydata.getIdentifier(), model)) {
169                 writer.scalarValue(anydata.body());
170                 writer.endNode();
171                 return true;
172             }
173
174             LOG.debug("Writer {} does not support anydata in form of {}", writer, model);
175         }
176
177         return false;
178     }
179
180     /**
181      * Emit events for all children and then emit an endNode() event.
182      *
183      * @param children Child iterable
184      * @return True
185      * @throws IOException when the writer reports it
186      */
187     protected boolean writeChildren(final Iterable<? extends NormalizedNode> children) throws IOException {
188         for (final NormalizedNode child : children) {
189             write(child);
190         }
191
192         writer.endNode();
193         return true;
194     }
195
196     protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
197         writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
198         return writeChildren(node.body());
199     }
200
201     protected boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
202         if (node instanceof ContainerNode) {
203             final ContainerNode n = (ContainerNode) node;
204             writer.startContainerNode(n.getIdentifier(), childSizeHint(n.body()));
205             return writeChildren(n.body());
206         }
207         if (node instanceof MapEntryNode) {
208             return writeMapEntryNode((MapEntryNode) node);
209         }
210         if (node instanceof UnkeyedListEntryNode) {
211             final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
212             writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.body()));
213             return writeChildren(n.body());
214         }
215         if (node instanceof ChoiceNode) {
216             final ChoiceNode n = (ChoiceNode) node;
217             writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.body()));
218             return writeChildren(n.body());
219         }
220         if (node instanceof AugmentationNode) {
221             final AugmentationNode n = (AugmentationNode) node;
222             writer.startAugmentationNode(n.getIdentifier());
223             return writeChildren(n.body());
224         }
225         if (node instanceof UnkeyedListNode) {
226             final UnkeyedListNode n = (UnkeyedListNode) node;
227             writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.body()));
228             return writeChildren(n.body());
229         }
230         if (node instanceof UserMapNode) {
231             final UserMapNode n = (UserMapNode) node;
232             writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.body()));
233             return writeChildren(n.body());
234         }
235         if (node instanceof SystemMapNode) {
236             final SystemMapNode n = (SystemMapNode) node;
237             writer.startMapNode(n.getIdentifier(), childSizeHint(n.body()));
238             return writeChildren(n.body());
239         }
240         if (node instanceof UserLeafSetNode) {
241             final UserLeafSetNode<?> n = (UserLeafSetNode<?>) node;
242             writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.body()));
243             return writeChildren(n.body());
244         }
245         if (node instanceof SystemLeafSetNode) {
246             final SystemLeafSetNode<?> n = (SystemLeafSetNode<?>) node;
247             writer.startLeafSet(n.getIdentifier(), childSizeHint(n.body()));
248             return writeChildren(n.body());
249         }
250
251         return false;
252     }
253
254     private static final class OrderedNormalizedNodeWriter extends NormalizedNodeWriter {
255         private static final Logger LOG = LoggerFactory.getLogger(OrderedNormalizedNodeWriter.class);
256
257         OrderedNormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
258             super(writer);
259         }
260
261         @Override
262         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
263             final NormalizedNodeStreamWriter nnWriter = getWriter();
264             nnWriter.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
265
266             final Set<QName> qnames = node.getIdentifier().keySet();
267             // Write out all the key children
268             for (final QName qname : qnames) {
269                 final DataContainerChild child = node.childByArg(new NodeIdentifier(qname));
270                 if (child != null) {
271                     write(child);
272                 } else {
273                     LOG.info("No child for key element {} found", qname);
274                 }
275             }
276
277             // Write all the rest
278             return writeChildren(Iterables.filter(node.body(), input -> {
279                 if (input instanceof AugmentationNode) {
280                     return true;
281                 }
282                 if (!qnames.contains(input.getIdentifier().getNodeType())) {
283                     return true;
284                 }
285
286                 LOG.debug("Skipping key child {}", input);
287                 return false;
288             }));
289         }
290     }
291 }