Adopt odlparent-10.0.0/yangtools-8.0.0-SNAPSHOT
[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.opendaylight.mdsal.binding.api.DataObjectModification;
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.tree.api.DataTreeCandidateNode;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * Lazily translated {@link DataObjectModification} based on {@link DataTreeCandidateNode}.
42  *
43  * <p>
44  * {@link LazyDataObjectModification} represents Data tree change event,
45  * but whole tree is not translated or resolved eagerly, but only child nodes
46  * which are directly accessed by user of data object modification.
47  *
48  * @param <T> Type of Binding Data Object
49  */
50 final class LazyDataObjectModification<T extends DataObject> implements DataObjectModification<T> {
51
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         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 <C extends ChildOf<? super T>> Collection<DataObjectModification<C>>
226             getModifiedChildren(final Class<C> childType) {
227         return streamModifiedChildren(childType).collect(Collectors.toList());
228     }
229
230     @Override
231     public <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>>
232             Collection<DataObjectModification<C>> getModifiedChildren(final Class<H> caseType,
233                     final Class<C> childType) {
234         return streamModifiedChildren(childType)
235                 .filter(child -> caseType.equals(child.identifier.getCaseType().orElse(null)))
236                 .collect(Collectors.toList());
237     }
238
239     @SuppressWarnings("unchecked")
240     private <C extends DataObject> Stream<LazyDataObjectModification<C>> streamModifiedChildren(
241             final Class<C> childType) {
242         return getModifiedChildren().stream()
243                 .filter(child -> childType.isAssignableFrom(child.getDataType()))
244                 .map(child -> (LazyDataObjectModification<C>) child);
245     }
246
247     @Override
248     public DataObjectModification<? extends DataObject> getModifiedChild(final PathArgument arg) {
249         final List<YangInstanceIdentifier.PathArgument> domArgumentList = new ArrayList<>();
250         final BindingDataObjectCodecTreeNode<?> childCodec = codec.bindingPathArgumentChild(arg, domArgumentList);
251         final Iterator<YangInstanceIdentifier.PathArgument> toEnter = domArgumentList.iterator();
252         DataTreeCandidateNode current = domData;
253         while (toEnter.hasNext() && current != null) {
254             current = current.getModifiedChild(toEnter.next()).orElse(null);
255         }
256         return current != null && current.getModificationType() != UNMODIFIED ? create(childCodec, current) : null;
257     }
258
259     @Override
260     @SuppressWarnings("unchecked")
261     public <C extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<C>> DataObjectModification<C>
262             getModifiedChildListItem(final Class<C> listItem, final K listKey) {
263         return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(listItem, listKey));
264     }
265
266     @Override
267     @SuppressWarnings("unchecked")
268     public <H extends ChoiceIn<? super T> & DataObject, C extends Identifiable<K> & ChildOf<? super H>,
269             K extends Identifier<C>> DataObjectModification<C> getModifiedChildListItem(final Class<H> caseType,
270                     final Class<C> listItem, final K listKey) {
271         return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(caseType, listItem, listKey));
272     }
273
274     @Override
275     @SuppressWarnings("unchecked")
276     public <C extends ChildOf<? super T>> DataObjectModification<C> getModifiedChildContainer(final Class<C> child) {
277         return (DataObjectModification<C>) getModifiedChild(Item.of(child));
278     }
279
280     @Override
281     @SuppressWarnings("unchecked")
282     public <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>> DataObjectModification<C>
283             getModifiedChildContainer(final Class<H> caseType, final Class<C> child) {
284         return (DataObjectModification<C>) getModifiedChild(Item.of(caseType, child));
285     }
286
287     @Override
288     @SuppressWarnings("unchecked")
289     public <C extends Augmentation<T> & DataObject> DataObjectModification<C> getModifiedAugmentation(
290             final Class<C> augmentation) {
291         return (DataObjectModification<C>) getModifiedChild(Item.of(augmentation));
292     }
293
294     @Override
295     public String toString() {
296         return MoreObjects.toStringHelper(this).add("identifier", identifier).add("domData", domData).toString();
297     }
298
299     private T deserialize(final Optional<NormalizedNode> dataAfter) {
300         return dataAfter.map(codec::deserialize).orElse(null);
301     }
302 }