c3aff15e7a600f4fe83743e1ee77688273dc46db
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / md / sal / binding / impl / LazyDataObjectModification.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.controller.md.sal.binding.impl;
9
10 import com.google.common.base.Preconditions;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.Iterator;
14 import java.util.List;
15 import java.util.Optional;
16 import java.util.stream.Collectors;
17 import java.util.stream.Stream;
18 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
19 import org.opendaylight.mdsal.binding.dom.adapter.BindingStructuralType;
20 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeNode;
21 import org.opendaylight.yangtools.yang.binding.Augmentation;
22 import org.opendaylight.yangtools.yang.binding.ChildOf;
23 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
24 import org.opendaylight.yangtools.yang.binding.DataObject;
25 import org.opendaylight.yangtools.yang.binding.Identifiable;
26 import org.opendaylight.yangtools.yang.binding.Identifier;
27 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
28 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
29 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * Lazily translated {@link DataObjectModification} based on {@link DataTreeCandidateNode}.
38  *
39  * {@link LazyDataObjectModification} represents Data tree change event,
40  * but whole tree is not translated or resolved eagerly, but only child nodes
41  * which are directly accessed by user of data object modification.
42  *
43  * @param <T> Type of Binding Data Object
44  */
45 final class LazyDataObjectModification<T extends DataObject> implements DataObjectModification<T> {
46
47     private static final Logger LOG = LoggerFactory.getLogger(LazyDataObjectModification.class);
48
49     private final BindingCodecTreeNode<T> codec;
50     private final DataTreeCandidateNode domData;
51     private final PathArgument identifier;
52
53     private volatile Collection<LazyDataObjectModification<? extends DataObject>> childNodesCache;
54     private volatile ModificationType modificationType;
55
56     private LazyDataObjectModification(final BindingCodecTreeNode<T> codec, final DataTreeCandidateNode domData) {
57         this.codec = Preconditions.checkNotNull(codec);
58         this.domData = Preconditions.checkNotNull(domData);
59         this.identifier = codec.deserializePathArgument(domData.getIdentifier());
60     }
61
62     static <T extends DataObject> LazyDataObjectModification<T> create(final BindingCodecTreeNode<T> codec,
63             final DataTreeCandidateNode domData) {
64         return new LazyDataObjectModification<>(codec,domData);
65     }
66
67     private static Collection<LazyDataObjectModification<? extends DataObject>> from(
68             final BindingCodecTreeNode<?> parentCodec, final Collection<DataTreeCandidateNode> domChildNodes) {
69         final List<LazyDataObjectModification<? extends DataObject>> result = new ArrayList<>(domChildNodes.size());
70         populateList(result, parentCodec, domChildNodes);
71         return result;
72     }
73
74     private static void populateList(final List<LazyDataObjectModification<? extends DataObject>> result,
75             final BindingCodecTreeNode<?> parentCodec, final Collection<DataTreeCandidateNode> domChildNodes) {
76         for (final DataTreeCandidateNode domChildNode : domChildNodes) {
77             final BindingStructuralType type = BindingStructuralType.from(domChildNode);
78             if (type != BindingStructuralType.NOT_ADDRESSABLE) {
79                 /*
80                  *  Even if type is UNKNOWN, from perspective of BindingStructuralType
81                  *  we try to load codec for it. We will use that type to further specify
82                  *  debug log.
83                  */
84                 try {
85                     final BindingCodecTreeNode<?> childCodec =
86                             parentCodec.yangPathArgumentChild(domChildNode.getIdentifier());
87                     populateList(result,type, childCodec, domChildNode);
88                 } catch (final IllegalArgumentException e) {
89                     if (type == BindingStructuralType.UNKNOWN) {
90                         LOG.debug("Unable to deserialize unknown DOM node {}",domChildNode,e);
91                     } else {
92                         LOG.debug("Binding representation for DOM node {} was not found",domChildNode,e);
93                     }
94                 }
95             }
96         }
97     }
98
99     private static void populateList(final List<LazyDataObjectModification<? extends DataObject>> result,
100             final BindingStructuralType type, final BindingCodecTreeNode<?> childCodec,
101             final DataTreeCandidateNode domChildNode) {
102         switch (type) {
103             case INVISIBLE_LIST:
104                 // We use parent codec intentionally.
105                 populateListWithSingleCodec(result, childCodec, domChildNode.getChildNodes());
106                 break;
107             case INVISIBLE_CONTAINER:
108                 populateList(result, childCodec, domChildNode.getChildNodes());
109                 break;
110             case UNKNOWN:
111             case VISIBLE_CONTAINER:
112                 result.add(create(childCodec, domChildNode));
113                 break;
114             default:
115                 break;
116         }
117     }
118
119     private static void populateListWithSingleCodec(final List<LazyDataObjectModification<? extends DataObject>> result,
120             final BindingCodecTreeNode<?> codec, final Collection<DataTreeCandidateNode> childNodes) {
121         for (final DataTreeCandidateNode child : childNodes) {
122             result.add(create(codec, child));
123         }
124     }
125
126     @Override
127     public T getDataBefore() {
128         return deserialize(domData.getDataBefore());
129     }
130
131     @Override
132     public T getDataAfter() {
133         return deserialize(domData.getDataAfter());
134     }
135
136     @Override
137     public Class<T> getDataType() {
138         return codec.getBindingClass();
139     }
140
141     @Override
142     public PathArgument getIdentifier() {
143         return identifier;
144     }
145
146     @Override
147     public ModificationType getModificationType() {
148         ModificationType localType = modificationType;
149         if (localType != null) {
150             return localType;
151         }
152
153         switch (domData.getModificationType()) {
154             case APPEARED:
155             case WRITE:
156                 localType = ModificationType.WRITE;
157                 break;
158             case DISAPPEARED:
159             case DELETE:
160                 localType = ModificationType.DELETE;
161                 break;
162             case SUBTREE_MODIFIED:
163                 localType = resolveSubtreeModificationType();
164                 break;
165             default:
166                 // TODO: Should we lie about modification type instead of exception?
167                 throw new IllegalStateException("Unsupported DOM Modification type " + domData.getModificationType());
168         }
169
170         modificationType = localType;
171         return localType;
172     }
173
174     private ModificationType resolveSubtreeModificationType() {
175         switch (codec.getChildAddressabilitySummary()) {
176             case ADDRESSABLE:
177                 // All children are addressable, it is safe to report SUBTREE_MODIFIED
178                 return ModificationType.SUBTREE_MODIFIED;
179             case UNADDRESSABLE:
180                 // All children are non-addressable, report WRITE
181                 return ModificationType.WRITE;
182             case MIXED:
183                 // This case is not completely trivial, as we may have NOT_ADDRESSABLE nodes underneath us. If that
184                 // is the case, we need to turn this modification into a WRITE operation, so that the user is able
185                 // to observe those nodes being introduced. This is not efficient, but unfortunately unavoidable,
186                 // as we cannot accurately represent such changes.
187                 for (DataTreeCandidateNode child : domData.getChildNodes()) {
188                     if (BindingStructuralType.recursiveFrom(child) == BindingStructuralType.NOT_ADDRESSABLE) {
189                         // We have a non-addressable child, turn this modification into a write
190                         return ModificationType.WRITE;
191                     }
192                 }
193
194                 // No unaddressable children found, proceed in addressed mode
195                 return ModificationType.SUBTREE_MODIFIED;
196             default:
197                 throw new IllegalStateException("Unsupported child addressability summary "
198                         + codec.getChildAddressabilitySummary());
199         }
200     }
201
202     @Override
203     public Collection<LazyDataObjectModification<? extends DataObject>> getModifiedChildren() {
204         Collection<LazyDataObjectModification<? extends DataObject>> local = childNodesCache;
205         if (local == null) {
206             childNodesCache = local = from(codec, domData.getChildNodes());
207         }
208         return local;
209     }
210
211     @Override
212     public <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>>
213             Collection<DataObjectModification<C>> getModifiedChildren(final Class<H> caseType,
214                     final Class<C> childType) {
215         return streamModifiedChildren(childType)
216                 .filter(child -> caseType.equals(child.identifier.getCaseType().orElse(null)))
217                 .collect(Collectors.toList());
218     }
219
220     @SuppressWarnings("unchecked")
221     private <C extends DataObject> Stream<LazyDataObjectModification<C>> streamModifiedChildren(
222             final Class<C> childType) {
223         return getModifiedChildren().stream()
224                 .filter(child -> childType.isAssignableFrom(child.getDataType()))
225                 .map(child -> (LazyDataObjectModification<C>) child);
226     }
227
228     @Override
229     public DataObjectModification<? extends DataObject> getModifiedChild(final PathArgument arg) {
230         final List<YangInstanceIdentifier.PathArgument> domArgumentList = new ArrayList<>();
231         final BindingCodecTreeNode<?> childCodec = codec.bindingPathArgumentChild(arg, domArgumentList);
232         final Iterator<YangInstanceIdentifier.PathArgument> toEnter = domArgumentList.iterator();
233         DataTreeCandidateNode current = domData;
234         while (toEnter.hasNext() && current != null) {
235             current = current.getModifiedChild(toEnter.next());
236         }
237         if (current != null) {
238             return create(childCodec, current);
239         }
240         return null;
241     }
242
243     @Override
244     @SuppressWarnings("unchecked")
245     public <C extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<C>> DataObjectModification<C>
246             getModifiedChildListItem(final Class<C> listItem, final K listKey) {
247         return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(listItem, listKey));
248     }
249
250     @Override
251     @SuppressWarnings("unchecked")
252     public <H extends ChoiceIn<? super T> & DataObject, C extends Identifiable<K> & ChildOf<? super H>,
253             K extends Identifier<C>> DataObjectModification<C> getModifiedChildListItem(final Class<H> caseType,
254                         final Class<C> listItem, final K listKey) {
255         return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(caseType, listItem, listKey));
256     }
257
258     @Override
259     @SuppressWarnings("unchecked")
260     public <C extends ChildOf<? super T>> DataObjectModification<C> getModifiedChildContainer(final Class<C> child) {
261         return (DataObjectModification<C>) getModifiedChild(Item.of(child));
262     }
263
264     @Override
265     @SuppressWarnings("unchecked")
266     public <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>> DataObjectModification<C>
267             getModifiedChildContainer(final Class<H> caseType, final Class<C> child) {
268         return (DataObjectModification<C>) getModifiedChild(Item.of(caseType, child));
269     }
270
271     @Override
272     @SuppressWarnings("unchecked")
273     public <C extends Augmentation<T> & DataObject> DataObjectModification<C> getModifiedAugmentation(
274             final Class<C> augmentation) {
275         return (DataObjectModification<C>) getModifiedChild(Item.of(augmentation));
276     }
277
278     private T deserialize(final Optional<NormalizedNode<?, ?>> dataAfter) {
279         return dataAfter.map(codec::deserialize).orElse(null);
280     }
281
282     @Override
283     public String toString() {
284         return getClass().getSimpleName() + "{identifier = " + identifier + ", domData = " + domData + "}";
285     }
286 }