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