2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. 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.netconf.util;
10 import static com.google.common.base.Preconditions.checkArgument;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.Iterables;
14 import java.io.IOException;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.HashMap;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.Optional;
23 import java.util.stream.Collectors;
24 import javax.xml.transform.dom.DOMSource;
25 import org.opendaylight.yangtools.concepts.Identifiable;
26 import org.opendaylight.yangtools.yang.common.Empty;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
35 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
36 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
39 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
49 abstract class StreamingContext<T extends PathArgument> implements Identifiable<T> {
50 private final T identifier;
52 StreamingContext(final T identifier) {
53 this.identifier = identifier;
56 static StreamingContext<?> fromSchemaAndQNameChecked(final DataNodeContainer schema, final QName child) {
57 final Optional<DataSchemaNode> potential = findChildSchemaNode(schema, child);
58 checkArgument(potential.isPresent(),
59 "Supplied QName %s is not valid according to schema %s, potential children nodes: %s", child, schema,
60 schema.getChildNodes());
62 final DataSchemaNode result = potential.get();
63 // We try to look up if this node was added by augmentation
64 if (schema instanceof DataSchemaNode && result.isAugmenting()) {
65 for (final AugmentationSchemaNode aug : ((AugmentationTarget)schema).getAvailableAugmentations()) {
66 if (aug.dataChildByName(result.getQName()) != null) {
67 return new Augmentation(aug, schema);
71 return fromDataSchemaNode(result);
74 static StreamingContext<?> fromDataSchemaNode(final DataSchemaNode potential) {
75 if (potential instanceof ContainerSchemaNode) {
76 return new Container((ContainerSchemaNode) potential);
77 } else if (potential instanceof ListSchemaNode) {
78 return fromListSchemaNode((ListSchemaNode) potential);
79 } else if (potential instanceof LeafSchemaNode) {
80 return new Leaf((LeafSchemaNode) potential);
81 } else if (potential instanceof ChoiceSchemaNode) {
82 return new Choice((ChoiceSchemaNode) potential);
83 } else if (potential instanceof LeafListSchemaNode) {
84 return fromLeafListSchemaNode((LeafListSchemaNode) potential);
85 } else if (potential instanceof AnyxmlSchemaNode) {
86 return new AnyXml((AnyxmlSchemaNode) potential);
92 public final T getIdentifier() {
96 abstract StreamingContext<?> getChild(PathArgument child);
99 * Writing node structure that is described by series of {@link PathArgument}
100 * into {@link NormalizedNodeStreamWriter}.
102 * @param writer output {@link NormalizedNode} writer
103 * @param first the first {@link PathArgument}
104 * @param others iterator that points to next path arguments
105 * @throws IOException failed to write a stream of path arguments into {@link NormalizedNodeStreamWriter}
107 abstract void streamToWriter(NormalizedNodeStreamWriter writer, PathArgument first, Iterator<PathArgument> others)
111 * Writing node structure that is described by provided {@link PathNode} into {@link NormalizedNodeStreamWriter}.
113 * @param writer output {@link NormalizedNode} writer
114 * @param first the first {@link PathArgument}
115 * @param tree subtree of path arguments that starts with the first path argument
116 * @throws IOException failed to write a stream of path arguments into {@link NormalizedNodeStreamWriter}
118 abstract void streamToWriter(NormalizedNodeStreamWriter writer, PathArgument first, PathNode tree)
121 abstract boolean isMixin();
123 private static Optional<DataSchemaNode> findChildSchemaNode(final DataNodeContainer parent, final QName child) {
124 final Optional<DataSchemaNode> potential = parent.findDataChildByName(child);
125 return potential.isPresent() ? potential
126 : findChoice(Iterables.filter(parent.getChildNodes(), ChoiceSchemaNode.class), child);
129 private static Optional<DataSchemaNode> findChoice(final Iterable<ChoiceSchemaNode> choices, final QName child) {
130 for (final ChoiceSchemaNode choice : choices) {
131 for (final CaseSchemaNode caze : choice.getCases()) {
132 if (findChildSchemaNode(caze, child).isPresent()) {
133 return Optional.of(choice);
137 return Optional.empty();
140 private static StreamingContext<?> fromListSchemaNode(final ListSchemaNode potential) {
141 final List<QName> keyDefinition = potential.getKeyDefinition();
142 if (keyDefinition == null || keyDefinition.isEmpty()) {
143 return new UnkeyedListMixin(potential);
145 return potential.isUserOrdered() ? new OrderedMapMixin(potential)
146 : new UnorderedMapMixin(potential);
149 private static StreamingContext<?> fromLeafListSchemaNode(final LeafListSchemaNode potential) {
150 return potential.isUserOrdered() ? new OrderedLeafListMixin(potential)
151 : new UnorderedLeafListMixin(potential);
154 private abstract static class AbstractComposite<T extends PathArgument> extends StreamingContext<T> {
155 AbstractComposite(final T identifier) {
160 final void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
161 final Iterator<PathArgument> others) throws IOException {
162 verifyActualPathArgument(first);
164 emitElementStart(writer, first, others.hasNext() ? 1 : 0);
165 if (others.hasNext()) {
166 final PathArgument childPath = others.next();
167 final StreamingContext<?> childOp = getChildOperation(childPath);
168 childOp.streamToWriter(writer, childPath, others);
174 final void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
175 final PathNode subtree) throws IOException {
176 verifyActualPathArgument(first);
178 final Collection<PathNode> children = subtree.children();
179 emitElementStart(writer, first, children.size());
180 for (final PathNode node : subtree.children()) {
181 emitChildTreeNode(writer, node);
186 void emitChildTreeNode(final NormalizedNodeStreamWriter writer, final PathNode node) throws IOException {
187 final PathArgument childPath = node.element();
188 getChildOperation(childPath).streamToWriter(writer, childPath, node);
191 private void verifyActualPathArgument(final PathArgument first) {
193 final QName type = getIdentifier().getNodeType();
194 final QName firstType = first.getNodeType();
195 checkArgument(type.equals(firstType), "Node QName must be %s was %s", type, firstType);
199 abstract void emitElementStart(NormalizedNodeStreamWriter writer, PathArgument arg,
200 int childSizeHint) throws IOException;
202 @SuppressWarnings("checkstyle:illegalCatch")
203 StreamingContext<?> getChildOperation(final PathArgument childPath) {
204 final StreamingContext<?> childOp;
206 childOp = getChild(childPath);
207 } catch (final RuntimeException e) {
208 throw new IllegalArgumentException(String.format("Failed to process child node %s", childPath), e);
210 checkArgument(childOp != null, "Node %s is not allowed inside %s", childPath, getIdentifier());
215 private abstract static class AbstractDataContainer<T extends PathArgument> extends AbstractComposite<T> {
216 private final Map<PathArgument, StreamingContext<?>> byArg = new HashMap<>();
217 private final DataNodeContainer schema;
219 AbstractDataContainer(final T identifier, final DataNodeContainer schema) {
221 this.schema = schema;
225 final StreamingContext<?> getChild(final PathArgument child) {
226 StreamingContext<?> potential = byArg.get(child);
227 if (potential != null) {
230 potential = fromLocalSchema(child);
231 if (potential != null) {
232 byArg.put(potential.getIdentifier(), potential);
237 private StreamingContext<?> fromLocalSchema(final PathArgument child) {
238 if (child instanceof AugmentationIdentifier) {
239 return fromSchemaAndQNameChecked(schema, ((AugmentationIdentifier) child).getPossibleChildNames()
242 return fromSchemaAndQNameChecked(schema, child.getNodeType());
246 private abstract static class AbstractMapMixin extends AbstractComposite<NodeIdentifier> {
247 private final ListEntry innerNode;
248 private final List<QName> keyLeaves;
250 AbstractMapMixin(final ListSchemaNode list) {
251 super(NodeIdentifier.create(list.getQName()));
252 innerNode = new ListEntry(NodeIdentifierWithPredicates.of(list.getQName()), list);
253 keyLeaves = list.getKeyDefinition();
257 final StreamingContext<?> getChild(final PathArgument child) {
258 return child.getNodeType().equals(getIdentifier().getNodeType()) ? innerNode : null;
262 final boolean isMixin() {
267 final void emitChildTreeNode(final NormalizedNodeStreamWriter writer, final PathNode node) throws IOException {
268 final PathArgument element = node.element();
269 if (!(element instanceof NodeIdentifierWithPredicates)) {
270 throw new IOException("Child identifier " + element + " is invalid in parent " + getIdentifier());
273 final NodeIdentifierWithPredicates childPath = (NodeIdentifierWithPredicates) element;
274 final StreamingContext<?> childOp = getChildOperation(childPath);
275 if (childPath.size() == 0 && node.isEmpty() || childPath.keySet().containsAll(keyLeaves)) {
276 // This is a query for the entire list, or the query specifies everything we need
277 childOp.streamToWriter(writer, childPath, node);
281 // Inexact query, we need to also request the leaf nodes we need to for reconstructing a valid instance
282 // NodeIdentifierWithPredicates.
283 childOp.streamToWriter(writer, childPath, node.copyWith(keyLeaves.stream()
284 .filter(qname -> !childPath.containsKey(qname))
285 .map(NodeIdentifier::new)
286 .collect(Collectors.toUnmodifiableList())));
290 private abstract static class AbstractSimple<T extends PathArgument> extends StreamingContext<T> {
291 AbstractSimple(final T identifier) {
296 final StreamingContext<?> getChild(final PathArgument child) {
301 final boolean isMixin() {
306 final void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
307 final PathNode tree) throws IOException {
308 streamToWriter(writer, first, Collections.emptyIterator());
312 private static final class AnyXml extends AbstractSimple<NodeIdentifier> {
313 AnyXml(final AnyxmlSchemaNode schema) {
314 super(NodeIdentifier.create(schema.getQName()));
318 void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
319 final Iterator<PathArgument> others) throws IOException {
320 writer.startAnyxmlNode(getIdentifier(), DOMSource.class);
321 // FIXME: why are we not emitting a value?
326 private static final class Choice extends AbstractComposite<NodeIdentifier> {
327 private final ImmutableMap<PathArgument, StreamingContext<?>> byArg;
329 Choice(final ChoiceSchemaNode schema) {
330 super(NodeIdentifier.create(schema.getQName()));
331 final ImmutableMap.Builder<PathArgument, StreamingContext<?>> byArgBuilder = ImmutableMap.builder();
333 for (final CaseSchemaNode caze : schema.getCases()) {
334 for (final DataSchemaNode cazeChild : caze.getChildNodes()) {
335 final StreamingContext<?> childOp = fromDataSchemaNode(cazeChild);
336 byArgBuilder.put(childOp.getIdentifier(), childOp);
339 byArg = byArgBuilder.build();
343 StreamingContext<?> getChild(final PathArgument child) {
344 return byArg.get(child);
353 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
354 final int childSizeHint) throws IOException {
355 writer.startChoiceNode(getIdentifier(), childSizeHint);
359 private static final class Leaf extends AbstractSimple<NodeIdentifier> {
360 Leaf(final LeafSchemaNode potential) {
361 super(new NodeIdentifier(potential.getQName()));
365 void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
366 final Iterator<PathArgument> others) throws IOException {
367 writer.startLeafNode(getIdentifier());
368 // FIXME: why are we not emitting a value?
373 private static final class LeafListEntry extends AbstractSimple<NodeWithValue<?>> {
374 LeafListEntry(final LeafListSchemaNode potential) {
375 super(new NodeWithValue<>(potential.getQName(), Empty.value()));
379 void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
380 final Iterator<PathArgument> others) throws IOException {
381 checkArgument(first instanceof NodeWithValue);
382 final NodeWithValue<?> identifier = (NodeWithValue<?>) first;
383 writer.startLeafSetEntryNode(identifier);
384 writer.scalarValue(identifier.getValue());
389 private static final class ListEntry extends AbstractDataContainer<NodeIdentifierWithPredicates> {
390 ListEntry(final NodeIdentifierWithPredicates identifier, final ListSchemaNode schema) {
391 super(identifier, schema);
400 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
401 final int childSizeHint) throws IOException {
402 final NodeIdentifierWithPredicates identifier = (NodeIdentifierWithPredicates) arg;
403 writer.startMapEntryNode(identifier, childSizeHint);
405 for (Entry<QName, Object> entry : identifier.entrySet()) {
406 writer.startLeafNode(new NodeIdentifier(entry.getKey()));
407 writer.scalarValue(entry.getValue());
413 private static final class UnkeyedListItem extends AbstractDataContainer<NodeIdentifier> {
414 UnkeyedListItem(final ListSchemaNode schema) {
415 super(NodeIdentifier.create(schema.getQName()), schema);
424 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
425 final int childSizeHint) throws IOException {
426 writer.startUnkeyedListItem(getIdentifier(), childSizeHint);
430 private static final class Container extends AbstractDataContainer<NodeIdentifier> {
431 Container(final ContainerSchemaNode schema) {
432 super(NodeIdentifier.create(schema.getQName()), schema);
441 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
442 final int childSizeHint) throws IOException {
443 writer.startContainerNode(getIdentifier(), childSizeHint);
447 private abstract static class LeafListMixin extends AbstractComposite<NodeIdentifier> {
448 private final StreamingContext<?> innerOp;
450 LeafListMixin(final LeafListSchemaNode potential) {
451 super(NodeIdentifier.create(potential.getQName()));
452 innerOp = new LeafListEntry(potential);
456 final StreamingContext<?> getChild(final PathArgument child) {
457 return child instanceof NodeWithValue ? innerOp : null;
461 final boolean isMixin() {
466 private static final class OrderedLeafListMixin extends LeafListMixin {
467 OrderedLeafListMixin(final LeafListSchemaNode potential) {
472 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
473 final int childSizeHint) throws IOException {
474 writer.startOrderedLeafSet(getIdentifier(), childSizeHint);
478 private static class UnorderedLeafListMixin extends LeafListMixin {
479 UnorderedLeafListMixin(final LeafListSchemaNode potential) {
484 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
485 final int childSizeHint) throws IOException {
486 writer.startLeafSet(getIdentifier(), childSizeHint);
490 private static final class Augmentation extends AbstractDataContainer<AugmentationIdentifier> {
491 Augmentation(final AugmentationSchemaNode augmentation, final DataNodeContainer schema) {
492 super(DataSchemaContextNode.augmentationIdentifierFrom(augmentation),
493 new EffectiveAugmentationSchema(augmentation, schema));
502 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
503 final int childSizeHint) throws IOException {
504 writer.startAugmentationNode(getIdentifier());
508 private static final class UnorderedMapMixin extends AbstractMapMixin {
509 UnorderedMapMixin(final ListSchemaNode list) {
514 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
515 final int childSizeHint) throws IOException {
516 writer.startMapNode(getIdentifier(), childSizeHint);
520 private static final class OrderedMapMixin extends AbstractMapMixin {
521 OrderedMapMixin(final ListSchemaNode list) {
526 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
527 final int childSizeHint) throws IOException {
528 writer.startOrderedMapNode(getIdentifier(), childSizeHint);
532 private static final class UnkeyedListMixin extends AbstractComposite<NodeIdentifier> {
533 private final UnkeyedListItem innerNode;
535 UnkeyedListMixin(final ListSchemaNode list) {
536 super(NodeIdentifier.create(list.getQName()));
537 innerNode = new UnkeyedListItem(list);
541 StreamingContext<?> getChild(final PathArgument child) {
542 return child.getNodeType().equals(getIdentifier().getNodeType()) ? innerNode : null;
551 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
552 final int childSizeHint) throws IOException {
553 writer.startUnkeyedList(getIdentifier(), childSizeHint);