6e2811faa1e53daa277281534a9f3e1807eb1168
[externalapi/nbi.git] / src / main / java / org / onap / nbi / apis / hub / service / 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;
16
17 import java.io.IOException;
18 import java.net.URI;
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;
43
44
45 @Service
46 public class CheckDMaaPEventsManager {
47
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 ";
51
52   @Autowired
53   private RestTemplate restTemplate;
54
55   @Autowired
56   private SubscriberRepository subscriberRepository;
57
58   @Autowired
59   private NotifierService notifier;
60
61   @Value("${dmaap.host}")
62   private String dmaapHostname;
63
64   @Value("${dmaap.topic}")
65   private String topic;
66
67   @Value("${dmaap.consumergroup}")
68   private String consumerGroup;
69
70   @Value("${dmaap.consumerid}")
71   private String consumerId;
72
73   @Value("${dmaap.timeout}")
74   private String timeout;
75
76   private final Logger logger = LoggerFactory.getLogger(CheckDMaaPEventsManager.class);
77
78   private String dmaapGetEventsUrl;
79
80   @PostConstruct
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);
85   }
86
87   public void checkForDMaaPAAIEvents() {
88     ObjectMapper mapper = new ObjectMapper();
89
90
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);
95
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);
102         }
103         try {
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);
110           }
111           if (aaiEventEntityType.equals("service-instance")) {
112             {
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");
132                 }
133                 processEvent(
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));
140               }
141
142
143             }
144
145           }
146
147         } catch (JsonParseException e) {
148           logger.error(" unable to Parse AAI Event JSON String {}, exception is", aaiEventString,
149               e.getMessage());
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,
155               e.getMessage());
156         }
157       }
158     }
159   }
160
161   public List<String> callDMaaPGetEvents(String dmaapGetEventsUrlFormated) {
162
163     if (logger.isDebugEnabled()) {
164       logger.debug("Calling DMaaP Url : " + dmaapGetEventsUrlFormated);
165     }
166     UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(dmaapGetEventsUrlFormated);
167     ResponseEntity<Object> response = callDMaaP(callURI.build().encode().toUri());
168     return (List<String>) response.getBody();
169
170   }
171
172   private ResponseEntity<Object> callDMaaP(URI callURI) {
173     ResponseEntity<Object> response =
174         restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
175
176     if (logger.isDebugEnabled()) {
177       logger.debug("response body : {} ", response.getBody().toString());
178       logger.debug("response status : {}", response.getStatusCodeValue());
179     }
180     return response;
181   }
182
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);
188   }
189
190   /**
191    * Retrieve subscribers that match an event and fire notification asynchronously
192    * 
193    * @param event
194    */
195   private void processEvent(Event event) {
196     subscriberRepository.findSubscribersUsingEvent(event).forEach(sub -> notifier.run(sub, event));
197   }
198
199 }