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