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.Closeable;
15 import java.io.Flushable;
16 import java.io.IOException;
17 import java.util.List;
18 import java.util.Map.Entry;
20 import javax.xml.transform.dom.DOMSource;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.opendaylight.restconf.api.query.DepthParam;
24 import org.opendaylight.yangtools.yang.common.Ordering;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.schema.AnydataNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
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.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.
50 // FIXME: this is a copy&paste from yangtools' NormalizedNodeWriter then adapted for filtering
52 public sealed class RestconfNormalizedNodeWriter implements Flushable, Closeable {
53 private static final QName ROOT_DATA_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "data");
55 final @NonNull NormalizedNodeStreamWriter writer;
56 private final Integer maxDepth;
57 private final List<Set<QName>> fields;
61 private RestconfNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParam depth,
62 final List<Set<QName>> fields) {
63 this.writer = requireNonNull(writer);
64 maxDepth = depth == null ? null : depth.value();
69 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
71 * @param writer Back-end writer
72 * @param maxDepth Maximal depth to write
73 * @return A new instance.
75 public static @NonNull RestconfNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
76 final @Nullable DepthParam maxDepth) {
77 return forStreamWriter(writer, true, maxDepth, null);
81 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
83 * @param writer Back-end writer
84 * @param maxDepth Maximal depth to write
85 * @param fields Selected child nodes to write
86 * @return A new instance.
88 public static @NonNull RestconfNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
89 final @Nullable DepthParam maxDepth, final @Nullable List<Set<QName>> fields) {
90 return forStreamWriter(writer, true, maxDepth, fields);
94 * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
95 * {@link #forStreamWriter(NormalizedNodeStreamWriter, DepthParam, List)} method, this allows the caller to
96 * switch off RFC6020 XML compliance, providing better throughput. The reason is that the XML mapping rules in
97 * RFC6020 require the encoding to emit leaf nodes which participate in a list's key first and in the order in which
98 * they are defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any
99 * way we see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we
100 * need to check whether it was already emitted.
102 * @param writer Back-end writer
103 * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
104 * @param depth Maximal depth to write
105 * @param fields Selected child nodes to write
106 * @return A new instance.
108 public static @NonNull RestconfNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
109 final boolean orderKeyLeaves, final DepthParam depth, final List<Set<QName>> fields) {
110 return orderKeyLeaves ? new OrderedRestconfNormalizedNodeWriter(writer, depth, fields)
111 : new RestconfNormalizedNodeWriter(writer, depth, fields);
115 * Iterate over the provided {@link NormalizedNode} and emit write events to the encapsulated
116 * {@link NormalizedNodeStreamWriter}.
119 * @return {@code ParameterAwareNormalizedNodeWriter}
120 * @throws IOException when thrown from the backing writer.
122 public final RestconfNormalizedNodeWriter write(final NormalizedNode node) throws IOException {
123 if (wasProcessedAsCompositeNode(node) || wasProcessAsSimpleNode(node)) {
126 throw new IllegalStateException("It wasn't possible to serialize node " + node);
130 public final void flush() throws IOException {
135 public final void close() throws IOException {
140 private boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
141 if (node instanceof LeafSetEntryNode<?> nodeAsLeafList) {
142 if (selectedByParameters(node, false)) {
143 writer.startLeafSetEntryNode(nodeAsLeafList.name());
144 writer.scalarValue(nodeAsLeafList.body());
147 } else if (node instanceof LeafNode<?> nodeAsLeaf) {
148 writer.startLeafNode(nodeAsLeaf.name());
149 writer.scalarValue(nodeAsLeaf.body());
151 } else if (node instanceof AnyxmlNode<?> anyxmlNode) {
152 final var objectModel = anyxmlNode.bodyObjectModel();
153 if (writer.startAnyxmlNode(anyxmlNode.name(), objectModel)) {
154 if (DOMSource.class.isAssignableFrom(objectModel)) {
155 writer.domSourceValue((DOMSource) anyxmlNode.body());
157 writer.scalarValue(anyxmlNode.body());
161 } else if (node instanceof AnydataNode<?> anydataNode) {
162 final var objectModel = anydataNode.bodyObjectModel();
163 if (writer.startAnydataNode(anydataNode.name(), objectModel)) {
164 writer.scalarValue(anydataNode.body());
174 * Check if node should be written according to parameters fields and depth.
175 * See <a href="https://tools.ietf.org/html/draft-ietf-netconf-restconf-18#page-49">Restconf draft</a>.
176 * @param node Node to be written
177 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
178 * @return {@code true} if node will be written, {@code false} otherwise
180 protected boolean selectedByParameters(final NormalizedNode node, final boolean mixinParent) {
181 // nodes to be written are not limited by fields, only by depth
182 if (fields == null) {
183 return maxDepth == null || currentDepth < maxDepth;
186 // children of mixin nodes are never selected in fields but must be written if they are first in selected target
187 if (mixinParent && currentDepth == 0) {
191 // write only selected nodes
192 if (currentDepth > 0 && currentDepth <= fields.size()) {
193 return fields.get(currentDepth - 1).contains(node.name().getNodeType());
196 // after this depth only depth parameter is used to determine when to write node
197 return maxDepth == null || currentDepth < maxDepth;
201 * Emit events for all children and then emit an endNode() event.
203 * @param children Child iterable
204 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
206 * @throws IOException when the writer reports it
208 protected final boolean writeChildren(final Iterable<? extends NormalizedNode> children, final boolean mixinParent)
210 for (var child : children) {
211 if (selectedByParameters(child, mixinParent)) {
219 private boolean writeMapEntryChildren(final MapEntryNode mapEntryNode) throws IOException {
220 if (selectedByParameters(mapEntryNode, false)) {
221 writeChildren(mapEntryNode.body(), false);
222 } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
223 writeOnlyKeys(mapEntryNode.name().entrySet());
228 private void writeOnlyKeys(final Set<Entry<QName, Object>> entries) throws IOException {
229 for (final Entry<QName, Object> entry : entries) {
230 writer.startLeafNode(new NodeIdentifier(entry.getKey()));
231 writer.scalarValue(entry.getValue());
237 boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
238 writer.startMapEntryNode(node.name(), node.size());
240 writeMapEntryChildren(node);
245 private boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
246 boolean processedAsCompositeNode = false;
247 if (node instanceof ContainerNode n) {
248 if (!n.name().getNodeType().withoutRevision().equals(ROOT_DATA_QNAME)) {
249 writer.startContainerNode(n.name(), n.size());
251 processedAsCompositeNode = writeChildren(n.body(), false);
254 // write child nodes of data root container
255 for (final NormalizedNode child : n.body()) {
257 if (selectedByParameters(child, false)) {
262 processedAsCompositeNode = true;
264 } else if (node instanceof MapEntryNode n) {
265 processedAsCompositeNode = writeMapEntryNode(n);
266 } else if (node instanceof UnkeyedListEntryNode n) {
267 writer.startUnkeyedListItem(n.name(), n.size());
269 processedAsCompositeNode = writeChildren(n.body(), false);
271 } else if (node instanceof ChoiceNode n) {
272 writer.startChoiceNode(n.name(), n.size());
273 processedAsCompositeNode = writeChildren(n.body(), true);
274 } else if (node instanceof UnkeyedListNode n) {
275 writer.startUnkeyedList(n.name(), n.size());
276 processedAsCompositeNode = writeChildren(n.body(), false);
277 } else if (node instanceof UserMapNode n) {
278 writer.startOrderedMapNode(n.name(), n.size());
279 processedAsCompositeNode = writeChildren(n.body(), true);
280 } else if (node instanceof SystemMapNode n) {
281 writer.startMapNode(n.name(), n.size());
282 processedAsCompositeNode = writeChildren(n.body(), true);
283 } else if (node instanceof LeafSetNode<?> n) {
284 if (n.ordering() == Ordering.USER) {
285 writer.startOrderedLeafSet(n.name(), n.size());
287 writer.startLeafSet(n.name(), n.size());
290 processedAsCompositeNode = writeChildren(n.body(), true);
294 return processedAsCompositeNode;
297 private static final class OrderedRestconfNormalizedNodeWriter extends RestconfNormalizedNodeWriter {
298 private static final Logger LOG = LoggerFactory.getLogger(OrderedRestconfNormalizedNodeWriter.class);
300 OrderedRestconfNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParam depth,
301 final List<Set<QName>> fields) {
302 super(writer, depth, fields);
306 boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
307 writer.startMapEntryNode(node.name(), node.size());
309 final var qnames = node.name().keySet();
310 // Write out all the key children
312 for (var qname : qnames) {
313 final var child = node.childByArg(new NodeIdentifier(qname));
315 if (selectedByParameters(child, false)) {
319 LOG.info("No child for key element {} found", qname);
323 // Write all the rest
324 final boolean result = writeChildren(Iterables.filter(node.body(), input -> {
325 if (!qnames.contains(input.name().getNodeType())) {
329 LOG.debug("Skipping key child {}", input);