27785f55a9af125cf03ed60174b1a67e1a80ac41
[mdsal.git] / binding / mdsal-binding-dom-adapter / src / main / java / org / opendaylight / mdsal / binding / dom / adapter / 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.mdsal.binding.dom.adapter;
9
10 import com.google.common.base.MoreObjects;
11 import com.google.common.base.Preconditions;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.Optional;
17 import java.util.stream.Collectors;
18 import java.util.stream.Stream;
19 import org.opendaylight.mdsal.binding.api.DataObjectModification;
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  * <p>
40  * {@link LazyDataObjectModification} represents Data tree change event,
41  * but whole tree is not translated or resolved eagerly, but only child nodes
42  * which are directly accessed by user of data object modification.
43  *
44  * @param <T> Type of Binding Data Object
45  */
46 final class LazyDataObjectModification<T extends DataObject> implements DataObjectModification<T> {
47
48     private static final Logger LOG = LoggerFactory.getLogger(LazyDataObjectModification.class);
49
50     private final BindingCodecTreeNode<T> codec;
51     private final DataTreeCandidateNode domData;
52     private final PathArgument identifier;
53
54     private volatile Collection<LazyDataObjectModification<? extends DataObject>> childNodesCache;
55     private volatile ModificationType modificationType;
56
57     private LazyDataObjectModification(final BindingCodecTreeNode<T> codec, final DataTreeCandidateNode domData) {
58         this.codec = Preconditions.checkNotNull(codec);
59         this.domData = Preconditions.checkNotNull(domData);
60         this.identifier = codec.deserializePathArgument(domData.getIdentifier());
61     }
62
63     static <T extends DataObject> LazyDataObjectModification<T> create(final BindingCodecTreeNode<T> codec,
64             final DataTreeCandidateNode domData) {
65         return new LazyDataObjectModification<>(codec,domData);
66     }
67
68     private static Collection<LazyDataObjectModification<? extends DataObject>> from(final BindingCodecTreeNode<?>
69             parentCodec, final Collection<DataTreeCandidateNode> domChildNodes) {
70         final List<LazyDataObjectModification<? extends DataObject>> result = new ArrayList<>(domChildNodes.size());
71         populateList(result, parentCodec, domChildNodes);
72         return result;
73     }
74
75     private static void populateList(final List<LazyDataObjectModification<? extends DataObject>> result,
76             final BindingCodecTreeNode<?> parentCodec, final Collection<DataTreeCandidateNode> domChildNodes) {
77         for (final DataTreeCandidateNode domChildNode : domChildNodes) {
78             final BindingStructuralType type = BindingStructuralType.from(domChildNode);
79             if (type != BindingStructuralType.NOT_ADDRESSABLE) {
80                 /*
81                  *  Even if type is UNKNOWN, from perspective of BindingStructuralType
82                  *  we try to load codec for it. We will use that type to further specify
83                  *  debug log.
84                  */
85                 try {
86                     final BindingCodecTreeNode<?> childCodec =
87                             parentCodec.yangPathArgumentChild(domChildNode.getIdentifier());
88                     populateList(result,type, childCodec, domChildNode);
89                 } catch (final IllegalArgumentException e) {
90                     if (type == BindingStructuralType.UNKNOWN) {
91                         LOG.debug("Unable to deserialize unknown DOM node {}",domChildNode,e);
92                     } else {
93                         LOG.debug("Binding representation for DOM node {} was not found",domChildNode,e);
94                     }
95                 }
96             }
97         }
98     }
99
100     private static void populateList(final List<LazyDataObjectModification<? extends DataObject>> result,
101             final BindingStructuralType type, final BindingCodecTreeNode<?> childCodec,
102             final DataTreeCandidateNode domChildNode) {
103         switch (type) {
104             case INVISIBLE_LIST:
105                 // We use parent codec intentionally.
106                 populateListWithSingleCodec(result, childCodec, domChildNode.getChildNodes());
107                 break;
108             case INVISIBLE_CONTAINER:
109                 populateList(result, childCodec, domChildNode.getChildNodes());
110                 break;
111             case UNKNOWN:
112             case VISIBLE_CONTAINER:
113                 result.add(create(childCodec, domChildNode));
114                 break;
115             default:
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 <C extends ChildOf<? super T>> Collection<DataObjectModification<C>>
213             getModifiedChildren(final Class<C> childType) {
214         return streamModifiedChildren(childType).collect(Collectors.toList());
215     }
216
217     @Override
218     public <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>>
219             Collection<DataObjectModification<C>> getModifiedChildren(final Class<H> caseType,
220                     final Class<C> childType) {
221         return streamModifiedChildren(childType)
222                 .filter(child -> caseType.equals(child.identifier.getCaseType().orElse(null)))
223                 .collect(Collectors.toList());
224     }
225
226     @SuppressWarnings("unchecked")
227     private <C extends DataObject> Stream<LazyDataObjectModification<C>> streamModifiedChildren(
228             final Class<C> childType) {
229         return getModifiedChildren().stream()
230                 .filter(child -> childType.isAssignableFrom(child.getDataType()))
231                 .map(child -> (LazyDataObjectModification<C>) child);
232     }
233
234     @Override
235     public DataObjectModification<? extends DataObject> getModifiedChild(final PathArgument arg) {
236         final List<YangInstanceIdentifier.PathArgument> domArgumentList = new ArrayList<>();
237         final BindingCodecTreeNode<?> childCodec = codec.bindingPathArgumentChild(arg, domArgumentList);
238         final Iterator<YangInstanceIdentifier.PathArgument> toEnter = domArgumentList.iterator();
239         DataTreeCandidateNode current = domData;
240         while (toEnter.hasNext() && current != null) {
241             current = current.getModifiedChild(toEnter.next());
242         }
243         if (current != null) {
244             return create(childCodec, current);
245         }
246         return null;
247     }
248
249     @Override
250     @SuppressWarnings("unchecked")
251     public <C extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<C>> DataObjectModification<C>
252             getModifiedChildListItem(final Class<C> listItem, final K listKey) {
253         return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(listItem, listKey));
254     }
255
256     @Override
257     @SuppressWarnings("unchecked")
258     public <H extends ChoiceIn<? super T> & DataObject, C extends Identifiable<K> & ChildOf<? super H>,
259             K extends Identifier<C>> DataObjectModification<C> getModifiedChildListItem(final Class<H> caseType,
260                     final Class<C> listItem, final K listKey) {
261         return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(caseType, listItem, listKey));
262     }
263
264     @Override
265     @SuppressWarnings("unchecked")
266     public <C extends ChildOf<? super T>> DataObjectModification<C> getModifiedChildContainer(final Class<C> child) {
267         return (DataObjectModification<C>) getModifiedChild(Item.of(child));
268     }
269
270     @Override
271     @SuppressWarnings("unchecked")
272     public <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>> DataObjectModification<C>
273             getModifiedChildContainer(final Class<H> caseType, final Class<C> child) {
274         return (DataObjectModification<C>) getModifiedChild(Item.of(caseType, child));
275     }
276
277     @Override
278     @SuppressWarnings("unchecked")
279     public <C extends Augmentation<T> & DataObject> DataObjectModification<C> getModifiedAugmentation(
280             final Class<C> augmentation) {
281         return (DataObjectModification<C>) getModifiedChild(Item.of(augmentation));
282     }
283
284     @Override
285     public String toString() {
286         return MoreObjects.toStringHelper(this).add("identifier", identifier).add("domData", domData).toString();
287     }
288
289     private T deserialize(final Optional<NormalizedNode<?, ?>> dataAfter) {
290         return dataAfter.map(codec::deserialize).orElse(null);
291     }
292 }