5b9c5d36d18e4a471260a08519d1061849e39a20
[clamp.git] / src / main / java / org / onap / clamp / clds / client / SdcCatalogServices.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP CLAMP\r
4  * ================================================================================\r
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights\r
6  *                             reserved.\r
7  * ================================================================================\r
8  * Licensed under the Apache License, Version 2.0 (the "License");\r
9  * you may not use this file except in compliance with the License.\r
10  * You may obtain a copy of the License at\r
11  *\r
12  * http://www.apache.org/licenses/LICENSE-2.0\r
13  *\r
14  * Unless required by applicable law or agreed to in writing, software\r
15  * distributed under the License is distributed on an "AS IS" BASIS,\r
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
17  * See the License for the specific language governing permissions and\r
18  * limitations under the License.\r
19  * ============LICENSE_END============================================\r
20  * ===================================================================\r
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
22  */\r
23 \r
24 package org.onap.clamp.clds.client;\r
25 \r
26 import com.att.eelf.configuration.EELFLogger;\r
27 import com.att.eelf.configuration.EELFManager;\r
28 import com.fasterxml.jackson.databind.JsonNode;\r
29 import com.fasterxml.jackson.databind.ObjectMapper;\r
30 import com.fasterxml.jackson.databind.node.ArrayNode;\r
31 import com.fasterxml.jackson.databind.node.ObjectNode;\r
32 import com.fasterxml.jackson.databind.node.TextNode;\r
33 \r
34 import java.io.BufferedReader;\r
35 import java.io.DataOutputStream;\r
36 import java.io.IOException;\r
37 import java.io.InputStream;\r
38 import java.io.InputStreamReader;\r
39 import java.io.Reader;\r
40 import java.io.StringReader;\r
41 import java.net.HttpURLConnection;\r
42 import java.net.URL;\r
43 import java.util.ArrayList;\r
44 import java.util.Collections;\r
45 import java.util.Date;\r
46 import java.util.Iterator;\r
47 import java.util.List;\r
48 \r
49 import javax.ws.rs.BadRequestException;\r
50 \r
51 import org.apache.commons.csv.CSVFormat;\r
52 import org.apache.commons.csv.CSVRecord;\r
53 import org.apache.commons.lang3.StringUtils;\r
54 import org.onap.clamp.clds.client.req.SdcReq;\r
55 import org.onap.clamp.clds.exception.SdcCommunicationException;\r
56 import org.onap.clamp.clds.model.CldsAlarmCondition;\r
57 import org.onap.clamp.clds.model.CldsDBServiceCache;\r
58 import org.onap.clamp.clds.model.CldsSdcArtifact;\r
59 import org.onap.clamp.clds.model.CldsSdcResource;\r
60 import org.onap.clamp.clds.model.CldsSdcResourceBasicInfo;\r
61 import org.onap.clamp.clds.model.CldsSdcServiceDetail;\r
62 import org.onap.clamp.clds.model.CldsSdcServiceInfo;\r
63 import org.onap.clamp.clds.model.CldsServiceData;\r
64 import org.onap.clamp.clds.model.CldsVfData;\r
65 import org.onap.clamp.clds.model.CldsVfKPIData;\r
66 import org.onap.clamp.clds.model.CldsVfcData;\r
67 import org.onap.clamp.clds.model.prop.Global;\r
68 import org.onap.clamp.clds.model.prop.ModelProperties;\r
69 import org.onap.clamp.clds.model.refprop.RefProp;\r
70 import org.onap.clamp.clds.util.LoggingUtils;\r
71 import org.springframework.beans.factory.annotation.Autowired;\r
72 \r
73 public class SdcCatalogServices {\r
74     protected static final EELFLogger logger            = EELFManager.getInstance().getLogger(SdcCatalogServices.class);\r
75     protected static final EELFLogger metricsLogger     = EELFManager.getInstance().getMetricsLogger();\r
76 \r
77     private static final String       RESOURCE_VF_TYPE  = "VF";\r
78     private static final String       RESOURCE_VFC_TYPE = "VFC";\r
79 \r
80     @Autowired\r
81     private RefProp                   refProp;\r
82 \r
83     /**\r
84      * This method get the SDC services Information with the corresponding\r
85      * Service UUID.\r
86      * \r
87      * @param uuid\r
88      *            The service UUID\r
89      * @return A Json String with all the service list\r
90      */\r
91     public String getSdcServicesInformation(String uuid) {\r
92         Date startTime = new Date();\r
93         String baseUrl = refProp.getStringValue("sdc.serviceUrl");\r
94         String basicAuth = SdcReq.getSdcBasicAuth(refProp);\r
95         LoggingUtils.setTargetContext("SDC", "getSdcServicesInformation");\r
96 \r
97         try {\r
98             String url = baseUrl;\r
99             if (uuid != null) {\r
100                 url = baseUrl + "/" + uuid + "/metadata";\r
101             }\r
102             URL urlObj = new URL(url);\r
103 \r
104             HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();\r
105 \r
106             conn.setRequestProperty(refProp.getStringValue("sdc.InstanceID"), "CLAMP-Tool");\r
107             conn.setRequestProperty("Authorization", basicAuth);\r
108             conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");\r
109             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
110             conn.setRequestMethod("GET");\r
111 \r
112             String resp = getResponse(conn);\r
113             if (resp != null) {\r
114                 logger.info(resp.toString());\r
115                 // metrics log\r
116                 LoggingUtils.setResponseContext("0", "Get sdc services success", this.getClass().getName());\r
117                 return resp;\r
118             }\r
119         } catch (IOException e) {\r
120             LoggingUtils.setResponseContext("900", "Get sdc services failed", this.getClass().getName());\r
121             LoggingUtils.setErrorContext("900", "Get sdc services error");\r
122             logger.error("not able to get any service information from sdc for uuid:" + uuid, e);\r
123         } finally {\r
124             LoggingUtils.setTimeContext(startTime, new Date());\r
125             metricsLogger.info("getSdcServicesInformation complete");\r
126         }\r
127 \r
128         return "";\r
129     }\r
130 \r
131     /**\r
132      * To remove duplicate serviceUUIDs from sdc services List.\r
133      *\r
134      * @param rawCldsSdcServiceList\r
135      *            A list of CldsSdcServiceInfo\r
136      * @return A list of CldsSdcServiceInfo without duplicate service UUID\r
137      */\r
138     public List<CldsSdcServiceInfo> removeDuplicateServices(List<CldsSdcServiceInfo> rawCldsSdcServiceList) {\r
139         List<CldsSdcServiceInfo> cldsSdcServiceInfoList = null;\r
140         if (rawCldsSdcServiceList != null && !rawCldsSdcServiceList.isEmpty()) {\r
141             // sort list\r
142             Collections.sort(rawCldsSdcServiceList);\r
143             // and then take only the services with the max version (last in the\r
144             // list with the same name)\r
145             cldsSdcServiceInfoList = new ArrayList<>();\r
146             for (int i = 1; i < rawCldsSdcServiceList.size(); i++) {\r
147                 // compare name with previous - if not equal, then keep the\r
148                 // previous (it's the last with that name)\r
149                 CldsSdcServiceInfo prev = rawCldsSdcServiceList.get(i - 1);\r
150                 if (!rawCldsSdcServiceList.get(i).getName().equals(prev.getName())) {\r
151                     cldsSdcServiceInfoList.add(prev);\r
152                 }\r
153             }\r
154             // add the last in the list\r
155             cldsSdcServiceInfoList.add(rawCldsSdcServiceList.get(rawCldsSdcServiceList.size() - 1));\r
156         }\r
157         return cldsSdcServiceInfoList;\r
158     }\r
159 \r
160     /**\r
161      * To remove duplicate serviceUUIDs from sdc resources List.\r
162      *\r
163      * @param rawCldsSdcResourceList\r
164      * @return\r
165      */\r
166     public List<CldsSdcResource> removeDuplicateSdcResourceInstances(List<CldsSdcResource> rawCldsSdcResourceList) {\r
167         List<CldsSdcResource> cldsSdcResourceList = null;\r
168         if (rawCldsSdcResourceList != null && !rawCldsSdcResourceList.isEmpty()) {\r
169             // sort list\r
170             Collections.sort(rawCldsSdcResourceList);\r
171             // and then take only the resources with the max version (last in\r
172             // the list with the same name)\r
173             cldsSdcResourceList = new ArrayList<>();\r
174             for (int i = 1; i < rawCldsSdcResourceList.size(); i++) {\r
175                 // compare name with previous - if not equal, then keep the\r
176                 // previous (it's the last with that name)\r
177                 CldsSdcResource prev = rawCldsSdcResourceList.get(i - 1);\r
178                 if (!rawCldsSdcResourceList.get(i).getResourceInstanceName().equals(prev.getResourceInstanceName())) {\r
179                     cldsSdcResourceList.add(prev);\r
180                 }\r
181             }\r
182             // add the last in the list\r
183             cldsSdcResourceList.add(rawCldsSdcResourceList.get(rawCldsSdcResourceList.size() - 1));\r
184         }\r
185         return cldsSdcResourceList;\r
186     }\r
187 \r
188     /**\r
189      * To remove duplicate basic resources with same resourceUUIDs.\r
190      *\r
191      * @param rawCldsSdcResourceListBasicList\r
192      * @return\r
193      */\r
194     public List<CldsSdcResourceBasicInfo> removeDuplicateSdcResourceBasicInfo(\r
195             List<CldsSdcResourceBasicInfo> rawCldsSdcResourceListBasicList) {\r
196         List<CldsSdcResourceBasicInfo> cldsSdcResourceBasicInfoList = null;\r
197         if (rawCldsSdcResourceListBasicList != null && !rawCldsSdcResourceListBasicList.isEmpty()) {\r
198             // sort list\r
199             Collections.sort(rawCldsSdcResourceListBasicList);\r
200             // and then take only the resources with the max version (last in\r
201             // the list with the same name)\r
202             cldsSdcResourceBasicInfoList = new ArrayList<>();\r
203             for (int i = 1; i < rawCldsSdcResourceListBasicList.size(); i++) {\r
204                 // compare name with previous - if not equal, then keep the\r
205                 // previous (it's the last with that name)\r
206                 CldsSdcResourceBasicInfo prev = rawCldsSdcResourceListBasicList.get(i - 1);\r
207                 if (!rawCldsSdcResourceListBasicList.get(i).getName().equals(prev.getName())) {\r
208                     cldsSdcResourceBasicInfoList.add(prev);\r
209                 }\r
210             }\r
211             // add the last in the list\r
212             cldsSdcResourceBasicInfoList\r
213                     .add(rawCldsSdcResourceListBasicList.get(rawCldsSdcResourceListBasicList.size() - 1));\r
214         }\r
215         return cldsSdcResourceBasicInfoList;\r
216     }\r
217 \r
218     /**\r
219      * To get ServiceUUID by using serviceInvariantUUID.\r
220      *\r
221      * @param invariantId\r
222      *            The invariant ID\r
223      * @return The service UUID\r
224      */\r
225     public String getServiceUuidFromServiceInvariantId(String invariantId) {\r
226         String serviceUuid = "";\r
227         String responseStr = getSdcServicesInformation(null);\r
228         List<CldsSdcServiceInfo> rawCldsSdcServicesList = getCldsSdcServicesListFromJson(responseStr);\r
229         List<CldsSdcServiceInfo> cldsSdcServicesList = removeDuplicateServices(rawCldsSdcServicesList);\r
230         if (cldsSdcServicesList != null && !cldsSdcServicesList.isEmpty()) {\r
231             for (CldsSdcServiceInfo currCldsSdcServiceInfo : cldsSdcServicesList) {\r
232                 if (currCldsSdcServiceInfo != null && currCldsSdcServiceInfo.getInvariantUUID() != null\r
233                         && currCldsSdcServiceInfo.getInvariantUUID().equalsIgnoreCase(invariantId)) {\r
234                     serviceUuid = currCldsSdcServiceInfo.getUuid();\r
235                     break;\r
236                 }\r
237             }\r
238         }\r
239         return serviceUuid;\r
240     }\r
241 \r
242     /**\r
243      * To get CldsAsdsServiceInfo class by parsing json string.\r
244      *\r
245      * @param jsonStr\r
246      *            The Json string that must be decoded\r
247      * @return The list of CldsSdcServiceInfo, if there is a failure it return\r
248      *         an empty list\r
249      */\r
250     public List<CldsSdcServiceInfo> getCldsSdcServicesListFromJson(String jsonStr) {\r
251         ObjectMapper objectMapper = new ObjectMapper();\r
252         if (StringUtils.isBlank(jsonStr)) {\r
253             return new ArrayList<>();\r
254         }\r
255         try {\r
256             return objectMapper.readValue(jsonStr,\r
257                     objectMapper.getTypeFactory().constructCollectionType(List.class, CldsSdcServiceInfo.class));\r
258         } catch (IOException e) {\r
259             logger.error("Error when attempting to decode the JSON containing CldsSdcServiceInfo", e);\r
260             return new ArrayList<>();\r
261         }\r
262     }\r
263 \r
264     /**\r
265      * To get List of CldsSdcResourceBasicInfo class by parsing json string.\r
266      *\r
267      * @param jsonStr\r
268      *            The JSOn string that must be decoded\r
269      * @return The list of CldsSdcResourceBasicInfo, an empty list in case of\r
270      *         issues\r
271      */\r
272     public List<CldsSdcResourceBasicInfo> getAllSdcResourcesListFromJson(String jsonStr) {\r
273         ObjectMapper objectMapper = new ObjectMapper();\r
274         if (StringUtils.isBlank(jsonStr)) {\r
275             return new ArrayList<>();\r
276         }\r
277 \r
278         try {\r
279             return objectMapper.readValue(jsonStr,\r
280                     objectMapper.getTypeFactory().constructCollectionType(List.class, CldsSdcResourceBasicInfo.class));\r
281         } catch (IOException e) {\r
282             logger.error("Exception occurred when attempting to decode the list of CldsSdcResourceBasicInfo JSON", e);\r
283             return new ArrayList<>();\r
284         }\r
285     }\r
286 \r
287     /**\r
288      * To get CldsAsdsResource class by parsing json string.\r
289      *\r
290      * @param jsonStr\r
291      * @return\r
292      * @throws IOException\r
293      */\r
294     public CldsSdcResource getCldsSdcResourceFromJson(String jsonStr) throws IOException {\r
295         ObjectMapper objectMapper = new ObjectMapper();\r
296         return objectMapper.readValue(jsonStr, CldsSdcResource.class);\r
297     }\r
298 \r
299     /**\r
300      * To get CldsSdcServiceDetail by parsing json string.\r
301      *\r
302      * @param jsonStr\r
303      * @return\r
304      */\r
305     public CldsSdcServiceDetail getCldsSdcServiceDetailFromJson(String jsonStr) {\r
306         ObjectMapper objectMapper = new ObjectMapper();\r
307         try {\r
308             return objectMapper.readValue(jsonStr, CldsSdcServiceDetail.class);\r
309         } catch (IOException e) {\r
310             logger.error("Exception when attempting to decode the CldsSdcServiceDetail JSON", e);\r
311             return null;\r
312         }\r
313     }\r
314 \r
315     /**\r
316      * To upload artifact to sdc based on serviceUUID and resource name on url.\r
317      *\r
318      * @param prop\r
319      * @param userid\r
320      * @param url\r
321      * @param formattedSdcReq\r
322      * @return\r
323      */\r
324     public String uploadArtifactToSdc(ModelProperties prop, String userid, String url, String formatttedSdcReq) {\r
325         // Verify whether it is triggered by Validation Test button from UI\r
326         if (prop.isTest()) {\r
327             return "sdc artifact upload not executed for test action";\r
328         }\r
329         try {\r
330             logger.info("userid=" + userid);\r
331             String md5Text = SdcReq.calculateMD5ByString(formatttedSdcReq);\r
332             byte[] postData = SdcReq.stringToByteArray(formatttedSdcReq);\r
333             int postDataLength = postData.length;\r
334             HttpURLConnection conn = getSdcHttpUrlConnection(userid, postDataLength, url, md5Text);\r
335             try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {\r
336                 wr.write(postData);\r
337             }\r
338             boolean requestFailed = true;\r
339             int responseCode = conn.getResponseCode();\r
340             logger.info("responseCode=" + responseCode);\r
341             if (responseCode == 200) {\r
342                 requestFailed = false;\r
343             }\r
344 \r
345             String responseStr = getResponse(conn);\r
346             if (responseStr != null && requestFailed) {\r
347                 logger.error("requestFailed - responseStr=" + responseStr);\r
348                 throw new BadRequestException(responseStr);\r
349             }\r
350             return responseStr;\r
351         } catch (IOException e) {\r
352             logger.error("Exception when attempting to communicate with SDC", e);\r
353             throw new SdcCommunicationException("Exception when attempting to communicate with SDC", e);\r
354         }\r
355 \r
356     }\r
357 \r
358     private HttpURLConnection getSdcHttpUrlConnection(String userid, int postDataLength, String url, String md5Text) {\r
359         try {\r
360             logger.info("userid=" + userid);\r
361             String basicAuth = SdcReq.getSdcBasicAuth(refProp);\r
362             String sdcXonapInstanceId = refProp.getStringValue("sdc.sdcX-InstanceID");\r
363             URL urlObj = new URL(url);\r
364             HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();\r
365             conn.setDoOutput(true);\r
366             conn.setRequestProperty(refProp.getStringValue("sdc.InstanceID"), sdcXonapInstanceId);\r
367             conn.setRequestProperty("Authorization", basicAuth);\r
368             conn.setRequestProperty("Content-Type", "application/json");\r
369             conn.setRequestProperty("Content-MD5", md5Text);\r
370             conn.setRequestProperty("USER_ID", userid);\r
371             conn.setRequestMethod("POST");\r
372             conn.setRequestProperty("charset", "utf-8");\r
373             conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));\r
374             conn.setUseCaches(false);\r
375             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
376             return conn;\r
377         } catch (IOException e) {\r
378             logger.error("Exception when attempting to open connection with SDC", e);\r
379             throw new SdcCommunicationException("Exception when attempting to open connection with SDC", e);\r
380         }\r
381     }\r
382 \r
383     private String getResponse(HttpURLConnection conn) {\r
384         try (InputStream is = getInputStream(conn)) {\r
385             if (is != null) {\r
386                 try (BufferedReader in = new BufferedReader(new InputStreamReader(is))) {\r
387                     StringBuilder response = new StringBuilder();\r
388                     String inputLine;\r
389                     while ((inputLine = in.readLine()) != null) {\r
390                         response.append(inputLine);\r
391                     }\r
392                     return response.toString();\r
393                 }\r
394             } else {\r
395                 return null;\r
396             }\r
397         } catch (IOException e) {\r
398             logger.error("Exception when attempting to open SDC response", e);\r
399             throw new SdcCommunicationException("Exception when attempting to open SDC response", e);\r
400         }\r
401     }\r
402 \r
403     private InputStream getInputStream(HttpURLConnection conn) {\r
404         try {\r
405             InputStream inStream = conn.getErrorStream();\r
406             if (inStream == null) {\r
407                 inStream = conn.getInputStream();\r
408             }\r
409             return inStream;\r
410         } catch (IOException e) {\r
411             logger.error("Exception when attempting to open SDC error stream", e);\r
412             throw new SdcCommunicationException("Exception when attempting to open SDC error stream", e);\r
413         }\r
414     }\r
415 \r
416     public CldsDBServiceCache getCldsDbServiceCacheUsingCldsServiceData(CldsServiceData cldsServiceData) {\r
417         try {\r
418             CldsDBServiceCache cldsDbServiceCache = new CldsDBServiceCache();\r
419             cldsDbServiceCache.setCldsDataInstream(cldsServiceData);\r
420             cldsDbServiceCache.setInvariantId(cldsServiceData.getServiceInvariantUUID());\r
421             cldsDbServiceCache.setServiceId(cldsServiceData.getServiceUUID());\r
422             return cldsDbServiceCache;\r
423         } catch (IOException e) {\r
424             logger.error("Exception when getting service in cache", e);\r
425             throw new SdcCommunicationException("Exception when getting service in cache", e);\r
426         }\r
427     }\r
428 \r
429     public boolean isCldsSdcCacheDataExpired(CldsServiceData cldsServiceData) {\r
430         boolean expired = false;\r
431         if (cldsServiceData != null && cldsServiceData.getServiceUUID() != null) {\r
432             String cachedServiceUuid = cldsServiceData.getServiceUUID();\r
433             String latestServiceUuid = getServiceUuidFromServiceInvariantId(cldsServiceData.getServiceInvariantUUID());\r
434             String defaultRecordAge = refProp.getStringValue("CLDS_SERVICE_CACHE_MAX_SECONDS");\r
435             if ((!cachedServiceUuid.equalsIgnoreCase(latestServiceUuid)) || (cldsServiceData.getAgeOfRecord() != null\r
436                     && cldsServiceData.getAgeOfRecord() > Long.parseLong(defaultRecordAge))) {\r
437                 expired = true;\r
438             }\r
439         } else {\r
440             expired = true;\r
441         }\r
442         return expired;\r
443     }\r
444 \r
445     public CldsServiceData getCldsServiceDataWithAlarmConditions(String invariantServiceUuid) {\r
446         String url = refProp.getStringValue("sdc.serviceUrl");\r
447         String catalogUrl = refProp.getStringValue("sdc.catalog.url");\r
448         String serviceUuid = getServiceUuidFromServiceInvariantId(invariantServiceUuid);\r
449         String serviceDetailUrl = url + "/" + serviceUuid + "/metadata";\r
450         String responseStr = getCldsServicesOrResourcesBasedOnURL(serviceDetailUrl, false);\r
451         ObjectMapper objectMapper = new ObjectMapper();\r
452         CldsServiceData cldsServiceData = new CldsServiceData();\r
453         if (responseStr != null) {\r
454             CldsSdcServiceDetail cldsSdcServiceDetail;\r
455             try {\r
456                 cldsSdcServiceDetail = objectMapper.readValue(responseStr, CldsSdcServiceDetail.class);\r
457             } catch (IOException e) {\r
458                 logger.error("Exception when decoding the CldsServiceData JSON from SDC", e);\r
459                 throw new SdcCommunicationException("Exception when decoding the CldsServiceData JSON from SDC", e);\r
460             }\r
461             cldsServiceData.setServiceUUID(cldsSdcServiceDetail.getUuid());\r
462             cldsServiceData.setServiceInvariantUUID(cldsSdcServiceDetail.getInvariantUUID());\r
463 \r
464             // To remove duplicate resources from serviceDetail and add valid\r
465             // vfs to service\r
466             if (cldsSdcServiceDetail != null && cldsSdcServiceDetail.getResources() != null) {\r
467                 List<CldsSdcResource> cldsSdcResourceList = removeDuplicateSdcResourceInstances(\r
468                         cldsSdcServiceDetail.getResources());\r
469                 if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {\r
470                     List<CldsVfData> cldsVfDataList = new ArrayList<>();\r
471                     for (CldsSdcResource currCldsSdcResource : cldsSdcResourceList) {\r
472                         if (currCldsSdcResource != null && currCldsSdcResource.getResoucreType() != null\r
473                                 && "VF".equalsIgnoreCase(currCldsSdcResource.getResoucreType())) {\r
474                             CldsVfData currCldsVfData = new CldsVfData();\r
475                             currCldsVfData.setVfName(currCldsSdcResource.getResourceInstanceName());\r
476                             currCldsVfData.setVfInvariantResourceUUID(currCldsSdcResource.getResourceInvariantUUID());\r
477                             cldsVfDataList.add(currCldsVfData);\r
478                         }\r
479                     }\r
480                     cldsServiceData.setCldsVfs(cldsVfDataList);\r
481                     // For each vf in the list , add all vfc's\r
482                     getAllVfcForVfList(cldsVfDataList, catalogUrl);\r
483                     logger.info("value of cldsServiceData:" + cldsServiceData);\r
484                     logger.info("value of cldsServiceData:" + cldsServiceData.getServiceInvariantUUID());\r
485                 }\r
486             }\r
487         }\r
488         return cldsServiceData;\r
489     }\r
490 \r
491     private void getAllVfcForVfList(List<CldsVfData> cldsVfDataList, String catalogUrl) {\r
492         // todo : refact this..\r
493         if (cldsVfDataList != null && !cldsVfDataList.isEmpty()) {\r
494             List<CldsSdcResourceBasicInfo> allVfResources = getAllSdcVForVfcResourcesBasedOnResourceType(\r
495                     RESOURCE_VF_TYPE);\r
496             List<CldsSdcResourceBasicInfo> allVfcResources = getAllSdcVForVfcResourcesBasedOnResourceType(\r
497                     RESOURCE_VFC_TYPE);\r
498             for (CldsVfData currCldsVfData : cldsVfDataList) {\r
499                 if (currCldsVfData != null && currCldsVfData.getVfInvariantResourceUUID() != null) {\r
500                     String resourceUuid = getResourceUuidFromResourceInvariantUuid(\r
501                             currCldsVfData.getVfInvariantResourceUUID(), allVfResources);\r
502                     if (resourceUuid != null) {\r
503                         String vfResourceUuidUrl = catalogUrl + "resources" + "/" + resourceUuid + "/metadata";\r
504                         String vfResponse = getCldsServicesOrResourcesBasedOnURL(vfResourceUuidUrl, false);\r
505                         if (vfResponse != null) {\r
506                             // Below 2 line are to get the KPI(field path) data\r
507                             // associated with the VF's\r
508                             List<CldsVfKPIData> cldsVfKPIDataList = getFieldPathFromVF(vfResponse);\r
509                             currCldsVfData.setCldsKPIList(cldsVfKPIDataList);\r
510 \r
511                             List<CldsVfcData> vfcDataListFromVfResponse = getVfcDataListFromVfResponse(vfResponse);\r
512                             if (vfcDataListFromVfResponse != null) {\r
513                                 currCldsVfData.setCldsVfcs(vfcDataListFromVfResponse);\r
514                                 if (!vfcDataListFromVfResponse.isEmpty()) {\r
515                                     // To get artifacts for every VFC and get\r
516                                     // alarm conditions from artifact\r
517                                     for (CldsVfcData currCldsVfcData : vfcDataListFromVfResponse) {\r
518                                         if (currCldsVfcData != null\r
519                                                 && currCldsVfcData.getVfcInvariantResourceUUID() != null) {\r
520                                             String resourceVfcUuid = getResourceUuidFromResourceInvariantUuid(\r
521                                                     currCldsVfcData.getVfcInvariantResourceUUID(), allVfcResources);\r
522                                             if (resourceVfcUuid != null) {\r
523                                                 String vfcResourceUuidUrl = catalogUrl + "resources" + "/"\r
524                                                         + resourceVfcUuid + "/metadata";\r
525                                                 String vfcResponse = getCldsServicesOrResourcesBasedOnURL(\r
526                                                         vfcResourceUuidUrl, false);\r
527                                                 if (vfcResponse != null) {\r
528                                                     List<CldsAlarmCondition> alarmCondtionsFromVfc = getAlarmCondtionsFromVfc(\r
529                                                             vfcResponse);\r
530                                                     currCldsVfcData.setCldsAlarmConditions(alarmCondtionsFromVfc);\r
531                                                 }\r
532                                             } else {\r
533                                                 logger.info("No resourceVFC UUID found for given invariantID:"\r
534                                                         + currCldsVfcData.getVfcInvariantResourceUUID());\r
535                                             }\r
536                                         }\r
537                                     }\r
538                                 }\r
539                             }\r
540                         }\r
541                     } else {\r
542                         logger.info("No resourceUUID found for given invariantREsourceUUID:"\r
543                                 + currCldsVfData.getVfInvariantResourceUUID());\r
544                     }\r
545                 }\r
546             }\r
547         }\r
548     }\r
549 \r
550     private List<CldsVfcData> getVfcDataListFromVfResponse(String vfResponse) {\r
551         ObjectMapper mapper = new ObjectMapper();\r
552         ObjectNode vfResponseNode;\r
553         try {\r
554             vfResponseNode = (ObjectNode) mapper.readTree(vfResponse);\r
555         } catch (IOException e) {\r
556             logger.error("Exception when decoding the JSON list of CldsVfcData", e);\r
557             return new ArrayList<>();\r
558         }\r
559         ArrayNode vfcArrayNode = (ArrayNode) vfResponseNode.get("resources");\r
560         List<CldsVfcData> cldsVfcDataList = new ArrayList<>();\r
561         if (vfcArrayNode != null) {\r
562             for (JsonNode vfcjsonNode : vfcArrayNode) {\r
563                 CldsVfcData currCldsVfcData = new CldsVfcData();\r
564                 ObjectNode currVfcNode = (ObjectNode) vfcjsonNode;\r
565                 TextNode resourceTypeNode = (TextNode) currVfcNode.get("resoucreType");\r
566                 if (resourceTypeNode != null && "VFC".equalsIgnoreCase(resourceTypeNode.textValue())) {\r
567                     TextNode vfcResourceName = (TextNode) currVfcNode.get("resourceInstanceName");\r
568                     TextNode vfcInvariantResourceUuid = (TextNode) currVfcNode.get("resourceInvariantUUID");\r
569                     currCldsVfcData.setVfcName(vfcResourceName.textValue());\r
570                     currCldsVfcData.setVfcInvariantResourceUUID(vfcInvariantResourceUuid.textValue());\r
571                     cldsVfcDataList.add(currCldsVfcData);\r
572                 } else if (resourceTypeNode != null && "CVFC".equalsIgnoreCase(resourceTypeNode.textValue())) {\r
573                     cldsVfcDataList.addAll(getVFCfromCVFC(currVfcNode.get("resourceUUID").textValue()));\r
574                 }\r
575             }\r
576         }\r
577         return cldsVfcDataList;\r
578     }\r
579 \r
580     private List<CldsVfcData> getVFCfromCVFC(String resourceUUID) {\r
581         String catalogUrl = refProp.getStringValue("sdc.catalog.url");\r
582         List<CldsVfcData> cldsVfcDataList = new ArrayList<>();\r
583 \r
584         if (resourceUUID != null) {\r
585             String vfcResourceUUIDUrl = catalogUrl + "resources" + "/" + resourceUUID + "/metadata";\r
586             try {\r
587                 String vfcResponse = getCldsServicesOrResourcesBasedOnURL(vfcResourceUUIDUrl, false);\r
588                 ObjectMapper mapper = new ObjectMapper();\r
589                 ObjectNode vfResponseNode = (ObjectNode) mapper.readTree(vfcResponse);\r
590                 ArrayNode vfcArrayNode = (ArrayNode) vfResponseNode.get("resources");\r
591 \r
592                 if (vfcArrayNode != null) {\r
593                     for (JsonNode vfcjsonNode : vfcArrayNode) {\r
594                         CldsVfcData currCldsVfcData = new CldsVfcData();\r
595                         ObjectNode currVfcNode = (ObjectNode) vfcjsonNode;\r
596                         TextNode resourceTypeNode = (TextNode) currVfcNode.get("resoucreType");\r
597                         if (resourceTypeNode != null && "VFC".equalsIgnoreCase(resourceTypeNode.textValue())) {\r
598                             TextNode vfcResourceName = (TextNode) currVfcNode.get("resourceInstanceName");\r
599                             TextNode vfcInvariantResourceUUID = (TextNode) currVfcNode.get("resourceInvariantUUID");\r
600                             currCldsVfcData.setVfcName(vfcResourceName.textValue());\r
601                             currCldsVfcData.setVfcInvariantResourceUUID(vfcInvariantResourceUUID.textValue());\r
602                             cldsVfcDataList.add(currCldsVfcData);\r
603                         }\r
604                     }\r
605                 }\r
606             } catch (IOException e) {\r
607                 logger.error("Exception during JSON analyzis", e);\r
608             }\r
609         }\r
610         return cldsVfcDataList;\r
611     }\r
612 \r
613     private String removeUnwantedBracesFromString(String id) {\r
614         return (id != null) ? id.replaceAll("\"", "") : "";\r
615     }\r
616 \r
617     private List<CldsAlarmCondition> getAlarmCondtionsFromVfc(String vfcResponse) {\r
618         List<CldsAlarmCondition> cldsAlarmConditionList = new ArrayList<>();\r
619         ObjectMapper mapper = new ObjectMapper();\r
620         ObjectNode vfcResponseNode;\r
621         try {\r
622             vfcResponseNode = (ObjectNode) mapper.readTree(vfcResponse);\r
623         } catch (IOException e) {\r
624             logger.error("Exception when decoding the JSON list of CldsAlarmCondition", e);\r
625             return cldsAlarmConditionList;\r
626         }\r
627         ArrayNode artifactsArrayNode = (ArrayNode) vfcResponseNode.get("artifacts");\r
628 \r
629         if (artifactsArrayNode != null && artifactsArrayNode.size() > 0) {\r
630             for (int index = 0; index < artifactsArrayNode.size(); index++) {\r
631                 ObjectNode currArtifactNode = (ObjectNode) artifactsArrayNode.get(index);\r
632                 TextNode artifactUrlNode = (TextNode) currArtifactNode.get("artifactURL");\r
633                 if (artifactUrlNode != null) {\r
634                     String responsesFromArtifactUrl = getResponsesFromArtifactUrl(artifactUrlNode.textValue());\r
635                     cldsAlarmConditionList.addAll(parseCsvToGetAlarmConditions(responsesFromArtifactUrl));\r
636                     logger.info(responsesFromArtifactUrl);\r
637                 }\r
638             }\r
639         }\r
640         return cldsAlarmConditionList;\r
641     }\r
642 \r
643     private List<CldsAlarmCondition> parseCsvToGetAlarmConditions(String allAlarmCondsValues) {\r
644         try {\r
645             List<CldsAlarmCondition> cldsAlarmConditionList = new ArrayList<>();\r
646             Reader alarmReader = new StringReader(allAlarmCondsValues);\r
647             Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(alarmReader);\r
648             if (records != null) {\r
649                 Iterator<CSVRecord> it = records.iterator();\r
650                 if (it.hasNext()) {\r
651                     it.next();\r
652                 }\r
653                 it.forEachRemaining(record -> processRecord(cldsAlarmConditionList, record));\r
654             }\r
655             return cldsAlarmConditionList;\r
656         } catch (IOException e) {\r
657             logger.error("Exception when attempting to parse the CSV containing the alarm", e);\r
658             return new ArrayList<>();\r
659         }\r
660     }\r
661 \r
662     // Method to get the artifact for any particular VF\r
663     private List<CldsVfKPIData> getFieldPathFromVF(String vfResponse) {\r
664         List<CldsVfKPIData> cldsVfKPIDataList = new ArrayList<>();\r
665         ObjectMapper mapper = new ObjectMapper();\r
666         ObjectNode vfResponseNode;\r
667         try {\r
668             vfResponseNode = (ObjectNode) mapper.readTree(vfResponse);\r
669         } catch (IOException e) {\r
670             logger.error("Exception when decoding the JSON list of CldsVfKPIData", e);\r
671             return cldsVfKPIDataList;\r
672         }\r
673         ArrayNode artifactsArrayNode = (ArrayNode) vfResponseNode.get("artifacts");\r
674 \r
675         if (artifactsArrayNode != null && artifactsArrayNode.size() > 0) {\r
676             for (int index = 0; index < artifactsArrayNode.size(); index++) {\r
677                 ObjectNode currArtifactNode = (ObjectNode) artifactsArrayNode.get(index);\r
678                 TextNode artifactUrlNode = (TextNode) currArtifactNode.get("artifactURL");\r
679                 TextNode artifactNameNode = (TextNode) currArtifactNode.get("artifactName");\r
680                 String artifactName = "";\r
681                 if (artifactNameNode != null) {\r
682                     artifactName = artifactNameNode.textValue();\r
683                     artifactName = artifactName.substring(artifactName.lastIndexOf('.') + 1);\r
684                 }\r
685                 if (artifactUrlNode != null && artifactName != null && !artifactName.isEmpty()\r
686                         && artifactName.equalsIgnoreCase("csv")) {\r
687                     String responsesFromArtifactUrl = getResponsesFromArtifactUrl(artifactUrlNode.textValue());\r
688                     cldsVfKPIDataList.addAll(parseCsvToGetFieldPath(responsesFromArtifactUrl));\r
689                     logger.info(responsesFromArtifactUrl);\r
690                 }\r
691             }\r
692         }\r
693         return cldsVfKPIDataList;\r
694     }\r
695 \r
696     private CldsVfKPIData convertCsvRecordToKpiData(CSVRecord record) {\r
697         if (record.size() < 6) {\r
698             logger.debug("invalid csv field path Record,total columns less than 6: " + record);\r
699             return null;\r
700         }\r
701 \r
702         if (StringUtils.isBlank(record.get(1)) || StringUtils.isBlank(record.get(3))\r
703                 || StringUtils.isBlank(record.get(5))) {\r
704             logger.debug("Invalid csv field path Record,one of column is having blank value : " + record);\r
705             return null;\r
706         }\r
707 \r
708         CldsVfKPIData cldsVfKPIData = new CldsVfKPIData();\r
709         cldsVfKPIData.setNfNamingCode(record.get(0).trim());\r
710         cldsVfKPIData.setNfNamingValue(record.get(1).trim());\r
711 \r
712         cldsVfKPIData.setFieldPath(record.get(2).trim());\r
713         cldsVfKPIData.setFieldPathValue(record.get(3).trim());\r
714 \r
715         cldsVfKPIData.setThresholdName(record.get(4).trim());\r
716         cldsVfKPIData.setThresholdValue(record.get(5).trim());\r
717         return cldsVfKPIData;\r
718 \r
719     }\r
720 \r
721     // Method to get the artifactURL Data and set the CldsVfKPIData node\r
722     private List<CldsVfKPIData> parseCsvToGetFieldPath(String allFieldPathValues) {\r
723         try {\r
724             List<CldsVfKPIData> cldsVfKPIDataList = new ArrayList<>();\r
725             Reader alarmReader = new StringReader(allFieldPathValues);\r
726             Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(alarmReader);\r
727             if (records != null) {\r
728                 for (CSVRecord record : records) {\r
729                     CldsVfKPIData kpiData = this.convertCsvRecordToKpiData(record);\r
730                     if (kpiData != null) {\r
731                         cldsVfKPIDataList.add(kpiData);\r
732                     }\r
733                 }\r
734             }\r
735             return cldsVfKPIDataList;\r
736         } catch (IOException e) {\r
737             logger.error("Exception when attempting to parse the CSV containing the alarm kpi data", e);\r
738             return new ArrayList<>();\r
739         }\r
740     }\r
741 \r
742     private void processRecord(List<CldsAlarmCondition> cldsAlarmConditionList, CSVRecord record) {\r
743         if (record == null) {\r
744             return;\r
745         }\r
746         if (record.size() < 5) {\r
747             logger.debug("invalid csv alarm Record,total columns less than 5: " + record);\r
748             return;\r
749         }\r
750         if (StringUtils.isBlank(record.get(1)) || StringUtils.isBlank(record.get(3))\r
751                 || StringUtils.isBlank(record.get(4))) {\r
752             logger.debug("invalid csv alarm Record,one of column is having blank value : " + record);\r
753             return;\r
754         }\r
755         CldsAlarmCondition cldsAlarmCondition = new CldsAlarmCondition();\r
756         cldsAlarmCondition.setEventSourceType(record.get(1));\r
757         cldsAlarmCondition.setEventName(record.get(2));\r
758         cldsAlarmCondition.setAlarmConditionKey(record.get(3));\r
759         cldsAlarmCondition.setSeverity(record.get(4));\r
760         cldsAlarmConditionList.add(cldsAlarmCondition);\r
761     }\r
762 \r
763     public String getResponsesFromArtifactUrl(String artifactsUrl) {\r
764         String hostUrl = refProp.getStringValue("sdc.hostUrl");\r
765         String artifactsUrlReworked = artifactsUrl.replaceAll("\"", "");\r
766         String artifactUrl = hostUrl + artifactsUrlReworked;\r
767         logger.info("value of artifactURl:" + artifactUrl);\r
768         String currArtifactResponse = getCldsServicesOrResourcesBasedOnURL(artifactUrl, true);\r
769         logger.info("value of artifactResponse:" + currArtifactResponse);\r
770         return currArtifactResponse;\r
771     }\r
772 \r
773     /**\r
774      * Service to services/resources/artifacts from sdc.Pass alarmConditions as\r
775      * true to get alarmconditons from artifact url and else it is false\r
776      *\r
777      * @param url\r
778      * @param alarmConditions\r
779      * @return\r
780      */\r
781     public String getCldsServicesOrResourcesBasedOnURL(String url, boolean alarmConditions) {\r
782         try {\r
783             String urlReworked = removeUnwantedBracesFromString(url);\r
784             URL urlObj = new URL(urlReworked);\r
785 \r
786             HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();\r
787             String basicAuth = SdcReq.getSdcBasicAuth(refProp);\r
788             conn.setRequestProperty(refProp.getStringValue("sdc.InstanceID"), "CLAMP-Tool");\r
789             conn.setRequestProperty("Authorization", basicAuth);\r
790             conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");\r
791             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
792             conn.setRequestMethod("GET");\r
793 \r
794             int responseCode = conn.getResponseCode();\r
795             logger.info("responseCode=" + responseCode);\r
796             StringBuilder response;\r
797             try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {\r
798                 response = new StringBuilder();\r
799                 String inputLine;\r
800                 while ((inputLine = in.readLine()) != null) {\r
801                     if (!inputLine.isEmpty()) {\r
802                         response.append(inputLine);\r
803                     }\r
804                     if (alarmConditions) {\r
805                         response.append("\n");\r
806                     }\r
807                 }\r
808             }\r
809             return response.toString();\r
810         } catch (IOException e) {\r
811             logger.error("Exception occurred during query to SDC", e);\r
812             return "";\r
813         }\r
814 \r
815     }\r
816 \r
817     /**\r
818      * To create properties object by using cldsServicedata.\r
819      *\r
820      * @param globalProps\r
821      * @param cldsServiceData\r
822      * @return\r
823      */\r
824     public String createPropertiesObjectByUUID(String globalProps, CldsServiceData cldsServiceData) {\r
825         String totalPropsStr;\r
826         ObjectMapper mapper = new ObjectMapper();\r
827         ObjectNode globalPropsJson;\r
828         if (cldsServiceData != null && cldsServiceData.getServiceUUID() != null) {\r
829 \r
830             // Objectnode to save all byservice, byvf , byvfc and byalarm nodes\r
831             ObjectNode byIdObjectNode = mapper.createObjectNode();\r
832 \r
833             // To create vf ResourceUUID node with serviceInvariantUUID\r
834             ObjectNode invariantUuidObjectNodeWithVf = createVfObjectNodeByServiceInvariantUuid(mapper,\r
835                     cldsServiceData);\r
836             byIdObjectNode.putPOJO("byService", invariantUuidObjectNodeWithVf);\r
837 \r
838             // To create byVf and vfcResourceNode with vfResourceUUID\r
839             ObjectNode vfcObjectNodeByVfUuid = createVfcObjectNodeByVfUuid(mapper, cldsServiceData.getCldsVfs());\r
840             byIdObjectNode.putPOJO("byVf", vfcObjectNodeByVfUuid);\r
841 \r
842             // To create byKpi\r
843             ObjectNode kpiObjectNode = mapper.createObjectNode();\r
844             if (cldsServiceData.getCldsVfs() != null && !cldsServiceData.getCldsVfs().isEmpty()) {\r
845                 for (CldsVfData currCldsVfData : cldsServiceData.getCldsVfs()) {\r
846                     if (currCldsVfData != null) {\r
847                         createKpiObjectNodeByVfUuid(mapper, kpiObjectNode, currCldsVfData.getCldsKPIList());\r
848                     }\r
849                 }\r
850             }\r
851             byIdObjectNode.putPOJO("byKpi", kpiObjectNode);\r
852 \r
853             // To create byVfc and alarmCondition with vfcResourceUUID\r
854             ObjectNode vfcResourceUuidObjectNode = mapper.createObjectNode();\r
855             if (cldsServiceData.getCldsVfs() != null && !cldsServiceData.getCldsVfs().isEmpty()) {\r
856                 for (CldsVfData currCldsVfData : cldsServiceData.getCldsVfs()) {\r
857                     if (currCldsVfData != null) {\r
858                         createAlarmCondObjectNodeByVfcUuid(mapper, vfcResourceUuidObjectNode,\r
859                                 currCldsVfData.getCldsVfcs());\r
860                     }\r
861                 }\r
862             }\r
863             byIdObjectNode.putPOJO("byVfc", vfcResourceUuidObjectNode);\r
864 \r
865             // To create byAlarmCondition with alarmConditionKey\r
866             List<CldsAlarmCondition> allAlarmConditions = getAllAlarmConditionsFromCldsServiceData(cldsServiceData,\r
867                     "alarmCondition");\r
868             ObjectNode alarmCondObjectNodeByAlarmKey = createAlarmCondObjectNodeByAlarmKey(mapper, allAlarmConditions);\r
869 \r
870             byIdObjectNode.putPOJO("byAlarmCondition", alarmCondObjectNodeByAlarmKey);\r
871 \r
872             // To create byAlertDescription with AlertDescription\r
873             List<CldsAlarmCondition> allAlertDescriptions = getAllAlarmConditionsFromCldsServiceData(cldsServiceData,\r
874                     "alertDescription");\r
875             ObjectNode alertDescObjectNodeByAlert = createAlarmCondObjectNodeByAlarmKey(mapper, allAlertDescriptions);\r
876 \r
877             byIdObjectNode.putPOJO("byAlertDescription", alertDescObjectNodeByAlert);\r
878 \r
879             globalPropsJson = decodeGlobalProp(globalProps, mapper);\r
880 \r
881             globalPropsJson.putPOJO("shared", byIdObjectNode);\r
882             logger.info("value of objNode:" + globalPropsJson);\r
883         } else {\r
884             /**\r
885              * to create json with total properties when no serviceUUID passed\r
886              */\r
887             globalPropsJson = decodeGlobalProp(globalProps, mapper);\r
888         }\r
889         totalPropsStr = globalPropsJson.toString();\r
890         return totalPropsStr;\r
891     }\r
892 \r
893     private ObjectNode decodeGlobalProp(String globalProps, ObjectMapper mapper) {\r
894         try {\r
895             return (ObjectNode) mapper.readValue(globalProps, JsonNode.class);\r
896         } catch (IOException e) {\r
897             logger.error("Exception occurred during decoding of the global props, returning an empty objectNode", e);\r
898             return mapper.createObjectNode();\r
899         }\r
900     }\r
901 \r
902     /**\r
903      * Method to get alarm conditions/alert description from Service Data.\r
904      * \r
905      * @param cldsServiceData\r
906      *            CldsServiceData the Service Data to analyze\r
907      * @param eventName\r
908      *            The String event name that will be used to filter the alarm\r
909      *            list\r
910      * @return The list of CldsAlarmCondition for the event name specified\r
911      */\r
912     public List<CldsAlarmCondition> getAllAlarmConditionsFromCldsServiceData(CldsServiceData cldsServiceData,\r
913             String eventName) {\r
914         List<CldsAlarmCondition> alarmCondList = new ArrayList<>();\r
915         if (cldsServiceData != null && cldsServiceData.getCldsVfs() != null\r
916                 && !cldsServiceData.getCldsVfs().isEmpty()) {\r
917             for (CldsVfData currCldsVfData : cldsServiceData.getCldsVfs()) {\r
918                 alarmCondList.addAll(getAllAlarmConditionsFromCldsVfData(currCldsVfData, eventName));\r
919             }\r
920         }\r
921         return alarmCondList;\r
922     }\r
923 \r
924     /**\r
925      * Method to get alarm conditions/alert description from VF Data.\r
926      * \r
927      * @param currCldsVfData\r
928      *            The Vf Data to analyze\r
929      * @param eventName\r
930      *            The String event name that will be used to filter the alarm\r
931      *            list\r
932      * @return The list of CldsAlarmCondition for the event name specified\r
933      */\r
934     private List<CldsAlarmCondition> getAllAlarmConditionsFromCldsVfData(CldsVfData currCldsVfData, String eventName) {\r
935         List<CldsAlarmCondition> alarmCondList = new ArrayList<>();\r
936 \r
937         if (currCldsVfData != null && currCldsVfData.getCldsVfcs() != null && !currCldsVfData.getCldsVfcs().isEmpty()) {\r
938             for (CldsVfcData currCldsVfcData : currCldsVfData.getCldsVfcs()) {\r
939                 alarmCondList.addAll(getAllAlarmConditionsFromCldsVfcData(currCldsVfcData, eventName));\r
940             }\r
941         }\r
942         return alarmCondList;\r
943     }\r
944 \r
945     /**\r
946      * Method to get alarm conditions/alert description from VFC Data.\r
947      * \r
948      * @param currCldsVfcData\r
949      *            The VfC Data to analyze\r
950      * @param eventName\r
951      *            The String event name that will be used to filter the alarm\r
952      *            list\r
953      * @return The list of CldsAlarmCondition for the event name specified\r
954      */\r
955     private List<CldsAlarmCondition> getAllAlarmConditionsFromCldsVfcData(CldsVfcData currCldsVfcData,\r
956             String eventName) {\r
957         List<CldsAlarmCondition> alarmCondList = new ArrayList<>();\r
958 \r
959         if (currCldsVfcData != null && currCldsVfcData.getCldsAlarmConditions() != null\r
960                 && !currCldsVfcData.getCldsAlarmConditions().isEmpty()) {\r
961             for (CldsAlarmCondition currCldsAlarmCondition : currCldsVfcData.getCldsAlarmConditions()) {\r
962                 if (currCldsAlarmCondition != null\r
963                         && currCldsAlarmCondition.getEventName().equalsIgnoreCase(eventName)) {\r
964                     alarmCondList.add(currCldsAlarmCondition);\r
965                 }\r
966             }\r
967         }\r
968         return alarmCondList;\r
969     }\r
970 \r
971     private ObjectNode createAlarmCondObjectNodeByAlarmKey(ObjectMapper mapper,\r
972             List<CldsAlarmCondition> cldsAlarmCondList) {\r
973         ObjectNode alarmCondKeyNode = mapper.createObjectNode();\r
974 \r
975         if (cldsAlarmCondList != null && !cldsAlarmCondList.isEmpty()) {\r
976             for (CldsAlarmCondition currCldsAlarmCondition : cldsAlarmCondList) {\r
977                 if (currCldsAlarmCondition != null) {\r
978                     ObjectNode alarmCondNode = mapper.createObjectNode();\r
979                     alarmCondNode.put("eventSourceType", currCldsAlarmCondition.getEventSourceType());\r
980                     alarmCondNode.put("eventSeverity", currCldsAlarmCondition.getSeverity());\r
981                     alarmCondKeyNode.putPOJO(currCldsAlarmCondition.getAlarmConditionKey(), alarmCondNode);\r
982                 }\r
983             }\r
984         } else {\r
985             ObjectNode alarmCondNode = mapper.createObjectNode();\r
986             alarmCondNode.put("eventSourceType", "");\r
987             alarmCondNode.put("eventSeverity", "");\r
988             alarmCondKeyNode.putPOJO("", alarmCondNode);\r
989         }\r
990         return alarmCondKeyNode;\r
991     }\r
992 \r
993     private ObjectNode createVfObjectNodeByServiceInvariantUuid(ObjectMapper mapper, CldsServiceData cldsServiceData) {\r
994         ObjectNode invariantUuidObjectNode = mapper.createObjectNode();\r
995         ObjectNode vfObjectNode = mapper.createObjectNode();\r
996         ObjectNode vfUuidNode = mapper.createObjectNode();\r
997         List<CldsVfData> cldsVfsList = cldsServiceData.getCldsVfs();\r
998         if (cldsVfsList != null && !cldsVfsList.isEmpty()) {\r
999             for (CldsVfData currCldsVfData : cldsVfsList) {\r
1000                 if (currCldsVfData != null) {\r
1001                     vfUuidNode.put(currCldsVfData.getVfInvariantResourceUUID(), currCldsVfData.getVfName());\r
1002                 }\r
1003             }\r
1004         } else {\r
1005             vfUuidNode.put("", "");\r
1006         }\r
1007         vfObjectNode.putPOJO("vf", vfUuidNode);\r
1008         invariantUuidObjectNode.putPOJO(cldsServiceData.getServiceInvariantUUID(), vfObjectNode);\r
1009         return invariantUuidObjectNode;\r
1010     }\r
1011 \r
1012     private void createKpiObjectNodeByVfUuid(ObjectMapper mapper, ObjectNode vfResourceUuidObjectNode,\r
1013             List<CldsVfKPIData> cldsVfKpiDataList) {\r
1014         if (cldsVfKpiDataList != null && !cldsVfKpiDataList.isEmpty()) {\r
1015             for (CldsVfKPIData currCldsVfKpiData : cldsVfKpiDataList) {\r
1016                 if (currCldsVfKpiData != null) {\r
1017                     ObjectNode thresholdNameObjectNode = mapper.createObjectNode();\r
1018 \r
1019                     ObjectNode fieldPathObjectNode = mapper.createObjectNode();\r
1020                     ObjectNode nfNamingCodeNode = mapper.createObjectNode();\r
1021 \r
1022                     fieldPathObjectNode.put(currCldsVfKpiData.getFieldPathValue(),\r
1023                             currCldsVfKpiData.getFieldPathValue());\r
1024                     nfNamingCodeNode.put(currCldsVfKpiData.getNfNamingValue(), currCldsVfKpiData.getNfNamingValue());\r
1025 \r
1026                     thresholdNameObjectNode.putPOJO("fieldPath", fieldPathObjectNode);\r
1027                     thresholdNameObjectNode.putPOJO("nfNamingCode", nfNamingCodeNode);\r
1028 \r
1029                     vfResourceUuidObjectNode.putPOJO(currCldsVfKpiData.getThresholdValue(), thresholdNameObjectNode);\r
1030                 }\r
1031             }\r
1032         }\r
1033     }\r
1034 \r
1035     private void createAlarmCondObjectNodeByVfcUuid(ObjectMapper mapper, ObjectNode vfcResourceUuidObjectNode,\r
1036             List<CldsVfcData> cldsVfcDataList) {\r
1037         ObjectNode vfcObjectNode = mapper.createObjectNode();\r
1038         ObjectNode alarmCondNode = mapper.createObjectNode();\r
1039         ObjectNode alertDescNode = mapper.createObjectNode();\r
1040         if (cldsVfcDataList != null && !cldsVfcDataList.isEmpty()) {\r
1041             for (CldsVfcData currCldsVfcData : cldsVfcDataList) {\r
1042                 if (currCldsVfcData != null) {\r
1043                     if (currCldsVfcData.getCldsAlarmConditions() != null\r
1044                             && !currCldsVfcData.getCldsAlarmConditions().isEmpty()) {\r
1045                         for (CldsAlarmCondition currCldsAlarmCondition : currCldsVfcData.getCldsAlarmConditions()) {\r
1046                             alarmCondNode.put(currCldsAlarmCondition.getAlarmConditionKey(),\r
1047                                     currCldsAlarmCondition.getAlarmConditionKey());\r
1048                             if (currCldsAlarmCondition.getEventName().equalsIgnoreCase("alarmCondition")) {\r
1049                                 alarmCondNode.put(currCldsAlarmCondition.getAlarmConditionKey(),\r
1050                                         currCldsAlarmCondition.getAlarmConditionKey());\r
1051                             } else {\r
1052                                 alertDescNode.put(currCldsAlarmCondition.getAlarmConditionKey(),\r
1053                                         currCldsAlarmCondition.getAlarmConditionKey());\r
1054                             }\r
1055                         }\r
1056                     }\r
1057 \r
1058                     vfcObjectNode.putPOJO("alarmCondition", alarmCondNode);\r
1059                     vfcObjectNode.putPOJO("alertDescription", alertDescNode);\r
1060                     vfcResourceUuidObjectNode.putPOJO(currCldsVfcData.getVfcInvariantResourceUUID(), vfcObjectNode);\r
1061                 }\r
1062             }\r
1063         } else {\r
1064             alarmCondNode.put("", "");\r
1065             vfcObjectNode.putPOJO("alarmCondition", alarmCondNode);\r
1066             alertDescNode.put("", "");\r
1067             vfcObjectNode.putPOJO("alertDescription", alarmCondNode);\r
1068             vfcResourceUuidObjectNode.putPOJO("", vfcObjectNode);\r
1069         }\r
1070     }\r
1071 \r
1072     private ObjectNode createVfcObjectNodeByVfUuid(ObjectMapper mapper, List<CldsVfData> cldsVfDataList) {\r
1073         ObjectNode vfUuidObjectNode = mapper.createObjectNode();\r
1074 \r
1075         if (cldsVfDataList != null && !cldsVfDataList.isEmpty()) {\r
1076             for (CldsVfData currCldsVfData : cldsVfDataList) {\r
1077                 if (currCldsVfData != null) {\r
1078                     ObjectNode vfcObjectNode = mapper.createObjectNode();\r
1079                     ObjectNode vfcUuidNode = mapper.createObjectNode();\r
1080                     if (currCldsVfData.getCldsVfcs() != null && !currCldsVfData.getCldsVfcs().isEmpty()) {\r
1081                         for (CldsVfcData currCldsVfcData : currCldsVfData.getCldsVfcs()) {\r
1082                             vfcUuidNode.put(currCldsVfcData.getVfcInvariantResourceUUID(),\r
1083                                     currCldsVfcData.getVfcName());\r
1084                         }\r
1085                     } else {\r
1086                         vfcUuidNode.put("", "");\r
1087                     }\r
1088                     vfcObjectNode.putPOJO("vfc", vfcUuidNode);\r
1089                     vfUuidObjectNode.putPOJO(currCldsVfData.getVfInvariantResourceUUID(), vfcObjectNode);\r
1090                 }\r
1091             }\r
1092         } else {\r
1093             ObjectNode vfcUuidNode = mapper.createObjectNode();\r
1094             vfcUuidNode.put("", "");\r
1095             ObjectNode vfcObjectNode = mapper.createObjectNode();\r
1096             vfcObjectNode.putPOJO("vfc", vfcUuidNode);\r
1097             vfUuidObjectNode.putPOJO("", vfcObjectNode);\r
1098         }\r
1099         return vfUuidObjectNode;\r
1100     }\r
1101 \r
1102     /**\r
1103      * This method searches the equivalent artifact UUID for a specific\r
1104      * artifactName in a SdcServiceDetail.\r
1105      * \r
1106      * @param cldsSdcServiceDetail\r
1107      *            The SdcServiceDetail that will be analyzed\r
1108      * @param artifactName\r
1109      *            The artifact name that will be searched\r
1110      * @return The artifact UUID found\r
1111      */\r
1112     public String getArtifactIdIfArtifactAlreadyExists(CldsSdcServiceDetail cldsSdcServiceDetail, String artifactName) {\r
1113         String artifactUuid = null;\r
1114         boolean artifactExists = false;\r
1115         if (cldsSdcServiceDetail != null && cldsSdcServiceDetail.getResources() != null\r
1116                 && !cldsSdcServiceDetail.getResources().isEmpty()) {\r
1117             for (CldsSdcResource currCldsSdcResource : cldsSdcServiceDetail.getResources()) {\r
1118                 if (artifactExists) {\r
1119                     break;\r
1120                 }\r
1121                 if (currCldsSdcResource != null && currCldsSdcResource.getArtifacts() != null\r
1122                         && !currCldsSdcResource.getArtifacts().isEmpty()) {\r
1123                     for (CldsSdcArtifact currCldsSdcArtifact : currCldsSdcResource.getArtifacts()) {\r
1124                         if (currCldsSdcArtifact != null && currCldsSdcArtifact.getArtifactName() != null\r
1125                                 && currCldsSdcArtifact.getArtifactName().equalsIgnoreCase(artifactName)) {\r
1126                             artifactUuid = currCldsSdcArtifact.getArtifactUUID();\r
1127                             artifactExists = true;\r
1128                             break;\r
1129                         }\r
1130                     }\r
1131                 }\r
1132             }\r
1133         }\r
1134         return artifactUuid;\r
1135     }\r
1136 \r
1137     public String updateControlLoopStatusToDcae(String dcaeUrl, String invariantResourceUuid,\r
1138             String invariantServiceUuid, String artifactName) {\r
1139         String baseUrl = refProp.getStringValue("sdc.serviceUrl");\r
1140         String basicAuth = SdcReq.getSdcBasicAuth(refProp);\r
1141         String postStatusData = "{ \n" + "\"event\" : \"" + "Created" + "\",\n" + "\"serviceUUID\" : \""\r
1142                 + invariantServiceUuid + "\",\n" + "\"resourceUUID\" :\"" + invariantResourceUuid + "\",\n"\r
1143                 + "\"artifactName\" : \"" + artifactName + "\",\n" + "} \n";\r
1144         try {\r
1145             String url = baseUrl;\r
1146             if (invariantServiceUuid != null) {\r
1147                 url = dcaeUrl + "/closed-loops";\r
1148             }\r
1149             URL urlObj = new URL(url);\r
1150 \r
1151             HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();\r
1152             conn.setRequestProperty(refProp.getStringValue("sdc.InstanceID"), "CLAMP-Tool");\r
1153             conn.setRequestProperty("Authorization", basicAuth);\r
1154             conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");\r
1155             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
1156             conn.setRequestMethod("POST");\r
1157 \r
1158             byte[] postData = SdcReq.stringToByteArray(postStatusData);\r
1159             try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {\r
1160                 wr.write(postData);\r
1161             }\r
1162 \r
1163             int responseCode = conn.getResponseCode();\r
1164             logger.info("responseCode=" + responseCode);\r
1165 \r
1166             String resp = getResponse(conn);\r
1167             if (resp != null) {\r
1168                 return resp;\r
1169             }\r
1170         } catch (IOException e) {\r
1171             logger.error("Not able to get any service information from sdc for uuid:" + invariantServiceUuid, e);\r
1172         }\r
1173         return "";\r
1174     }\r
1175 \r
1176     /**\r
1177      * To get all sdc VF/VFC Resources basic info.\r
1178      * \r
1179      * @param resourceType\r
1180      *            The resourceType\r
1181      * @return The list of CldsSdcResourceBasicInfo\r
1182      */\r
1183     private List<CldsSdcResourceBasicInfo> getAllSdcVForVfcResourcesBasedOnResourceType(String resourceType) {\r
1184         String catalogUrl = refProp.getStringValue("sdc.catalog.url");\r
1185         String resourceUrl = catalogUrl + "resources?resourceType=" + resourceType;\r
1186         String allSdcVfcResources = getCldsServicesOrResourcesBasedOnURL(resourceUrl, false);\r
1187         return removeDuplicateSdcResourceBasicInfo(getAllSdcResourcesListFromJson(allSdcVfcResources));\r
1188     }\r
1189 \r
1190     private String getResourceUuidFromResourceInvariantUuid(String resourceInvariantUuid,\r
1191             List<CldsSdcResourceBasicInfo> resourceInfoList) {\r
1192         String resourceUuid = null;\r
1193         if (resourceInfoList != null && !resourceInfoList.isEmpty()) {\r
1194             for (CldsSdcResourceBasicInfo currResource : resourceInfoList) {\r
1195                 if (currResource != null && currResource.getInvariantUUID() != null && currResource.getUuid() != null\r
1196                         && currResource.getInvariantUUID().equalsIgnoreCase(resourceInvariantUuid)) {\r
1197                     resourceUuid = currResource.getUuid();\r
1198                     break;\r
1199                 }\r
1200             }\r
1201         }\r
1202         return resourceUuid;\r
1203     }\r
1204 \r
1205     /**\r
1206      * Method to get service invariant uuid from model properties.\r
1207      * \r
1208      * @param props\r
1209      *            The Clds model properties\r
1210      * @return The Service Id\r
1211      */\r
1212     private String getServiceInvariantUuidFromProps(ModelProperties props) {\r
1213         String invariantUuid = "";\r
1214         Global globalProps = props.getGlobal();\r
1215         if (globalProps != null && globalProps.getService() != null) {\r
1216             invariantUuid = globalProps.getService();\r
1217         }\r
1218         return invariantUuid;\r
1219     }\r
1220 \r
1221     /**\r
1222      * This method upload the BluePrint to SDC.\r
1223      * \r
1224      * @param prop\r
1225      *            The Clds model Properties\r
1226      * @param userid\r
1227      *            The user id for SDC\r
1228      * @param sdcReqUrlsList\r
1229      *            The list of SDC URL to try\r
1230      * @param formattedSdcReq\r
1231      *            The blueprint to upload\r
1232      * @param formattedSdcLocationReq\r
1233      *            THe location Blueprint to upload\r
1234      * @param artifactName\r
1235      *            The artifact name from where we can get the Artifact UUID\r
1236      * @param locationArtifactName\r
1237      *            The location artifact name from where we can get the Artifact\r
1238      *            UUID\r
1239      * \r
1240      */\r
1241     public void uploadToSdc(ModelProperties prop, String userid, List<String> sdcReqUrlsList, String formattedSdcReq,\r
1242             String formattedSdcLocationReq, String artifactName, String locationArtifactName) {\r
1243         logger.info("userid=" + userid);\r
1244         String serviceInvariantUuid = getServiceInvariantUuidFromProps(prop);\r
1245         if (sdcReqUrlsList != null && !sdcReqUrlsList.isEmpty()) {\r
1246             for (String url : sdcReqUrlsList) {\r
1247                 if (url != null) {\r
1248                     String originalServiceUuid = getServiceUuidFromServiceInvariantId(serviceInvariantUuid);\r
1249                     logger.info("ServiceUUID used before upload in url:" + originalServiceUuid);\r
1250                     String sdcServicesInformation = getSdcServicesInformation(originalServiceUuid);\r
1251                     CldsSdcServiceDetail cldsSdcServiceDetail = getCldsSdcServiceDetailFromJson(sdcServicesInformation);\r
1252                     String uploadedArtifactUuid = getArtifactIdIfArtifactAlreadyExists(cldsSdcServiceDetail,\r
1253                             artifactName);\r
1254                     // Upload artifacts to sdc\r
1255                     String updateUrl = uploadedArtifactUuid != null ? url + "/" + uploadedArtifactUuid : url;\r
1256                     String responseStr = uploadArtifactToSdc(prop, userid, updateUrl, formattedSdcReq);\r
1257                     logger.info("value of sdc Response of uploading to sdc :" + responseStr);\r
1258                     String updatedServiceUuid = getServiceUuidFromServiceInvariantId(serviceInvariantUuid);\r
1259                     if (!originalServiceUuid.equalsIgnoreCase(updatedServiceUuid)) {\r
1260                         url = url.replace(originalServiceUuid, updatedServiceUuid);\r
1261                     }\r
1262                     logger.info("ServiceUUID used after upload in ulr:" + updatedServiceUuid);\r
1263                     sdcServicesInformation = getSdcServicesInformation(updatedServiceUuid);\r
1264                     cldsSdcServiceDetail = getCldsSdcServiceDetailFromJson(sdcServicesInformation);\r
1265                     uploadedArtifactUuid = getArtifactIdIfArtifactAlreadyExists(cldsSdcServiceDetail,\r
1266                             locationArtifactName);\r
1267                     // To send location information also to sdc\r
1268                     updateUrl = uploadedArtifactUuid != null ? url + "/" + uploadedArtifactUuid : url;\r
1269                     responseStr = uploadArtifactToSdc(prop, userid, updateUrl, formattedSdcLocationReq);\r
1270                     logger.info("value of sdc Response of uploading location to sdc :" + responseStr);\r
1271                 }\r
1272             }\r
1273         }\r
1274     }\r
1275 }\r