Remove Augmentation{Identifier,Node}
[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.ChoiceNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
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.MapEntryNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
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 static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeWriter.class);
53
54     private final @NonNull NormalizedNodeStreamWriter writer;
55
56     protected NormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
57         this.writer = requireNonNull(writer);
58     }
59
60     protected final NormalizedNodeStreamWriter getWriter() {
61         return writer;
62     }
63
64     /**
65      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
66      *
67      * @param writer Back-end writer
68      * @return A new instance.
69      */
70     public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer) {
71         return forStreamWriter(writer, true);
72     }
73
74     /**
75      * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
76      * {@link #forStreamWriter(NormalizedNodeStreamWriter)} method, this allows the caller to switch off RFC6020 XML
77      * compliance, providing better throughput. The reason is that the XML mapping rules in RFC6020 require
78      * the encoding to emit leaf nodes which participate in a list's key first and in the order in which they are
79      * defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any way we
80      * see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we need
81      * to check whether it was already emitted.
82      *
83      * @param writer Back-end writer
84      * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
85      * @return A new instance.
86      */
87     public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
88             final boolean orderKeyLeaves) {
89         return orderKeyLeaves ? new OrderedNormalizedNodeWriter(writer) : new NormalizedNodeWriter(writer);
90     }
91
92     /**
93      * Iterate over the provided {@link NormalizedNode} and emit write
94      * events to the encapsulated {@link NormalizedNodeStreamWriter}.
95      *
96      * @param node Node
97      * @return NormalizedNodeWriter this
98      * @throws IOException when thrown from the backing writer.
99      */
100     public NormalizedNodeWriter write(final NormalizedNode node) throws IOException {
101         if (wasProcessedAsCompositeNode(node)) {
102             return this;
103         }
104
105         if (wasProcessAsSimpleNode(node)) {
106             return this;
107         }
108
109         throw new IllegalStateException("It wasn't possible to serialize node " + node);
110     }
111
112     @Override
113     public void flush() throws IOException {
114         writer.flush();
115     }
116
117     @Override
118     public void close() throws IOException {
119         writer.flush();
120         writer.close();
121     }
122
123     /**
124      * Emit a best guess of a hint for a particular set of children. It evaluates the
125      * iterable to see if the size can be easily gotten to. If it is, we hint at the
126      * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
127      *
128      * @param children Child nodes
129      * @return Best estimate of the collection size required to hold all the children.
130      */
131     protected static int childSizeHint(final Iterable<?> children) {
132         return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
133     }
134
135     protected boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
136         if (node instanceof LeafSetEntryNode<?> nodeAsLeafList) {
137             writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
138             writer.scalarValue(nodeAsLeafList.body());
139             writer.endNode();
140             return true;
141         } else if (node instanceof LeafNode<?> nodeAsLeaf) {
142             writer.startLeafNode(nodeAsLeaf.getIdentifier());
143             writer.scalarValue(nodeAsLeaf.body());
144             writer.endNode();
145             return true;
146         } else if (node instanceof AnyxmlNode<?> anyxmlNode) {
147             final Class<?> model = anyxmlNode.bodyObjectModel();
148             if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), model)) {
149                 final Object value = node.body();
150                 if (DOMSource.class.isAssignableFrom(model)) {
151                     verify(value instanceof DOMSource, "Inconsistent anyxml node %s", anyxmlNode);
152                     writer.domSourceValue((DOMSource) value);
153                 } else {
154                     writer.scalarValue(value);
155                 }
156                 writer.endNode();
157                 return true;
158             }
159
160             LOG.debug("Ignoring unhandled anyxml node {}", anyxmlNode);
161         } else if (node instanceof AnydataNode<?> anydata) {
162             final Class<?> model = anydata.bodyObjectModel();
163             if (writer.startAnydataNode(anydata.getIdentifier(), model)) {
164                 writer.scalarValue(anydata.body());
165                 writer.endNode();
166                 return true;
167             }
168
169             LOG.debug("Writer {} does not support anydata in form of {}", writer, model);
170         }
171
172         return false;
173     }
174
175     /**
176      * Emit events for all children and then emit an endNode() event.
177      *
178      * @param children Child iterable
179      * @return True
180      * @throws IOException when the writer reports it
181      */
182     protected boolean writeChildren(final Iterable<? extends NormalizedNode> children) throws IOException {
183         for (final NormalizedNode child : children) {
184             write(child);
185         }
186
187         writer.endNode();
188         return true;
189     }
190
191     protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
192         writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
193         return writeChildren(node.body());
194     }
195
196     protected boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
197         if (node instanceof ContainerNode n) {
198             writer.startContainerNode(n.getIdentifier(), childSizeHint(n.body()));
199             return writeChildren(n.body());
200         } else if (node instanceof MapEntryNode n) {
201             return writeMapEntryNode(n);
202         } else if (node instanceof UnkeyedListEntryNode n) {
203             writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.body()));
204             return writeChildren(n.body());
205         } else if (node instanceof ChoiceNode n) {
206             writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.body()));
207             return writeChildren(n.body());
208         } else if (node instanceof UnkeyedListNode n) {
209             writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.body()));
210             return writeChildren(n.body());
211         } else if (node instanceof UserMapNode n) {
212             writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.body()));
213             return writeChildren(n.body());
214         } else if (node instanceof SystemMapNode n) {
215             writer.startMapNode(n.getIdentifier(), childSizeHint(n.body()));
216             return writeChildren(n.body());
217         } else if (node instanceof UserLeafSetNode<?> n) {
218             writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.body()));
219             return writeChildren(n.body());
220         } else if (node instanceof SystemLeafSetNode<?> n) {
221             writer.startLeafSet(n.getIdentifier(), childSizeHint(n.body()));
222             return writeChildren(n.body());
223         }
224         return false;
225     }
226
227     private static final class OrderedNormalizedNodeWriter extends NormalizedNodeWriter {
228         private static final Logger LOG = LoggerFactory.getLogger(OrderedNormalizedNodeWriter.class);
229
230         OrderedNormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
231             super(writer);
232         }
233
234         @Override
235         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
236             final NormalizedNodeStreamWriter nnWriter = getWriter();
237             nnWriter.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
238
239             final Set<QName> qnames = node.getIdentifier().keySet();
240             // Write out all the key children
241             for (final QName qname : qnames) {
242                 final DataContainerChild child = node.childByArg(new NodeIdentifier(qname));
243                 if (child != null) {
244                     write(child);
245                 } else {
246                     LOG.info("No child for key element {} found", qname);
247                 }
248             }
249
250             // Write all the rest
251             return writeChildren(Iterables.filter(node.body(), input -> {
252                 if (qnames.contains(input.getIdentifier().getNodeType())) {
253                     LOG.debug("Skipping key child {}", input);
254                     return false;
255                 }
256                 return true;
257             }));
258         }
259     }
260 }