Use pattern matching on instanceof in NormalizedNodeWriter
[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<?> nodeAsLeafList) {
138             writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
139             writer.scalarValue(nodeAsLeafList.body());
140             writer.endNode();
141             return true;
142         } else if (node instanceof LeafNode<?> nodeAsLeaf) {
143             writer.startLeafNode(nodeAsLeaf.getIdentifier());
144             writer.scalarValue(nodeAsLeaf.body());
145             writer.endNode();
146             return true;
147         } else if (node instanceof AnyxmlNode<?> anyxmlNode) {
148             final Class<?> model = anyxmlNode.bodyObjectModel();
149             if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), model)) {
150                 final Object value = node.body();
151                 if (DOMSource.class.isAssignableFrom(model)) {
152                     verify(value instanceof DOMSource, "Inconsistent anyxml node %s", anyxmlNode);
153                     writer.domSourceValue((DOMSource) value);
154                 } else {
155                     writer.scalarValue(value);
156                 }
157                 writer.endNode();
158                 return true;
159             }
160
161             LOG.debug("Ignoring unhandled anyxml node {}", anyxmlNode);
162         } else if (node instanceof AnydataNode<?> anydata) {
163             final Class<?> model = anydata.bodyObjectModel();
164             if (writer.startAnydataNode(anydata.getIdentifier(), model)) {
165                 writer.scalarValue(anydata.body());
166                 writer.endNode();
167                 return true;
168             }
169
170             LOG.debug("Writer {} does not support anydata in form of {}", writer, model);
171         }
172
173         return false;
174     }
175
176     /**
177      * Emit events for all children and then emit an endNode() event.
178      *
179      * @param children Child iterable
180      * @return True
181      * @throws IOException when the writer reports it
182      */
183     protected boolean writeChildren(final Iterable<? extends NormalizedNode> children) throws IOException {
184         for (final NormalizedNode child : children) {
185             write(child);
186         }
187
188         writer.endNode();
189         return true;
190     }
191
192     protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
193         writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
194         return writeChildren(node.body());
195     }
196
197     protected boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
198         if (node instanceof ContainerNode n) {
199             writer.startContainerNode(n.getIdentifier(), childSizeHint(n.body()));
200             return writeChildren(n.body());
201         } else if (node instanceof MapEntryNode n) {
202             return writeMapEntryNode(n);
203         } else if (node instanceof UnkeyedListEntryNode n) {
204             writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.body()));
205             return writeChildren(n.body());
206         } else if (node instanceof ChoiceNode n) {
207             writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.body()));
208             return writeChildren(n.body());
209         } else if (node instanceof AugmentationNode n) {
210             writer.startAugmentationNode(n.getIdentifier());
211             return writeChildren(n.body());
212         } else if (node instanceof UnkeyedListNode n) {
213             writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.body()));
214             return writeChildren(n.body());
215         } else if (node instanceof UserMapNode n) {
216             writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.body()));
217             return writeChildren(n.body());
218         } else if (node instanceof SystemMapNode n) {
219             writer.startMapNode(n.getIdentifier(), childSizeHint(n.body()));
220             return writeChildren(n.body());
221         } else if (node instanceof UserLeafSetNode<?> n) {
222             writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.body()));
223             return writeChildren(n.body());
224         } else if (node instanceof SystemLeafSetNode<?> n) {
225             writer.startLeafSet(n.getIdentifier(), childSizeHint(n.body()));
226             return writeChildren(n.body());
227         }
228         return false;
229     }
230
231     private static final class OrderedNormalizedNodeWriter extends NormalizedNodeWriter {
232         private static final Logger LOG = LoggerFactory.getLogger(OrderedNormalizedNodeWriter.class);
233
234         OrderedNormalizedNodeWriter(final NormalizedNodeStreamWriter writer) {
235             super(writer);
236         }
237
238         @Override
239         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
240             final NormalizedNodeStreamWriter nnWriter = getWriter();
241             nnWriter.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
242
243             final Set<QName> qnames = node.getIdentifier().keySet();
244             // Write out all the key children
245             for (final QName qname : qnames) {
246                 final DataContainerChild child = node.childByArg(new NodeIdentifier(qname));
247                 if (child != null) {
248                     write(child);
249                 } else {
250                     LOG.info("No child for key element {} found", qname);
251                 }
252             }
253
254             // Write all the rest
255             return writeChildren(Iterables.filter(node.body(), input -> {
256                 if (input instanceof AugmentationNode) {
257                     return true;
258                 }
259                 if (!qnames.contains(input.getIdentifier().getNodeType())) {
260                     return true;
261                 }
262
263                 LOG.debug("Skipping key child {}", input);
264                 return false;
265             }));
266         }
267     }
268 }