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 java.util.List;
14 import org.opendaylight.yangtools.yang.common.QName;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
29 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
30 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListEntryNodeBuilder;
31 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
32 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
33 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
34 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 abstract class SchemaAwareApplyOperation implements ModificationApplyOperation {
44 private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
46 public static SchemaAwareApplyOperation from(final DataSchemaNode schemaNode) {
47 if (schemaNode instanceof ContainerSchemaNode) {
48 return new DataNodeContainerModificationStrategy.ContainerModificationStrategy((ContainerSchemaNode) schemaNode);
49 } else if (schemaNode instanceof ListSchemaNode) {
50 return fromListSchemaNode((ListSchemaNode) schemaNode);
51 } else if (schemaNode instanceof ChoiceNode) {
52 return new NormalizedNodeContainerModificationStrategy.ChoiceModificationStrategy((ChoiceNode) schemaNode);
53 } else if (schemaNode instanceof LeafListSchemaNode) {
54 return fromLeafListSchemaNode((LeafListSchemaNode) schemaNode);
55 } else if (schemaNode instanceof LeafSchemaNode) {
56 return new ValueNodeModificationStrategy.LeafModificationStrategy((LeafSchemaNode) schemaNode);
58 throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
61 public static SchemaAwareApplyOperation from(final DataNodeContainer resolvedTree,
62 final AugmentationTarget augSchemas, final AugmentationIdentifier identifier) {
63 AugmentationSchema augSchema = null;
66 for (AugmentationSchema potential : augSchemas.getAvailableAugmentations()) {
67 for (DataSchemaNode child : potential.getChildNodes()) {
68 if (identifier.getPossibleChildNames().contains(child.getQName())) {
69 augSchema = potential;
75 if (augSchema != null) {
76 return new DataNodeContainerModificationStrategy.AugmentationModificationStrategy(augSchema, resolvedTree);
81 public static boolean checkConflicting(final YangInstanceIdentifier path, final boolean condition, final String message) throws ConflictingModificationAppliedException {
83 throw new ConflictingModificationAppliedException(path, message);
88 private static SchemaAwareApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode) {
89 List<QName> keyDefinition = schemaNode.getKeyDefinition();
90 if (keyDefinition == null || keyDefinition.isEmpty()) {
91 return new UnkeyedListModificationStrategy(schemaNode);
93 if (schemaNode.isUserOrdered()) {
94 return new NormalizedNodeContainerModificationStrategy.OrderedMapModificationStrategy(schemaNode);
97 return new NormalizedNodeContainerModificationStrategy.UnorderedMapModificationStrategy(schemaNode);
100 private static SchemaAwareApplyOperation fromLeafListSchemaNode(final LeafListSchemaNode schemaNode) {
101 if(schemaNode.isUserOrdered()) {
102 return new NormalizedNodeContainerModificationStrategy.OrderedLeafSetModificationStrategy(schemaNode);
104 return new NormalizedNodeContainerModificationStrategy.UnorderedLeafSetModificationStrategy(schemaNode);
108 private static final void checkNotConflicting(final YangInstanceIdentifier path, final TreeNode original, final TreeNode current) throws ConflictingModificationAppliedException {
109 checkConflicting(path, original.getVersion().equals(current.getVersion()),
110 "Node was replaced by other transaction.");
111 checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
112 "Node children was modified by other transaction");
115 protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
116 Optional<ModificationApplyOperation> potential = getChild(child);
117 Preconditions.checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
118 return potential.get();
122 public void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
123 if (modification.getType() == ModificationType.WRITE) {
124 verifyWrittenStructure(modification.getWrittenValue());
129 public final void checkApplicable(final YangInstanceIdentifier path,final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
130 switch (modification.getType()) {
132 checkDeleteApplicable(modification, current);
133 case SUBTREE_MODIFIED:
134 checkSubtreeModificationApplicable(path, modification, current);
137 checkWriteApplicable(path, modification, current);
140 checkMergeApplicable(path, modification, current);
145 throw new UnsupportedOperationException("Suplied modification type "+ modification.getType()+ "is not supported.");
150 protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
151 Optional<TreeNode> original = modification.getOriginal();
152 if (original.isPresent() && current.isPresent()) {
154 * We need to do conflict detection only and only if the value of leaf changed
155 * before two transactions. If value of leaf is unchanged between two transactions
156 * it should not cause transaction to fail, since result of this merge
157 * leads to same data.
159 if(!original.get().getData().equals(current.get().getData())) {
160 checkNotConflicting(path, original.get(), current.get());
166 * Checks if write operation can be applied to current TreeNode.
167 * The operation checks if original tree node to which the modification is going to be applied exists and if
168 * current node in TreeNode structure exists.
170 * @param path Path from current node in TreeNode
171 * @param modification modification to apply
172 * @param current current node in TreeNode for modification to apply
173 * @throws DataValidationFailedException
175 protected void checkWriteApplicable(final YangInstanceIdentifier path, final NodeModification modification,
176 final Optional<TreeNode> current) throws DataValidationFailedException {
177 Optional<TreeNode> original = modification.getOriginal();
178 if (original.isPresent() && current.isPresent()) {
179 checkNotConflicting(path, original.get(), current.get());
180 } else if(original.isPresent()) {
181 throw new ConflictingModificationAppliedException(path,"Node was deleted by other transaction.");
182 } else if(current.isPresent()) {
183 throw new ConflictingModificationAppliedException(path,"Node was created by other transaction.");
187 private void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
188 // Delete is always applicable, we do not expose it to subclasses
189 if (current.isPresent()) {
190 LOG.trace("Delete operation turned to no-op on missing node {}", modification);
194 boolean isOrdered() {
199 public final Optional<TreeNode> apply(final ModifiedNode modification,
200 final Optional<TreeNode> currentMeta, final Version version) {
202 switch (modification.getType()) {
204 return modification.setSnapshot(Optional.<TreeNode> absent());
205 case SUBTREE_MODIFIED:
206 Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification",
208 return modification.setSnapshot(Optional.of(applySubtreeChange(modification, currentMeta.get(),
211 final TreeNode result;
213 // This is a slight optimization: a merge on a non-existing node equals to a write
214 if (currentMeta.isPresent()) {
215 result = applyMerge(modification,currentMeta.get(), version);
217 result = applyWrite(modification, currentMeta, version);
220 return modification.setSnapshot(Optional.of(result));
222 return modification.setSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
226 throw new IllegalArgumentException("Provided modification type is not supported.");
230 protected abstract TreeNode applyMerge(ModifiedNode modification,
231 TreeNode currentMeta, Version version);
233 protected abstract TreeNode applyWrite(ModifiedNode modification,
234 Optional<TreeNode> currentMeta, Version version);
236 protected abstract TreeNode applySubtreeChange(ModifiedNode modification,
237 TreeNode currentMeta, Version version);
241 * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
243 * @param path Path to current node
244 * @param modification Node modification which should be applied.
245 * @param current Current state of data tree
246 * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
247 * @throws IncorrectDataStructureException If subtree modification is not applicable (e.g. leaf node).
249 protected abstract void checkSubtreeModificationApplicable(YangInstanceIdentifier path, final NodeModification modification,
250 final Optional<TreeNode> current) throws DataValidationFailedException;
252 protected abstract void verifyWrittenStructure(NormalizedNode<?, ?> writtenValue);
254 public static class UnkeyedListModificationStrategy extends SchemaAwareApplyOperation {
256 private final Optional<ModificationApplyOperation> entryStrategy;
258 protected UnkeyedListModificationStrategy(final ListSchemaNode schema) {
259 entryStrategy = Optional.<ModificationApplyOperation> of(new DataNodeContainerModificationStrategy.UnkeyedListItemModificationStrategy(schema));
263 boolean isOrdered() {
268 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta,
269 final Version version) {
270 return applyWrite(modification, Optional.of(currentMeta), version);
274 protected TreeNode applySubtreeChange(final ModifiedNode modification,
275 final TreeNode currentMeta, final Version version) {
276 throw new UnsupportedOperationException("UnkeyedList does not support subtree change.");
280 protected TreeNode applyWrite(final ModifiedNode modification,
281 final Optional<TreeNode> currentMeta, final Version version) {
282 final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
283 final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
285 if (Iterables.isEmpty(modification.getChildren())) {
290 * This is where things get interesting. The user has performed a write and
291 * then she applied some more modifications to it. So we need to make sense
292 * of that an apply the operations on top of the written value. We could have
293 * done it during the write, but this operation is potentially expensive, so
294 * we have left it out of the fast path.
296 * As it turns out, once we materialize the written data, we can share the
297 * code path with the subtree change. So let's create an unsealed TreeNode
298 * and run the common parts on it -- which end with the node being sealed.
300 final MutableTreeNode mutable = newValueMeta.mutable();
301 mutable.setSubtreeVersion(version);
303 @SuppressWarnings("rawtypes")
304 final NormalizedNodeContainerBuilder dataBuilder = ImmutableUnkeyedListEntryNodeBuilder
305 .create((UnkeyedListEntryNode) newValue);
307 return mutateChildren(mutable, dataBuilder, version, modification.getChildren());
311 * Applies write/remove diff operation for each modification child in modification subtree.
312 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
314 * @param meta MutableTreeNode (IndexTreeNode)
315 * @param data DataBuilder
316 * @param nodeVersion Version of TreeNode
317 * @param modifications modification operations to apply
318 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
320 @SuppressWarnings({ "rawtypes", "unchecked" })
321 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
322 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
324 for (ModifiedNode mod : modifications) {
325 final PathArgument id = mod.getIdentifier();
326 final Optional<TreeNode> cm = meta.getChild(id);
328 Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
329 if (result.isPresent()) {
330 final TreeNode tn = result.get();
332 data.addChild(tn.getData());
334 meta.removeChild(id);
335 data.removeChild(id);
339 meta.setData(data.build());
344 public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
345 if (child instanceof NodeIdentifier) {
346 return entryStrategy;
348 return Optional.absent();
352 protected void verifyWrittenStructure(final NormalizedNode<?, ?> writtenValue) {
357 protected void checkSubtreeModificationApplicable(final YangInstanceIdentifier path, final NodeModification modification,
358 final Optional<TreeNode> current) throws IncorrectDataStructureException {
359 throw new IncorrectDataStructureException(path, "Subtree modification is not allowed.");