Fix Sonar bugs
[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.core.JsonProcessingException;\r
29 import com.fasterxml.jackson.databind.JsonNode;\r
30 import com.fasterxml.jackson.databind.ObjectMapper;\r
31 import com.fasterxml.jackson.databind.node.ArrayNode;\r
32 import com.fasterxml.jackson.databind.node.ObjectNode;\r
33 import com.fasterxml.jackson.databind.node.TextNode;\r
34 \r
35 import java.io.BufferedReader;\r
36 import java.io.DataOutputStream;\r
37 import java.io.IOException;\r
38 import java.io.InputStream;\r
39 import java.io.InputStreamReader;\r
40 import java.io.Reader;\r
41 import java.io.StringReader;\r
42 import java.net.HttpURLConnection;\r
43 import java.net.URL;\r
44 import java.util.ArrayList;\r
45 import java.util.Collections;\r
46 import java.util.Date;\r
47 import java.util.Iterator;\r
48 import java.util.List;\r
49 \r
50 import javax.ws.rs.BadRequestException;\r
51 \r
52 import org.apache.commons.csv.CSVFormat;\r
53 import org.apache.commons.csv.CSVRecord;\r
54 import org.apache.commons.lang3.StringUtils;\r
55 import org.onap.clamp.clds.client.req.SdcReq;\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.size() > 0) {\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.size() > 0) {\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.size() > 0) {\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      * @throws IOException\r
225      *             In case of issues with the JSON decoder\r
226      */\r
227     public String getServiceUuidFromServiceInvariantId(String invariantId) throws IOException {\r
228         String serviceUuid = "";\r
229         String responseStr = getSdcServicesInformation(null);\r
230         List<CldsSdcServiceInfo> rawCldsSdcServicesList = getCldsSdcServicesListFromJson(responseStr);\r
231         List<CldsSdcServiceInfo> cldsSdcServicesList = removeDuplicateServices(rawCldsSdcServicesList);\r
232         if (cldsSdcServicesList != null && cldsSdcServicesList.size() > 0) {\r
233             for (CldsSdcServiceInfo currCldsSdcServiceInfo : cldsSdcServicesList) {\r
234                 if (currCldsSdcServiceInfo != null && currCldsSdcServiceInfo.getInvariantUUID() != null\r
235                         && currCldsSdcServiceInfo.getInvariantUUID().equalsIgnoreCase(invariantId)) {\r
236                     serviceUuid = currCldsSdcServiceInfo.getUuid();\r
237                     break;\r
238                 }\r
239             }\r
240         }\r
241         return serviceUuid;\r
242     }\r
243 \r
244     /**\r
245      * To get CldsAsdsServiceInfo class by parsing json string.\r
246      *\r
247      * @param jsonStr\r
248      * @return\r
249      * @throws IOException\r
250      */\r
251     public List<CldsSdcServiceInfo> getCldsSdcServicesListFromJson(String jsonStr) throws IOException {\r
252         ObjectMapper objectMapper = new ObjectMapper();\r
253         if (StringUtils.isBlank(jsonStr)) {\r
254             return null;\r
255         }\r
256         return objectMapper.readValue(jsonStr,\r
257                 objectMapper.getTypeFactory().constructCollectionType(List.class, CldsSdcServiceInfo.class));\r
258     }\r
259 \r
260     /**\r
261      * To get List of CldsSdcResourceBasicInfo class by parsing json string.\r
262      *\r
263      * @param jsonStr\r
264      * @return\r
265      * @throws IOException\r
266      */\r
267     public List<CldsSdcResourceBasicInfo> getAllSdcResourcesListFromJson(String jsonStr) throws IOException {\r
268         ObjectMapper objectMapper = new ObjectMapper();\r
269         if (StringUtils.isBlank(jsonStr)) {\r
270             return null;\r
271         }\r
272         return objectMapper.readValue(jsonStr,\r
273                 objectMapper.getTypeFactory().constructCollectionType(List.class, CldsSdcResourceBasicInfo.class));\r
274     }\r
275 \r
276     /**\r
277      * To get CldsAsdsResource class by parsing json string.\r
278      *\r
279      * @param jsonStr\r
280      * @return\r
281      * @throws IOException\r
282      */\r
283     public CldsSdcResource getCldsSdcResourceFromJson(String jsonStr) throws IOException {\r
284         ObjectMapper objectMapper = new ObjectMapper();\r
285         return objectMapper.readValue(jsonStr, CldsSdcResource.class);\r
286     }\r
287 \r
288     /**\r
289      * To get CldsSdcServiceDetail by parsing json string.\r
290      *\r
291      * @param jsonStr\r
292      * @return\r
293      * @throws IOException\r
294      */\r
295     public CldsSdcServiceDetail getCldsSdcServiceDetailFromJson(String jsonStr) throws IOException {\r
296         ObjectMapper objectMapper = new ObjectMapper();\r
297         return objectMapper.readValue(jsonStr, CldsSdcServiceDetail.class);\r
298     }\r
299 \r
300     /**\r
301      * To upload artifact to sdc based on serviceUUID and resourcename on url.\r
302      *\r
303      * @param prop\r
304      * @param userid\r
305      * @param url\r
306      * @param formatttedSdcReq\r
307      * @return\r
308      * @throws IOException\r
309      */\r
310     public String uploadArtifactToSdc(ModelProperties prop, String userid, String url, String formatttedSdcReq)\r
311             throws IOException {\r
312         // Verify whether it is triggered by Validation Test button from UI\r
313         if (prop.isTest()) {\r
314             return "sdc artifact upload not executed for test action";\r
315         }\r
316         logger.info("userid=" + userid);\r
317         String md5Text = SdcReq.calculateMD5ByString(formatttedSdcReq);\r
318         byte[] postData = SdcReq.stringToByteArray(formatttedSdcReq);\r
319         int postDataLength = postData.length;\r
320         HttpURLConnection conn = getSdcHttpUrlConnection(userid, postDataLength, url, md5Text);\r
321         try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {\r
322             wr.write(postData);\r
323         }\r
324         boolean requestFailed = true;\r
325         int responseCode = conn.getResponseCode();\r
326         logger.info("responseCode=" + responseCode);\r
327         if (responseCode == 200) {\r
328             requestFailed = false;\r
329         }\r
330 \r
331         String responseStr = getResponse(conn);\r
332         if (responseStr != null) {\r
333             if (requestFailed) {\r
334                 logger.error("requestFailed - responseStr=" + responseStr);\r
335                 throw new BadRequestException(responseStr);\r
336             }\r
337         }\r
338         return responseStr;\r
339     }\r
340 \r
341     private HttpURLConnection getSdcHttpUrlConnection(String userid, int postDataLength, String url, String md5Text)\r
342             throws IOException {\r
343         logger.info("userid=" + userid);\r
344         String basicAuth = SdcReq.getSdcBasicAuth(refProp);\r
345         String sdcXonapInstanceId = refProp.getStringValue("sdc.sdcX-InstanceID");\r
346         URL urlObj = new URL(url);\r
347         HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();\r
348         conn.setDoOutput(true);\r
349         conn.setRequestProperty(refProp.getStringValue("sdc.InstanceID"), sdcXonapInstanceId);\r
350         conn.setRequestProperty("Authorization", basicAuth);\r
351         conn.setRequestProperty("Content-Type", "application/json");\r
352         conn.setRequestProperty("Content-MD5", md5Text);\r
353         conn.setRequestProperty("USER_ID", userid);\r
354         conn.setRequestMethod("POST");\r
355         conn.setRequestProperty("charset", "utf-8");\r
356         conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));\r
357         conn.setUseCaches(false);\r
358         conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
359         return conn;\r
360     }\r
361 \r
362     private String getResponse(HttpURLConnection conn) throws IOException {\r
363         try (InputStream is = getInputStream(conn)) {\r
364             if (is != null) {\r
365                 try (BufferedReader in = new BufferedReader(new InputStreamReader(is))) {\r
366                     StringBuilder response = new StringBuilder();\r
367                     String inputLine;\r
368                     while ((inputLine = in.readLine()) != null) {\r
369                         response.append(inputLine);\r
370                     }\r
371                     return response.toString();\r
372                 }\r
373             }\r
374         }\r
375         return null;\r
376     }\r
377 \r
378     private InputStream getInputStream(HttpURLConnection conn) throws IOException {\r
379         InputStream inStream = conn.getErrorStream();\r
380         if (inStream == null) {\r
381             inStream = conn.getInputStream();\r
382         }\r
383         return inStream;\r
384     }\r
385 \r
386     public CldsDBServiceCache getCldsDbServiceCacheUsingCldsServiceData(CldsServiceData cldsServiceData)\r
387             throws IOException {\r
388         CldsDBServiceCache cldsDbServiceCache = new CldsDBServiceCache();\r
389         cldsDbServiceCache.setCldsDataInstream(cldsServiceData);\r
390         cldsDbServiceCache.setInvariantId(cldsServiceData.getServiceInvariantUUID());\r
391         cldsDbServiceCache.setServiceId(cldsServiceData.getServiceUUID());\r
392         return cldsDbServiceCache;\r
393     }\r
394 \r
395     public boolean isCldsSdcCacheDataExpired(CldsServiceData cldsServiceData) throws IOException {\r
396         boolean expired = false;\r
397         if (cldsServiceData != null && cldsServiceData.getServiceUUID() != null) {\r
398             String cachedServiceUuid = cldsServiceData.getServiceUUID();\r
399             String latestServiceUuid = getServiceUuidFromServiceInvariantId(cldsServiceData.getServiceInvariantUUID());\r
400             String defaultRecordAge = refProp.getStringValue("CLDS_SERVICE_CACHE_MAX_SECONDS");\r
401             if ((!cachedServiceUuid.equalsIgnoreCase(latestServiceUuid)) || (cldsServiceData.getAgeOfRecord() != null\r
402                     && cldsServiceData.getAgeOfRecord() > Long.parseLong(defaultRecordAge))) {\r
403                 expired = true;\r
404             }\r
405         } else {\r
406             expired = true;\r
407         }\r
408         return expired;\r
409     }\r
410 \r
411     public CldsServiceData getCldsServiceDataWithAlarmConditions(String invariantServiceUuid) throws IOException {\r
412         String url = refProp.getStringValue("sdc.serviceUrl");\r
413         String catalogUrl = refProp.getStringValue("sdc.catalog.url");\r
414         String serviceUuid = getServiceUuidFromServiceInvariantId(invariantServiceUuid);\r
415         String serviceDetailUrl = url + "/" + serviceUuid + "/metadata";\r
416         String responseStr = getCldsServicesOrResourcesBasedOnURL(serviceDetailUrl, false);\r
417         ObjectMapper objectMapper = new ObjectMapper();\r
418         CldsServiceData cldsServiceData = new CldsServiceData();\r
419         if (responseStr != null) {\r
420             CldsSdcServiceDetail cldsSdcServiceDetail = objectMapper.readValue(responseStr, CldsSdcServiceDetail.class);\r
421             cldsServiceData.setServiceUUID(cldsSdcServiceDetail.getUuid());\r
422             cldsServiceData.setServiceInvariantUUID(cldsSdcServiceDetail.getInvariantUUID());\r
423 \r
424             // To remove duplicate resources from serviceDetail and add valid\r
425             // vfs to service\r
426             if (cldsSdcServiceDetail.getResources() != null) {\r
427                 List<CldsSdcResource> cldsSdcResourceList = removeDuplicateSdcResourceInstances(\r
428                         cldsSdcServiceDetail.getResources());\r
429                 if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {\r
430                     List<CldsVfData> cldsVfDataList = new ArrayList<>();\r
431                     for (CldsSdcResource currCldsSdcResource : cldsSdcResourceList) {\r
432                         if (currCldsSdcResource != null && currCldsSdcResource.getResoucreType() != null\r
433                                 && "VF".equalsIgnoreCase(currCldsSdcResource.getResoucreType())) {\r
434                             CldsVfData currCldsVfData = new CldsVfData();\r
435                             currCldsVfData.setVfName(currCldsSdcResource.getResourceInstanceName());\r
436                             currCldsVfData.setVfInvariantResourceUUID(currCldsSdcResource.getResourceInvariantUUID());\r
437                             cldsVfDataList.add(currCldsVfData);\r
438                         }\r
439                     }\r
440                     cldsServiceData.setCldsVfs(cldsVfDataList);\r
441                     // For each vf in the list , add all vfc's\r
442                     getAllVfcForVfList(cldsVfDataList, catalogUrl);\r
443                     logger.info("value of cldsServiceData:" + cldsServiceData);\r
444                     logger.info("value of cldsServiceData:" + cldsServiceData.getServiceInvariantUUID());\r
445                 }\r
446             }\r
447         }\r
448         return cldsServiceData;\r
449     }\r
450 \r
451     /**\r
452      * @param cldsVfDataList\r
453      * @throws IOException\r
454      */\r
455     private void getAllVfcForVfList(List<CldsVfData> cldsVfDataList, String catalogUrl) throws IOException {\r
456         // todo : refact this..\r
457         if (cldsVfDataList != null && !cldsVfDataList.isEmpty()) {\r
458             List<CldsSdcResourceBasicInfo> allVfResources = getAllSdcVForVfcResourcesBasedOnResourceType(\r
459                     RESOURCE_VF_TYPE);\r
460             List<CldsSdcResourceBasicInfo> allVfcResources = getAllSdcVForVfcResourcesBasedOnResourceType(\r
461                     RESOURCE_VFC_TYPE);\r
462             for (CldsVfData currCldsVfData : cldsVfDataList) {\r
463                 if (currCldsVfData != null && currCldsVfData.getVfInvariantResourceUUID() != null) {\r
464                     String resourceUuid = getResourceUuidFromResourceInvariantUuid(\r
465                             currCldsVfData.getVfInvariantResourceUUID(), allVfResources);\r
466                     if (resourceUuid != null) {\r
467                         String vfResourceUuidUrl = catalogUrl + "resources" + "/" + resourceUuid + "/metadata";\r
468                         String vfResponse = getCldsServicesOrResourcesBasedOnURL(vfResourceUuidUrl, false);\r
469                         if (vfResponse != null) {\r
470                             // Below 2 line are to get the KPI(field path) data\r
471                             // associated with the VF's\r
472                             List<CldsVfKPIData> cldsVfKPIDataList = getFieldPathFromVF(vfResponse);\r
473                             currCldsVfData.setCldsKPIList(cldsVfKPIDataList);\r
474 \r
475                             List<CldsVfcData> vfcDataListFromVfResponse = getVfcDataListFromVfResponse(vfResponse);\r
476                             if (vfcDataListFromVfResponse != null) {\r
477                                 currCldsVfData.setCldsVfcs(vfcDataListFromVfResponse);\r
478                                 if (!vfcDataListFromVfResponse.isEmpty()) {\r
479                                     // To get artifacts for every VFC and get\r
480                                     // alarm conditions from artifact\r
481                                     for (CldsVfcData currCldsVfcData : vfcDataListFromVfResponse) {\r
482                                         if (currCldsVfcData != null\r
483                                                 && currCldsVfcData.getVfcInvariantResourceUUID() != null) {\r
484                                             String resourceVfcUuid = getResourceUuidFromResourceInvariantUuid(\r
485                                                     currCldsVfcData.getVfcInvariantResourceUUID(), allVfcResources);\r
486                                             if (resourceVfcUuid != null) {\r
487                                                 String vfcResourceUuidUrl = catalogUrl + "resources" + "/"\r
488                                                         + resourceVfcUuid + "/metadata";\r
489                                                 String vfcResponse = getCldsServicesOrResourcesBasedOnURL(\r
490                                                         vfcResourceUuidUrl, false);\r
491                                                 if (vfcResponse != null) {\r
492                                                     List<CldsAlarmCondition> alarmCondtionsFromVfc = getAlarmCondtionsFromVfc(\r
493                                                             vfcResponse);\r
494                                                     currCldsVfcData.setCldsAlarmConditions(alarmCondtionsFromVfc);\r
495                                                 }\r
496                                             } else {\r
497                                                 logger.info("No resourceVFC UUID found for given invariantID:"\r
498                                                         + currCldsVfcData.getVfcInvariantResourceUUID());\r
499                                             }\r
500                                         }\r
501                                     }\r
502                                 }\r
503                             }\r
504                         }\r
505                     } else {\r
506                         logger.info("No resourceUUID found for given invariantREsourceUUID:"\r
507                                 + currCldsVfData.getVfInvariantResourceUUID());\r
508                     }\r
509                 }\r
510             }\r
511         }\r
512     }\r
513 \r
514     private List<CldsVfcData> getVfcDataListFromVfResponse(String vfResponse) throws IOException {\r
515         ObjectMapper mapper = new ObjectMapper();\r
516         ObjectNode vfResponseNode = (ObjectNode) mapper.readTree(vfResponse);\r
517         ArrayNode vfcArrayNode = (ArrayNode) vfResponseNode.get("resources");\r
518         List<CldsVfcData> cldsVfcDataList = new ArrayList<>();\r
519         if (vfcArrayNode != null) {\r
520             for (JsonNode vfcjsonNode : vfcArrayNode) {\r
521                 CldsVfcData currCldsVfcData = new CldsVfcData();\r
522                 ObjectNode currVfcNode = (ObjectNode) vfcjsonNode;\r
523                 TextNode resourceTypeNode = (TextNode) currVfcNode.get("resoucreType");\r
524                 if (resourceTypeNode != null && "VFC".equalsIgnoreCase(resourceTypeNode.textValue())) {\r
525                     TextNode vfcResourceName = (TextNode) currVfcNode.get("resourceInstanceName");\r
526                     TextNode vfcInvariantResourceUuid = (TextNode) currVfcNode.get("resourceInvariantUUID");\r
527                     currCldsVfcData.setVfcName(vfcResourceName.textValue());\r
528                     currCldsVfcData.setVfcInvariantResourceUUID(vfcInvariantResourceUuid.textValue());\r
529                     cldsVfcDataList.add(currCldsVfcData);\r
530                 } else if (resourceTypeNode != null && "CVFC".equalsIgnoreCase(resourceTypeNode.textValue())) {\r
531                     cldsVfcDataList.addAll(getVFCfromCVFC(currVfcNode.get("resourceUUID").textValue()));\r
532                 }\r
533             }\r
534         }\r
535         return cldsVfcDataList;\r
536     }\r
537 \r
538     private List<CldsVfcData> getVFCfromCVFC(String resourceUUID) {\r
539         String catalogUrl = refProp.getStringValue("sdc.catalog.url");\r
540         List<CldsVfcData> cldsVfcDataList = new ArrayList<>();\r
541 \r
542         if (resourceUUID != null) {\r
543             String vfcResourceUUIDUrl = catalogUrl + "resources" + "/" + resourceUUID + "/metadata";\r
544             try {\r
545                 String vfcResponse = getCldsServicesOrResourcesBasedOnURL(vfcResourceUUIDUrl, false);\r
546                 ObjectMapper mapper = new ObjectMapper();\r
547                 ObjectNode vfResponseNode = (ObjectNode) mapper.readTree(vfcResponse);\r
548                 ArrayNode vfcArrayNode = (ArrayNode) vfResponseNode.get("resources");\r
549 \r
550                 if (vfcArrayNode != null) {\r
551                     for (JsonNode vfcjsonNode : vfcArrayNode) {\r
552                         CldsVfcData currCldsVfcData = new CldsVfcData();\r
553                         ObjectNode currVfcNode = (ObjectNode) vfcjsonNode;\r
554                         TextNode resourceTypeNode = (TextNode) currVfcNode.get("resoucreType");\r
555                         if (resourceTypeNode != null && "VFC".equalsIgnoreCase(resourceTypeNode.textValue())) {\r
556                             TextNode vfcResourceName = (TextNode) currVfcNode.get("resourceInstanceName");\r
557                             TextNode vfcInvariantResourceUUID = (TextNode) currVfcNode.get("resourceInvariantUUID");\r
558                             currCldsVfcData.setVfcName(vfcResourceName.textValue());\r
559                             currCldsVfcData.setVfcInvariantResourceUUID(vfcInvariantResourceUUID.textValue());\r
560                             cldsVfcDataList.add(currCldsVfcData);\r
561                         }\r
562                     }\r
563                 }\r
564             } catch (IOException e) {\r
565                 logger.error("Exception during JSON analyzis", e);\r
566             }\r
567         }\r
568         return cldsVfcDataList;\r
569     }\r
570 \r
571     private String removeUnwantedBracesFromString(String id) {\r
572         String idReworked = "";\r
573         if (id != null && id.contains("\"")) {\r
574             idReworked = id.replaceAll("\"", "");\r
575         }\r
576         return idReworked;\r
577     }\r
578 \r
579     private List<CldsAlarmCondition> getAlarmCondtionsFromVfc(String vfcResponse) throws IOException {\r
580         List<CldsAlarmCondition> cldsAlarmConditionList = new ArrayList<>();\r
581         ObjectMapper mapper = new ObjectMapper();\r
582         ObjectNode vfcResponseNode = (ObjectNode) mapper.readTree(vfcResponse);\r
583         ArrayNode artifactsArrayNode = (ArrayNode) vfcResponseNode.get("artifacts");\r
584 \r
585         if (artifactsArrayNode != null && artifactsArrayNode.size() > 0) {\r
586             for (int index = 0; index < artifactsArrayNode.size(); index++) {\r
587                 ObjectNode currArtifactNode = (ObjectNode) artifactsArrayNode.get(index);\r
588                 TextNode artifactUrlNode = (TextNode) currArtifactNode.get("artifactURL");\r
589                 if (artifactUrlNode != null) {\r
590                     String responsesFromArtifactUrl = getResponsesFromArtifactUrl(artifactUrlNode.textValue());\r
591                     cldsAlarmConditionList.addAll(parseCsvToGetAlarmConditions(responsesFromArtifactUrl));\r
592                     logger.info(responsesFromArtifactUrl);\r
593                 }\r
594             }\r
595         }\r
596         return cldsAlarmConditionList;\r
597     }\r
598 \r
599     private List<CldsAlarmCondition> parseCsvToGetAlarmConditions(String allAlarmCondsValues) throws IOException {\r
600         List<CldsAlarmCondition> cldsAlarmConditionList = new ArrayList<>();\r
601         Reader alarmReader = new StringReader(allAlarmCondsValues);\r
602         Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(alarmReader);\r
603         if (records != null) {\r
604             Iterator<CSVRecord> it = records.iterator();\r
605             if (it.hasNext()) {\r
606                 it.next();\r
607             }\r
608             it.forEachRemaining(record -> processRecord(cldsAlarmConditionList, record));\r
609         }\r
610         return cldsAlarmConditionList;\r
611     }\r
612 \r
613     // Method to get the artifact for any particular VF\r
614     private List<CldsVfKPIData> getFieldPathFromVF(String vfResponse) throws JsonProcessingException, IOException {\r
615         List<CldsVfKPIData> cldsVfKPIDataList = new ArrayList<>();\r
616         ObjectMapper mapper = new ObjectMapper();\r
617         ObjectNode vfResponseNode = (ObjectNode) mapper.readTree(vfResponse);\r
618         ArrayNode artifactsArrayNode = (ArrayNode) vfResponseNode.get("artifacts");\r
619 \r
620         if (artifactsArrayNode != null && artifactsArrayNode.size() > 0) {\r
621             for (int index = 0; index < artifactsArrayNode.size(); index++) {\r
622                 ObjectNode currArtifactNode = (ObjectNode) artifactsArrayNode.get(index);\r
623                 TextNode artifactUrlNode = (TextNode) currArtifactNode.get("artifactURL");\r
624                 TextNode artifactNameNode = (TextNode) currArtifactNode.get("artifactName");\r
625                 String artifactName = "";\r
626                 if (artifactNameNode != null) {\r
627                     artifactName = artifactNameNode.textValue();\r
628                     artifactName = artifactName.substring(artifactName.lastIndexOf(".") + 1);\r
629                 }\r
630                 if (artifactUrlNode != null && artifactName != null && !artifactName.isEmpty()\r
631                         && artifactName.equalsIgnoreCase("csv")) {\r
632                     String responsesFromArtifactUrl = getResponsesFromArtifactUrl(artifactUrlNode.textValue());\r
633                     cldsVfKPIDataList.addAll(parseCsvToGetFieldPath(responsesFromArtifactUrl));\r
634                     logger.info(responsesFromArtifactUrl);\r
635                 }\r
636             }\r
637         }\r
638         return cldsVfKPIDataList;\r
639     }\r
640 \r
641     private CldsVfKPIData convertCsvRecordToKpiData(CSVRecord record) {\r
642         if (record.size() < 6) {\r
643             logger.debug("invalid csv field path Record,total columns less than 6: " + record);\r
644             return null;\r
645         }\r
646 \r
647         if (StringUtils.isBlank(record.get(1)) || StringUtils.isBlank(record.get(3))\r
648                 || StringUtils.isBlank(record.get(5))) {\r
649             logger.debug("Invalid csv field path Record,one of column is having blank value : " + record);\r
650             return null;\r
651         }\r
652 \r
653         CldsVfKPIData cldsVfKPIData = new CldsVfKPIData();\r
654         cldsVfKPIData.setNfNamingCode(record.get(0).trim());\r
655         cldsVfKPIData.setNfNamingValue(record.get(1).trim());\r
656 \r
657         cldsVfKPIData.setFieldPath(record.get(2).trim());\r
658         cldsVfKPIData.setFieldPathValue(record.get(3).trim());\r
659 \r
660         cldsVfKPIData.setThresholdName(record.get(4).trim());\r
661         cldsVfKPIData.setThresholdValue(record.get(5).trim());\r
662         return cldsVfKPIData;\r
663 \r
664     }\r
665 \r
666     // Method to get the artifactURL Data and set the CldsVfKPIData node\r
667     private List<CldsVfKPIData> parseCsvToGetFieldPath(String allFieldPathValues) throws IOException {\r
668         List<CldsVfKPIData> cldsVfKPIDataList = new ArrayList<>();\r
669         Reader alarmReader = new StringReader(allFieldPathValues);\r
670         Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(alarmReader);\r
671         if (records != null) {\r
672             for (CSVRecord record : records) {\r
673                 CldsVfKPIData kpiData = this.convertCsvRecordToKpiData(record);\r
674                 if (kpiData != null) {\r
675                     cldsVfKPIDataList.add(kpiData);\r
676                 }\r
677             }\r
678         }\r
679         return cldsVfKPIDataList;\r
680     }\r
681 \r
682     private void processRecord(List<CldsAlarmCondition> cldsAlarmConditionList, CSVRecord record) {\r
683         if (record == null) {\r
684             return;\r
685         }\r
686         if (record.size() < 5) {\r
687             logger.debug("invalid csv alarm Record,total columns less than 5: " + record);\r
688             return;\r
689         }\r
690         if (StringUtils.isBlank(record.get(1)) || StringUtils.isBlank(record.get(3))\r
691                 || StringUtils.isBlank(record.get(4))) {\r
692             logger.debug("invalid csv alarm Record,one of column is having blank value : " + record);\r
693             return;\r
694         }\r
695         CldsAlarmCondition cldsAlarmCondition = new CldsAlarmCondition();\r
696         cldsAlarmCondition.setEventSourceType(record.get(1));\r
697         cldsAlarmCondition.setEventName(record.get(2));\r
698         cldsAlarmCondition.setAlarmConditionKey(record.get(3));\r
699         cldsAlarmCondition.setSeverity(record.get(4));\r
700         cldsAlarmConditionList.add(cldsAlarmCondition);\r
701     }\r
702 \r
703     public String getResponsesFromArtifactUrl(String artifactsUrl) {\r
704         String hostUrl = refProp.getStringValue("sdc.hostUrl");\r
705         String artifactsUrlReworked = artifactsUrl.replaceAll("\"", "");\r
706         String artifactUrl = hostUrl + artifactsUrlReworked;\r
707         logger.info("value of artifactURl:" + artifactUrl);\r
708         String currArtifactResponse = getCldsServicesOrResourcesBasedOnURL(artifactUrl, true);\r
709         logger.info("value of artifactResponse:" + currArtifactResponse);\r
710         return currArtifactResponse;\r
711     }\r
712 \r
713     /**\r
714      * Service to services/resources/artifacts from sdc.Pass alarmConditions as\r
715      * true to get alarmconditons from artifact url and else it is false\r
716      *\r
717      * @param url\r
718      * @param alarmConditions\r
719      * @return\r
720      * @throws IOException\r
721      */\r
722     public String getCldsServicesOrResourcesBasedOnURL(String url, boolean alarmConditions) {\r
723         try {\r
724             String urlReworked = removeUnwantedBracesFromString(url);\r
725             URL urlObj = new URL(urlReworked);\r
726 \r
727             HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();\r
728             String basicAuth = SdcReq.getSdcBasicAuth(refProp);\r
729             conn.setRequestProperty(refProp.getStringValue("sdc.InstanceID"), "CLAMP-Tool");\r
730             conn.setRequestProperty("Authorization", basicAuth);\r
731             conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");\r
732             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
733             conn.setRequestMethod("GET");\r
734 \r
735             int responseCode = conn.getResponseCode();\r
736             logger.info("responseCode=" + responseCode);\r
737             StringBuilder response;\r
738             try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {\r
739                 response = new StringBuilder();\r
740                 String inputLine;\r
741                 while ((inputLine = in.readLine()) != null) {\r
742                     if (!inputLine.isEmpty()) {\r
743                         response.append(inputLine);\r
744                     }\r
745                     if (alarmConditions) {\r
746                         response.append("\n");\r
747                     }\r
748                 }\r
749             }\r
750             return response.toString();\r
751         } catch (IOException e) {\r
752             logger.error("Exception occurred during query to SDC", e);\r
753             return "";\r
754         }\r
755 \r
756     }\r
757 \r
758     /**\r
759      * To create properties object by using cldsServicedata.\r
760      *\r
761      * @param globalProps\r
762      * @param cldsServiceData\r
763      * @return\r
764      * @throws IOException\r
765      */\r
766     public String createPropertiesObjectByUUID(String globalProps, CldsServiceData cldsServiceData) throws IOException {\r
767         String totalPropsStr;\r
768         ObjectMapper mapper = new ObjectMapper();\r
769         ObjectNode globalPropsJson;\r
770         if (cldsServiceData != null && cldsServiceData.getServiceUUID() != null) {\r
771 \r
772             // Objectnode to save all byservice, byvf , byvfc and byalarm nodes\r
773             ObjectNode byIdObjectNode = mapper.createObjectNode();\r
774 \r
775             // To create vf ResourceUUID node with serviceInvariantUUID\r
776             ObjectNode invariantUuidObjectNodeWithVf = createVfObjectNodeByServiceInvariantUuid(mapper,\r
777                     cldsServiceData);\r
778             byIdObjectNode.putPOJO("byService", invariantUuidObjectNodeWithVf);\r
779 \r
780             // To create byVf and vfcResourceNode with vfResourceUUID\r
781             ObjectNode vfcObjectNodeByVfUuid = createVfcObjectNodeByVfUuid(mapper, cldsServiceData.getCldsVfs());\r
782             byIdObjectNode.putPOJO("byVf", vfcObjectNodeByVfUuid);\r
783 \r
784             // To create byKpi\r
785             ObjectNode kpiObjectNode = mapper.createObjectNode();\r
786             if (cldsServiceData.getCldsVfs() != null && !cldsServiceData.getCldsVfs().isEmpty()) {\r
787                 for (CldsVfData currCldsVfData : cldsServiceData.getCldsVfs()) {\r
788                     if (currCldsVfData != null) {\r
789                         createKpiObjectNodeByVfUuid(mapper, kpiObjectNode, currCldsVfData.getCldsKPIList());\r
790                     }\r
791                 }\r
792             }\r
793             byIdObjectNode.putPOJO("byKpi", kpiObjectNode);\r
794 \r
795             // To create byVfc and alarmCondition with vfcResourceUUID\r
796             ObjectNode vfcResourceUuidObjectNode = mapper.createObjectNode();\r
797             if (cldsServiceData.getCldsVfs() != null && !cldsServiceData.getCldsVfs().isEmpty()) {\r
798                 for (CldsVfData currCldsVfData : cldsServiceData.getCldsVfs()) {\r
799                     if (currCldsVfData != null) {\r
800                         createAlarmCondObjectNodeByVfcUuid(mapper, vfcResourceUuidObjectNode,\r
801                                 currCldsVfData.getCldsVfcs());\r
802                     }\r
803                 }\r
804             }\r
805             byIdObjectNode.putPOJO("byVfc", vfcResourceUuidObjectNode);\r
806 \r
807             // To create byAlarmCondition with alarmConditionKey\r
808             List<CldsAlarmCondition> allAlarmConditions = getAllAlarmConditionsFromCldsServiceData(cldsServiceData,\r
809                     "alarmCondition");\r
810             ObjectNode alarmCondObjectNodeByAlarmKey = createAlarmCondObjectNodeByAlarmKey(mapper, allAlarmConditions);\r
811 \r
812             byIdObjectNode.putPOJO("byAlarmCondition", alarmCondObjectNodeByAlarmKey);\r
813 \r
814             // To create byAlertDescription with AlertDescription\r
815             List<CldsAlarmCondition> allAlertDescriptions = getAllAlarmConditionsFromCldsServiceData(cldsServiceData,\r
816                     "alertDescription");\r
817             ObjectNode alertDescObjectNodeByAlert = createAlarmCondObjectNodeByAlarmKey(mapper, allAlertDescriptions);\r
818 \r
819             byIdObjectNode.putPOJO("byAlertDescription", alertDescObjectNodeByAlert);\r
820 \r
821             globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);\r
822 \r
823             globalPropsJson.putPOJO("shared", byIdObjectNode);\r
824             logger.info("valuie of objNode:" + globalPropsJson);\r
825         } else {\r
826             /**\r
827              * to create json with total properties when no serviceUUID passed\r
828              */\r
829             globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);\r
830         }\r
831         totalPropsStr = globalPropsJson.toString();\r
832         return totalPropsStr;\r
833     }\r
834 \r
835     /**\r
836      * Method to get alarm conditions/alert description from Service Data.\r
837      * \r
838      * @param cldsServiceData\r
839      *            CldsServiceData the Service Data to analyze\r
840      * @param eventName\r
841      *            The String event name that will be used to filter the alarm\r
842      *            list\r
843      * @return The list of CldsAlarmCondition for the event name specified\r
844      */\r
845     public List<CldsAlarmCondition> getAllAlarmConditionsFromCldsServiceData(CldsServiceData cldsServiceData,\r
846             String eventName) {\r
847         List<CldsAlarmCondition> alarmCondList = new ArrayList<>();\r
848         if (cldsServiceData != null && cldsServiceData.getCldsVfs() != null\r
849                 && !cldsServiceData.getCldsVfs().isEmpty()) {\r
850             for (CldsVfData currCldsVfData : cldsServiceData.getCldsVfs()) {\r
851                 alarmCondList.addAll(getAllAlarmConditionsFromCldsVfData(currCldsVfData, eventName));\r
852             }\r
853         }\r
854         return alarmCondList;\r
855     }\r
856 \r
857     /**\r
858      * Method to get alarm conditions/alert description from VF Data.\r
859      * \r
860      * @param currCldsVfData\r
861      *            The Vf Data to analyze\r
862      * @param eventName\r
863      *            The String event name that will be used to filter the alarm\r
864      *            list\r
865      * @return The list of CldsAlarmCondition for the event name specified\r
866      */\r
867     private List<CldsAlarmCondition> getAllAlarmConditionsFromCldsVfData(CldsVfData currCldsVfData, String eventName) {\r
868         List<CldsAlarmCondition> alarmCondList = new ArrayList<>();\r
869 \r
870         if (currCldsVfData != null && currCldsVfData.getCldsVfcs() != null && !currCldsVfData.getCldsVfcs().isEmpty()) {\r
871             for (CldsVfcData currCldsVfcData : currCldsVfData.getCldsVfcs()) {\r
872                 alarmCondList.addAll(getAllAlarmConditionsFromCldsVfcData(currCldsVfcData, eventName));\r
873             }\r
874         }\r
875         return alarmCondList;\r
876     }\r
877 \r
878     /**\r
879      * Method to get alarm conditions/alert description from VFC Data.\r
880      * \r
881      * @param currCldsVfcData\r
882      *            The VfC Data to analyze\r
883      * @param eventName\r
884      *            The String event name that will be used to filter the alarm\r
885      *            list\r
886      * @return The list of CldsAlarmCondition for the event name specified\r
887      */\r
888     private List<CldsAlarmCondition> getAllAlarmConditionsFromCldsVfcData(CldsVfcData currCldsVfcData,\r
889             String eventName) {\r
890         List<CldsAlarmCondition> alarmCondList = new ArrayList<>();\r
891 \r
892         if (currCldsVfcData != null && currCldsVfcData.getCldsAlarmConditions() != null\r
893                 && !currCldsVfcData.getCldsAlarmConditions().isEmpty()) {\r
894             for (CldsAlarmCondition currCldsAlarmCondition : currCldsVfcData.getCldsAlarmConditions()) {\r
895                 if (currCldsAlarmCondition != null\r
896                         && currCldsAlarmCondition.getEventName().equalsIgnoreCase(eventName)) {\r
897                     alarmCondList.add(currCldsAlarmCondition);\r
898                 }\r
899             }\r
900         }\r
901         return alarmCondList;\r
902     }\r
903 \r
904     private ObjectNode createAlarmCondObjectNodeByAlarmKey(ObjectMapper mapper,\r
905             List<CldsAlarmCondition> cldsAlarmCondList) {\r
906         ObjectNode alarmCondKeyNode = mapper.createObjectNode();\r
907 \r
908         if (cldsAlarmCondList != null && !cldsAlarmCondList.isEmpty()) {\r
909             for (CldsAlarmCondition currCldsAlarmCondition : cldsAlarmCondList) {\r
910                 if (currCldsAlarmCondition != null) {\r
911                     ObjectNode alarmCondNode = mapper.createObjectNode();\r
912                     alarmCondNode.put("eventSourceType", currCldsAlarmCondition.getEventSourceType());\r
913                     alarmCondNode.put("eventSeverity", currCldsAlarmCondition.getSeverity());\r
914                     alarmCondKeyNode.putPOJO(currCldsAlarmCondition.getAlarmConditionKey(), alarmCondNode);\r
915                 }\r
916             }\r
917         } else {\r
918             ObjectNode alarmCondNode = mapper.createObjectNode();\r
919             alarmCondNode.put("eventSourceType", "");\r
920             alarmCondNode.put("eventSeverity", "");\r
921             alarmCondKeyNode.putPOJO("", alarmCondNode);\r
922         }\r
923         return alarmCondKeyNode;\r
924     }\r
925 \r
926     private ObjectNode createVfObjectNodeByServiceInvariantUuid(ObjectMapper mapper, CldsServiceData cldsServiceData) {\r
927         ObjectNode invariantUuidObjectNode = mapper.createObjectNode();\r
928         ObjectNode vfObjectNode = mapper.createObjectNode();\r
929         ObjectNode vfUuidNode = mapper.createObjectNode();\r
930         List<CldsVfData> cldsVfsList = cldsServiceData.getCldsVfs();\r
931         if (cldsVfsList != null && !cldsVfsList.isEmpty()) {\r
932             for (CldsVfData currCldsVfData : cldsVfsList) {\r
933                 if (currCldsVfData != null) {\r
934                     vfUuidNode.put(currCldsVfData.getVfInvariantResourceUUID(), currCldsVfData.getVfName());\r
935                 }\r
936             }\r
937         } else {\r
938             vfUuidNode.put("", "");\r
939         }\r
940         vfObjectNode.putPOJO("vf", vfUuidNode);\r
941         invariantUuidObjectNode.putPOJO(cldsServiceData.getServiceInvariantUUID(), vfObjectNode);\r
942         return invariantUuidObjectNode;\r
943     }\r
944 \r
945     private void createKpiObjectNodeByVfUuid(ObjectMapper mapper, ObjectNode vfResourceUuidObjectNode,\r
946             List<CldsVfKPIData> cldsVfKpiDataList) {\r
947         if (cldsVfKpiDataList != null && !cldsVfKpiDataList.isEmpty()) {\r
948             for (CldsVfKPIData currCldsVfKpiData : cldsVfKpiDataList) {\r
949                 if (currCldsVfKpiData != null) {\r
950                     ObjectNode thresholdNameObjectNode = mapper.createObjectNode();\r
951 \r
952                     ObjectNode fieldPathObjectNode = mapper.createObjectNode();\r
953                     ObjectNode nfNamingCodeNode = mapper.createObjectNode();\r
954 \r
955                     fieldPathObjectNode.put(currCldsVfKpiData.getFieldPathValue(),\r
956                             currCldsVfKpiData.getFieldPathValue());\r
957                     nfNamingCodeNode.put(currCldsVfKpiData.getNfNamingValue(), currCldsVfKpiData.getNfNamingValue());\r
958 \r
959                     thresholdNameObjectNode.putPOJO("fieldPath", fieldPathObjectNode);\r
960                     thresholdNameObjectNode.putPOJO("nfNamingCode", nfNamingCodeNode);\r
961 \r
962                     vfResourceUuidObjectNode.putPOJO(currCldsVfKpiData.getThresholdValue(), thresholdNameObjectNode);\r
963                 }\r
964             }\r
965         }\r
966     }\r
967 \r
968     private void createAlarmCondObjectNodeByVfcUuid(ObjectMapper mapper, ObjectNode vfcResourceUuidObjectNode,\r
969             List<CldsVfcData> cldsVfcDataList) {\r
970         ObjectNode vfcObjectNode = mapper.createObjectNode();\r
971         ObjectNode alarmCondNode = mapper.createObjectNode();\r
972         ObjectNode alertDescNode = mapper.createObjectNode();\r
973         if (cldsVfcDataList != null && !cldsVfcDataList.isEmpty()) {\r
974             for (CldsVfcData currCldsVfcData : cldsVfcDataList) {\r
975                 if (currCldsVfcData != null) {\r
976                     if (currCldsVfcData.getCldsAlarmConditions() != null\r
977                             && !currCldsVfcData.getCldsAlarmConditions().isEmpty()) {\r
978                         for (CldsAlarmCondition currCldsAlarmCondition : currCldsVfcData.getCldsAlarmConditions()) {\r
979                             alarmCondNode.put(currCldsAlarmCondition.getAlarmConditionKey(),\r
980                                     currCldsAlarmCondition.getAlarmConditionKey());\r
981                             if (currCldsAlarmCondition.getEventName().equalsIgnoreCase("alarmCondition")) {\r
982                                 alarmCondNode.put(currCldsAlarmCondition.getAlarmConditionKey(),\r
983                                         currCldsAlarmCondition.getAlarmConditionKey());\r
984                             } else {\r
985                                 alertDescNode.put(currCldsAlarmCondition.getAlarmConditionKey(),\r
986                                         currCldsAlarmCondition.getAlarmConditionKey());\r
987                             }\r
988                         }\r
989                     }\r
990                     vfcObjectNode.putPOJO("alarmCondition", alarmCondNode);\r
991                     vfcObjectNode.putPOJO("alertDescription", alertDescNode);\r
992                     vfcResourceUuidObjectNode.putPOJO(currCldsVfcData.getVfcInvariantResourceUUID(), vfcObjectNode);\r
993                 }\r
994             }\r
995         } else {\r
996             alarmCondNode.put("", "");\r
997             vfcObjectNode.putPOJO("alarmCondition", alarmCondNode);\r
998             alertDescNode.put("", "");\r
999             vfcObjectNode.putPOJO("alertDescription", alarmCondNode);\r
1000             vfcResourceUuidObjectNode.putPOJO("", vfcObjectNode);\r
1001         }\r
1002     }\r
1003 \r
1004     private ObjectNode createVfcObjectNodeByVfUuid(ObjectMapper mapper, List<CldsVfData> cldsVfDataList) {\r
1005         ObjectNode vfUuidObjectNode = mapper.createObjectNode();\r
1006 \r
1007         if (cldsVfDataList != null && !cldsVfDataList.isEmpty()) {\r
1008             for (CldsVfData currCldsVfData : cldsVfDataList) {\r
1009                 if (currCldsVfData != null) {\r
1010                     ObjectNode vfcObjectNode = mapper.createObjectNode();\r
1011                     ObjectNode vfcUuidNode = mapper.createObjectNode();\r
1012                     if (currCldsVfData.getCldsVfcs() != null && !currCldsVfData.getCldsVfcs().isEmpty()) {\r
1013                         for (CldsVfcData currCldsVfcData : currCldsVfData.getCldsVfcs()) {\r
1014                             vfcUuidNode.put(currCldsVfcData.getVfcInvariantResourceUUID(),\r
1015                                     currCldsVfcData.getVfcName());\r
1016                         }\r
1017                     } else {\r
1018                         vfcUuidNode.put("", "");\r
1019                     }\r
1020                     vfcObjectNode.putPOJO("vfc", vfcUuidNode);\r
1021                     vfUuidObjectNode.putPOJO(currCldsVfData.getVfInvariantResourceUUID(), vfcObjectNode);\r
1022                 }\r
1023             }\r
1024         } else {\r
1025             ObjectNode vfcUuidNode = mapper.createObjectNode();\r
1026             vfcUuidNode.put("", "");\r
1027             ObjectNode vfcObjectNode = mapper.createObjectNode();\r
1028             vfcObjectNode.putPOJO("vfc", vfcUuidNode);\r
1029             vfUuidObjectNode.putPOJO("", vfcObjectNode);\r
1030         }\r
1031         return vfUuidObjectNode;\r
1032     }\r
1033 \r
1034     /**\r
1035      * This method searches the equivalent artifact UUID for a specific\r
1036      * artifactName in a SdcServiceDetail.\r
1037      * \r
1038      * @param cldsSdcServiceDetail\r
1039      *            The SdcServiceDetail that will be analyzed\r
1040      * @param artifactName\r
1041      *            The artifact name that will be searched\r
1042      * @return The artifact UUID found\r
1043      */\r
1044     public String getArtifactIdIfArtifactAlreadyExists(CldsSdcServiceDetail cldsSdcServiceDetail, String artifactName) {\r
1045         String artifactUuid = null;\r
1046         boolean artifactExists = false;\r
1047         if (cldsSdcServiceDetail != null && cldsSdcServiceDetail.getResources() != null\r
1048                 && !cldsSdcServiceDetail.getResources().isEmpty()) {\r
1049             for (CldsSdcResource currCldsSdcResource : cldsSdcServiceDetail.getResources()) {\r
1050                 if (artifactExists) {\r
1051                     break;\r
1052                 }\r
1053                 if (currCldsSdcResource != null && currCldsSdcResource.getArtifacts() != null\r
1054                         && !currCldsSdcResource.getArtifacts().isEmpty()) {\r
1055                     for (CldsSdcArtifact currCldsSdcArtifact : currCldsSdcResource.getArtifacts()) {\r
1056                         if (currCldsSdcArtifact != null && currCldsSdcArtifact.getArtifactName() != null) {\r
1057                             if (currCldsSdcArtifact.getArtifactName().equalsIgnoreCase(artifactName)) {\r
1058                                 artifactUuid = currCldsSdcArtifact.getArtifactUUID();\r
1059                                 artifactExists = true;\r
1060                                 break;\r
1061                             }\r
1062                         }\r
1063                     }\r
1064                 }\r
1065             }\r
1066         }\r
1067         return artifactUuid;\r
1068     }\r
1069 \r
1070     public String updateControlLoopStatusToDcae(String dcaeUrl, String invariantResourceUuid,\r
1071             String invariantServiceUuid, String artifactName) {\r
1072         String baseUrl = refProp.getStringValue("sdc.serviceUrl");\r
1073         String basicAuth = SdcReq.getSdcBasicAuth(refProp);\r
1074         String postStatusData = "{ \n" + "\"event\" : \"" + "Created" + "\",\n" + "\"serviceUUID\" : \""\r
1075                 + invariantServiceUuid + "\",\n" + "\"resourceUUID\" :\"" + invariantResourceUuid + "\",\n"\r
1076                 + "\"artifactName\" : \"" + artifactName + "\",\n" + "} \n";\r
1077         try {\r
1078             String url = baseUrl;\r
1079             if (invariantServiceUuid != null) {\r
1080                 url = dcaeUrl + "/closed-loops";\r
1081             }\r
1082             URL urlObj = new URL(url);\r
1083 \r
1084             HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();\r
1085             conn.setRequestProperty(refProp.getStringValue("sdc.InstanceID"), "CLAMP-Tool");\r
1086             conn.setRequestProperty("Authorization", basicAuth);\r
1087             conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");\r
1088             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
1089             conn.setRequestMethod("POST");\r
1090 \r
1091             byte[] postData = SdcReq.stringToByteArray(postStatusData);\r
1092             try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {\r
1093                 wr.write(postData);\r
1094             }\r
1095 \r
1096             int responseCode = conn.getResponseCode();\r
1097             logger.info("responseCode=" + responseCode);\r
1098 \r
1099             String resp = getResponse(conn);\r
1100             if (resp != null) {\r
1101                 return resp;\r
1102             }\r
1103         } catch (IOException e) {\r
1104             logger.error("Not able to get any service information from sdc for uuid:" + invariantServiceUuid, e);\r
1105         }\r
1106         return "";\r
1107     }\r
1108 \r
1109     /**\r
1110      * To get all sdc VF/VFC Resources basic info.\r
1111      * \r
1112      * @param resourceType\r
1113      *            The resourceType\r
1114      * @return The list of CldsSdcResourceBasicInfo\r
1115      * @throws IOException\r
1116      *             In case of issues with the Streams\r
1117      */\r
1118     private List<CldsSdcResourceBasicInfo> getAllSdcVForVfcResourcesBasedOnResourceType(String resourceType)\r
1119             throws IOException {\r
1120         List<CldsSdcResourceBasicInfo> allSdcResourceVfcBasicInfo = new ArrayList<CldsSdcResourceBasicInfo>();\r
1121         String catalogUrl = refProp.getStringValue("sdc.catalog.url");\r
1122         String resourceUrl = catalogUrl + "resources?resourceType=" + resourceType;\r
1123         String allSdcVfcResources = getCldsServicesOrResourcesBasedOnURL(resourceUrl, false);\r
1124 \r
1125         allSdcResourceVfcBasicInfo = getAllSdcResourcesListFromJson(allSdcVfcResources);\r
1126         return removeDuplicateSdcResourceBasicInfo(allSdcResourceVfcBasicInfo);\r
1127     }\r
1128 \r
1129     private String getResourceUuidFromResourceInvariantUuid(String resourceInvariantUuid,\r
1130             List<CldsSdcResourceBasicInfo> resourceInfoList) throws IOException {\r
1131         String resourceUuid = null;\r
1132         if (resourceInfoList != null && !resourceInfoList.isEmpty()) {\r
1133             for (CldsSdcResourceBasicInfo currResource : resourceInfoList) {\r
1134                 if (currResource != null && currResource.getInvariantUUID() != null && currResource.getUuid() != null\r
1135                         && currResource.getInvariantUUID().equalsIgnoreCase(resourceInvariantUuid)) {\r
1136                     resourceUuid = currResource.getUuid();\r
1137                     break;\r
1138                 }\r
1139             }\r
1140         }\r
1141         return resourceUuid;\r
1142     }\r
1143 \r
1144     /**\r
1145      * Method to get service invariant uuid from model properties.\r
1146      * \r
1147      * @param props\r
1148      *            The Clds model properties\r
1149      * @return The Service Id\r
1150      */\r
1151     private String getServiceInvariantUuidFromProps(ModelProperties props) {\r
1152         String invariantUuid = "";\r
1153         Global globalProps = props.getGlobal();\r
1154         if (globalProps != null && globalProps.getService() != null) {\r
1155             invariantUuid = globalProps.getService();\r
1156         }\r
1157         return invariantUuid;\r
1158     }\r
1159 \r
1160     /**\r
1161      * This method upload the BluePrint to SDC.\r
1162      * \r
1163      * @param prop\r
1164      *            The Clds model Properties\r
1165      * @param userid\r
1166      *            The user id for SDC\r
1167      * @param sdcReqUrlsList\r
1168      *            The list of SDC URL to try\r
1169      * @param formattedSdcReq\r
1170      *            The blueprint to upload\r
1171      * @param formattedSdcLocationReq\r
1172      *            THe location Blueprint to upload\r
1173      * @param artifactName\r
1174      *            The artifact name from where we can get the Artifact UUID\r
1175      * @param locationArtifactName\r
1176      *            The location artifact name from where we can get the Artifact\r
1177      *            UUID\r
1178      * @throws IOException\r
1179      *             In case of issues with the streams\r
1180      * \r
1181      */\r
1182     public void uploadToSdc(ModelProperties prop, String userid, List<String> sdcReqUrlsList, String formattedSdcReq,\r
1183             String formattedSdcLocationReq, String artifactName, String locationArtifactName) throws IOException {\r
1184         logger.info("userid=" + userid);\r
1185         String serviceInvariantUuid = getServiceInvariantUuidFromProps(prop);\r
1186         if (sdcReqUrlsList != null && !sdcReqUrlsList.isEmpty()) {\r
1187             for (String url : sdcReqUrlsList) {\r
1188                 if (url != null) {\r
1189                     String originalServiceUuid = getServiceUuidFromServiceInvariantId(serviceInvariantUuid);\r
1190                     logger.info("ServiceUUID used before upload in url:" + originalServiceUuid);\r
1191                     String sdcServicesInformation = getSdcServicesInformation(originalServiceUuid);\r
1192                     CldsSdcServiceDetail cldsSdcServiceDetail = getCldsSdcServiceDetailFromJson(sdcServicesInformation);\r
1193                     String uploadedArtifactUuid = getArtifactIdIfArtifactAlreadyExists(cldsSdcServiceDetail,\r
1194                             artifactName);\r
1195                     // Upload artifacts to sdc\r
1196                     String updateUrl = uploadedArtifactUuid != null ? url + "/" + uploadedArtifactUuid : url;\r
1197                     String responseStr = uploadArtifactToSdc(prop, userid, updateUrl, formattedSdcReq);\r
1198                     logger.info("value of sdc Response of uploading to sdc :" + responseStr);\r
1199                     String updatedServiceUuid = getServiceUuidFromServiceInvariantId(serviceInvariantUuid);\r
1200                     if (!originalServiceUuid.equalsIgnoreCase(updatedServiceUuid)) {\r
1201                         url = url.replace(originalServiceUuid, updatedServiceUuid);\r
1202                     }\r
1203                     logger.info("ServiceUUID used after upload in ulr:" + updatedServiceUuid);\r
1204                     sdcServicesInformation = getSdcServicesInformation(updatedServiceUuid);\r
1205                     cldsSdcServiceDetail = getCldsSdcServiceDetailFromJson(sdcServicesInformation);\r
1206                     uploadedArtifactUuid = getArtifactIdIfArtifactAlreadyExists(cldsSdcServiceDetail,\r
1207                             locationArtifactName);\r
1208                     // To send location information also to sdc\r
1209                     updateUrl = uploadedArtifactUuid != null ? url + "/" + uploadedArtifactUuid : url;\r
1210                     responseStr = uploadArtifactToSdc(prop, userid, updateUrl, formattedSdcLocationReq);\r
1211                     logger.info("value of sdc Response of uploading location to sdc :" + responseStr);\r
1212                 }\r
1213             }\r
1214         }\r
1215     }\r
1216 }\r