Remove NormalizedNodeStreamAttributeWriter
[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 java.util.Objects.requireNonNull;
11 import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.collect.Iterables;
15 import java.io.Closeable;
16 import java.io.Flushable;
17 import java.io.IOException;
18 import java.util.Collection;
19 import java.util.Optional;
20 import java.util.Set;
21 import javax.xml.stream.XMLStreamReader;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.YangModeledAnyXmlNode;
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 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 NormalizedNodeWriter implements Closeable, Flushable {
50     private final NormalizedNodeStreamWriter writer;
51
52     protected NormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
53         this.writer = requireNonNull(writer);
54     }
55
56     protected final NormalizedNodeStreamWriter getWriter() {
57         return writer;
58     }
59
60     /**
61      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
62      *
63      * @param writer Back-end writer
64      * @return A new instance.
65      */
66     public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer) {
67         return forStreamWriter(writer, true);
68     }
69
70     /**
71      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
72      * {@link #forStreamWriter(NormalizedNodeStreamWriter)} method, this allows the caller to switch off RFC6020 XML
73      * compliance, providing better throughput. The reason is that the XML mapping rules in RFC6020 require
74      * the encoding to emit leaf nodes which participate in a list's key first and in the order in which they are
75      * defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any way we
76      * see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we need
77      * to check whether it was already emitted.
78      *
79      * @param writer Back-end writer
80      * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
81      * @return A new instance.
82      */
83     public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
84             final boolean orderKeyLeaves) {
85         return orderKeyLeaves ? new OrderedNormalizedNodeWriter(writer) : new NormalizedNodeWriter(writer);
86     }
87
88     /**
89      * Iterate over the provided {@link NormalizedNode} and emit write
90      * events to the encapsulated {@link NormalizedNodeStreamWriter}.
91      *
92      * @param node Node
93      * @return NormalizedNodeWriter this
94      * @throws IOException when thrown from the backing writer.
95      */
96     public NormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException {
97         if (wasProcessedAsCompositeNode(node)) {
98             return this;
99         }
100
101         if (wasProcessAsSimpleNode(node)) {
102             return this;
103         }
104
105         throw new IllegalStateException("It wasn't possible to serialize node " + node);
106     }
107
108     @Override
109     public void flush() throws IOException {
110         writer.flush();
111     }
112
113     @Override
114     public void close() throws IOException {
115         writer.flush();
116         writer.close();
117     }
118
119     /**
120      * Emit a best guess of a hint for a particular set of children. It evaluates the
121      * iterable to see if the size can be easily gotten to. If it is, we hint at the
122      * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
123      *
124      * @param children Child nodes
125      * @return Best estimate of the collection size required to hold all the children.
126      */
127     protected static int childSizeHint(final Iterable<?> children) {
128         return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
129     }
130
131     protected boolean wasProcessAsSimpleNode(final NormalizedNode<?, ?> node) throws IOException {
132         if (node instanceof LeafSetEntryNode) {
133             final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>)node;
134             writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
135             writer.scalarValue(nodeAsLeafList.getValue());
136             writer.endNode();
137             return true;
138         } else if (node instanceof LeafNode) {
139             final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
140             writer.startLeafNode(nodeAsLeaf.getIdentifier());
141             writer.scalarValue(nodeAsLeaf.getValue());
142             writer.endNode();
143             return true;
144         } else if (node instanceof AnyXmlNode) {
145             final AnyXmlNode anyXmlNode = (AnyXmlNode)node;
146             writer.startAnyxmlNode(anyXmlNode.getIdentifier());
147             writer.domSourceValue(anyXmlNode.getValue());
148             writer.endNode();
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 boolean writeChildren(final Iterable<? extends NormalizedNode<?, ?>> children) throws IOException {
163         for (final 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     protected 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 YangModeledAnyXmlNode) {
183             final YangModeledAnyXmlNode n = (YangModeledAnyXmlNode) node;
184             writer.startYangModeledAnyXmlNode(n.getIdentifier(), childSizeHint(n.getValue()));
185             return writeChildren(n.getValue());
186         }
187         if (node instanceof MapEntryNode) {
188             return writeMapEntryNode((MapEntryNode) node);
189         }
190         if (node instanceof UnkeyedListEntryNode) {
191             final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
192             writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.getValue()));
193             return writeChildren(n.getValue());
194         }
195         if (node instanceof ChoiceNode) {
196             final ChoiceNode n = (ChoiceNode) node;
197             writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.getValue()));
198             return writeChildren(n.getValue());
199         }
200         if (node instanceof AugmentationNode) {
201             final AugmentationNode n = (AugmentationNode) node;
202             writer.startAugmentationNode(n.getIdentifier());
203             return writeChildren(n.getValue());
204         }
205         if (node instanceof UnkeyedListNode) {
206             final UnkeyedListNode n = (UnkeyedListNode) node;
207             writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.getValue()));
208             return writeChildren(n.getValue());
209         }
210         if (node instanceof OrderedMapNode) {
211             final OrderedMapNode n = (OrderedMapNode) node;
212             writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
213             return writeChildren(n.getValue());
214         }
215         if (node instanceof MapNode) {
216             final MapNode n = (MapNode) node;
217             writer.startMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
218             return writeChildren(n.getValue());
219         }
220         if (node instanceof OrderedLeafSetNode) {
221             final LeafSetNode<?> n = (LeafSetNode<?>) node;
222             writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
223             return writeChildren(n.getValue());
224         }
225         if (node instanceof LeafSetNode) {
226             final LeafSetNode<?> n = (LeafSetNode<?>) node;
227             writer.startLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
228             return writeChildren(n.getValue());
229         }
230
231         return false;
232     }
233
234     private static final class OrderedNormalizedNodeWriter extends NormalizedNodeWriter {
235         private static final Logger LOG = LoggerFactory.getLogger(OrderedNormalizedNodeWriter.class);
236
237         OrderedNormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
238             super(writer);
239         }
240
241         @Override
242         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
243             final NormalizedNodeStreamWriter nnWriter = getWriter();
244             nnWriter.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
245
246             final Set<QName> qnames = node.getIdentifier().getKeyValues().keySet();
247             // Write out all the key children
248             for (final QName qname : qnames) {
249                 final Optional<? extends NormalizedNode<?, ?>> child = node.getChild(new NodeIdentifier(qname));
250                 if (child.isPresent()) {
251                     write(child.get());
252                 } else {
253                     LOG.info("No child for key element {} found", qname);
254                 }
255             }
256
257             // Write all the rest
258             return writeChildren(Iterables.filter(node.getValue(), input -> {
259                 if (input instanceof AugmentationNode) {
260                     return true;
261                 }
262                 if (!qnames.contains(input.getNodeType())) {
263                     return true;
264                 }
265
266                 LOG.debug("Skipping key child {}", input);
267                 return false;
268             }));
269         }
270     }
271 }