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;
17 import java.io.IOException;
19 import java.util.List;
20 import javax.annotation.PostConstruct;
21 import org.onap.nbi.OnapComponentsUrlPaths;
22 import org.onap.nbi.apis.hub.model.Event;
23 import org.onap.nbi.apis.hub.model.EventType;
24 import org.onap.nbi.apis.hub.model.ServiceInstanceEvent;
25 import org.onap.nbi.apis.hub.repository.SubscriberRepository;
26 import org.onap.nbi.apis.serviceorder.model.RelatedParty;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import org.springframework.beans.factory.annotation.Autowired;
30 import org.springframework.beans.factory.annotation.Value;
31 import org.springframework.http.HttpEntity;
32 import org.springframework.http.HttpHeaders;
33 import org.springframework.http.HttpMethod;
34 import org.springframework.http.ResponseEntity;
35 import org.springframework.stereotype.Service;
36 import org.springframework.util.CollectionUtils;
37 import org.springframework.web.client.RestTemplate;
38 import org.springframework.web.util.UriComponentsBuilder;
39 import com.fasterxml.jackson.core.JsonParseException;
40 import com.fasterxml.jackson.databind.JsonMappingException;
41 import com.fasterxml.jackson.databind.JsonNode;
42 import com.fasterxml.jackson.databind.ObjectMapper;
46 public class CheckDMaaPEventsManager {
48 public static final String RESPONSE_STATUS = "response status : ";
49 public static final String RETURNS = " returns ";
50 public static final String ERROR_ON_CALLING = "error on calling ";
53 private RestTemplate restTemplate;
56 private SubscriberRepository subscriberRepository;
59 private NotifierService notifier;
61 @Value("${dmaap.host}")
62 private String dmaapHostname;
64 @Value("${dmaap.topic}")
67 @Value("${dmaap.consumergroup}")
68 private String consumerGroup;
70 @Value("${dmaap.consumerid}")
71 private String consumerId;
73 @Value("${dmaap.timeout}")
74 private String timeout;
76 private final Logger logger = LoggerFactory.getLogger(CheckDMaaPEventsManager.class);
78 private String dmaapGetEventsUrl;
81 private void setUpAndLogDMaaPUrl() {
82 dmaapGetEventsUrl = new StringBuilder().append(dmaapHostname)
83 .append(OnapComponentsUrlPaths.DMAAP_CONSUME_EVENTS).toString();
84 logger.info("DMaaP Get Events url : " + dmaapGetEventsUrl);
87 public void checkForDMaaPAAIEvents() {
88 ObjectMapper mapper = new ObjectMapper();
92 List<String> dmaapResponse = callDMaaPGetEvents();
93 if (!CollectionUtils.isEmpty(dmaapResponse)) {
94 for (int i = 0; i < dmaapResponse.size(); i++) {
95 String aaiEventString = dmaapResponse.get(i);
96 if (logger.isDebugEnabled()) {
97 logger.debug("aai event returned was {}", aaiEventString);
100 JsonNode jsonNode = mapper.readValue(aaiEventString, JsonNode.class);
101 JsonNode eventHeader = jsonNode.get("event-header");
102 String aaiEventEntityType = eventHeader.get("entity-type").asText();
103 String action = eventHeader.get("action").asText();
104 if (logger.isDebugEnabled()) {
105 logger.debug("aaiEventEntityType is {} and action is {}", aaiEventEntityType, action);
107 if (aaiEventEntityType.equals("service-instance")) {
109 // parse the AAI-EVENT service-instance tree
110 ServiceInstanceEvent serviceInstanceEvent = new ServiceInstanceEvent();
111 RelatedParty relatedParty = new RelatedParty();
112 JsonNode entity = jsonNode.get("entity");
113 relatedParty.setId(entity.get("global-customer-id").asText());
114 relatedParty.setName(entity.get("subscriber-name").asText());
115 serviceInstanceEvent.setRelatedParty(relatedParty);
116 JsonNode childServiceSubscription = entity.get("service-subscriptions");
117 JsonNode serviceSubscriptions = childServiceSubscription.get("service-subscription");
118 JsonNode serviceSubscription = serviceSubscriptions.get(0);
119 String serviceSubscriptionPrint = serviceSubscription.toString();
120 JsonNode childserviceInstances = serviceSubscription.get("service-instances");
121 JsonNode serviceInstances = childserviceInstances.get("service-instance");
122 JsonNode serviceInstance = serviceInstances.get(0);
123 serviceInstanceEvent.setId(serviceInstance.get("service-instance-id").asText());
124 serviceInstanceEvent.setHref("service/" + serviceInstance.get("service-instance-id").asText());
125 serviceInstanceEvent.setState(serviceInstance.get("orchestration-status").asText());
126 if (action.equals("CREATE")) {
127 if (logger.isDebugEnabled()) {
128 logger.debug("sending service inventory event to listeners");
131 EventFactory.getEvent(EventType.SERVICE_CREATION, serviceInstanceEvent));
132 } else if (action.equals("DELETE")) {
133 processEvent(EventFactory.getEvent(EventType.SERVICE_REMOVE, serviceInstanceEvent));
134 } else if (action.equals("UPDATE")) {
135 processEvent(EventFactory.getEvent(EventType.SERVICE_ATTRIBUTE_VALUE_CHANGE,
136 serviceInstanceEvent));
144 } catch (JsonParseException e) {
145 logger.error(" unable to Parse AAI Event JSON String {}, exception is", aaiEventString,
147 } catch (JsonMappingException e) {
148 logger.error(" unable to Map AAI Event JSON String {} to Java Pojo, exception is",
149 aaiEventString, e.getMessage());
150 } catch (IOException e) {
151 logger.error("IO Error when parsing AAI Event JSON String {} ", aaiEventString,
158 public List<String> callDMaaPGetEvents() {
160 String dmaapGetEventsUrlFormated = dmaapGetEventsUrl.replace("$topic", topic);
161 dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$consumergroup", consumerGroup);
162 dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$consumerid", consumerId);
163 dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$timeout", timeout);
166 if (logger.isDebugEnabled()) {
167 logger.debug("Calling DMaaP Url : " + dmaapGetEventsUrlFormated);
169 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(dmaapGetEventsUrlFormated);
170 ResponseEntity<Object> response = callDMaaP(callURI.build().encode().toUri());
171 return (List<String>) response.getBody();
175 private ResponseEntity<Object> callDMaaP(URI callURI) {
176 ResponseEntity<Object> response =
177 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
179 if (logger.isDebugEnabled()) {
180 logger.debug("response body : {} ", response.getBody().toString());
181 logger.debug("response status : {}", response.getStatusCodeValue());
186 private HttpEntity<String> buildRequestHeader() {
187 HttpHeaders httpHeaders = new HttpHeaders();
188 httpHeaders.add("Accept", "application/json");
189 httpHeaders.add("Content-Type", "application/json");
190 return new HttpEntity<>("parameters", httpHeaders);
194 * Retrieve subscribers that match an event and fire notification asynchronously
198 private void processEvent(Event event) {
199 subscriberRepository.findSubscribersUsingEvent(event).forEach(sub -> notifier.run(sub, event));