2 * Copyright (c) 2019 Huawei
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
7 * http://www.apache.org/licenses/LICENSE-2.0
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
15 package org.onap.nbi.apis.hub.service.dmaap;
17 import java.io.IOException;
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;
50 public class CheckDMaaPEventsManager {
52 public static final String RESPONSE_STATUS = "response status : ";
53 public static final String RETURNS = " returns ";
54 public static final String ERROR_ON_CALLING = "error on calling ";
55 private final Logger logger = LoggerFactory.getLogger(CheckDMaaPEventsManager.class);
57 private RestTemplate restTemplate;
59 private SubscriberRepository subscriberRepository;
61 private NotifierService notifier;
62 @Value("${dmaap.host}")
63 private String dmaapHostname;
64 @Value("${dmaap.aai.topic}")
65 private String aaiTopic;
66 @Value("${dmaap.sdc.topic}")
67 private String sdcTopic;
68 @Value("${dmaap.consumergroup}")
69 private String consumerGroup;
70 @Value("${dmaap.consumerid}")
71 private String consumerId;
72 @Value("${dmaap.timeout}")
73 private String timeout;
74 private String dmaapGetEventsUrl;
77 private void setUpAndLogDMaaPUrl() {
78 dmaapGetEventsUrl = new StringBuilder().append(dmaapHostname)
79 .append(OnapComponentsUrlPaths.DMAAP_CONSUME_EVENTS).toString();
80 logger.info("DMaaP Get Events url : " + dmaapGetEventsUrl);
83 public void checkForDMaaPAAIEvents() {
84 ObjectMapper mapper = new ObjectMapper();
85 List<String> dmaapResponse = callDMaaPGetEvents(aaiTopic);
86 if (!CollectionUtils.isEmpty(dmaapResponse)) {
87 for (int i = 0; i < dmaapResponse.size(); i++) {
88 String aaiEventString = dmaapResponse.get(i);
89 if (logger.isDebugEnabled()) {
90 logger.debug("aai event returned was {}", aaiEventString);
93 JsonNode jsonNode = mapper.readValue(aaiEventString, JsonNode.class);
94 JsonNode eventHeader = jsonNode.get("event-header");
95 String aaiEventEntityType = eventHeader.get("entity-type").asText();
96 String action = eventHeader.get("action").asText();
97 if (logger.isDebugEnabled()) {
98 logger.debug("aaiEventEntityType is {} and action is {}", aaiEventEntityType, action);
100 if (aaiEventEntityType.equals("service-instance")) {
102 // parse the AAI-EVENT service-instance tree
103 ServiceInstanceEvent serviceInstanceEvent = new ServiceInstanceEvent();
104 RelatedParty relatedParty = new RelatedParty();
105 JsonNode entity = jsonNode.get("entity");
106 relatedParty.setId(entity.get("global-customer-id").asText());
107 relatedParty.setName(entity.get("subscriber-name").asText());
108 serviceInstanceEvent.setRelatedParty(relatedParty);
109 JsonNode childServiceSubscription = entity.get("service-subscriptions");
110 JsonNode serviceSubscriptions = childServiceSubscription.get("service-subscription");
111 JsonNode serviceSubscription = serviceSubscriptions.get(0);
112 String serviceSubscriptionPrint = serviceSubscription.toString();
113 JsonNode childserviceInstances = serviceSubscription.get("service-instances");
114 JsonNode serviceInstances = childserviceInstances.get("service-instance");
115 JsonNode serviceInstance = serviceInstances.get(0);
116 serviceInstanceEvent.setId(serviceInstance.get("service-instance-id").asText());
118 .setHref("service/" + serviceInstance.get("service-instance-id").asText());
119 if (serviceInstance.get("orchestration-status") != null) {
120 serviceInstanceEvent.setState(serviceInstance.get("orchestration-status").asText());
122 if (action.equals("CREATE")) {
123 if (logger.isDebugEnabled()) {
124 logger.debug("sending service inventory event to listeners");
127 EventFactory.getEvent(EventType.SERVICE_CREATION, serviceInstanceEvent));
128 } else if (action.equals("DELETE")) {
129 processEvent(EventFactory.getEvent(EventType.SERVICE_REMOVE, serviceInstanceEvent));
130 } else if (action.equals("UPDATE")) {
131 processEvent(EventFactory.getEvent(EventType.SERVICE_ATTRIBUTE_VALUE_CHANGE,
132 serviceInstanceEvent));
140 } catch (JsonParseException e) {
141 logger.error(" unable to Parse AAI Event JSON String {}, exception is", aaiEventString,
143 } catch (JsonMappingException e) {
144 logger.error(" unable to Map AAI Event JSON String {} to Java Pojo, exception is",
145 aaiEventString, e.getMessage());
146 } catch (IOException e) {
147 logger.error("IO Error when parsing AAI Event JSON String {} ", aaiEventString,
154 public void checkForDMaaPSDCEvents() {
155 List<String> dmaapResponse = callDMaaPGetEvents(sdcTopic);
156 if (!CollectionUtils.isEmpty(dmaapResponse)) {
157 for (int i = 0; i < dmaapResponse.size(); i++) {
158 String sdcEventString = dmaapResponse.get(i);
159 if (logger.isDebugEnabled()) {
160 logger.debug("sdc event returned was {}", sdcEventString);
162 processEvent(EventFactory.getEvent(EventType.SDC_DISTRIBUTION, sdcEventString));
168 public List<String> callDMaaPGetEvents(String topic) {
170 URI callURI = buildRequest(topic);
171 ResponseEntity<Object> response = callDMaaP(callURI);
172 if (response != null) {
173 return (List<String>) response.getBody();
180 public ResponseEntity<Object> callCheckConnectivity() {
181 URI callURI = buildRequest(null);
183 ResponseEntity<Object> response =
184 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
186 if (logger.isDebugEnabled()) {
187 logger.debug("response body : {} ", response.getBody().toString());
188 logger.debug("response status : {}", response.getStatusCodeValue());
195 private URI buildRequest(String topic) {
196 if (StringUtils.isEmpty(topic)) {
199 String dmaapGetEventsUrlFormated = dmaapGetEventsUrl.replace("$topic", topic);
200 dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$consumergroup", consumerGroup);
201 dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$consumerid", consumerId);
202 dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$timeout", timeout);
203 if (logger.isDebugEnabled()) {
204 logger.debug("Calling DMaaP Url : " + dmaapGetEventsUrlFormated);
206 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(dmaapGetEventsUrlFormated);
207 return callURI.build().encode().toUri();
210 private ResponseEntity<Object> callDMaaP(URI callURI) {
212 ResponseEntity<Object> response =
213 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
214 if (logger.isDebugEnabled()) {
215 logger.debug("response body : {} ", response.getBody().toString());
216 logger.debug("response status : {}", response.getStatusCodeValue());
219 } catch (Exception e) {
220 String message = MessageFormat.format("Exception while calling dmaap : {0}", callURI);
221 logger.error(message);
228 private HttpEntity<String> buildRequestHeader() {
229 HttpHeaders httpHeaders = new HttpHeaders();
230 httpHeaders.add("Accept", "application/json");
231 httpHeaders.add("Content-Type", "application/json");
232 return new HttpEntity<>("parameters", httpHeaders);
236 * Retrieve subscribers that match an event and fire notification asynchronously
238 private void processEvent(Event event) {
239 subscriberRepository.findSubscribersUsingEvent(event).forEach(sub -> notifier.run(sub, event));