Improve nbi status
[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
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);
98         }
99         try {
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);
106           }
107           if (aaiEventEntityType.equals("service-instance")) {
108             {
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.setState(serviceInstance.get("orchestration-status").asText());
125               if (action.equals("CREATE")) {
126                 if (logger.isDebugEnabled()) {
127                   logger.debug("sending service inventory event to listeners");
128                 }
129                 processEvent(
130                     EventFactory.getEvent(EventType.SERVICE_CREATION, serviceInstanceEvent));
131               } else if (action.equals("DELETE")) {
132                 processEvent(EventFactory.getEvent(EventType.SERVICE_REMOVE, serviceInstanceEvent));
133               } else if (action.equals("UPDATE")) {
134                 processEvent(EventFactory.getEvent(EventType.SERVICE_ATTRIBUTE_VALUE_CHANGE,
135                     serviceInstanceEvent));
136               }
137
138
139             }
140
141           }
142
143         } catch (JsonParseException e) {
144           logger.error(" unable to Parse AAI Event JSON String {}, exception is", aaiEventString,
145               e.getMessage());
146         } catch (JsonMappingException e) {
147           logger.error(" unable to Map AAI Event JSON String {} to Java Pojo, exception is",
148               aaiEventString, e.getMessage());
149         } catch (IOException e) {
150           logger.error("IO Error when parsing AAI Event JSON String {} ", aaiEventString,
151               e.getMessage());
152         }
153       }
154     }
155   }
156
157   public List<String> callDMaaPGetEvents() {
158
159     String dmaapGetEventsUrlFormated = dmaapGetEventsUrl.replace("$topic", topic);
160     dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$consumergroup", consumerGroup);
161     dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$consumerid", consumerId);
162     dmaapGetEventsUrlFormated = dmaapGetEventsUrlFormated.replace("$timeout", timeout);
163
164
165     if (logger.isDebugEnabled()) {
166       logger.debug("Calling DMaaP Url : " + dmaapGetEventsUrlFormated);
167     }
168     UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(dmaapGetEventsUrlFormated);
169     ResponseEntity<Object> response = callDMaaP(callURI.build().encode().toUri());
170     return (List<String>) response.getBody();
171
172   }
173
174   private ResponseEntity<Object> callDMaaP(URI callURI) {
175     ResponseEntity<Object> response =
176         restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
177
178     if (logger.isDebugEnabled()) {
179       logger.debug("response body : {} ", response.getBody().toString());
180       logger.debug("response status : {}", response.getStatusCodeValue());
181     }
182     return response;
183   }
184
185   private HttpEntity<String> buildRequestHeader() {
186     HttpHeaders httpHeaders = new HttpHeaders();
187     httpHeaders.add("Accept", "application/json");
188     httpHeaders.add("Content-Type", "application/json");
189     return new HttpEntity<>("parameters", httpHeaders);
190   }
191
192   /**
193    * Retrieve subscribers that match an event and fire notification asynchronously
194    * 
195    * @param event
196    */
197   private void processEvent(Event event) {
198     subscriberRepository.findSubscribersUsingEvent(event).forEach(sub -> notifier.run(sub, event));
199   }
200
201 }