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