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();
91 String dmaapGetEventsUrlFormated = dmaapGetEventsUrl.replace("$topic", topic);
92 dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$consumergroup", consumerGroup);
93 dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$consumerid", consumerId);
94 dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$timeout", timeout);
96 List<String> dmaapResponse = callDMaaPGetEvents(dmaapGetEventsUrlFormated);
97 if (!CollectionUtils.isEmpty(dmaapResponse)) {
98 for (int i = 0; i < dmaapResponse.size(); i++) {
99 String aaiEventString = dmaapResponse.get(i);
100 if (logger.isDebugEnabled()) {
101 logger.debug("aai event returned was {}", aaiEventString);
104 JsonNode jsonNode = mapper.readValue(aaiEventString, JsonNode.class);
105 JsonNode eventHeader = jsonNode.get("event-header");
106 String aaiEventEntityType = eventHeader.get("entity-type").asText();
107 String action = eventHeader.get("action").asText();
108 if (logger.isDebugEnabled()) {
109 logger.debug("aaiEventEntityType is {} and action is {}", aaiEventEntityType, action);
111 if (aaiEventEntityType.equals("service-instance")) {
113 // parse the AAI-EVENT service-instance tree
114 ServiceInstanceEvent serviceInstanceEvent = new ServiceInstanceEvent();
115 RelatedParty relatedParty = new RelatedParty();
116 JsonNode entity = jsonNode.get("entity");
117 relatedParty.setId(entity.get("global-customer-id").asText());
118 relatedParty.setName(entity.get("subscriber-name").asText());
119 serviceInstanceEvent.setRelatedParty(relatedParty);
120 JsonNode childServiceSubscription = entity.get("service-subscriptions");
121 JsonNode serviceSubscriptions = childServiceSubscription.get("service-subscription");
122 JsonNode serviceSubscription = serviceSubscriptions.get(0);
123 String serviceSubscriptionPrint = serviceSubscription.toString();
124 JsonNode childserviceInstances = serviceSubscription.get("service-instances");
125 JsonNode serviceInstances = childserviceInstances.get("service-instance");
126 JsonNode serviceInstance = serviceInstances.get(0);
127 serviceInstanceEvent.setId(serviceInstance.get("service-instance-id").asText());
128 serviceInstanceEvent.setState(serviceInstance.get("orchestration-status").asText());
129 if (action.equals("CREATE")) {
130 if (logger.isDebugEnabled()) {
131 logger.debug("sending service inventory event to listeners");
134 EventFactory.getEvent(EventType.SERVICE_CREATION, serviceInstanceEvent));
135 } else if (action.equals("DELETE")) {
136 processEvent(EventFactory.getEvent(EventType.SERVICE_REMOVE, serviceInstanceEvent));
137 } else if (action.equals("UPDATE")) {
138 processEvent(EventFactory.getEvent(EventType.SERVICE_ATTRIBUTE_VALUE_CHANGE,
139 serviceInstanceEvent));
147 } catch (JsonParseException e) {
148 logger.error(" unable to Parse AAI Event JSON String {}, exception is", aaiEventString,
150 } catch (JsonMappingException e) {
151 logger.error(" unable to Map AAI Event JSON String {} to Java Pojo, exception is",
152 aaiEventString, e.getMessage());
153 } catch (IOException e) {
154 logger.error("IO Error when parsing AAI Event JSON String {} ", aaiEventString,
161 public List<String> callDMaaPGetEvents(String dmaapGetEventsUrlFormated) {
163 if (logger.isDebugEnabled()) {
164 logger.debug("Calling DMaaP Url : " + dmaapGetEventsUrlFormated);
166 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(dmaapGetEventsUrlFormated);
167 ResponseEntity<Object> response = callDMaaP(callURI.build().encode().toUri());
168 return (List<String>) response.getBody();
172 private ResponseEntity<Object> callDMaaP(URI callURI) {
173 ResponseEntity<Object> response =
174 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
176 if (logger.isDebugEnabled()) {
177 logger.debug("response body : {} ", response.getBody().toString());
178 logger.debug("response status : {}", response.getStatusCodeValue());
183 private HttpEntity<String> buildRequestHeader() {
184 HttpHeaders httpHeaders = new HttpHeaders();
185 httpHeaders.add("Accept", "application/json");
186 httpHeaders.add("Content-Type", "application/json");
187 return new HttpEntity<>("parameters", httpHeaders);
191 * Retrieve subscribers that match an event and fire notification asynchronously
195 private void processEvent(Event event) {
196 subscriberRepository.findSubscribersUsingEvent(event).forEach(sub -> notifier.run(sub, event));