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.base.Predicate;
17 import com.google.common.collect.Iterables;
18 import java.io.IOException;
19 import java.util.Collection;
20 import java.util.List;
23 import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
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.OrderedLeafSetNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
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.stream.NormalizedNodeStreamAttributeWriter;
41 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
47 * the opposite of a {@link javax.xml.stream.XMLStreamReader} -- unlike instantiating an iterator over
48 * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
49 * us to write multiple nodes.
52 public class ParameterAwareNormalizedNodeWriter implements RestconfNormalizedNodeWriter {
53 private static final QName ROOT_DATA_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "data");
55 private final NormalizedNodeStreamWriter writer;
56 private final Integer maxDepth;
57 protected final List<Set<QName>> fields;
58 protected int currentDepth = 0;
60 private ParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final Integer maxDepth,
61 final List<Set<QName>> fields) {
62 this.writer = Preconditions.checkNotNull(writer);
63 this.maxDepth = maxDepth;
67 protected final NormalizedNodeStreamWriter getWriter() {
72 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
74 * @param writer Back-end writer
75 * @param maxDepth Maximal depth to write
76 * @param fields Selected child nodes to write
77 * @return A new instance.
79 public static ParameterAwareNormalizedNodeWriter forStreamWriter(
80 final NormalizedNodeStreamWriter writer, final Integer maxDepth, final List<Set<QName>> fields) {
81 return forStreamWriter(writer, true, maxDepth, fields);
85 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
86 * {@link #forStreamWriter(NormalizedNodeStreamWriter, Integer, List)}
87 * method, this allows the caller to switch off RFC6020 XML compliance, providing better
88 * throughput. The reason is that the XML mapping rules in RFC6020 require the encoding
89 * to emit leaf nodes which participate in a list's key first and in the order in which
90 * they are defined in the key. For JSON, this requirement is completely relaxed and leaves
91 * can be ordered in any way we see fit. The former requires a bit of work: first a lookup
92 * for each key and then for each emitted node we need to check whether it was already
95 * @param writer Back-end writer
96 * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
97 * @param maxDepth Maximal depth to write
98 * @param fields Selected child nodes to write
99 * @return A new instance.
101 public static ParameterAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
102 final boolean orderKeyLeaves,
103 final Integer maxDepth,
104 final List<Set<QName>> fields) {
105 if (orderKeyLeaves) {
106 return new OrderedParameterAwareNormalizedNodeWriter(writer, maxDepth, fields);
108 return new ParameterAwareNormalizedNodeWriter(writer, maxDepth, fields);
113 * Iterate over the provided {@link NormalizedNode} and emit write
114 * events to the encapsulated {@link NormalizedNodeStreamWriter}.
118 * @throws IOException when thrown from the backing writer.
120 public final ParameterAwareNormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException {
121 if (wasProcessedAsCompositeNode(node)) {
125 if (wasProcessAsSimpleNode(node)) {
129 throw new IllegalStateException("It wasn't possible to serialize node " + node);
133 public void flush() throws IOException {
138 public void close() throws IOException {
144 * Emit a best guess of a hint for a particular set of children. It evaluates the
145 * iterable to see if the size can be easily gotten to. If it is, we hint at the
146 * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
148 * @param children Child nodes
149 * @return Best estimate of the collection size required to hold all the children.
151 static final int childSizeHint(final Iterable<?> children) {
152 return (children instanceof Collection) ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
155 private boolean wasProcessAsSimpleNode(final NormalizedNode<?, ?> node) throws IOException {
156 if (node instanceof LeafSetEntryNode) {
157 if (selectedByParameters(node, false)) {
158 final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>) node;
159 if (writer instanceof NormalizedNodeStreamAttributeWriter) {
160 ((NormalizedNodeStreamAttributeWriter) writer).leafSetEntryNode(nodeAsLeafList.getNodeType(),
161 nodeAsLeafList.getValue(), nodeAsLeafList.getAttributes());
163 writer.leafSetEntryNode(nodeAsLeafList.getNodeType(), nodeAsLeafList.getValue());
167 } else if (node instanceof LeafNode) {
168 final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
169 if (writer instanceof NormalizedNodeStreamAttributeWriter) {
170 ((NormalizedNodeStreamAttributeWriter) writer).leafNode(
171 nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue(), nodeAsLeaf.getAttributes());
173 writer.leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue());
176 } else if (node instanceof AnyXmlNode) {
177 final AnyXmlNode anyXmlNode = (AnyXmlNode)node;
178 writer.anyxmlNode(anyXmlNode.getIdentifier(), anyXmlNode.getValue());
186 * Check if node should be written according to parameters fields and depth.
187 * See <a href="https://tools.ietf.org/html/draft-ietf-netconf-restconf-18#page-49">Restconf draft</a>.
188 * @param node Node to be written
189 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
190 * @return {@code true} if node will be written, {@code false} otherwise
192 protected boolean selectedByParameters(final NormalizedNode<?, ?> node, final boolean mixinParent) {
193 // nodes to be written are not limited by fields, only by depth
194 if (fields == null) {
195 return (maxDepth == null || currentDepth < maxDepth);
198 // children of mixin nodes are never selected in fields but must be written if they are first in selected target
199 if (mixinParent && currentDepth == 0) {
203 // always write augmentation nodes
204 if (node instanceof AugmentationNode) {
208 // write only selected nodes
209 if (currentDepth > 0 && currentDepth <= fields.size()) {
210 if (fields.get(currentDepth - 1).contains(node.getNodeType())) {
217 // after this depth only depth parameter is used to determine when to write node
218 return (maxDepth == null || currentDepth < maxDepth);
222 * Emit events for all children and then emit an endNode() event.
224 * @param children Child iterable
225 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
227 * @throws IOException when the writer reports it
229 protected final boolean writeChildren(final Iterable<? extends NormalizedNode<?, ?>> children,
230 final boolean mixinParent) throws IOException {
231 for (final NormalizedNode<?, ?> child : children) {
232 if (selectedByParameters(child, mixinParent)) {
240 protected boolean writeMapEntryChildren(final MapEntryNode mapEntryNode) throws IOException {
241 if (selectedByParameters(mapEntryNode, false)) {
242 writeChildren(mapEntryNode.getValue(), false);
243 } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
244 writeOnlyKeys(mapEntryNode.getIdentifier().getKeyValues());
249 private void writeOnlyKeys(final Map<QName, Object> keyValues) throws IllegalArgumentException, IOException {
250 for (final Map.Entry<QName, Object> entry : keyValues.entrySet()) {
251 writer.leafNode(new NodeIdentifier(entry.getKey()), entry.getValue());
256 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
257 if (writer instanceof NormalizedNodeStreamAttributeWriter) {
258 ((NormalizedNodeStreamAttributeWriter) writer)
259 .startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
261 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
264 writeMapEntryChildren(node);
269 private boolean wasProcessedAsCompositeNode(final NormalizedNode<?, ?> node) throws IOException {
270 boolean processedAsCompositeNode = false;
271 if (node instanceof ContainerNode) {
272 final ContainerNode n = (ContainerNode) node;
273 if (!n.getNodeType().equals(ROOT_DATA_QNAME)) {
274 if (writer instanceof NormalizedNodeStreamAttributeWriter) {
275 ((NormalizedNodeStreamAttributeWriter) writer).startContainerNode(
276 n.getIdentifier(), childSizeHint(n.getValue()), n.getAttributes());
278 writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
281 processedAsCompositeNode = writeChildren(n.getValue(), false);
284 // write child nodes of data root container
285 for (final NormalizedNode<?, ?> child : n.getValue()) {
287 if (selectedByParameters(child, false)) {
291 processedAsCompositeNode = true;
295 else if (node instanceof MapEntryNode) {
296 processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
298 else if (node instanceof UnkeyedListEntryNode) {
299 final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
300 writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.getValue()));
302 processedAsCompositeNode = writeChildren(n.getValue(), false);
305 else if (node instanceof ChoiceNode) {
306 final ChoiceNode n = (ChoiceNode) node;
307 writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.getValue()));
308 processedAsCompositeNode = writeChildren(n.getValue(), true);
310 else if (node instanceof AugmentationNode) {
311 final AugmentationNode n = (AugmentationNode) node;
312 writer.startAugmentationNode(n.getIdentifier());
313 processedAsCompositeNode = writeChildren(n.getValue(), true);
315 else if (node instanceof UnkeyedListNode) {
316 final UnkeyedListNode n = (UnkeyedListNode) node;
317 writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.getValue()));
318 processedAsCompositeNode = writeChildren(n.getValue(), false);
320 else if (node instanceof OrderedMapNode) {
321 final OrderedMapNode n = (OrderedMapNode) node;
322 writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
323 processedAsCompositeNode = writeChildren(n.getValue(), true);
325 else if (node instanceof MapNode) {
326 final MapNode n = (MapNode) node;
327 writer.startMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
328 processedAsCompositeNode = writeChildren(n.getValue(), true);
330 else if (node instanceof LeafSetNode) {
331 final LeafSetNode<?> n = (LeafSetNode<?>) node;
332 if (node instanceof OrderedLeafSetNode) {
333 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
335 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
338 processedAsCompositeNode = writeChildren(n.getValue(), true);
342 return processedAsCompositeNode;
345 private static final class OrderedParameterAwareNormalizedNodeWriter extends ParameterAwareNormalizedNodeWriter {
346 private static final Logger LOG = LoggerFactory.getLogger(OrderedParameterAwareNormalizedNodeWriter.class);
348 OrderedParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final Integer maxDepth,
349 final List<Set<QName>> fields) {
350 super(writer, maxDepth, fields);
354 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
355 final NormalizedNodeStreamWriter writer = getWriter();
356 if (writer instanceof NormalizedNodeStreamAttributeWriter) {
357 ((NormalizedNodeStreamAttributeWriter) writer).startMapEntryNode(
358 node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
360 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
363 final Set<QName> qnames = node.getIdentifier().getKeyValues().keySet();
364 // Write out all the key children
366 for (final QName qname : qnames) {
367 final Optional<? extends NormalizedNode<?, ?>> child = node.getChild(new NodeIdentifier(qname));
368 if (child.isPresent()) {
369 if (selectedByParameters(child.get(), false)) {
373 LOG.info("No child for key element {} found", qname);
379 // Write all the rest
380 final boolean result = writeChildren(Iterables.filter(node.getValue(), new Predicate<NormalizedNode<?, ?>>() {
382 public boolean apply(final NormalizedNode<?, ?> input) {
383 if (input instanceof AugmentationNode) {
386 if (!qnames.contains(input.getNodeType())) {
390 LOG.debug("Skipping key child {}", input);