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.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.restconf.api.query.DepthParam;
21 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.api.RestconfNormalizedNodeWriter;
22 import org.opendaylight.yangtools.yang.common.Ordering;
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.AnydataNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
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.DataContainerChild;
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.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
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.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 DepthParam depth,
59 final List<Set<QName>> fields) {
60 this.writer = requireNonNull(writer);
61 maxDepth = depth == null ? null : depth.value();
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 @NonNull ParameterAwareNormalizedNodeWriter forStreamWriter(
78 final NormalizedNodeStreamWriter writer, final DepthParam 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, DepthParam, List)} method, this allows the caller to
85 * switch off RFC6020 XML compliance, providing better throughput. The reason is that the XML mapping rules in
86 * RFC6020 require the encoding to emit leaf nodes which participate in a list's key first and in the order in which
87 * they are defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any
88 * way we see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we
89 * need to check whether it was already emitted.
91 * @param writer Back-end writer
92 * @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
93 * @param depth Maximal depth to write
94 * @param fields Selected child nodes to write
95 * @return A new instance.
97 public static @NonNull ParameterAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
98 final boolean orderKeyLeaves, final DepthParam depth, final List<Set<QName>> fields) {
99 return orderKeyLeaves ? new OrderedParameterAwareNormalizedNodeWriter(writer, depth, fields)
100 : new ParameterAwareNormalizedNodeWriter(writer, depth, fields);
104 * Iterate over the provided {@link NormalizedNode} and emit write
105 * events to the encapsulated {@link NormalizedNodeStreamWriter}.
108 * @return {@code ParameterAwareNormalizedNodeWriter}
109 * @throws IOException when thrown from the backing writer.
112 public final ParameterAwareNormalizedNodeWriter write(final NormalizedNode node) throws IOException {
113 if (wasProcessedAsCompositeNode(node)) {
117 if (wasProcessAsSimpleNode(node)) {
121 throw new IllegalStateException("It wasn't possible to serialize node " + node);
125 public void flush() throws IOException {
130 public void close() throws IOException {
135 private boolean wasProcessAsSimpleNode(final NormalizedNode node) throws IOException {
136 if (node instanceof LeafSetEntryNode<?> nodeAsLeafList) {
137 if (selectedByParameters(node, false)) {
138 writer.startLeafSetEntryNode(nodeAsLeafList.name());
139 writer.scalarValue(nodeAsLeafList.body());
143 } else if (node instanceof LeafNode<?> nodeAsLeaf) {
144 writer.startLeafNode(nodeAsLeaf.name());
145 writer.scalarValue(nodeAsLeaf.body());
148 } else if (node instanceof AnyxmlNode<?> anyxmlNode) {
149 final Class<?> objectModel = anyxmlNode.bodyObjectModel();
150 if (writer.startAnyxmlNode(anyxmlNode.name(), objectModel)) {
151 if (DOMSource.class.isAssignableFrom(objectModel)) {
152 writer.domSourceValue((DOMSource) anyxmlNode.body());
154 writer.scalarValue(anyxmlNode.body());
159 } else if (node instanceof AnydataNode<?> anydataNode) {
160 final Class<?> objectModel = anydataNode.bodyObjectModel();
161 if (writer.startAnydataNode(anydataNode.name(), objectModel)) {
162 writer.scalarValue(anydataNode.body());
172 * Check if node should be written according to parameters fields and depth.
173 * See <a href="https://tools.ietf.org/html/draft-ietf-netconf-restconf-18#page-49">Restconf draft</a>.
174 * @param node Node to be written
175 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
176 * @return {@code true} if node will be written, {@code false} otherwise
178 protected boolean selectedByParameters(final NormalizedNode node, final boolean mixinParent) {
179 // nodes to be written are not limited by fields, only by depth
180 if (fields == null) {
181 return maxDepth == null || currentDepth < maxDepth;
184 // children of mixin nodes are never selected in fields but must be written if they are first in selected target
185 if (mixinParent && currentDepth == 0) {
189 // write only selected nodes
190 if (currentDepth > 0 && currentDepth <= fields.size()) {
191 return fields.get(currentDepth - 1).contains(node.name().getNodeType());
194 // after this depth only depth parameter is used to determine when to write node
195 return maxDepth == null || currentDepth < maxDepth;
199 * Emit events for all children and then emit an endNode() event.
201 * @param children Child iterable
202 * @param mixinParent {@code true} if parent is mixin, {@code false} otherwise
204 * @throws IOException when the writer reports it
206 protected final boolean writeChildren(final Iterable<? extends NormalizedNode> children,
207 final boolean mixinParent) throws IOException {
208 for (final NormalizedNode child : children) {
209 if (selectedByParameters(child, mixinParent)) {
217 protected boolean writeMapEntryChildren(final MapEntryNode mapEntryNode) throws IOException {
218 if (selectedByParameters(mapEntryNode, false)) {
219 writeChildren(mapEntryNode.body(), false);
220 } else if (fields == null && maxDepth != null && currentDepth == maxDepth) {
221 writeOnlyKeys(mapEntryNode.name().entrySet());
226 private void writeOnlyKeys(final Set<Entry<QName, Object>> entries) throws IOException {
227 for (final Entry<QName, Object> entry : entries) {
228 writer.startLeafNode(new NodeIdentifier(entry.getKey()));
229 writer.scalarValue(entry.getValue());
235 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
236 writer.startMapEntryNode(node.name(), node.size());
238 writeMapEntryChildren(node);
243 private boolean wasProcessedAsCompositeNode(final NormalizedNode node) throws IOException {
244 boolean processedAsCompositeNode = false;
245 if (node instanceof ContainerNode n) {
246 if (!n.name().getNodeType().withoutRevision().equals(ROOT_DATA_QNAME)) {
247 writer.startContainerNode(n.name(), n.size());
249 processedAsCompositeNode = writeChildren(n.body(), false);
252 // write child nodes of data root container
253 for (final NormalizedNode child : n.body()) {
255 if (selectedByParameters(child, false)) {
260 processedAsCompositeNode = true;
262 } else if (node instanceof MapEntryNode n) {
263 processedAsCompositeNode = writeMapEntryNode(n);
264 } else if (node instanceof UnkeyedListEntryNode n) {
265 writer.startUnkeyedListItem(n.name(), n.size());
267 processedAsCompositeNode = writeChildren(n.body(), false);
269 } else if (node instanceof ChoiceNode n) {
270 writer.startChoiceNode(n.name(), n.size());
271 processedAsCompositeNode = writeChildren(n.body(), true);
272 } else if (node instanceof UnkeyedListNode n) {
273 writer.startUnkeyedList(n.name(), n.size());
274 processedAsCompositeNode = writeChildren(n.body(), false);
275 } else if (node instanceof UserMapNode n) {
276 writer.startOrderedMapNode(n.name(), n.size());
277 processedAsCompositeNode = writeChildren(n.body(), true);
278 } else if (node instanceof SystemMapNode n) {
279 writer.startMapNode(n.name(), n.size());
280 processedAsCompositeNode = writeChildren(n.body(), true);
281 } else if (node instanceof LeafSetNode<?> n) {
282 if (n.ordering() == Ordering.USER) {
283 writer.startOrderedLeafSet(n.name(), n.size());
285 writer.startLeafSet(n.name(), n.size());
288 processedAsCompositeNode = writeChildren(n.body(), true);
292 return processedAsCompositeNode;
295 private static final class OrderedParameterAwareNormalizedNodeWriter extends ParameterAwareNormalizedNodeWriter {
296 private static final Logger LOG = LoggerFactory.getLogger(OrderedParameterAwareNormalizedNodeWriter.class);
298 OrderedParameterAwareNormalizedNodeWriter(final NormalizedNodeStreamWriter writer, final DepthParam depth,
299 final List<Set<QName>> fields) {
300 super(writer, depth, fields);
304 protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
305 final NormalizedNodeStreamWriter writer = getWriter();
306 writer.startMapEntryNode(node.name(), node.size());
308 final Set<QName> qnames = node.name().keySet();
309 // Write out all the key children
311 for (final QName qname : qnames) {
312 final DataContainerChild child = node.childByArg(new NodeIdentifier(qname));
314 if (selectedByParameters(child, false)) {
318 LOG.info("No child for key element {} found", qname);
324 // Write all the rest
325 final boolean result =
326 writeChildren(Iterables.filter(node.body(), input -> {
327 if (!qnames.contains(input.name().getNodeType())) {
331 LOG.debug("Skipping key child {}", input);