12edc99f2d8919aacac8ec18cbf883a0e4fbac2e
[holmes/engine-management.git] / engine-d / src / main / java / org / onap / holmes / engine / dmaap / SubscriberAction.java
1 /*
2  * Copyright 2017 ZTE Corporation.
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  */
16 package org.onap.holmes.engine.dmaap;
17
18 import java.util.HashMap;
19 import java.util.Iterator;
20 import java.util.Map;
21 import java.util.concurrent.ConcurrentHashMap;
22 import javax.annotation.PreDestroy;
23 import javax.inject.Inject;
24 import lombok.extern.slf4j.Slf4j;
25 import org.jvnet.hk2.annotations.Service;
26 import org.onap.holmes.dsa.dmaappolling.Subscriber;
27 import org.onap.holmes.engine.manager.DroolsEngine;
28
29 @Service
30 @Slf4j
31 public class SubscriberAction {
32
33     @Inject
34     private DroolsEngine droolsEngine;
35     private HashMap<String, DMaaPAlarmPolling> pollingTasks = new HashMap<>();
36
37     public synchronized void addSubscriber(Subscriber subscriber) {
38         if (!pollingTasks.containsKey(subscriber.getTopic())) {
39             DMaaPAlarmPolling pollingTask = new DMaaPAlarmPolling(subscriber, droolsEngine);
40             Thread thread = new Thread(pollingTask);
41             thread.start();
42             pollingTasks.put(subscriber.getTopic(), pollingTask);
43             log.info("Subscribe to topic: " + subscriber.getUrl());
44         }
45     }
46
47     public synchronized void removeSubscriber(Subscriber subscriber) {
48         if (pollingTasks.containsKey(subscriber.getTopic())) {
49             pollingTasks.get(subscriber.getTopic()).stopTask();
50             pollingTasks.remove(subscriber.getTopic());
51         }
52         log.info("Topic unsubscribed: " + subscriber.getUrl());
53     }
54
55     @PreDestroy
56     public void stopPollingTasks() {
57         Iterator iterator = pollingTasks.entrySet().iterator();
58         while (iterator.hasNext()) {
59             Map.Entry entry = (Map.Entry)iterator.next();
60             String key = (String) entry.getKey();
61             pollingTasks.get(key).stopTask();
62         }
63         pollingTasks.clear();
64     }
65 }