2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.restconf.jersey.providers;
11 import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.Iterables;
17 import java.io.IOException;
18 import java.util.Collection;
19 import java.util.List;
22 import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
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.OrderedLeafSetNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
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.stream.NormalizedNodeStreamAttributeWriter;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
45 * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
46 * the opposite of a {@link javax.xml.stream.XMLStreamReader} -- unlike instantiating an iterator over
47 * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
48 * us to write multiple nodes.
51 public class ParameterAwareNormalizedNodeWriter implements RestconfNormalizedNodeWriter {
52 private static final QName ROOT_DATA_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "data");
54 private final NormalizedNodeStreamWriter writer;
55 private final Integer maxDepth;
56 protected final List<Set<QName>> fields;
57 protected int currentDepth = 0;
59 private ParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final Integer maxDepth,
60 final List<Set<QName>> fields) {
61 this.writer = Preconditions.checkNotNull(writer);
62 this.maxDepth = maxDepth;
66 protected final NormalizedNodeStreamWriter getWriter() {
71 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
73 * @param writer Back-end writer
74 * @param maxDepth Maximal depth to write
75 * @param fields Selected child nodes to write
76 * @return A new instance.
78 public static ParameterAwareNormalizedNodeWriter forStreamWriter(
79 final NormalizedNodeStreamWriter writer, final Integer maxDepth, final List<Set<QName>> fields) {
80 return forStreamWriter(writer, true, maxDepth, fields);
84 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
85 * {@link #forStreamWriter(NormalizedNodeStreamWriter, Integer, List)}
86 * method, this allows the caller to switch off RFC6020 XML compliance, providing better
87 * throughput. The reason is that the XML mapping rules in RFC6020 require the encoding
88 * to emit leaf nodes which participate in a list's key first and in the order in which
89 * they are defined in the key. For JSON, this requirement is completely relaxed and leaves
90 * can be ordered in any way we see fit. The former requires a bit of work: first a lookup
91 * for each key and then for each emitted node we need to check whether it was already
94 * @param writer Back-end writer
95 * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
96 * @param maxDepth Maximal depth to write
97 * @param fields Selected child nodes to write
98 * @return A new instance.
100 public static ParameterAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
101 final boolean orderKeyLeaves,
102 final Integer maxDepth,
103 final List<Set<QName>> fields) {
104 return orderKeyLeaves ? new OrderedParameterAwareNormalizedNodeWriter(writer, maxDepth, fields)
105 : new ParameterAwareNormalizedNodeWriter(writer, maxDepth, fields);
109 * Iterate over the provided {@link NormalizedNode} and emit write
110 * events to the encapsulated {@link NormalizedNodeStreamWriter}.
113 * @return {@code ParameterAwareNormalizedNodeWriter}
114 * @throws IOException when thrown from the backing writer.
117 public final ParameterAwareNormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException {
118 if (wasProcessedAsCompositeNode(node)) {
122 if (wasProcessAsSimpleNode(node)) {
126 throw new IllegalStateException("It wasn't possible to serialize node " + node);
130 public void flush() throws IOException {
135 public void close() throws IOException {
141 * Emit a best guess of a hint for a particular set of children. It evaluates the
142 * iterable to see if the size can be easily gotten to. If it is, we hint at the
143 * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
145 * @param children Child nodes
146 * @return Best estimate of the collection size required to hold all the children.
148 static final int childSizeHint(final Iterable<?> children) {
149 return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
152 private boolean wasProcessAsSimpleNode(final NormalizedNode<?, ?> node) throws IOException {
153 if (node instanceof LeafSetEntryNode) {
154 if (selectedByParameters(node, false)) {
155 final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>) node;
156 if (writer instanceof NormalizedNodeStreamAttributeWriter) {
157 ((NormalizedNodeStreamAttributeWriter) writer).leafSetEntryNode(nodeAsLeafList.getNodeType(),
158 nodeAsLeafList.getValue(), nodeAsLeafList.getAttributes());
160 writer.leafSetEntryNode(nodeAsLeafList.getNodeType(), nodeAsLeafList.getValue());
164 } else if (node instanceof LeafNode) {
165 final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
166 if (writer instanceof NormalizedNodeStreamAttributeWriter) {
167 ((NormalizedNodeStreamAttributeWriter) writer).leafNode(
168 nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue(), nodeAsLeaf.getAttributes());
170 writer.leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue());
173 } else if (node instanceof AnyXmlNode) {
174 final AnyXmlNode anyXmlNode = (AnyXmlNode)node;
175 writer.anyxmlNode(anyXmlNode.getIdentifier(), anyXmlNode.getValue());
183 * Check if node should be written according to parameters fields and depth.
184 * See <a href="https://tools.ietf.org/html/draft-ietf-netconf-restconf-18#page-49">Restconf draft</a>.
185 * @param node Node to be written
186 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
187 * @return {@code true} if node will be written, {@code false} otherwise
189 protected boolean selectedByParameters(final NormalizedNode<?, ?> node, final boolean mixinParent) {
190 // nodes to be written are not limited by fields, only by depth
191 if (fields == null) {
192 return maxDepth == null || currentDepth < maxDepth;
195 // children of mixin nodes are never selected in fields but must be written if they are first in selected target
196 if (mixinParent && currentDepth == 0) {
200 // always write augmentation nodes
201 if (node instanceof AugmentationNode) {
205 // write only selected nodes
206 if (currentDepth > 0 && currentDepth <= fields.size()) {
207 return fields.get(currentDepth - 1).contains(node.getNodeType());
210 // after this depth only depth parameter is used to determine when to write node
211 return maxDepth == null || currentDepth < maxDepth;
215 * Emit events for all children and then emit an endNode() event.
217 * @param children Child iterable
218 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
220 * @throws IOException when the writer reports it
222 protected final boolean writeChildren(final Iterable<? extends NormalizedNode<?, ?>> children,
223 final boolean mixinParent) throws IOException {
224 for (final NormalizedNode<?, ?> child : children) {
225 if (selectedByParameters(child, mixinParent)) {
233 protected boolean writeMapEntryChildren(final MapEntryNode mapEntryNode) throws IOException {
234 if (selectedByParameters(mapEntryNode, false)) {
235 writeChildren(mapEntryNode.getValue(), false);
236 } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
237 writeOnlyKeys(mapEntryNode.getIdentifier().getKeyValues());
242 private void writeOnlyKeys(final Map<QName, Object> keyValues) throws IllegalArgumentException, IOException {
243 for (final Map.Entry<QName, Object> entry : keyValues.entrySet()) {
244 writer.leafNode(new NodeIdentifier(entry.getKey()), entry.getValue());
249 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
250 if (writer instanceof NormalizedNodeStreamAttributeWriter) {
251 ((NormalizedNodeStreamAttributeWriter) writer)
252 .startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
254 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
257 writeMapEntryChildren(node);
262 private boolean wasProcessedAsCompositeNode(final NormalizedNode<?, ?> node) throws IOException {
263 boolean processedAsCompositeNode = false;
264 if (node instanceof ContainerNode) {
265 final ContainerNode n = (ContainerNode) node;
266 if (!n.getNodeType().equals(ROOT_DATA_QNAME)) {
267 if (writer instanceof NormalizedNodeStreamAttributeWriter) {
268 ((NormalizedNodeStreamAttributeWriter) writer).startContainerNode(
269 n.getIdentifier(), childSizeHint(n.getValue()), n.getAttributes());
271 writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
274 processedAsCompositeNode = writeChildren(n.getValue(), false);
277 // write child nodes of data root container
278 for (final NormalizedNode<?, ?> child : n.getValue()) {
280 if (selectedByParameters(child, false)) {
284 processedAsCompositeNode = true;
287 } else if (node instanceof MapEntryNode) {
288 processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
289 } else if (node instanceof UnkeyedListEntryNode) {
290 final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
291 writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.getValue()));
293 processedAsCompositeNode = writeChildren(n.getValue(), false);
295 } else if (node instanceof ChoiceNode) {
296 final ChoiceNode n = (ChoiceNode) node;
297 writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.getValue()));
298 processedAsCompositeNode = writeChildren(n.getValue(), true);
299 } else if (node instanceof AugmentationNode) {
300 final AugmentationNode n = (AugmentationNode) node;
301 writer.startAugmentationNode(n.getIdentifier());
302 processedAsCompositeNode = writeChildren(n.getValue(), true);
303 } else if (node instanceof UnkeyedListNode) {
304 final UnkeyedListNode n = (UnkeyedListNode) node;
305 writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.getValue()));
306 processedAsCompositeNode = writeChildren(n.getValue(), false);
307 } else if (node instanceof OrderedMapNode) {
308 final OrderedMapNode n = (OrderedMapNode) node;
309 writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
310 processedAsCompositeNode = writeChildren(n.getValue(), true);
311 } else if (node instanceof MapNode) {
312 final MapNode n = (MapNode) node;
313 writer.startMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
314 processedAsCompositeNode = writeChildren(n.getValue(), true);
315 } else if (node instanceof LeafSetNode) {
316 final LeafSetNode<?> n = (LeafSetNode<?>) node;
317 if (node instanceof OrderedLeafSetNode) {
318 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
320 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
323 processedAsCompositeNode = writeChildren(n.getValue(), true);
327 return processedAsCompositeNode;
330 private static final class OrderedParameterAwareNormalizedNodeWriter extends ParameterAwareNormalizedNodeWriter {
331 private static final Logger LOG = LoggerFactory.getLogger(OrderedParameterAwareNormalizedNodeWriter.class);
333 OrderedParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final Integer maxDepth,
334 final List<Set<QName>> fields) {
335 super(writer, maxDepth, fields);
339 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
340 final NormalizedNodeStreamWriter writer = getWriter();
341 if (writer instanceof NormalizedNodeStreamAttributeWriter) {
342 ((NormalizedNodeStreamAttributeWriter) writer).startMapEntryNode(
343 node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
345 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
348 final Set<QName> qnames = node.getIdentifier().getKeyValues().keySet();
349 // Write out all the key children
351 for (final QName qname : qnames) {
352 final Optional<? extends NormalizedNode<?, ?>> child = node.getChild(new NodeIdentifier(qname));
353 if (child.isPresent()) {
354 if (selectedByParameters(child.get(), false)) {
358 LOG.info("No child for key element {} found", qname);
364 // Write all the rest
365 final boolean result =
366 writeChildren(Iterables.filter(node.getValue(), input -> {
367 if (input instanceof AugmentationNode) {
370 if (!qnames.contains(input.getNodeType())) {
374 LOG.debug("Skipping key child {}", input);