blob: aa424602fc11e86ad71ae2ac425eae3b5bf60f87 [file] [log] [blame]
HIGUCHI Yuta9092db82016-01-03 18:45:01 -08001/*
2 * Copyright 2016 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.event;
17
18import java.util.ArrayList;
19import java.util.List;
20
21import javax.annotation.concurrent.NotThreadSafe;
22
23import org.apache.commons.lang3.tuple.Pair;
24
25import com.google.common.annotations.Beta;
26import com.google.common.collect.Lists;
27
28/**
29 * Utility to keeps track of registered Listeners.
30 * <p>
31 * Usage Example:
32 * <pre>
33 * <code>
34 private ListenerTracker listeners;
35
36 {@code @Activate}
37 protected void activate() {
38 listeners = new ListenerTracker();
39 listeners.addListener(mastershipService, new InternalMastershipListener())
40 .addListener(deviceService, new InternalDeviceListener())
41 .addListener(linkService, new InternalLinkListener())
42 .addListener(topologyService, new InternalTopologyListener())
43 .addListener(hostService, new InternalHostListener());
44 }
45
46 {@code @Deactivate}
47 protected void deactivate() {
48 listeners.removeListeners();
49 }
50 * </code>
51 * </pre>
52 */
53@Beta
54@NotThreadSafe
55public class ListenerTracker {
56
57 @SuppressWarnings("rawtypes")
58 private List<Pair<ListenerService, EventListener>> listeners = new ArrayList<>();
59
60 /**
61 * Adds {@link EventListener} to specified {@link ListenerService}.
62 *
63 * @param service {@link ListenerService}
64 * @param listener {@link EventListener}
65 * @return self
66 */
67 public <E extends Event<?, ?>, L extends EventListener<E>>
68 ListenerTracker addListener(ListenerService<E, L> service, L listener) {
69 service.addListener(listener);
70 listeners.add(Pair.of(service, listener));
71 return this;
72 }
73
74 /**
75 * Removes all listeners in reverse order they have been registered.
76 */
77 public void removeListeners() {
78 Lists.reverse(listeners)
79 .forEach(r -> r.getLeft().removeListener(r.getRight()));
80 listeners.clear();
81 }
82}