Merge "Sonar improvements and class renaming"
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / SdcReq.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23
24 package org.onap.clamp.clds.client.req;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.core.JsonParseException;
29 import com.fasterxml.jackson.core.JsonProcessingException;
30 import com.fasterxml.jackson.databind.JsonMappingException;
31 import com.fasterxml.jackson.databind.JsonNode;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import com.fasterxml.jackson.databind.node.ArrayNode;
34 import com.fasterxml.jackson.databind.node.ObjectNode;
35 import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;
36
37 import java.io.IOException;
38 import java.nio.charset.StandardCharsets;
39 import java.util.ArrayList;
40 import java.util.Base64;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Map.Entry;
45
46 import org.apache.commons.codec.digest.DigestUtils;
47 import org.camunda.bpm.engine.delegate.DelegateExecution;
48 import org.onap.clamp.clds.client.SdcCatalogServices;
49 import org.onap.clamp.clds.exception.SdcCommunicationException;
50 import org.onap.clamp.clds.model.CldsSdcResource;
51 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
52 import org.onap.clamp.clds.model.prop.Global;
53 import org.onap.clamp.clds.model.prop.ModelProperties;
54 import org.onap.clamp.clds.model.prop.StringMatch;
55 import org.onap.clamp.clds.model.prop.Tca;
56 import org.onap.clamp.clds.model.refprop.RefProp;
57
58 /**
59  * Construct a Sdc request given CLDS objects.
60  */
61 public class SdcReq {
62     protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(SdcReq.class);
63     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
64
65     /**
66      * Format the Blueprint from a Yaml
67      *
68      * @param refProp
69      *            The RefProp instance containing the Clds config
70      * @param prop
71      *            The ModelProperties describing the clds model
72      * @param docText
73      *            The Yaml file that must be converted
74      *
75      * @return A String containing the BluePrint
76      * @throws JsonParseException
77      *             In case of issues
78      * @throws JsonMappingException
79      *             In case of issues
80      * @throws IOException
81      *             In case of issues
82      */
83     public static String formatBlueprint(RefProp refProp, ModelProperties prop, String docText)
84             throws JsonParseException, JsonMappingException, IOException {
85
86         Global globalProp = prop.getGlobal();
87         String service = globalProp.getService();
88
89         String yamlvalue = getYamlvalue(docText);
90
91         String updatedBlueprint = "";
92         StringMatch stringMatch = prop.getType(StringMatch.class);
93         Tca tca = prop.getType(Tca.class);
94         if (stringMatch.isFound()) {
95             prop.setCurrentModelElementId(stringMatch.getId());
96             ObjectMapper objectMapper = new ObjectMapper();
97             ObjectNode serviceConfigurations = objectMapper.createObjectNode();
98
99             StringMatchPolicyReq.appendServiceConfigurations(refProp, service, serviceConfigurations, stringMatch,
100                     prop);
101             logger.info("Value of serviceConfigurations:" + serviceConfigurations);
102             ObjectNode servConfNode = (ObjectNode) serviceConfigurations.get("serviceConfigurations");
103
104             // get updated blueprint by attaching service Conf from
105             // globalProperties
106             updatedBlueprint = getUpdatedBlueprintWithServiceConf(refProp, prop, yamlvalue, servConfNode);
107         } else if (tca.isFound()) {
108             prop.setCurrentModelElementId(tca.getId());
109             ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.template", service);
110             ObjectNode content = rootNode.with("content");
111             TcaMPolicyReq.appendSignatures(refProp, service, content, tca, prop);
112             logger.info("Value of content:" + content);
113             // ObjectNode servConfNode =
114             // (ObjectNode)signatures.get("signatures");
115
116             // get updated blueprint by attaching service Conf from
117             // globalProperties
118             updatedBlueprint = getUpdatedBlueprintWithConfiguration(refProp, prop, yamlvalue, content);
119         }
120
121         logger.info("value of blueprint:" + updatedBlueprint);
122         return updatedBlueprint;
123     }
124
125     private static String getUpdatedBlueprintWithServiceConf(RefProp refProp, ModelProperties prop, String yamlValue,
126             ObjectNode serviceConf) throws IOException {
127         Yaml yaml = new Yaml();
128
129         // Serialiaze Yaml file
130         Map<String, Map> loadedYaml = (Map<String, Map>) yaml.load(yamlValue);
131         // Get node templates information from Yaml
132         Map<String, Map> nodeTemplates = loadedYaml.get("node_templates");
133         logger.info("value of NodeTemplates:" + nodeTemplates);
134
135         // Get StringMatch Object information from node templates of Yaml
136         Map<String, Map> smObject = nodeTemplates.get("SM");
137         logger.info("value of StringMatch:" + smObject);
138
139         // Get Properties Object information from stringmatch of Yaml
140         Map<String, String> propsObject = smObject.get("properties");
141         logger.info("value of PropsObject:" + propsObject);
142
143         String deploymentJsonObject = propsObject.get("deployment_JSON");
144         logger.info("value of deploymentJson:" + deploymentJsonObject);
145
146         ObjectMapper mapper = new ObjectMapper();
147         ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
148         ObjectNode configurationObjectNode = (ObjectNode) deployJsonNode.get("configuration");
149
150         // "policyName":"example_model06.ClosedLoop_FRWL_SIG_0538e6f2_8c1b_4656_9999_3501b3c59ad7_StringMatch_",
151         String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
152         String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
153         configurationObjectNode.put("policyName", policyName);
154
155         // "closedLoopControlName":"ClosedLoop-FRWL-SIG-0538e6f2-8c1b-4656-9999-3501b3c59ad7",
156         configurationObjectNode.put("closedLoopControlName", prop.getControlName());
157         configurationObjectNode.put("messageReaderConsumerGroup", prop.getModelName());
158         configurationObjectNode.set("serviceConfigurations", serviceConf);
159         propsObject.put("deployment_JSON", deployJsonNode.toString());
160         String blueprint = yaml.dump(loadedYaml);
161         logger.info("value of updated Yaml File:" + blueprint);
162
163         blueprint = yaml.dump(loadedYaml);
164         logger.info("value of updated Yaml File:" + blueprint);
165
166         return blueprint;
167     }
168
169     private static String getUpdatedBlueprintWithConfiguration(RefProp refProp, ModelProperties prop, String yamlValue,
170             ObjectNode serviceConf) throws JsonProcessingException, IOException {
171         String blueprint = "";
172         Yaml yaml = new Yaml();
173         // Serialiaze Yaml file
174         Map<String, Map> loadedYaml = (Map<String, Map>) yaml.load(yamlValue);
175         // Get node templates information from Yaml
176         Map<String, Map> nodeTemplates = loadedYaml.get("node_templates");
177         logger.info("value of NodeTemplates:" + nodeTemplates);
178         // Get Tca Object information from node templates of Yaml
179         Map<String, Map> tcaObject = nodeTemplates.get("MTCA");
180         logger.info("value of Tca:" + tcaObject);
181         // Get Properties Object information from tca of Yaml
182         Map<String, String> propsObject = tcaObject.get("properties");
183         logger.info("value of PropsObject:" + propsObject);
184         String deploymentJsonObject = propsObject.get("deployment_JSON");
185         logger.info("value of deploymentJson:" + deploymentJsonObject);
186
187         ObjectMapper mapper = new ObjectMapper();
188
189         ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
190
191         // "policyName":"example_model06.ClosedLoop_FRWL_SIG_0538e6f2_8c1b_4656_9999_3501b3c59ad7_Tca_",
192         String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
193         String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
194         serviceConf.put("policyName", policyName);
195
196         deployJsonNode.set("configuration", serviceConf);
197         propsObject.put("deployment_JSON", deployJsonNode.toString());
198         blueprint = yaml.dump(loadedYaml);
199         logger.info("value of updated Yaml File:" + blueprint);
200
201         return blueprint;
202     }
203
204     public static String formatSdcLocationsReq(ModelProperties prop, String artifactName) {
205         ObjectMapper objectMapper = new ObjectMapper();
206         Global global = prop.getGlobal();
207         List<String> locationsList = global.getLocation();
208         ArrayNode locationsArrayNode = objectMapper.createArrayNode();
209         ObjectNode locationObject = objectMapper.createObjectNode();
210         for (String currLocation : locationsList) {
211             locationsArrayNode.add(currLocation);
212         }
213         locationObject.put("artifactName", artifactName);
214         locationObject.putPOJO("locations", locationsArrayNode);
215         String locationJsonFormat = locationObject.toString();
216         logger.info("Value of locaation Json Artifact:" + locationsArrayNode);
217         return locationJsonFormat;
218     }
219
220     public static String formatSdcReq(String payloadData, String artifactName, String artifactLabel,
221             String artifactType) throws IOException {
222         logger.info("artifact=" + payloadData);
223         String base64Artifact = base64Encode(payloadData);
224         return "{ \n" + "\"payloadData\" : \"" + base64Artifact + "\",\n" + "\"artifactLabel\" : \"" + artifactLabel
225                 + "\",\n" + "\"artifactName\" :\"" + artifactName + "\",\n" + "\"artifactType\" : \"" + artifactType
226                 + "\",\n" + "\"artifactGroupType\" : \"DEPLOYMENT\",\n" + "\"description\" : \"from CLAMP Cockpit\"\n"
227                 + "} \n";
228     }
229
230     public static String getSdcReqUrl(ModelProperties prop, String url) {
231         Global globalProps = prop.getGlobal();
232         String serviceUUID = "";
233         String resourceInstanceName = "";
234         if (globalProps != null) {
235             List<String> resourceVf = globalProps.getResourceVf();
236             if (resourceVf != null && !resourceVf.isEmpty()) {
237                 resourceInstanceName = resourceVf.get(0);
238             }
239             if (globalProps.getService() != null) {
240                 serviceUUID = globalProps.getService();
241             }
242         }
243         String normalizedResourceInstanceName = normalizeResourceInstanceName(resourceInstanceName);
244         return url + "/" + serviceUUID + "/resourceInstances/" + normalizedResourceInstanceName + "/artifacts";
245     }
246
247     /**
248      * To get List of urls for all vfresources
249      *
250      * @param prop
251      * @param baseUrl
252      * @param sdcCatalogServices
253      * @return
254      * @throws Exception
255      */
256     public static List<String> getSdcReqUrlsList(ModelProperties prop, String baseUrl,
257             SdcCatalogServices sdcCatalogServices, DelegateExecution execution) {
258         // TODO : refact and regroup with very similar code
259         List<String> urlList = new ArrayList<>();
260         try {
261         Global globalProps = prop.getGlobal();
262         if (globalProps != null) {
263             if (globalProps.getService() != null) {
264                 String serviceInvariantUUID = globalProps.getService();
265                 execution.setVariable("serviceInvariantUUID", serviceInvariantUUID);
266                 List<String> resourceVfList = globalProps.getResourceVf();
267                 String serviceUUID = sdcCatalogServices.getServiceUuidFromServiceInvariantId(serviceInvariantUUID);
268                 String sdcServicesInformation = sdcCatalogServices.getSdcServicesInformation(serviceUUID);
269                 CldsSdcServiceDetail CldsSdcServiceDetail = sdcCatalogServices
270                         .getCldsSdcServiceDetailFromJson(sdcServicesInformation);
271                 if (CldsSdcServiceDetail != null && resourceVfList != null) {
272                     List<CldsSdcResource> CldsSdcResourcesList = CldsSdcServiceDetail.getResources();
273                         if (CldsSdcResourcesList != null && !CldsSdcResourcesList.isEmpty()) {
274                         for (CldsSdcResource CldsSdcResource : CldsSdcResourcesList) {
275                             if (CldsSdcResource != null && CldsSdcResource.getResoucreType() != null
276                                     && CldsSdcResource.getResoucreType().equalsIgnoreCase("VF")) {
277                                 if (resourceVfList.contains(CldsSdcResource.getResourceInvariantUUID())) {
278                                     String normalizedResourceInstanceName = normalizeResourceInstanceName(
279                                             CldsSdcResource.getResourceInstanceName());
280                                     String svcUrl = baseUrl + "/" + serviceUUID + "/resourceInstances/"
281                                             + normalizedResourceInstanceName + "/artifacts";
282                                     urlList.add(svcUrl);
283                                 }
284                             }
285                         }
286                     }
287                 }
288             }
289         }
290         } catch (IOException e) {
291             throw new SdcCommunicationException("Exception occurred during the SDC communication",e);
292         }
293         return urlList;
294     }
295
296     /**
297      * "Normalize" the resource instance name: - Remove spaces, underscores,
298      * dashes, and periods. - make lower case This is required by SDC when using
299      * the resource instance name to upload an artifact.
300      *
301      * @param inText
302      * @return
303      */
304     public static String normalizeResourceInstanceName(String inText) {
305         return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
306     }
307
308     /**
309      * from michael
310      *
311      * @param data
312      * @return
313      */
314     public static String calculateMD5ByString(String data) {
315         String calculatedMd5 = DigestUtils.md5Hex(data);
316         // encode base-64 result
317         return base64Encode(calculatedMd5.getBytes());
318     }
319
320     /**
321      * Base 64 encode a String.
322      *
323      * @param inText
324      * @return
325      */
326     public static String base64Encode(String inText) {
327         return base64Encode(stringToByteArray(inText));
328     }
329
330     /**
331      * Convert String to byte array.
332      *
333      * @param inText
334      * @return
335      */
336     public static byte[] stringToByteArray(String inText) {
337         return inText.getBytes(StandardCharsets.UTF_8);
338     }
339
340     /**
341      * Base 64 encode a byte array.
342      *
343      * @param bytes
344      * @return
345      */
346     public static String base64Encode(byte[] bytes) {
347         Base64.Encoder encoder = Base64.getEncoder();
348         return encoder.encodeToString(bytes);
349     }
350
351     /**
352      * Return SDC id and pw as a HTTP Basic Auth string (for example: Basic
353      * dGVzdDoxMjM0NTY=).
354      *
355      * @return
356      */
357     public static String getSdcBasicAuth(RefProp refProp) {
358         String sdcId = refProp.getStringValue("sdc.serviceUsername");
359         String sdcPw = refProp.getStringValue("sdc.servicePassword");
360         String idPw = base64Encode(sdcId + ":" + sdcPw);
361         return "Basic " + idPw;
362     }
363
364     /**
365      * Method to get yaml/template properties value from json
366      *
367      * @param docText
368      * @return
369      * @throws IOException
370      */
371     public static String getYamlvalue(String docText) throws IOException {
372         ObjectMapper objectMapper = new ObjectMapper();
373         String yamlFileValue = "";
374         ObjectNode root = objectMapper.readValue(docText, ObjectNode.class);
375         Iterator<Entry<String, JsonNode>> entryItr = root.fields();
376         while (entryItr.hasNext()) {
377             Entry<String, JsonNode> entry = entryItr.next();
378             String key = entry.getKey();
379             if (key != null && key.equalsIgnoreCase("global")) {
380                 ArrayNode arrayNode = (ArrayNode) entry.getValue();
381                 for (JsonNode anArrayNode : arrayNode) {
382                     ObjectNode node = (ObjectNode) anArrayNode;
383                     ArrayNode arrayValueNode = (ArrayNode) node.get("value");
384                     JsonNode jsonNode = arrayValueNode.get(0);
385                     yamlFileValue = jsonNode.asText();
386                     logger.info("value:" + yamlFileValue);
387                 }
388                 break;
389             }
390         }
391         return yamlFileValue;
392     }
393 }