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