c7f850e04e9edcf77672b9de1096fde73cb90049
[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 @Deprecated
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                 break;
128         }
129     }
130
131     private static void populateListWithSingleCodec(final List<LazyDataObjectModification<? extends DataObject>> result,
132             final BindingDataObjectCodecTreeNode<?> codec, final Collection<DataTreeCandidateNode> childNodes) {
133         for (final DataTreeCandidateNode child : childNodes) {
134             if (child.getModificationType() != UNMODIFIED) {
135                 result.add(create(codec, child));
136             }
137         }
138     }
139
140     @Override
141     public T getDataBefore() {
142         return deserialize(domData.getDataBefore());
143     }
144
145     @Override
146     public T getDataAfter() {
147         return deserialize(domData.getDataAfter());
148     }
149
150     @Override
151     public Class<T> getDataType() {
152         return codec.getBindingClass();
153     }
154
155     @Override
156     public PathArgument getIdentifier() {
157         return identifier;
158     }
159
160     @Override
161     public ModificationType getModificationType() {
162         ModificationType localType = modificationType;
163         if (localType != null) {
164             return localType;
165         }
166
167         switch (domData.getModificationType()) {
168             case APPEARED:
169             case WRITE:
170                 localType = ModificationType.WRITE;
171                 break;
172             case DISAPPEARED:
173             case DELETE:
174                 localType = ModificationType.DELETE;
175                 break;
176             case SUBTREE_MODIFIED:
177                 localType = resolveSubtreeModificationType();
178                 break;
179             default:
180                 // TODO: Should we lie about modification type instead of exception?
181                 throw new IllegalStateException("Unsupported DOM Modification type " + domData.getModificationType());
182         }
183
184         modificationType = localType;
185         return localType;
186     }
187
188     private ModificationType resolveSubtreeModificationType() {
189         switch (codec.getChildAddressabilitySummary()) {
190             case ADDRESSABLE:
191                 // All children are addressable, it is safe to report SUBTREE_MODIFIED
192                 return ModificationType.SUBTREE_MODIFIED;
193             case UNADDRESSABLE:
194                 // All children are non-addressable, report WRITE
195                 return ModificationType.WRITE;
196             case MIXED:
197                 // This case is not completely trivial, as we may have NOT_ADDRESSABLE nodes underneath us. If that
198                 // is the case, we need to turn this modification into a WRITE operation, so that the user is able
199                 // to observe those nodes being introduced. This is not efficient, but unfortunately unavoidable,
200                 // as we cannot accurately represent such changes.
201                 for (DataTreeCandidateNode child : domData.getChildNodes()) {
202                     if (BindingStructuralType.recursiveFrom(child) == BindingStructuralType.NOT_ADDRESSABLE) {
203                         // We have a non-addressable child, turn this modification into a write
204                         return ModificationType.WRITE;
205                     }
206                 }
207
208                 // No unaddressable children found, proceed in addressed mode
209                 return ModificationType.SUBTREE_MODIFIED;
210             default:
211                 throw new IllegalStateException("Unsupported child addressability summary "
212                         + codec.getChildAddressabilitySummary());
213         }
214     }
215
216     @Override
217     public Collection<LazyDataObjectModification<? extends DataObject>> getModifiedChildren() {
218         Collection<LazyDataObjectModification<? extends DataObject>> local = childNodesCache;
219         if (local == null) {
220             childNodesCache = local = from(codec, domData.getChildNodes());
221         }
222         return local;
223     }
224
225     @Override
226     public <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>>
227             Collection<DataObjectModification<C>> getModifiedChildren(final Class<H> caseType,
228                     final Class<C> childType) {
229         return streamModifiedChildren(childType)
230                 .filter(child -> caseType.equals(child.identifier.getCaseType().orElse(null)))
231                 .collect(Collectors.toList());
232     }
233
234     @SuppressWarnings("unchecked")
235     private <C extends DataObject> Stream<LazyDataObjectModification<C>> streamModifiedChildren(
236             final Class<C> childType) {
237         return getModifiedChildren().stream()
238                 .filter(child -> childType.isAssignableFrom(child.getDataType()))
239                 .map(child -> (LazyDataObjectModification<C>) child);
240     }
241
242     @Override
243     public DataObjectModification<? extends DataObject> getModifiedChild(final PathArgument arg) {
244         final List<YangInstanceIdentifier.PathArgument> domArgumentList = new ArrayList<>();
245         final BindingDataObjectCodecTreeNode<?> childCodec = codec.bindingPathArgumentChild(arg, domArgumentList);
246         final Iterator<YangInstanceIdentifier.PathArgument> toEnter = domArgumentList.iterator();
247         DataTreeCandidateNode current = domData;
248         while (toEnter.hasNext() && current != null) {
249             current = current.getModifiedChild(toEnter.next()).orElse(null);
250         }
251         return current != null && current.getModificationType() != UNMODIFIED ? create(childCodec, current) : null;
252     }
253
254     @Override
255     @SuppressWarnings("unchecked")
256     public <C extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<C>> DataObjectModification<C>
257             getModifiedChildListItem(final Class<C> listItem, final K listKey) {
258         return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(listItem, listKey));
259     }
260
261     @Override
262     @SuppressWarnings("unchecked")
263     public <H extends ChoiceIn<? super T> & DataObject, C extends Identifiable<K> & ChildOf<? super H>,
264             K extends Identifier<C>> DataObjectModification<C> getModifiedChildListItem(final Class<H> caseType,
265                         final Class<C> listItem, final K listKey) {
266         return (DataObjectModification<C>) getModifiedChild(IdentifiableItem.of(caseType, listItem, listKey));
267     }
268
269     @Override
270     @SuppressWarnings("unchecked")
271     public <C extends ChildOf<? super T>> DataObjectModification<C> getModifiedChildContainer(final Class<C> child) {
272         return (DataObjectModification<C>) getModifiedChild(Item.of(child));
273     }
274
275     @Override
276     @SuppressWarnings("unchecked")
277     public <H extends ChoiceIn<? super T> & DataObject, C extends ChildOf<? super H>> DataObjectModification<C>
278             getModifiedChildContainer(final Class<H> caseType, final Class<C> child) {
279         return (DataObjectModification<C>) getModifiedChild(Item.of(caseType, child));
280     }
281
282     @Override
283     @SuppressWarnings("unchecked")
284     public <C extends Augmentation<T> & DataObject> DataObjectModification<C> getModifiedAugmentation(
285             final Class<C> augmentation) {
286         return (DataObjectModification<C>) getModifiedChild(Item.of(augmentation));
287     }
288
289     private T deserialize(final Optional<NormalizedNode<?, ?>> dataAfter) {
290         return dataAfter.map(codec::deserialize).orElse(null);
291     }
292
293     @Override
294     public String toString() {
295         return getClass().getSimpleName() + "{identifier = " + identifier + ", domData = " + domData + "}";
296     }
297 }