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