Fix automatic lifecycle delete stacking
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / StructuralContainerModificationStrategy.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.yangtools.yang.data.impl.schema.tree;
9
10 import java.util.Optional;
11 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
12 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
13 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
14 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
15 import org.opendaylight.yangtools.yang.data.api.schema.OrderedNodeContainer;
16 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
17 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
18 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
22 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
23 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
24
25 /**
26  * Structural containers are special in that they appear when implied by child nodes and disappear whenever they are
27  * empty. We could implement this as a subclass of {@link SchemaAwareApplyOperation}, but the automatic semantic
28  * is quite different from all the other strategies. We create a {@link ContainerModificationStrategy} to tap into that
29  * logic, but wrap it so we only call out into it. We do not use {@link PresenceContainerModificationStrategy} because
30  * it enforces presence of mandatory leaves, which is not something we want here, as structural containers are not
31  * root anchors for that validation.
32  */
33 final class StructuralContainerModificationStrategy extends ModificationApplyOperation {
34     /**
35      * Fake TreeNode version used in
36      * {@link #checkApplicable(ModificationPath, NodeModification, Optional, Version)}.
37      * It is okay to use a global constant, as the delegate will ignore it anyway. For
38      * {@link #apply(ModifiedNode, Optional, Version)} we will use the appropriate version as provided to us.
39      */
40     private static final Version FAKE_VERSION = Version.initial();
41
42     private final ContainerModificationStrategy delegate;
43     private final ContainerNode emptyNode;
44
45     StructuralContainerModificationStrategy(final ContainerSchemaNode schemaNode,
46         final DataTreeConfiguration treeConfig) {
47         this.delegate = new ContainerModificationStrategy(schemaNode, treeConfig);
48         this.emptyNode = ImmutableNodes.containerNode(schemaNode.getQName());
49     }
50
51     private Optional<TreeNode> fakeMeta(final Version version) {
52         return Optional.of(TreeNodeFactory.createTreeNode(emptyNode, version));
53     }
54
55     @Override
56     Optional<TreeNode> apply(final ModifiedNode modification, final Optional<TreeNode> storeMeta,
57             final Version version) {
58         // The only way a tree node can disappear is through delete (which we handle here explicitly) or through
59         // actions of disappearResult(). It is therefore safe to perform Optional.get() on the results of
60         // delegate.apply()
61         final TreeNode ret;
62         if (modification.getOperation() == LogicalOperation.DELETE) {
63             if (modification.getChildren().isEmpty()) {
64                 return delegate.apply(modification, storeMeta, version);
65             }
66             // Delete with children, implies it really is an empty write
67             ret = delegate.applyWrite(modification, emptyNode, storeMeta, version);
68         } else if (modification.getOperation() == LogicalOperation.TOUCH && !storeMeta.isPresent()) {
69             ret = applyTouch(modification, storeMeta, version);
70         } else {
71             // No special handling required here, run normal apply operation
72             ret = delegate.apply(modification, storeMeta, version).get();
73         }
74
75         return disappearResult(modification, ret, storeMeta);
76     }
77
78     @Override
79     void checkApplicable(final ModificationPath path, final NodeModification modification,
80             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
81         if (modification.getOperation() == LogicalOperation.TOUCH && !current.isPresent()) {
82             // Structural containers are created as needed, so we pretend this container is here
83             delegate.checkApplicable(path, modification, fakeMeta(FAKE_VERSION), version);
84         } else {
85             delegate.checkApplicable(path, modification, current, version);
86         }
87     }
88
89     @Override
90     void verifyStructure(final NormalizedNode<?, ?> modification, final boolean verifyChildren) {
91         delegate.verifyStructure(modification, verifyChildren);
92     }
93
94     @Override
95     void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
96         delegate.recursivelyVerifyStructure(value);
97     }
98
99     @Override
100     ChildTrackingPolicy getChildPolicy() {
101         return delegate.getChildPolicy();
102     }
103
104     @Override
105     void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
106             final Version version) {
107         delegate.mergeIntoModifiedNode(modification, value, version);
108     }
109
110     @Override
111     public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
112         return delegate.getChild(child);
113     }
114
115     private TreeNode applyTouch(final ModifiedNode modification, final Optional<TreeNode> storeMeta,
116             final Version version) {
117         // Container is not present, let's take care of the 'magically appear' part of our job
118         final Optional<TreeNode> ret = delegate.apply(modification, fakeMeta(version), version);
119
120         // If the delegate indicated SUBTREE_MODIFIED, account for the fake and report APPEARED
121         if (modification.getModificationType() == ModificationType.SUBTREE_MODIFIED) {
122             modification.resolveModificationType(ModificationType.APPEARED);
123         }
124         return ret.get();
125     }
126
127     private static Optional<TreeNode> disappearResult(final ModifiedNode modification, final TreeNode result,
128             final Optional<TreeNode> storeMeta) {
129         // Check if the result is in fact empty before pulling any tricks
130         if (!isEmpty(result)) {
131             return Optional.of(result);
132         }
133
134         // We are pulling the 'disappear' trick, but what we report can be three different things
135         final ModificationType finalType;
136         if (!storeMeta.isPresent()) {
137             // ... there was nothing in the datastore, no change
138             finalType = ModificationType.UNMODIFIED;
139         } else if (modification.getModificationType() == ModificationType.WRITE) {
140             // ... this was an empty write, possibly originally a delete
141             finalType = ModificationType.DELETE;
142         } else {
143             // ... it really disappeared
144             finalType = ModificationType.DISAPPEARED;
145         }
146         modification.resolveModificationType(finalType);
147         return Optional.empty();
148     }
149
150     private static boolean isEmpty(final TreeNode treeNode) {
151         final NormalizedNode<?, ?> data = treeNode.getData();
152         if (data instanceof NormalizedNodeContainer) {
153             return ((NormalizedNodeContainer<?, ?, ?>) data).getValue().isEmpty();
154         }
155         if (data instanceof OrderedNodeContainer) {
156             return ((OrderedNodeContainer<?>) data).getSize() == 0;
157         }
158         throw new IllegalStateException("Unhandled data " + data);
159     }
160 }