Fix checkstyle violations in sal-inmemory-datastore
[controller.git] / opendaylight / md-sal / sal-inmemory-datastore / src / main / java / org / opendaylight / controller / md / sal / dom / store / impl / ResolveDataChangeEventsTask.java
1 /*
2  * Copyright (c) 2014 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.dom.store.impl;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ArrayListMultimap;
13 import com.google.common.collect.Multimap;
14 import java.util.Collection;
15 import java.util.Map.Entry;
16 import java.util.Optional;
17 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
18 import org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent.Builder;
19 import org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent.SimpleEventFactory;
20 import org.opendaylight.controller.md.sal.dom.store.impl.tree.ListenerTree;
21 import org.opendaylight.mdsal.dom.spi.RegistrationTreeSnapshot;
22 import org.opendaylight.yangtools.util.concurrent.NotificationManager;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
24 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33  * Resolve Data Change Events based on modifications and listeners
34  *
35  * <p>
36  * Computes data change events for all affected registered listeners in data tree.
37  */
38 @Beta
39 public final class ResolveDataChangeEventsTask {
40     private static final Logger LOG = LoggerFactory.getLogger(ResolveDataChangeEventsTask.class);
41
42     private final DataTreeCandidate candidate;
43     private final ListenerTree listenerRoot;
44
45     private Multimap<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> collectedEvents;
46
47     private ResolveDataChangeEventsTask(final DataTreeCandidate candidate, final ListenerTree listenerTree) {
48         this.candidate = Preconditions.checkNotNull(candidate);
49         this.listenerRoot = Preconditions.checkNotNull(listenerTree);
50     }
51
52     /**
53      * Resolves and submits notification tasks to the specified manager.
54      */
55     public synchronized void resolve(final NotificationManager<DataChangeListenerRegistration<?>,
56             DOMImmutableDataChangeEvent> manager) {
57         try (RegistrationTreeSnapshot<DataChangeListenerRegistration<?>> w = listenerRoot.takeSnapshot()) {
58             // Defensive: reset internal state
59             collectedEvents = ArrayListMultimap.create();
60
61             // Run through the tree
62             final ResolveDataChangeState s = ResolveDataChangeState.initial(candidate.getRootPath(), w.getRootNode());
63             resolveAnyChangeEvent(s, candidate.getRootNode());
64
65             /*
66              * Convert to tasks, but be mindful of multiple values -- those indicate multiple
67              * wildcard matches, which need to be merged.
68              */
69             for (Entry<DataChangeListenerRegistration<?>, Collection<DOMImmutableDataChangeEvent>> e :
70                     collectedEvents.asMap().entrySet()) {
71                 final Collection<DOMImmutableDataChangeEvent> col = e.getValue();
72                 final DOMImmutableDataChangeEvent event;
73
74                 if (col.size() != 1) {
75                     final Builder b = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE);
76                     for (DOMImmutableDataChangeEvent i : col) {
77                         b.merge(i);
78                     }
79
80                     event = b.build();
81                     LOG.trace("Merged events {} into event {}", col, event);
82                 } else {
83                     event = col.iterator().next();
84                 }
85
86                 manager.submitNotification(e.getKey(), event);
87             }
88         }
89     }
90
91     /**
92      * Resolves data change event for supplied node.
93      *
94      * @param path
95      *            Path to current node in tree
96      * @param listeners
97      *            Collection of Listener registration nodes interested in
98      *            subtree
99      * @param modification
100      *            Modification of current node
101      * @param before
102      *            - Original (before) state of current node
103      * @param after
104      *            - After state of current node
105      * @return True if the subtree changed, false otherwise
106      */
107     private boolean resolveAnyChangeEvent(final ResolveDataChangeState state, final DataTreeCandidateNode node) {
108         final Optional<NormalizedNode<?, ?>> maybeBefore = node.getDataBefore();
109         final Optional<NormalizedNode<?, ?>> maybeAfter = node.getDataAfter();
110         final ModificationType type = node.getModificationType();
111
112         if (type != ModificationType.UNMODIFIED && !maybeAfter.isPresent() && !maybeBefore.isPresent()) {
113             LOG.debug("Modification at {} has type {}, but no before- and after-data. Assuming unchanged.",
114                     state.getPath(), type);
115             return false;
116         }
117
118         // no before and after state is present
119
120         switch (type) {
121             case SUBTREE_MODIFIED:
122                 return resolveSubtreeChangeEvent(state, node);
123             case APPEARED:
124             case WRITE:
125                 Preconditions.checkArgument(maybeAfter.isPresent(),
126                         "Modification at {} has type {} but no after-data", state.getPath(), type);
127                 if (!maybeBefore.isPresent()) {
128                     @SuppressWarnings({ "unchecked", "rawtypes" })
129                     final NormalizedNode<PathArgument, ?> afterNode = (NormalizedNode)maybeAfter.get();
130                     resolveSameEventRecursivelly(state, afterNode, DOMImmutableDataChangeEvent.getCreateEventFactory());
131                     return true;
132                 }
133
134                 return resolveReplacedEvent(state, maybeBefore.get(), maybeAfter.get());
135             case DISAPPEARED:
136             case DELETE:
137                 Preconditions.checkArgument(maybeBefore.isPresent(),
138                         "Modification at {} has type {} but no before-data", state.getPath(), type);
139
140                 @SuppressWarnings({ "unchecked", "rawtypes" })
141                 final NormalizedNode<PathArgument, ?> beforeNode = (NormalizedNode)maybeBefore.get();
142                 resolveSameEventRecursivelly(state, beforeNode, DOMImmutableDataChangeEvent.getRemoveEventFactory());
143                 return true;
144             case UNMODIFIED:
145                 return false;
146             default:
147                 break;
148         }
149
150         throw new IllegalStateException(String.format("Unhandled node state %s at %s", type, state.getPath()));
151     }
152
153     private boolean resolveReplacedEvent(final ResolveDataChangeState state,
154             final NormalizedNode<?, ?> beforeData, final NormalizedNode<?, ?> afterData) {
155
156         if (beforeData instanceof NormalizedNodeContainer<?, ?, ?>) {
157             /*
158              * Node is a container (contains a child) and we have interested
159              * listeners registered for it, that means we need to do
160              * resolution of changes on children level and can not
161              * shortcut resolution.
162              */
163             LOG.trace("Resolving subtree replace event for {} before {}, after {}", state.getPath(), beforeData,
164                     afterData);
165             @SuppressWarnings("unchecked")
166             NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> beforeCont =
167                 (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) beforeData;
168             @SuppressWarnings("unchecked")
169             NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> afterCont =
170                 (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) afterData;
171             return resolveNodeContainerReplaced(state, beforeCont, afterCont);
172         }
173
174         // Node is a Leaf type (does not contain child nodes)
175         // so normal equals method is sufficient for determining change.
176         if (beforeData.equals(afterData)) {
177             LOG.trace("Skipping equal leaf {}", state.getPath());
178             return false;
179         }
180
181         LOG.trace("Resolving leaf replace event for {} , before {}, after {}", state.getPath(), beforeData, afterData);
182         DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE)
183                 .addUpdated(state.getPath(), beforeData, afterData).build();
184         state.addEvent(event);
185         state.collectEvents(beforeData, afterData, collectedEvents);
186         return true;
187     }
188
189     private boolean resolveNodeContainerReplaced(final ResolveDataChangeState state,
190             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> beforeCont,
191                     final NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> afterCont) {
192         if (!state.needsProcessing()) {
193             LOG.trace("Not processing replaced container {}", state.getPath());
194             return true;
195         }
196
197         // We look at all children from before and compare it with after state.
198         boolean childChanged = false;
199         for (NormalizedNode<PathArgument, ?> beforeChild : beforeCont.getValue()) {
200             final PathArgument childId = beforeChild.getIdentifier();
201
202             if (resolveNodeContainerChildUpdated(state.child(childId), beforeChild, afterCont.getChild(childId))) {
203                 childChanged = true;
204             }
205         }
206
207         for (NormalizedNode<PathArgument, ?> afterChild : afterCont.getValue()) {
208             final PathArgument childId = afterChild.getIdentifier();
209
210             /*
211              * We have already iterated of the before-children, so have already
212              * emitted modify/delete events. This means the child has been
213              * created.
214              */
215             if (!beforeCont.getChild(childId).isPresent()) {
216                 resolveSameEventRecursivelly(state.child(childId), afterChild,
217                         DOMImmutableDataChangeEvent.getCreateEventFactory());
218                 childChanged = true;
219             }
220         }
221
222         if (childChanged) {
223             DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE)
224                     .addUpdated(state.getPath(), beforeCont, afterCont).build();
225             state.addEvent(event);
226         }
227
228         state.collectEvents(beforeCont, afterCont, collectedEvents);
229         return childChanged;
230     }
231
232     private boolean resolveNodeContainerChildUpdated(final ResolveDataChangeState state,
233             final NormalizedNode<PathArgument, ?> before, final Optional<NormalizedNode<PathArgument, ?>> after) {
234         if (after.isPresent()) {
235             // REPLACE or SUBTREE Modified
236             return resolveReplacedEvent(state, before, after.get());
237         }
238
239         // AFTER state is not present - child was deleted.
240         resolveSameEventRecursivelly(state, before, DOMImmutableDataChangeEvent.getRemoveEventFactory());
241         return true;
242     }
243
244     private void resolveSameEventRecursivelly(final ResolveDataChangeState state,
245             final NormalizedNode<PathArgument, ?> node, final SimpleEventFactory eventFactory) {
246         if (!state.needsProcessing()) {
247             LOG.trace("Skipping child {}", state.getPath());
248             return;
249         }
250
251         // We have listeners for this node or it's children, so we will try
252         // to do additional processing
253         if (node instanceof NormalizedNodeContainer<?, ?, ?>) {
254             LOG.trace("Resolving subtree recursive event for {}, type {}", state.getPath(), eventFactory);
255
256             // Node has children, so we will try to resolve it's children
257             // changes.
258             @SuppressWarnings("unchecked")
259             NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>> container =
260                 (NormalizedNodeContainer<?, PathArgument, NormalizedNode<PathArgument, ?>>) node;
261             for (NormalizedNode<PathArgument, ?> child : container.getValue()) {
262                 final PathArgument childId = child.getIdentifier();
263
264                 LOG.trace("Resolving event for child {}", childId);
265                 resolveSameEventRecursivelly(state.child(childId), child, eventFactory);
266             }
267         }
268
269         final DOMImmutableDataChangeEvent event = eventFactory.create(state.getPath(), node);
270         LOG.trace("Adding event {} at path {}", event, state.getPath());
271         state.addEvent(event);
272         state.collectEvents(event.getOriginalSubtree(), event.getUpdatedSubtree(), collectedEvents);
273     }
274
275     private boolean resolveSubtreeChangeEvent(final ResolveDataChangeState state,
276             final DataTreeCandidateNode modification) {
277         final Optional<NormalizedNode<?, ?>> maybeBefore = modification.getDataBefore();
278         final Optional<NormalizedNode<?, ?>> maybeAfter = modification.getDataAfter();
279
280         Preconditions.checkArgument(maybeBefore.isPresent(), "Subtree change with before-data not present at path %s",
281                 state.getPath());
282         Preconditions.checkArgument(maybeAfter.isPresent(), "Subtree change with after-data not present at path %s",
283                 state.getPath());
284
285         if (!state.needsProcessing()) {
286             LOG.trace("Not processing modified subtree {}", state.getPath());
287             return true;
288         }
289
290         DataChangeScope scope = null;
291         for (DataTreeCandidateNode childMod : modification.getChildNodes()) {
292             final ResolveDataChangeState childState = state.child(childMod.getIdentifier());
293
294             switch (childMod.getModificationType()) {
295                 case APPEARED:
296                 case DELETE:
297                 case DISAPPEARED:
298                 case WRITE:
299                     if (resolveAnyChangeEvent(childState, childMod)) {
300                         scope = DataChangeScope.ONE;
301                     }
302                     break;
303                 case SUBTREE_MODIFIED:
304                     if (resolveSubtreeChangeEvent(childState, childMod) && scope == null) {
305                         scope = DataChangeScope.SUBTREE;
306                     }
307                     break;
308                 case UNMODIFIED:
309                     // no-op
310                     break;
311                 default:
312                     break;
313             }
314         }
315
316         final NormalizedNode<?, ?> before = maybeBefore.get();
317         final NormalizedNode<?, ?> after = maybeAfter.get();
318
319         if (scope != null) {
320             DOMImmutableDataChangeEvent one = DOMImmutableDataChangeEvent.builder(scope)
321                     .addUpdated(state.getPath(), before, after).build();
322             state.addEvent(one);
323         }
324
325         state.collectEvents(before, after, collectedEvents);
326         return scope != null;
327     }
328
329     public static ResolveDataChangeEventsTask create(final DataTreeCandidate candidate,
330             final ListenerTree listenerTree) {
331         return new ResolveDataChangeEventsTask(candidate, listenerTree);
332     }
333 }