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