2f1fc44bda006402e37544c1040a3889568a894b
[netconf.git] / netconf / netconf-util / src / main / java / org / opendaylight / netconf / util / StreamingContext.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netconf.util;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
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;
20 import java.util.Map;
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;
48
49 abstract class StreamingContext<T extends PathArgument> implements Identifiable<T> {
50     private final T identifier;
51
52     StreamingContext(final T identifier) {
53         this.identifier = identifier;
54     }
55
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());
61
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);
68                 }
69             }
70         }
71         return fromDataSchemaNode(result);
72     }
73
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);
87         }
88         return null;
89     }
90
91     @Override
92     public final T getIdentifier() {
93         return identifier;
94     }
95
96     abstract StreamingContext<?> getChild(PathArgument child);
97
98     /**
99      * Writing node structure that is described by series of {@link PathArgument}
100      * into {@link NormalizedNodeStreamWriter}.
101      *
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}
106      */
107     abstract void streamToWriter(NormalizedNodeStreamWriter writer, PathArgument first, Iterator<PathArgument> others)
108             throws IOException;
109
110     /**
111      * Writing node structure that is described by provided {@link PathNode} into {@link NormalizedNodeStreamWriter}.
112      *
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}
117      */
118     abstract void streamToWriter(NormalizedNodeStreamWriter writer, PathArgument first, PathNode tree)
119             throws IOException;
120
121     abstract boolean isMixin();
122
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);
127     }
128
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);
134                 }
135             }
136         }
137         return Optional.empty();
138     }
139
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);
144         }
145         return potential.isUserOrdered() ? new OrderedMapMixin(potential)
146                 : new UnorderedMapMixin(potential);
147     }
148
149     private static StreamingContext<?> fromLeafListSchemaNode(final LeafListSchemaNode potential) {
150         return potential.isUserOrdered() ? new OrderedLeafListMixin(potential)
151                 : new UnorderedLeafListMixin(potential);
152     }
153
154     private abstract static class AbstractComposite<T extends PathArgument> extends StreamingContext<T> {
155         AbstractComposite(final T identifier) {
156             super(identifier);
157         }
158
159         @Override
160         final void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
161                 final Iterator<PathArgument> others) throws IOException {
162             verifyActualPathArgument(first);
163
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);
169             }
170             writer.endNode();
171         }
172
173         @Override
174         final void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
175                                   final PathNode subtree) throws IOException {
176             verifyActualPathArgument(first);
177
178             final Collection<PathNode> children = subtree.children();
179             emitElementStart(writer, first, children.size());
180             for (final PathNode node : subtree.children()) {
181                 emitChildTreeNode(writer, node);
182             }
183             writer.endNode();
184         }
185
186         void emitChildTreeNode(final NormalizedNodeStreamWriter writer, final PathNode node) throws IOException {
187             final PathArgument childPath = node.element();
188             getChildOperation(childPath).streamToWriter(writer, childPath, node);
189         }
190
191         private void verifyActualPathArgument(final PathArgument first) {
192             if (!isMixin()) {
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);
196             }
197         }
198
199         abstract void emitElementStart(NormalizedNodeStreamWriter writer, PathArgument arg,
200                                        int childSizeHint) throws IOException;
201
202         @SuppressWarnings("checkstyle:illegalCatch")
203         StreamingContext<?> getChildOperation(final PathArgument childPath) {
204             final StreamingContext<?> childOp;
205             try {
206                 childOp = getChild(childPath);
207             } catch (final RuntimeException e) {
208                 throw new IllegalArgumentException(String.format("Failed to process child node %s", childPath), e);
209             }
210             checkArgument(childOp != null, "Node %s is not allowed inside %s", childPath, getIdentifier());
211             return childOp;
212         }
213     }
214
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;
218
219         AbstractDataContainer(final T identifier, final DataNodeContainer schema) {
220             super(identifier);
221             this.schema = schema;
222         }
223
224         @Override
225         final StreamingContext<?> getChild(final PathArgument child) {
226             StreamingContext<?> potential = byArg.get(child);
227             if (potential != null) {
228                 return potential;
229             }
230             potential = fromLocalSchema(child);
231             if (potential != null) {
232                 byArg.put(potential.getIdentifier(), potential);
233             }
234             return potential;
235         }
236
237         private StreamingContext<?> fromLocalSchema(final PathArgument child) {
238             if (child instanceof AugmentationIdentifier) {
239                 return fromSchemaAndQNameChecked(schema, ((AugmentationIdentifier) child).getPossibleChildNames()
240                         .iterator().next());
241             }
242             return fromSchemaAndQNameChecked(schema, child.getNodeType());
243         }
244     }
245
246     private abstract static class AbstractMapMixin extends AbstractComposite<NodeIdentifier> {
247         private final ListEntry innerNode;
248         private final List<QName> keyLeaves;
249
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();
254         }
255
256         @Override
257         final StreamingContext<?> getChild(final PathArgument child) {
258             return child.getNodeType().equals(getIdentifier().getNodeType()) ? innerNode : null;
259         }
260
261         @Override
262         final boolean isMixin() {
263             return true;
264         }
265
266         @Override
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);
273                 return;
274             }
275
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())));
282         }
283     }
284
285     private abstract static class AbstractSimple<T extends PathArgument> extends StreamingContext<T> {
286         AbstractSimple(final T identifier) {
287             super(identifier);
288         }
289
290         @Override
291         final StreamingContext<?> getChild(final PathArgument child) {
292             return null;
293         }
294
295         @Override
296         final boolean isMixin() {
297             return false;
298         }
299
300         @Override
301         final void streamToWriter(final NormalizedNodeStreamWriter writer, final PathArgument first,
302                             final PathNode tree) throws IOException {
303             streamToWriter(writer, first, Collections.emptyIterator());
304         }
305     }
306
307     private static final class AnyXml extends AbstractSimple<NodeIdentifier> {
308         AnyXml(final AnyxmlSchemaNode schema) {
309             super(NodeIdentifier.create(schema.getQName()));
310         }
311
312         @Override
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?
317             writer.endNode();
318         }
319     }
320
321     private static final class Choice extends AbstractComposite<NodeIdentifier> {
322         private final ImmutableMap<PathArgument, StreamingContext<?>> byArg;
323
324         Choice(final ChoiceSchemaNode schema) {
325             super(NodeIdentifier.create(schema.getQName()));
326             final ImmutableMap.Builder<PathArgument, StreamingContext<?>> byArgBuilder = ImmutableMap.builder();
327
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);
332                 }
333             }
334             byArg = byArgBuilder.build();
335         }
336
337         @Override
338         StreamingContext<?> getChild(final PathArgument child) {
339             return byArg.get(child);
340         }
341
342         @Override
343         boolean isMixin() {
344             return true;
345         }
346
347         @Override
348         void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
349                               final int childSizeHint) throws IOException {
350             writer.startChoiceNode(getIdentifier(), childSizeHint);
351         }
352     }
353
354     private static final class Leaf extends AbstractSimple<NodeIdentifier> {
355         Leaf(final LeafSchemaNode potential) {
356             super(new NodeIdentifier(potential.getQName()));
357         }
358
359         @Override
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?
364             writer.endNode();
365         }
366     }
367
368     private static final class LeafListEntry extends AbstractSimple<NodeWithValue<?>> {
369         LeafListEntry(final LeafListSchemaNode potential) {
370             super(new NodeWithValue<>(potential.getQName(), Empty.getInstance()));
371         }
372
373         @Override
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());
380             writer.endNode();
381         }
382     }
383
384     private static final class ListEntry extends AbstractDataContainer<NodeIdentifierWithPredicates> {
385         ListEntry(final NodeIdentifierWithPredicates identifier, final ListSchemaNode schema) {
386             super(identifier, schema);
387         }
388
389         @Override
390         boolean isMixin() {
391             return false;
392         }
393
394         @Override
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);
399
400             for (Entry<QName, Object> entry : identifier.entrySet()) {
401                 writer.startLeafNode(new NodeIdentifier(entry.getKey()));
402                 writer.scalarValue(entry.getValue());
403                 writer.endNode();
404             }
405         }
406     }
407
408     private static final class UnkeyedListItem extends AbstractDataContainer<NodeIdentifier> {
409         UnkeyedListItem(final ListSchemaNode schema) {
410             super(NodeIdentifier.create(schema.getQName()), schema);
411         }
412
413         @Override
414         boolean isMixin() {
415             return false;
416         }
417
418         @Override
419         void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
420                               final int childSizeHint) throws IOException {
421             writer.startUnkeyedListItem(getIdentifier(), childSizeHint);
422         }
423     }
424
425     private static final class Container extends AbstractDataContainer<NodeIdentifier> {
426         Container(final ContainerSchemaNode schema) {
427             super(NodeIdentifier.create(schema.getQName()), schema);
428         }
429
430         @Override
431         boolean isMixin() {
432             return false;
433         }
434
435         @Override
436         void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
437                               final int childSizeHint) throws IOException {
438             writer.startContainerNode(getIdentifier(), childSizeHint);
439         }
440     }
441
442     private abstract static class LeafListMixin extends AbstractComposite<NodeIdentifier> {
443         private final StreamingContext<?> innerOp;
444
445         LeafListMixin(final LeafListSchemaNode potential) {
446             super(NodeIdentifier.create(potential.getQName()));
447             innerOp = new LeafListEntry(potential);
448         }
449
450         @Override
451         final StreamingContext<?> getChild(final PathArgument child) {
452             return child instanceof NodeWithValue ? innerOp : null;
453         }
454
455         @Override
456         final boolean isMixin() {
457             return true;
458         }
459     }
460
461     private static final class OrderedLeafListMixin extends LeafListMixin {
462         OrderedLeafListMixin(final LeafListSchemaNode potential) {
463             super(potential);
464         }
465
466         @Override
467         void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
468                               final int childSizeHint) throws IOException {
469             writer.startOrderedLeafSet(getIdentifier(), childSizeHint);
470         }
471     }
472
473     private static class UnorderedLeafListMixin extends LeafListMixin {
474         UnorderedLeafListMixin(final LeafListSchemaNode potential) {
475             super(potential);
476         }
477
478         @Override
479         void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
480                               final int childSizeHint) throws IOException {
481             writer.startLeafSet(getIdentifier(), childSizeHint);
482         }
483     }
484
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));
489         }
490
491         @Override
492         boolean isMixin() {
493             return true;
494         }
495
496         @Override
497         void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
498                               final int childSizeHint) throws IOException {
499             writer.startAugmentationNode(getIdentifier());
500         }
501     }
502
503     private static final class UnorderedMapMixin extends AbstractMapMixin {
504         UnorderedMapMixin(final ListSchemaNode list) {
505             super(list);
506         }
507
508         @Override
509         void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
510                               final int childSizeHint) throws IOException {
511             writer.startMapNode(getIdentifier(), childSizeHint);
512         }
513     }
514
515     private static final class OrderedMapMixin extends AbstractMapMixin {
516         OrderedMapMixin(final ListSchemaNode list) {
517             super(list);
518         }
519
520         @Override
521         void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
522                               final int childSizeHint) throws IOException {
523             writer.startOrderedMapNode(getIdentifier(), childSizeHint);
524         }
525     }
526
527     private static final class UnkeyedListMixin extends AbstractComposite<NodeIdentifier> {
528         private final UnkeyedListItem innerNode;
529
530         UnkeyedListMixin(final ListSchemaNode list) {
531             super(NodeIdentifier.create(list.getQName()));
532             this.innerNode = new UnkeyedListItem(list);
533         }
534
535         @Override
536         StreamingContext<?> getChild(final PathArgument child) {
537             return child.getNodeType().equals(getIdentifier().getNodeType()) ? innerNode : null;
538         }
539
540         @Override
541         boolean isMixin() {
542             return true;
543         }
544
545         @Override
546         void emitElementStart(final NormalizedNodeStreamWriter writer, final PathArgument arg,
547                               final int childSizeHint) throws IOException {
548             writer.startUnkeyedList(getIdentifier(), childSizeHint);
549         }
550     }
551 }