blob: 395d869be06bebce12ebab23b7ceb7898bee42c9 [file] [log] [blame]
HIGUCHI Yuta9092db82016-01-03 18:45:01 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2016-present Open Networking Laboratory
HIGUCHI Yuta9092db82016-01-03 18:45:01 -08003 *
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>
HIGUCHI Yuta9092db82016-01-03 18:45:01 -080033 private ListenerTracker listeners;
34
35 {@code @Activate}
36 protected void activate() {
37 listeners = new ListenerTracker();
38 listeners.addListener(mastershipService, new InternalMastershipListener())
39 .addListener(deviceService, new InternalDeviceListener())
40 .addListener(linkService, new InternalLinkListener())
41 .addListener(topologyService, new InternalTopologyListener())
42 .addListener(hostService, new InternalHostListener());
43 }
44
45 {@code @Deactivate}
46 protected void deactivate() {
47 listeners.removeListeners();
48 }
HIGUCHI Yuta9092db82016-01-03 18:45:01 -080049 * </pre>
50 */
51@Beta
52@NotThreadSafe
53public class ListenerTracker {
54
55 @SuppressWarnings("rawtypes")
56 private List<Pair<ListenerService, EventListener>> listeners = new ArrayList<>();
57
58 /**
59 * Adds {@link EventListener} to specified {@link ListenerService}.
60 *
Jian Li7f256f52016-01-24 15:08:05 -080061 * @param <E> event
62 * @param <L> listener
HIGUCHI Yuta9092db82016-01-03 18:45:01 -080063 * @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}