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.jersey.providers.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.UnkeyedListEntryNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
45 * the opposite of a {@link javax.xml.stream.XMLStreamReader} -- unlike instantiating an iterator over
46 * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
47 * us to write multiple nodes.
50 public class ParameterAwareNormalizedNodeWriter implements RestconfNormalizedNodeWriter {
51 private static final QName ROOT_DATA_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "data");
53 private final NormalizedNodeStreamWriter writer;
54 private final Integer maxDepth;
55 protected final List<Set<QName>> fields;
56 protected int currentDepth = 0;
58 private ParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final Integer maxDepth,
59 final List<Set<QName>> fields) {
60 this.writer = requireNonNull(writer);
61 this.maxDepth = maxDepth;
65 protected final NormalizedNodeStreamWriter getWriter() {
70 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
72 * @param writer Back-end writer
73 * @param maxDepth Maximal depth to write
74 * @param fields Selected child nodes to write
75 * @return A new instance.
77 public static ParameterAwareNormalizedNodeWriter forStreamWriter(
78 final NormalizedNodeStreamWriter writer, final Integer maxDepth, final List<Set<QName>> fields) {
79 return forStreamWriter(writer, true, maxDepth, fields);
83 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
84 * {@link #forStreamWriter(NormalizedNodeStreamWriter, Integer, List)}
85 * method, this allows the caller to switch off RFC6020 XML compliance, providing better
86 * throughput. The reason is that the XML mapping rules in RFC6020 require the encoding
87 * 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
89 * can be ordered in any way we see fit. The former requires a bit of work: first a lookup
90 * for each key and then for each emitted node we need to check whether it was already
93 * @param writer Back-end writer
94 * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
95 * @param maxDepth Maximal depth to write
96 * @param fields Selected child nodes to write
97 * @return A new instance.
99 public static ParameterAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
100 final boolean orderKeyLeaves,
101 final Integer maxDepth,
102 final List<Set<QName>> fields) {
103 return orderKeyLeaves ? new OrderedParameterAwareNormalizedNodeWriter(writer, maxDepth, fields)
104 : new ParameterAwareNormalizedNodeWriter(writer, maxDepth, fields);
108 * Iterate over the provided {@link NormalizedNode} and emit write
109 * events to the encapsulated {@link NormalizedNodeStreamWriter}.
112 * @return {@code ParameterAwareNormalizedNodeWriter}
113 * @throws IOException when thrown from the backing writer.
116 public final ParameterAwareNormalizedNodeWriter write(final NormalizedNode node) throws IOException {
117 if (wasProcessedAsCompositeNode(node)) {
121 if (wasProcessAsSimpleNode(node)) {
125 throw new IllegalStateException("It wasn't possible to serialize node " + node);
129 public void flush() throws IOException {
134 public void close() throws IOException {
140 * Emit a best guess of a hint for a particular set of children. It evaluates the
141 * iterable to see if the size can be easily gotten to. If it is, we hint at the
142 * real number of child nodes. Otherwise we emit UNKNOWN_SIZE.
144 * @param children Child nodes
145 * @return Best estimate of the collection size required to hold all the children.
147 static final int childSizeHint(final Iterable<?> children) {
148 return children instanceof Collection ? ((Collection<?>) children).size() : UNKNOWN_SIZE;
151 private boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
152 if (node instanceof LeafSetEntryNode) {
153 if (selectedByParameters(node, false)) {
154 final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>) node;
155 writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
156 writer.scalarValue(nodeAsLeafList.body());
160 } else if (node instanceof LeafNode) {
161 final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
162 writer.startLeafNode(nodeAsLeaf.getIdentifier());
163 writer.scalarValue(nodeAsLeaf.body());
166 } else if (node instanceof AnyxmlNode) {
167 final AnyxmlNode<?> anyxmlNode = (AnyxmlNode<?>)node;
168 final Class<?> objectModel = anyxmlNode.bodyObjectModel();
169 if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), objectModel)) {
170 if (DOMSource.class.isAssignableFrom(objectModel)) {
171 writer.domSourceValue((DOMSource) anyxmlNode.body());
173 writer.scalarValue(anyxmlNode.body());
184 * Check if node should be written according to parameters fields and depth.
185 * See <a href="https://tools.ietf.org/html/draft-ietf-netconf-restconf-18#page-49">Restconf draft</a>.
186 * @param node Node to be written
187 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
188 * @return {@code true} if node will be written, {@code false} otherwise
190 protected boolean selectedByParameters(final NormalizedNode node, final boolean mixinParent) {
191 // nodes to be written are not limited by fields, only by depth
192 if (fields == null) {
193 return maxDepth == null || currentDepth < maxDepth;
196 // children of mixin nodes are never selected in fields but must be written if they are first in selected target
197 if (mixinParent && currentDepth == 0) {
201 // always write augmentation nodes
202 if (node instanceof AugmentationNode) {
206 // write only selected nodes
207 if (currentDepth > 0 && currentDepth <= fields.size()) {
208 return fields.get(currentDepth - 1).contains(node.getIdentifier().getNodeType());
211 // after this depth only depth parameter is used to determine when to write node
212 return maxDepth == null || currentDepth < maxDepth;
216 * Emit events for all children and then emit an endNode() event.
218 * @param children Child iterable
219 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
221 * @throws IOException when the writer reports it
223 protected final boolean writeChildren(final Iterable<? extends NormalizedNode> children,
224 final boolean mixinParent) throws IOException {
225 for (final NormalizedNode child : children) {
226 if (selectedByParameters(child, mixinParent)) {
234 protected boolean writeMapEntryChildren(final MapEntryNode mapEntryNode) throws IOException {
235 if (selectedByParameters(mapEntryNode, false)) {
236 writeChildren(mapEntryNode.body(), false);
237 } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
238 writeOnlyKeys(mapEntryNode.getIdentifier().entrySet());
243 private void writeOnlyKeys(final Set<Entry<QName, Object>> entries) throws IOException {
244 for (final Entry<QName, Object> entry : entries) {
245 writer.startLeafNode(new NodeIdentifier(entry.getKey()));
246 writer.scalarValue(entry.getValue());
252 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
253 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
255 writeMapEntryChildren(node);
260 private boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
261 boolean processedAsCompositeNode = false;
262 if (node instanceof ContainerNode) {
263 final ContainerNode n = (ContainerNode) node;
264 if (!n.getIdentifier().getNodeType().withoutRevision().equals(ROOT_DATA_QNAME)) {
265 writer.startContainerNode(n.getIdentifier(), childSizeHint(n.body()));
267 processedAsCompositeNode = writeChildren(n.body(), false);
270 // write child nodes of data root container
271 for (final NormalizedNode child : n.body()) {
273 if (selectedByParameters(child, false)) {
277 processedAsCompositeNode = true;
280 } else if (node instanceof MapEntryNode) {
281 processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
282 } else if (node instanceof UnkeyedListEntryNode) {
283 final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
284 writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.body()));
286 processedAsCompositeNode = writeChildren(n.body(), false);
288 } else if (node instanceof ChoiceNode) {
289 final ChoiceNode n = (ChoiceNode) node;
290 writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.body()));
291 processedAsCompositeNode = writeChildren(n.body(), true);
292 } else if (node instanceof AugmentationNode) {
293 final AugmentationNode n = (AugmentationNode) node;
294 writer.startAugmentationNode(n.getIdentifier());
295 processedAsCompositeNode = writeChildren(n.body(), true);
296 } else if (node instanceof UnkeyedListNode) {
297 final UnkeyedListNode n = (UnkeyedListNode) node;
298 writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.body()));
299 processedAsCompositeNode = writeChildren(n.body(), false);
300 } else if (node instanceof UserMapNode) {
301 final UserMapNode n = (UserMapNode) node;
302 writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.body()));
303 processedAsCompositeNode = writeChildren(n.body(), true);
304 } else if (node instanceof MapNode) {
305 final MapNode n = (MapNode) node;
306 writer.startMapNode(n.getIdentifier(), childSizeHint(n.body()));
307 processedAsCompositeNode = writeChildren(n.body(), true);
308 } else if (node instanceof LeafSetNode) {
309 final LeafSetNode<?> n = (LeafSetNode<?>) node;
310 if (node instanceof UserLeafSetNode) {
311 writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.body()));
313 writer.startLeafSet(n.getIdentifier(), childSizeHint(n.body()));
316 processedAsCompositeNode = writeChildren(n.body(), true);
320 return processedAsCompositeNode;
323 private static final class OrderedParameterAwareNormalizedNodeWriter extends ParameterAwareNormalizedNodeWriter {
324 private static final Logger LOG = LoggerFactory.getLogger(OrderedParameterAwareNormalizedNodeWriter.class);
326 OrderedParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final Integer maxDepth,
327 final List<Set<QName>> fields) {
328 super(writer, maxDepth, fields);
332 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
333 final NormalizedNodeStreamWriter writer = getWriter();
334 writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.body()));
336 final Set<QName> qnames = node.getIdentifier().keySet();
337 // Write out all the key children
339 for (final QName qname : qnames) {
340 final Optional<? extends NormalizedNode> child = node.findChildByArg(new NodeIdentifier(qname));
341 if (child.isPresent()) {
342 if (selectedByParameters(child.get(), false)) {
346 LOG.info("No child for key element {} found", qname);
352 // Write all the rest
353 final boolean result =
354 writeChildren(Iterables.filter(node.body(), input -> {
355 if (input instanceof AugmentationNode) {
358 if (!qnames.contains(input.getIdentifier().getNodeType())) {
362 LOG.debug("Skipping key child {}", input);