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;
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.Iterables;
14 import java.io.IOException;
15 import java.util.List;
16 import java.util.Map.Entry;
18 import javax.xml.transform.dom.DOMSource;
19 import org.opendaylight.restconf.api.query.DepthParam;
20 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.api.RestconfNormalizedNodeWriter;
21 import org.opendaylight.yangtools.yang.common.Ordering;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.schema.AnydataNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
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.NormalizedNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
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.UserMapNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
44 * the opposite of a {@link javax.xml.stream.XMLStreamReader} -- unlike instantiating an iterator over
45 * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
46 * us to write multiple nodes.
49 public class ParameterAwareNormalizedNodeWriter implements RestconfNormalizedNodeWriter {
50 private static final QName ROOT_DATA_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "data");
52 private final NormalizedNodeStreamWriter writer;
53 private final Integer maxDepth;
54 protected final List<Set<QName>> fields;
55 protected int currentDepth = 0;
57 private ParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParam depth,
58 final List<Set<QName>> fields) {
59 this.writer = requireNonNull(writer);
60 maxDepth = depth == null ? null : depth.value();
64 protected final NormalizedNodeStreamWriter getWriter() {
69 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
71 * @param writer Back-end writer
72 * @param maxDepth Maximal depth to write
73 * @param fields Selected child nodes to write
74 * @return A new instance.
76 public static ParameterAwareNormalizedNodeWriter forStreamWriter(
77 final NormalizedNodeStreamWriter writer, final DepthParam maxDepth, final List<Set<QName>> fields) {
78 return forStreamWriter(writer, true, maxDepth, fields);
82 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
83 * {@link #forStreamWriter(NormalizedNodeStreamWriter, DepthParam, List)} method, this allows the caller to
84 * switch off RFC6020 XML compliance, providing better throughput. The reason is that the XML mapping rules in
85 * RFC6020 require the encoding to emit leaf nodes which participate in a list's key first and in the order in which
86 * they are defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any
87 * way we see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we
88 * need to check whether it was already emitted.
90 * @param writer Back-end writer
91 * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
92 * @param depth Maximal depth to write
93 * @param fields Selected child nodes to write
94 * @return A new instance.
96 public static ParameterAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
97 final boolean orderKeyLeaves,
98 final DepthParam depth,
99 final List<Set<QName>> fields) {
100 return orderKeyLeaves ? new OrderedParameterAwareNormalizedNodeWriter(writer, depth, fields)
101 : new ParameterAwareNormalizedNodeWriter(writer, depth, fields);
105 * Iterate over the provided {@link NormalizedNode} and emit write
106 * events to the encapsulated {@link NormalizedNodeStreamWriter}.
109 * @return {@code ParameterAwareNormalizedNodeWriter}
110 * @throws IOException when thrown from the backing writer.
113 public final ParameterAwareNormalizedNodeWriter write(final NormalizedNode node) throws IOException {
114 if (wasProcessedAsCompositeNode(node)) {
118 if (wasProcessAsSimpleNode(node)) {
122 throw new IllegalStateException("It wasn't possible to serialize node " + node);
126 public void flush() throws IOException {
131 public void close() throws IOException {
136 private boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
137 if (node instanceof LeafSetEntryNode<?> nodeAsLeafList) {
138 if (selectedByParameters(node, false)) {
139 writer.startLeafSetEntryNode(nodeAsLeafList.getIdentifier());
140 writer.scalarValue(nodeAsLeafList.body());
144 } else if (node instanceof LeafNode<?> nodeAsLeaf) {
145 writer.startLeafNode(nodeAsLeaf.getIdentifier());
146 writer.scalarValue(nodeAsLeaf.body());
149 } else if (node instanceof AnyxmlNode<?> anyxmlNode) {
150 final Class<?> objectModel = anyxmlNode.bodyObjectModel();
151 if (writer.startAnyxmlNode(anyxmlNode.getIdentifier(), objectModel)) {
152 if (DOMSource.class.isAssignableFrom(objectModel)) {
153 writer.domSourceValue((DOMSource) anyxmlNode.body());
155 writer.scalarValue(anyxmlNode.body());
160 } else if (node instanceof AnydataNode<?> anydataNode) {
161 final Class<?> objectModel = anydataNode.bodyObjectModel();
162 if (writer.startAnydataNode(anydataNode.getIdentifier(), objectModel)) {
163 writer.scalarValue(anydataNode.body());
173 * Check if node should be written according to parameters fields and depth.
174 * See <a href="https://tools.ietf.org/html/draft-ietf-netconf-restconf-18#page-49">Restconf draft</a>.
175 * @param node Node to be written
176 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
177 * @return {@code true} if node will be written, {@code false} otherwise
179 protected boolean selectedByParameters(final NormalizedNode node, final boolean mixinParent) {
180 // nodes to be written are not limited by fields, only by depth
181 if (fields == null) {
182 return maxDepth == null || currentDepth < maxDepth;
185 // children of mixin nodes are never selected in fields but must be written if they are first in selected target
186 if (mixinParent && currentDepth == 0) {
190 // write only selected nodes
191 if (currentDepth > 0 && currentDepth <= fields.size()) {
192 return fields.get(currentDepth - 1).contains(node.name().getNodeType());
195 // after this depth only depth parameter is used to determine when to write node
196 return maxDepth == null || currentDepth < maxDepth;
200 * Emit events for all children and then emit an endNode() event.
202 * @param children Child iterable
203 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
205 * @throws IOException when the writer reports it
207 protected final boolean writeChildren(final Iterable<? extends NormalizedNode> children,
208 final boolean mixinParent) throws IOException {
209 for (final NormalizedNode child : children) {
210 if (selectedByParameters(child, mixinParent)) {
218 protected boolean writeMapEntryChildren(final MapEntryNode mapEntryNode) throws IOException {
219 if (selectedByParameters(mapEntryNode, false)) {
220 writeChildren(mapEntryNode.body(), false);
221 } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
222 writeOnlyKeys(mapEntryNode.getIdentifier().entrySet());
227 private void writeOnlyKeys(final Set<Entry<QName, Object>> entries) throws IOException {
228 for (final Entry<QName, Object> entry : entries) {
229 writer.startLeafNode(new NodeIdentifier(entry.getKey()));
230 writer.scalarValue(entry.getValue());
236 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
237 writer.startMapEntryNode(node.getIdentifier(), node.size());
239 writeMapEntryChildren(node);
244 private boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
245 boolean processedAsCompositeNode = false;
246 if (node instanceof ContainerNode n) {
247 if (!n.name().getNodeType().withoutRevision().equals(ROOT_DATA_QNAME)) {
248 writer.startContainerNode(n.name(), n.size());
250 processedAsCompositeNode = writeChildren(n.body(), false);
253 // write child nodes of data root container
254 for (final NormalizedNode child : n.body()) {
256 if (selectedByParameters(child, false)) {
261 processedAsCompositeNode = true;
263 } else if (node instanceof MapEntryNode n) {
264 processedAsCompositeNode = writeMapEntryNode(n);
265 } else if (node instanceof UnkeyedListEntryNode n) {
266 writer.startUnkeyedListItem(n.name(), n.size());
268 processedAsCompositeNode = writeChildren(n.body(), false);
270 } else if (node instanceof ChoiceNode n) {
271 writer.startChoiceNode(n.name(), n.size());
272 processedAsCompositeNode = writeChildren(n.body(), true);
273 } else if (node instanceof UnkeyedListNode n) {
274 writer.startUnkeyedList(n.name(), n.size());
275 processedAsCompositeNode = writeChildren(n.body(), false);
276 } else if (node instanceof UserMapNode n) {
277 writer.startOrderedMapNode(n.name(), n.size());
278 processedAsCompositeNode = writeChildren(n.body(), true);
279 } else if (node instanceof SystemMapNode n) {
280 writer.startMapNode(n.name(), n.size());
281 processedAsCompositeNode = writeChildren(n.body(), true);
282 } else if (node instanceof LeafSetNode<?> n) {
283 if (n.ordering() == Ordering.USER) {
284 writer.startOrderedLeafSet(n.name(), n.size());
286 writer.startLeafSet(n.name(), n.size());
289 processedAsCompositeNode = writeChildren(n.body(), true);
293 return processedAsCompositeNode;
296 private static final class OrderedParameterAwareNormalizedNodeWriter extends ParameterAwareNormalizedNodeWriter {
297 private static final Logger LOG = LoggerFactory.getLogger(OrderedParameterAwareNormalizedNodeWriter.class);
299 OrderedParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParam depth,
300 final List<Set<QName>> fields) {
301 super(writer, depth, fields);
305 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
306 final NormalizedNodeStreamWriter writer = getWriter();
307 writer.startMapEntryNode(node.name(), node.size());
309 final Set<QName> qnames = node.name().keySet();
310 // Write out all the key children
312 for (final QName qname : qnames) {
313 final DataContainerChild child = node.childByArg(new NodeIdentifier(qname));
315 if (selectedByParameters(child, false)) {
319 LOG.info("No child for key element {} found", qname);
325 // Write all the rest
326 final boolean result =
327 writeChildren(Iterables.filter(node.body(), input -> {
328 if (!qnames.contains(input.name().getNodeType())) {
332 LOG.debug("Skipping key child {}", input);