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