2 * Copyright (c) 2014 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.yangtools.yang.data.impl.schema.tree;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Iterables;
13 import org.opendaylight.yangtools.yang.common.QName;
14 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
28 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
29 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListEntryNodeBuilder;
30 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
31 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
32 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
33 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import java.util.List;
44 abstract class SchemaAwareApplyOperation implements ModificationApplyOperation {
45 private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
47 public static SchemaAwareApplyOperation from(final DataSchemaNode schemaNode) {
48 if (schemaNode instanceof ContainerSchemaNode) {
49 return new DataNodeContainerModificationStrategy.ContainerModificationStrategy((ContainerSchemaNode) schemaNode);
50 } else if (schemaNode instanceof ListSchemaNode) {
51 return fromListSchemaNode((ListSchemaNode) schemaNode);
52 } else if (schemaNode instanceof ChoiceNode) {
53 return new NormalizedNodeContainerModificationStrategy.ChoiceModificationStrategy((ChoiceNode) schemaNode);
54 } else if (schemaNode instanceof LeafListSchemaNode) {
55 return fromLeafListSchemaNode((LeafListSchemaNode) schemaNode);
56 } else if (schemaNode instanceof LeafSchemaNode) {
57 return new ValueNodeModificationStrategy.LeafModificationStrategy((LeafSchemaNode) schemaNode);
59 throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
62 public static SchemaAwareApplyOperation from(final DataNodeContainer resolvedTree,
63 final AugmentationTarget augSchemas, final AugmentationIdentifier identifier) {
64 AugmentationSchema augSchema = null;
67 for (AugmentationSchema potential : augSchemas.getAvailableAugmentations()) {
68 for (DataSchemaNode child : potential.getChildNodes()) {
69 if (identifier.getPossibleChildNames().contains(child.getQName())) {
70 augSchema = potential;
76 if (augSchema != null) {
77 return new DataNodeContainerModificationStrategy.AugmentationModificationStrategy(augSchema, resolvedTree);
82 public static boolean checkConflicting(final YangInstanceIdentifier path, final boolean condition, final String message) throws ConflictingModificationAppliedException {
84 throw new ConflictingModificationAppliedException(path, message);
89 private static SchemaAwareApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode) {
90 List<QName> keyDefinition = schemaNode.getKeyDefinition();
91 if (keyDefinition == null || keyDefinition.isEmpty()) {
92 return new UnkeyedListModificationStrategy(schemaNode);
94 if (schemaNode.isUserOrdered()) {
95 return new NormalizedNodeContainerModificationStrategy.OrderedMapModificationStrategy(schemaNode);
98 return new NormalizedNodeContainerModificationStrategy.UnorderedMapModificationStrategy(schemaNode);
101 private static SchemaAwareApplyOperation fromLeafListSchemaNode(final LeafListSchemaNode schemaNode) {
102 if(schemaNode.isUserOrdered()) {
103 return new NormalizedNodeContainerModificationStrategy.OrderedLeafSetModificationStrategy(schemaNode);
105 return new NormalizedNodeContainerModificationStrategy.UnorderedLeafSetModificationStrategy(schemaNode);
109 private static final void checkNotConflicting(final YangInstanceIdentifier path, final TreeNode original, final TreeNode current) throws ConflictingModificationAppliedException {
110 checkConflicting(path, original.getVersion().equals(current.getVersion()),
111 "Node was replaced by other transaction.");
112 checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
113 "Node children was modified by other transaction");
116 protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
117 Optional<ModificationApplyOperation> potential = getChild(child);
118 Preconditions.checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
119 return potential.get();
123 public void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
124 if (modification.getType() == ModificationType.WRITE) {
125 verifyWrittenStructure(modification.getWrittenValue());
130 public final void checkApplicable(final YangInstanceIdentifier path,final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
131 switch (modification.getType()) {
133 checkDeleteApplicable(modification, current);
134 case SUBTREE_MODIFIED:
135 checkSubtreeModificationApplicable(path, modification, current);
138 checkWriteApplicable(path, modification, current);
141 checkMergeApplicable(path, modification, current);
146 throw new UnsupportedOperationException("Suplied modification type "+ modification.getType()+ "is not supported.");
151 protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
152 Optional<TreeNode> original = modification.getOriginal();
153 if (original.isPresent() && current.isPresent()) {
155 * We need to do conflict detection only and only if the value of leaf changed
156 * before two transactions. If value of leaf is unchanged between two transactions
157 * it should not cause transaction to fail, since result of this merge
158 * leads to same data.
160 if(!original.get().getData().equals(current.get().getData())) {
161 checkNotConflicting(path, original.get(), current.get());
167 * Checks if write operation can be applied to current TreeNode.
168 * The operation checks if original tree node to which the modification is going to be applied exists and if
169 * current node in TreeNode structure exists.
171 * @param path Path from current node in TreeNode
172 * @param modification modification to apply
173 * @param current current node in TreeNode for modification to apply
174 * @throws DataValidationFailedException
176 protected void checkWriteApplicable(final YangInstanceIdentifier path, final NodeModification modification,
177 final Optional<TreeNode> current) throws DataValidationFailedException {
178 Optional<TreeNode> original = modification.getOriginal();
179 if (original.isPresent() && current.isPresent()) {
180 checkNotConflicting(path, original.get(), current.get());
181 } else if(original.isPresent()) {
182 throw new ConflictingModificationAppliedException(path,"Node was deleted by other transaction.");
183 } else if(current.isPresent()) {
184 throw new ConflictingModificationAppliedException(path,"Node was created by other transaction.");
188 private void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
189 // Delete is always applicable, we do not expose it to subclasses
190 if (current.isPresent()) {
191 LOG.trace("Delete operation turned to no-op on missing node {}", modification);
195 boolean isOrdered() {
200 public final Optional<TreeNode> apply(final ModifiedNode modification,
201 final Optional<TreeNode> currentMeta, final Version version) {
203 switch (modification.getType()) {
205 return modification.storeSnapshot(Optional.<TreeNode> absent());
206 case SUBTREE_MODIFIED:
207 Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification",
209 return modification.storeSnapshot(Optional.of(applySubtreeChange(modification, currentMeta.get(),
212 if(currentMeta.isPresent()) {
213 return modification.storeSnapshot(Optional.of(applyMerge(modification,currentMeta.get(), version)));
215 // intentional fall-through: if the node does not exist a merge is same as a write
217 return modification.storeSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
221 throw new IllegalArgumentException("Provided modification type is not supported.");
225 protected abstract TreeNode applyMerge(ModifiedNode modification,
226 TreeNode currentMeta, Version version);
228 protected abstract TreeNode applyWrite(ModifiedNode modification,
229 Optional<TreeNode> currentMeta, Version version);
231 protected abstract TreeNode applySubtreeChange(ModifiedNode modification,
232 TreeNode currentMeta, Version version);
236 * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
238 * @param path Path to current node
239 * @param modification Node modification which should be applied.
240 * @param current Current state of data tree
241 * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
242 * @throws IncorrectDataStructureException If subtree modification is not applicable (e.g. leaf node).
244 protected abstract void checkSubtreeModificationApplicable(YangInstanceIdentifier path, final NodeModification modification,
245 final Optional<TreeNode> current) throws DataValidationFailedException;
247 protected abstract void verifyWrittenStructure(NormalizedNode<?, ?> writtenValue);
249 public static class UnkeyedListModificationStrategy extends SchemaAwareApplyOperation {
251 private final Optional<ModificationApplyOperation> entryStrategy;
253 protected UnkeyedListModificationStrategy(final ListSchemaNode schema) {
254 entryStrategy = Optional.<ModificationApplyOperation> of(new DataNodeContainerModificationStrategy.UnkeyedListItemModificationStrategy(schema));
258 boolean isOrdered() {
263 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta,
264 final Version version) {
265 return applyWrite(modification, Optional.of(currentMeta), version);
269 protected TreeNode applySubtreeChange(final ModifiedNode modification,
270 final TreeNode currentMeta, final Version version) {
271 throw new UnsupportedOperationException("UnkeyedList does not support subtree change.");
275 protected TreeNode applyWrite(final ModifiedNode modification,
276 final Optional<TreeNode> currentMeta, final Version version) {
277 final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
278 final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
280 if (Iterables.isEmpty(modification.getChildren())) {
285 * This is where things get interesting. The user has performed a write and
286 * then she applied some more modifications to it. So we need to make sense
287 * of that an apply the operations on top of the written value. We could have
288 * done it during the write, but this operation is potentially expensive, so
289 * we have left it out of the fast path.
291 * As it turns out, once we materialize the written data, we can share the
292 * code path with the subtree change. So let's create an unsealed TreeNode
293 * and run the common parts on it -- which end with the node being sealed.
295 final MutableTreeNode mutable = newValueMeta.mutable();
296 mutable.setSubtreeVersion(version);
298 @SuppressWarnings("rawtypes")
299 final NormalizedNodeContainerBuilder dataBuilder = ImmutableUnkeyedListEntryNodeBuilder
300 .create((UnkeyedListEntryNode) newValue);
302 return mutateChildren(mutable, dataBuilder, version, modification.getChildren());
306 * Applies write/remove diff operation for each modification child in modification subtree.
307 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
309 * @param meta MutableTreeNode (IndexTreeNode)
310 * @param data DataBuilder
311 * @param nodeVersion Version of TreeNode
312 * @param modifications modification operations to apply
313 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
315 @SuppressWarnings({ "rawtypes", "unchecked" })
316 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
317 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
319 for (ModifiedNode mod : modifications) {
320 final PathArgument id = mod.getIdentifier();
321 final Optional<TreeNode> cm = meta.getChild(id);
323 Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
324 if (result.isPresent()) {
325 final TreeNode tn = result.get();
327 data.addChild(tn.getData());
329 meta.removeChild(id);
330 data.removeChild(id);
334 meta.setData(data.build());
339 public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
340 if (child instanceof NodeIdentifier) {
341 return entryStrategy;
343 return Optional.absent();
347 protected void verifyWrittenStructure(final NormalizedNode<?, ?> writtenValue) {
352 protected void checkSubtreeModificationApplicable(final YangInstanceIdentifier path, final NodeModification modification,
353 final Optional<TreeNode> current) throws IncorrectDataStructureException {
354 throw new IncorrectDataStructureException(path, "Subtree modification is not allowed.");