Merge "save csar file path add directory version"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / java / org / onap / so / bpmn / infrastructure / pnf / dmaap / PnfEventReadyDmaapClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.pnf.dmaap;
22
23 import java.io.IOException;
24 import java.net.URI;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ScheduledThreadPoolExecutor;
30 import java.util.concurrent.TimeUnit;
31
32 import javax.ws.rs.core.UriBuilder;
33
34 import org.apache.http.HttpResponse;
35 import org.apache.http.client.HttpClient;
36 import org.apache.http.client.methods.HttpGet;
37 import org.apache.http.impl.client.HttpClientBuilder;
38 import org.apache.http.util.EntityUtils;
39 import org.onap.so.logger.MsoLogger;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.context.annotation.Scope;
42 import org.springframework.core.env.Environment;
43 import org.springframework.stereotype.Component;
44
45 @Component
46 @Scope("prototype")
47 public class PnfEventReadyDmaapClient implements DmaapClient {
48
49     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, PnfEventReadyDmaapClient.class);
50
51     private final Environment env;
52     private HttpClient httpClient;
53     private String dmaapHost;
54     private int dmaapPort;
55     private String dmaapProtocol;
56     private String dmaapUriPathPrefix;
57     private String dmaapTopicName;
58     private String consumerId;
59     private String consumerGroup;
60     private Map<String, Runnable> pnfCorrelationIdToThreadMap;
61     private HttpGet getRequest;
62     private int dmaapClientDelayInSeconds;
63     private volatile ScheduledThreadPoolExecutor executor;
64     private volatile boolean dmaapThreadListenerIsRunning;
65
66     @Autowired
67     public PnfEventReadyDmaapClient(Environment env) {
68         this.env = env;
69     }
70
71     public void init() {
72         httpClient = HttpClientBuilder.create().build();
73         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
74         dmaapHost = env.getProperty("pnf.dmaap.host");
75         dmaapPort = env.getProperty("pnf.dmaap.port", Integer.class);
76         executor = null;
77         getRequest = new HttpGet(buildURI());
78     }
79
80     @Override
81     public synchronized void registerForUpdate(String correlationId, Runnable informConsumer) {
82         LOGGER.debug("registering for pnf ready dmaap event for correlation id: " + correlationId);
83         pnfCorrelationIdToThreadMap.put(correlationId, informConsumer);
84         if (!dmaapThreadListenerIsRunning) {
85             startDmaapThreadListener();
86         }
87     }
88
89     @Override
90     public synchronized Runnable unregister(String correlationId) {
91         LOGGER.debug("unregistering from pnf ready dmaap event for correlation id: " + correlationId);
92         Runnable runnable = pnfCorrelationIdToThreadMap.remove(correlationId);
93         if (pnfCorrelationIdToThreadMap.isEmpty()) {
94             stopDmaapThreadListener();
95         }
96         return runnable;
97     }
98
99     private synchronized void startDmaapThreadListener() {
100         if (!dmaapThreadListenerIsRunning) {
101             executor = new ScheduledThreadPoolExecutor(1);
102             executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
103             executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
104             executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0,
105                     dmaapClientDelayInSeconds, TimeUnit.SECONDS);
106             dmaapThreadListenerIsRunning = true;
107         }
108     }
109
110     private synchronized void stopDmaapThreadListener() {
111         if (dmaapThreadListenerIsRunning) {
112             executor.shutdown();
113             dmaapThreadListenerIsRunning = false;
114             executor = null;
115         }
116     }
117
118     private URI buildURI() {
119         return UriBuilder.fromUri(dmaapUriPathPrefix)
120                 .scheme(dmaapProtocol)
121                 .host(dmaapHost)
122                 .port(dmaapPort).path(dmaapTopicName)
123                 .path(consumerGroup).path(consumerId).build();
124     }
125
126     public void setDmaapProtocol(String dmaapProtocol) {
127         this.dmaapProtocol = dmaapProtocol;
128     }
129
130     public void setDmaapUriPathPrefix(String dmaapUriPathPrefix) {
131         this.dmaapUriPathPrefix = dmaapUriPathPrefix;
132     }
133
134     public void setDmaapTopicName(String dmaapTopicName) {
135         this.dmaapTopicName = dmaapTopicName;
136     }
137
138     public void setConsumerId(String consumerId) {
139         this.consumerId = consumerId;
140     }
141
142     public void setConsumerGroup(String consumerGroup) {
143         this.consumerGroup = consumerGroup;
144     }
145
146     public void setDmaapClientDelayInSeconds(int dmaapClientDelayInSeconds) {
147         this.dmaapClientDelayInSeconds = dmaapClientDelayInSeconds;
148     }
149
150     class DmaapTopicListenerThread implements Runnable {
151
152         @Override
153         public void run() {
154             try {
155                 HttpResponse response = httpClient.execute(getRequest);
156                 getCorrelationIdListFromResponse(response).forEach(this::informAboutPnfReadyIfCorrelationIdFound);
157             } catch (IOException e) {
158                 LOGGER.error("Exception caught during sending rest request to dmaap for listening event topic", e);
159             }
160         }
161
162         private List<String> getCorrelationIdListFromResponse(HttpResponse response) throws IOException {
163             if (response.getStatusLine().getStatusCode() == 200) {
164                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
165                 if (responseString != null) {
166                     return JsonUtilForCorrelationId.parseJsonToGelAllCorrelationId(responseString);
167                 }
168             }
169             return Collections.emptyList();
170         }
171
172         private void informAboutPnfReadyIfCorrelationIdFound(String correlationId) {
173             Runnable runnable = unregister(correlationId);
174             if (runnable != null) {
175                 LOGGER.debug("pnf ready event got from dmaap for correlationId: " + correlationId);
176                 runnable.run();
177             }
178         }
179     }
180
181 }