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 this.innerNode = new ListEntry(NodeIdentifierWithPredicates.of(list.getQName()), list);
253 this.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 NodeIdentifierWithPredicates childPath = (NodeIdentifierWithPredicates) node.element();
269 final StreamingContext<?> childOp = getChildOperation(childPath);
270 if (childPath.size() == 0 && node.isEmpty() || childPath.keySet().containsAll(keyLeaves)) {
271 // This is a query for the entire list, or the query specifies everything we need
272 childOp.streamToWriter(writer, childPath, node);
276 // Inexact query, we need to also request the leaf nodes we need to for reconstructing a valid instance
277 // NodeIdentifierWithPredicates.
278 childOp.streamToWriter(writer, childPath, node.copyWith(keyLeaves.stream()
279 .filter(qname -> !childPath.containsKey(qname))
280 .map(NodeIdentifier::new)
281 .collect(Collectors.toUnmodifiableList())));
285 private abstract static class AbstractSimple<T extends PathArgument> extends StreamingContext<T> {
286 AbstractSimple(final T identifier) {
291 final StreamingContext<?> getChild(final PathArgument child) {
296 final boolean isMixin() {
301 final void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
302 final PathNode tree) throws IOException {
303 streamToWriter(writer, first, Collections.emptyIterator());
307 private static final class AnyXml extends AbstractSimple<NodeIdentifier> {
308 AnyXml(final AnyxmlSchemaNode schema) {
309 super(NodeIdentifier.create(schema.getQName()));
313 void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
314 final Iterator<PathArgument> others) throws IOException {
315 writer.startAnyxmlNode(getIdentifier(), DOMSource.class);
316 // FIXME: why are we not emitting a value?
321 private static final class Choice extends AbstractComposite<NodeIdentifier> {
322 private final ImmutableMap<PathArgument, StreamingContext<?>> byArg;
324 Choice(final ChoiceSchemaNode schema) {
325 super(NodeIdentifier.create(schema.getQName()));
326 final ImmutableMap.Builder<PathArgument, StreamingContext<?>> byArgBuilder = ImmutableMap.builder();
328 for (final CaseSchemaNode caze : schema.getCases()) {
329 for (final DataSchemaNode cazeChild : caze.getChildNodes()) {
330 final StreamingContext<?> childOp = fromDataSchemaNode(cazeChild);
331 byArgBuilder.put(childOp.getIdentifier(), childOp);
334 byArg = byArgBuilder.build();
338 StreamingContext<?> getChild(final PathArgument child) {
339 return byArg.get(child);
348 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
349 final int childSizeHint) throws IOException {
350 writer.startChoiceNode(getIdentifier(), childSizeHint);
354 private static final class Leaf extends AbstractSimple<NodeIdentifier> {
355 Leaf(final LeafSchemaNode potential) {
356 super(new NodeIdentifier(potential.getQName()));
360 void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
361 final Iterator<PathArgument> others) throws IOException {
362 writer.startLeafNode(getIdentifier());
363 // FIXME: why are we not emitting a value?
368 private static final class LeafListEntry extends AbstractSimple<NodeWithValue<?>> {
369 LeafListEntry(final LeafListSchemaNode potential) {
370 super(new NodeWithValue<>(potential.getQName(), Empty.getInstance()));
374 void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
375 final Iterator<PathArgument> others) throws IOException {
376 checkArgument(first instanceof NodeWithValue);
377 final NodeWithValue<?> identifier = (NodeWithValue<?>) first;
378 writer.startLeafSetEntryNode(identifier);
379 writer.scalarValue(identifier.getValue());
384 private static final class ListEntry extends AbstractDataContainer<NodeIdentifierWithPredicates> {
385 ListEntry(final NodeIdentifierWithPredicates identifier, final ListSchemaNode schema) {
386 super(identifier, schema);
395 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
396 final int childSizeHint) throws IOException {
397 final NodeIdentifierWithPredicates identifier = (NodeIdentifierWithPredicates) arg;
398 writer.startMapEntryNode(identifier, childSizeHint);
400 for (Entry<QName, Object> entry : identifier.entrySet()) {
401 writer.startLeafNode(new NodeIdentifier(entry.getKey()));
402 writer.scalarValue(entry.getValue());
408 private static final class UnkeyedListItem extends AbstractDataContainer<NodeIdentifier> {
409 UnkeyedListItem(final ListSchemaNode schema) {
410 super(NodeIdentifier.create(schema.getQName()), schema);
419 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
420 final int childSizeHint) throws IOException {
421 writer.startUnkeyedListItem(getIdentifier(), childSizeHint);
425 private static final class Container extends AbstractDataContainer<NodeIdentifier> {
426 Container(final ContainerSchemaNode schema) {
427 super(NodeIdentifier.create(schema.getQName()), schema);
436 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
437 final int childSizeHint) throws IOException {
438 writer.startContainerNode(getIdentifier(), childSizeHint);
442 private abstract static class LeafListMixin extends AbstractComposite<NodeIdentifier> {
443 private final StreamingContext<?> innerOp;
445 LeafListMixin(final LeafListSchemaNode potential) {
446 super(NodeIdentifier.create(potential.getQName()));
447 innerOp = new LeafListEntry(potential);
451 final StreamingContext<?> getChild(final PathArgument child) {
452 return child instanceof NodeWithValue ? innerOp : null;
456 final boolean isMixin() {
461 private static final class OrderedLeafListMixin extends LeafListMixin {
462 OrderedLeafListMixin(final LeafListSchemaNode potential) {
467 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
468 final int childSizeHint) throws IOException {
469 writer.startOrderedLeafSet(getIdentifier(), childSizeHint);
473 private static class UnorderedLeafListMixin extends LeafListMixin {
474 UnorderedLeafListMixin(final LeafListSchemaNode potential) {
479 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
480 final int childSizeHint) throws IOException {
481 writer.startLeafSet(getIdentifier(), childSizeHint);
485 private static final class Augmentation extends AbstractDataContainer<AugmentationIdentifier> {
486 Augmentation(final AugmentationSchemaNode augmentation, final DataNodeContainer schema) {
487 super(DataSchemaContextNode.augmentationIdentifierFrom(augmentation),
488 EffectiveAugmentationSchema.create(augmentation, schema));
497 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
498 final int childSizeHint) throws IOException {
499 writer.startAugmentationNode(getIdentifier());
503 private static final class UnorderedMapMixin extends AbstractMapMixin {
504 UnorderedMapMixin(final ListSchemaNode list) {
509 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
510 final int childSizeHint) throws IOException {
511 writer.startMapNode(getIdentifier(), childSizeHint);
515 private static final class OrderedMapMixin extends AbstractMapMixin {
516 OrderedMapMixin(final ListSchemaNode list) {
521 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
522 final int childSizeHint) throws IOException {
523 writer.startOrderedMapNode(getIdentifier(), childSizeHint);
527 private static final class UnkeyedListMixin extends AbstractComposite<NodeIdentifier> {
528 private final UnkeyedListItem innerNode;
530 UnkeyedListMixin(final ListSchemaNode list) {
531 super(NodeIdentifier.create(list.getQName()));
532 this.innerNode = new UnkeyedListItem(list);
536 StreamingContext<?> getChild(final PathArgument child) {
537 return child.getNodeType().equals(getIdentifier().getNodeType()) ? innerNode : null;
546 void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
547 final int childSizeHint) throws IOException {
548 writer.startUnkeyedList(getIdentifier(), childSizeHint);