Format Java code with respect to ONAP Code Style
[externalapi/nbi.git] / src / main / java / org / onap / nbi / apis / hub / service / dmaap / CheckDMaaPEventsManager.java
1 /**
2  * Copyright (c) 2019 Huawei
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14
15 package org.onap.nbi.apis.hub.service.dmaap;
16
17 import java.io.IOException;
18 import java.net.URI;
19 import java.text.MessageFormat;
20 import java.util.List;
21 import javax.annotation.PostConstruct;
22 import org.apache.commons.lang3.StringUtils;
23 import org.onap.nbi.OnapComponentsUrlPaths;
24 import org.onap.nbi.apis.hub.model.Event;
25 import org.onap.nbi.apis.hub.model.EventType;
26 import org.onap.nbi.apis.hub.model.ServiceInstanceEvent;
27 import org.onap.nbi.apis.hub.repository.SubscriberRepository;
28 import org.onap.nbi.apis.hub.service.EventFactory;
29 import org.onap.nbi.apis.hub.service.NotifierService;
30 import org.onap.nbi.apis.serviceorder.model.RelatedParty;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.springframework.beans.factory.annotation.Autowired;
34 import org.springframework.beans.factory.annotation.Value;
35 import org.springframework.http.HttpEntity;
36 import org.springframework.http.HttpHeaders;
37 import org.springframework.http.HttpMethod;
38 import org.springframework.http.ResponseEntity;
39 import org.springframework.stereotype.Service;
40 import org.springframework.util.CollectionUtils;
41 import org.springframework.web.client.RestTemplate;
42 import org.springframework.web.util.UriComponentsBuilder;
43 import com.fasterxml.jackson.core.JsonParseException;
44 import com.fasterxml.jackson.databind.JsonMappingException;
45 import com.fasterxml.jackson.databind.JsonNode;
46 import com.fasterxml.jackson.databind.ObjectMapper;
47
48 @Service
49 public class CheckDMaaPEventsManager {
50
51     public static final String RESPONSE_STATUS = "response status : ";
52     public static final String RETURNS = " returns ";
53     public static final String ERROR_ON_CALLING = "error on calling ";
54     private final Logger logger = LoggerFactory.getLogger(CheckDMaaPEventsManager.class);
55     @Autowired
56     private RestTemplate restTemplate;
57     @Autowired
58     private SubscriberRepository subscriberRepository;
59     @Autowired
60     private NotifierService notifier;
61     @Value("${dmaap.host}")
62     private String dmaapHostname;
63     @Value("${dmaap.aai.topic}")
64     private String aaiTopic;
65     @Value("${dmaap.sdc.topic}")
66     private String sdcTopic;
67     @Value("${dmaap.consumergroup}")
68     private String consumerGroup;
69     @Value("${dmaap.consumerid}")
70     private String consumerId;
71     @Value("${dmaap.timeout}")
72     private String timeout;
73     private String dmaapGetEventsUrl;
74
75     @PostConstruct
76     private void setUpAndLogDMaaPUrl() {
77         dmaapGetEventsUrl = new StringBuilder().append(dmaapHostname)
78                 .append(OnapComponentsUrlPaths.DMAAP_CONSUME_EVENTS).toString();
79         logger.info("DMaaP Get Events url :  " + dmaapGetEventsUrl);
80     }
81
82     public void checkForDMaaPAAIEvents() {
83         ObjectMapper mapper = new ObjectMapper();
84         List<String> dmaapResponse = callDMaaPGetEvents(aaiTopic);
85         if (!CollectionUtils.isEmpty(dmaapResponse)) {
86             for (int i = 0; i < dmaapResponse.size(); i++) {
87                 String aaiEventString = dmaapResponse.get(i);
88                 if (logger.isDebugEnabled()) {
89                     logger.debug("aai event returned was {}", aaiEventString);
90                 }
91                 try {
92                     JsonNode jsonNode = mapper.readValue(aaiEventString, JsonNode.class);
93                     JsonNode eventHeader = jsonNode.get("event-header");
94                     String aaiEventEntityType = eventHeader.get("entity-type").asText();
95                     String action = eventHeader.get("action").asText();
96                     if (logger.isDebugEnabled()) {
97                         logger.debug("aaiEventEntityType is {} and action is {}", aaiEventEntityType, action);
98                     }
99                     if (aaiEventEntityType.equals("service-instance")) {
100                         {
101                             // parse the AAI-EVENT service-instance tree
102                             ServiceInstanceEvent serviceInstanceEvent = new ServiceInstanceEvent();
103                             RelatedParty relatedParty = new RelatedParty();
104                             JsonNode entity = jsonNode.get("entity");
105                             relatedParty.setId(entity.get("global-customer-id").asText());
106                             relatedParty.setName(entity.get("subscriber-name").asText());
107                             serviceInstanceEvent.setRelatedParty(relatedParty);
108                             JsonNode childServiceSubscription = entity.get("service-subscriptions");
109                             JsonNode serviceSubscriptions = childServiceSubscription.get("service-subscription");
110                             JsonNode serviceSubscription = serviceSubscriptions.get(0);
111                             String serviceSubscriptionPrint = serviceSubscription.toString();
112                             JsonNode childserviceInstances = serviceSubscription.get("service-instances");
113                             JsonNode serviceInstances = childserviceInstances.get("service-instance");
114                             JsonNode serviceInstance = serviceInstances.get(0);
115                             serviceInstanceEvent.setId(serviceInstance.get("service-instance-id").asText());
116                             serviceInstanceEvent
117                                     .setHref("service/" + serviceInstance.get("service-instance-id").asText());
118                             if (serviceInstance.get("orchestration-status") != null) {
119                                 serviceInstanceEvent.setState(serviceInstance.get("orchestration-status").asText());
120                             }
121                             if (action.equals("CREATE")) {
122                                 if (logger.isDebugEnabled()) {
123                                     logger.debug("sending service inventory event to listeners");
124                                 }
125                                 processEvent(EventFactory.getEvent(EventType.SERVICE_CREATION, serviceInstanceEvent));
126                             } else if (action.equals("DELETE")) {
127                                 processEvent(EventFactory.getEvent(EventType.SERVICE_REMOVE, serviceInstanceEvent));
128                             } else if (action.equals("UPDATE")) {
129                                 processEvent(EventFactory.getEvent(EventType.SERVICE_ATTRIBUTE_VALUE_CHANGE,
130                                         serviceInstanceEvent));
131                             }
132
133                         }
134
135                     }
136
137                 } catch (JsonParseException e) {
138                     logger.error(" unable to Parse AAI Event JSON String {}, exception is", aaiEventString,
139                             e.getMessage());
140                 } catch (JsonMappingException e) {
141                     logger.error(" unable to Map AAI Event JSON String {} to Java Pojo, exception is", aaiEventString,
142                             e.getMessage());
143                 } catch (IOException e) {
144                     logger.error("IO Error when parsing AAI Event JSON String {} ", aaiEventString, e.getMessage());
145                 }
146             }
147         }
148     }
149
150     public void checkForDMaaPSDCEvents() {
151         List<String> dmaapResponse = callDMaaPGetEvents(sdcTopic);
152         if (!CollectionUtils.isEmpty(dmaapResponse)) {
153             for (int i = 0; i < dmaapResponse.size(); i++) {
154                 String sdcEventString = dmaapResponse.get(i);
155                 if (logger.isDebugEnabled()) {
156                     logger.debug("sdc event returned was {}", sdcEventString);
157                 }
158                 processEvent(EventFactory.getEvent(EventType.SDC_DISTRIBUTION, sdcEventString));
159             }
160         }
161     }
162
163     public List<String> callDMaaPGetEvents(String topic) {
164
165         URI callURI = buildRequest(topic);
166         ResponseEntity<Object> response = callDMaaP(callURI);
167         if (response != null) {
168             return (List<String>) response.getBody();
169
170         } else {
171             return null;
172         }
173     }
174
175     public ResponseEntity<Object> callCheckConnectivity() {
176         URI callURI = buildRequest(null);
177
178         ResponseEntity<Object> response =
179                 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
180
181         if (logger.isDebugEnabled()) {
182             logger.debug("response body : {} ", response.getBody().toString());
183             logger.debug("response status : {}", response.getStatusCodeValue());
184         }
185         return response;
186
187     }
188
189     private URI buildRequest(String topic) {
190         if (StringUtils.isEmpty(topic)) {
191             topic = aaiTopic;
192         }
193         String dmaapGetEventsUrlFormated = dmaapGetEventsUrl.replace("$topic", topic);
194         dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$consumergroup", consumerGroup);
195         dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$consumerid", consumerId);
196         dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$timeout", timeout);
197         if (logger.isDebugEnabled()) {
198             logger.debug("Calling DMaaP Url : " + dmaapGetEventsUrlFormated);
199         }
200         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(dmaapGetEventsUrlFormated);
201         return callURI.build().encode().toUri();
202     }
203
204     private ResponseEntity<Object> callDMaaP(URI callURI) {
205         try {
206             ResponseEntity<Object> response =
207                     restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
208             if (logger.isDebugEnabled()) {
209                 logger.debug("response body : {} ", response.getBody().toString());
210                 logger.debug("response status : {}", response.getStatusCodeValue());
211             }
212             return response;
213         } catch (Exception e) {
214             String message = MessageFormat.format("Exception while calling dmaap : {0}", callURI);
215             logger.error(message);
216             return null;
217         }
218
219     }
220
221     private HttpEntity<String> buildRequestHeader() {
222         HttpHeaders httpHeaders = new HttpHeaders();
223         httpHeaders.add("Accept", "application/json");
224         httpHeaders.add("Content-Type", "application/json");
225         return new HttpEntity<>("parameters", httpHeaders);
226     }
227
228     /**
229      * Retrieve subscribers that match an event and fire notification asynchronously
230      */
231     private void processEvent(Event event) {
232         subscriberRepository.findSubscribersUsingEvent(event).forEach(sub -> notifier.run(sub, event));
233     }
234
235 }