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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.