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
8 package org.opendaylight.restconf.nb.rfc8040.jersey.providers;
10 import static java.util.Objects.requireNonNull;
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.collect.Iterables;
15 import java.io.IOException;
16 import java.util.Collection;
17 import java.util.List;
18 import java.util.Map.Entry;
19 import java.util.Optional;
21 import javax.xml.transform.dom.DOMSource;
22 import org.opendaylight.restconf.nb.rfc8040.DepthParameter;
23 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.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.UnkeyedListEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
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 DepthParameter depth,
60 final List<Set<QName>> fields) {
61 this.writer = requireNonNull(writer);
62 maxDepth = depth == null ? null : depth.value();
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 DepthParameter 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, DepthParameter, List)} method, this allows the caller to
86 * switch off RFC6020 XML compliance, providing better throughput. The reason is that the XML mapping rules in
87 * RFC6020 require the encoding to emit leaf nodes which participate in a list's key first and in the order in which
88 * they are defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any
89 * way we see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we
90 * need to check whether it was already emitted.
92 * @param writer Back-end writer
93 * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
94 * @param depth Maximal depth to write
95 * @param fields Selected child nodes to write
96 * @return A new instance.
98 public static ParameterAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
99 final boolean orderKeyLeaves,
100 final DepthParameter depth,
101 final List<Set<QName>> fields) {
102 return orderKeyLeaves ? new OrderedParameterAwareNormalizedNodeWriter(writer, depth, fields)
103 : new ParameterAwareNormalizedNodeWriter(writer, depth, fields);
107 * Iterate over the provided {@link NormalizedNode} and emit write
108 * events to the encapsulated {@link NormalizedNodeStreamWriter}.
111 * @return {@code ParameterAwareNormalizedNodeWriter}
112 * @throws IOException when thrown from the backing writer.
115 public final ParameterAwareNormalizedNodeWriter write(final NormalizedNode node) throws IOException {
116 if (wasProcessedAsCompositeNode(node)) {
120 if (wasProcessAsSimpleNode(node)) {
124 throw new IllegalStateException("It wasn't possible to serialize node " + node);
128 public void flush() throws IOException {
133 public void close() throws IOException {
139 * Emit a best guess of a hint for a particular set of children. It evaluates the
140 * iterable to see if the size can be easily gotten to. If it is, we hint at the
141 * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
143 * @param children Child nodes
144 * @return Best estimate of the collection size required to hold all the children.
146 static final int childSizeHint(final Iterable<?> children) {
147 return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
150 private boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
151 if (node instanceof LeafSetEntryNode) {
152 if (selectedByParameters(node, false)) {
153 final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>) node;
154 writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
155 writer.scalarValue(nodeAsLeafList.body());
159 } else if (node instanceof LeafNode) {
160 final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
161 writer.startLeafNode(nodeAsLeaf.getIdentifier());
162 writer.scalarValue(nodeAsLeaf.body());
165 } else if (node instanceof AnyxmlNode) {
166 final AnyxmlNode<?> anyxmlNode = (AnyxmlNode<?>)node;
167 final Class<?> objectModel = anyxmlNode.bodyObjectModel();
168 if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), objectModel)) {
169 if (DOMSource.class.isAssignableFrom(objectModel)) {
170 writer.domSourceValue((DOMSource) anyxmlNode.body());
172 writer.scalarValue(anyxmlNode.body());
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.getIdentifier().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.body(), false);
236 } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
237 writeOnlyKeys(mapEntryNode.getIdentifier().entrySet());
242 private void writeOnlyKeys(final Set<Entry<QName, Object>> entries) throws IOException {
243 for (final Entry<QName, Object> entry : entries) {
244 writer.startLeafNode(new NodeIdentifier(entry.getKey()));
245 writer.scalarValue(entry.getValue());
251 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
252 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
254 writeMapEntryChildren(node);
259 private boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
260 boolean processedAsCompositeNode = false;
261 if (node instanceof ContainerNode) {
262 final ContainerNode n = (ContainerNode) node;
263 if (!n.getIdentifier().getNodeType().withoutRevision().equals(ROOT_DATA_QNAME)) {
264 writer.startContainerNode(n.getIdentifier(), childSizeHint(n.body()));
266 processedAsCompositeNode = writeChildren(n.body(), false);
269 // write child nodes of data root container
270 for (final NormalizedNode child : n.body()) {
272 if (selectedByParameters(child, false)) {
276 processedAsCompositeNode = true;
279 } else if (node instanceof MapEntryNode) {
280 processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
281 } else if (node instanceof UnkeyedListEntryNode) {
282 final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
283 writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.body()));
285 processedAsCompositeNode = writeChildren(n.body(), false);
287 } else if (node instanceof ChoiceNode) {
288 final ChoiceNode n = (ChoiceNode) node;
289 writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.body()));
290 processedAsCompositeNode = writeChildren(n.body(), true);
291 } else if (node instanceof AugmentationNode) {
292 final AugmentationNode n = (AugmentationNode) node;
293 writer.startAugmentationNode(n.getIdentifier());
294 processedAsCompositeNode = writeChildren(n.body(), true);
295 } else if (node instanceof UnkeyedListNode) {
296 final UnkeyedListNode n = (UnkeyedListNode) node;
297 writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.body()));
298 processedAsCompositeNode = writeChildren(n.body(), false);
299 } else if (node instanceof UserMapNode) {
300 final UserMapNode n = (UserMapNode) node;
301 writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.body()));
302 processedAsCompositeNode = writeChildren(n.body(), true);
303 } else if (node instanceof MapNode) {
304 final MapNode n = (MapNode) node;
305 writer.startMapNode(n.getIdentifier(), childSizeHint(n.body()));
306 processedAsCompositeNode = writeChildren(n.body(), true);
307 } else if (node instanceof LeafSetNode) {
308 final LeafSetNode<?> n = (LeafSetNode<?>) node;
309 if (node instanceof UserLeafSetNode) {
310 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.body()));
312 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.body()));
315 processedAsCompositeNode = writeChildren(n.body(), true);
319 return processedAsCompositeNode;
322 private static final class OrderedParameterAwareNormalizedNodeWriter extends ParameterAwareNormalizedNodeWriter {
323 private static final Logger LOG = LoggerFactory.getLogger(OrderedParameterAwareNormalizedNodeWriter.class);
325 OrderedParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParameter depth,
326 final List<Set<QName>> fields) {
327 super(writer, depth, fields);
331 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
332 final NormalizedNodeStreamWriter writer = getWriter();
333 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
335 final Set<QName> qnames = node.getIdentifier().keySet();
336 // Write out all the key children
338 for (final QName qname : qnames) {
339 final Optional<? extends NormalizedNode> child = node.findChildByArg(new NodeIdentifier(qname));
340 if (child.isPresent()) {
341 if (selectedByParameters(child.get(), false)) {
345 LOG.info("No child for key element {} found", qname);
351 // Write all the rest
352 final boolean result =
353 writeChildren(Iterables.filter(node.body(), input -> {
354 if (input instanceof AugmentationNode) {
357 if (!qnames.contains(input.getIdentifier().getNodeType())) {
361 LOG.debug("Skipping key child {}", input);