Rework the javadoc
[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 java.io.IOException;
27 import java.nio.charset.StandardCharsets;
28 import java.util.ArrayList;
29 import java.util.Base64;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Map.Entry;
34
35 import org.apache.commons.codec.digest.DigestUtils;
36 import org.camunda.bpm.engine.delegate.DelegateExecution;
37 import org.onap.clamp.clds.client.SdcCatalogServices;
38 import org.onap.clamp.clds.model.CldsSdcResource;
39 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
40 import org.onap.clamp.clds.model.prop.Global;
41 import org.onap.clamp.clds.model.prop.ModelProperties;
42 import org.onap.clamp.clds.model.prop.StringMatch;
43 import org.onap.clamp.clds.model.prop.Tca;
44 import org.onap.clamp.clds.model.refprop.RefProp;
45
46 import com.att.eelf.configuration.EELFLogger;
47 import com.att.eelf.configuration.EELFManager;
48 import com.fasterxml.jackson.core.JsonParseException;
49 import com.fasterxml.jackson.core.JsonProcessingException;
50 import com.fasterxml.jackson.databind.JsonMappingException;
51 import com.fasterxml.jackson.databind.JsonNode;
52 import com.fasterxml.jackson.databind.ObjectMapper;
53 import com.fasterxml.jackson.databind.node.ArrayNode;
54 import com.fasterxml.jackson.databind.node.ObjectNode;
55 import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;
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.size() > 0) {
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      * @throws Exception
254      */
255     public static List<String> getSdcReqUrlsList(ModelProperties prop, String baseUrl,
256             SdcCatalogServices sdcCatalogServices, DelegateExecution execution) throws Exception {
257         // TODO : refact and regroup with very similar code
258         List<String> urlList = new ArrayList<>();
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.size() > 0) {
272                         for (CldsSdcResource CldsSdcResource : CldsSdcResourcesList) {
273                             if (CldsSdcResource != null && CldsSdcResource.getResoucreType() != null
274                                     && CldsSdcResource.getResoucreType().equalsIgnoreCase("VF")) {
275                                 if (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         return urlList;
289     }
290
291     /**
292      * "Normalize" the resource instance name: - Remove spaces, underscores,
293      * dashes, and periods. - make lower case This is required by SDC when using
294      * the resource instance name to upload an artifact.
295      *
296      * @param inText
297      * @return
298      */
299     public static String normalizeResourceInstanceName(String inText) {
300         return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
301     }
302
303     /**
304      * from michael
305      *
306      * @param data
307      * @return
308      */
309     public static String calculateMD5ByString(String data) {
310         String calculatedMd5 = DigestUtils.md5Hex(data);
311         // encode base-64 result
312         return base64Encode(calculatedMd5.getBytes());
313     }
314
315     /**
316      * Base 64 encode a String.
317      *
318      * @param inText
319      * @return
320      */
321     public static String base64Encode(String inText) {
322         return base64Encode(stringToByteArray(inText));
323     }
324
325     /**
326      * Convert String to byte array.
327      *
328      * @param inText
329      * @return
330      */
331     public static byte[] stringToByteArray(String inText) {
332         return inText.getBytes(StandardCharsets.UTF_8);
333     }
334
335     /**
336      * Base 64 encode a byte array.
337      *
338      * @param bytes
339      * @return
340      */
341     public static String base64Encode(byte[] bytes) {
342         Base64.Encoder encoder = Base64.getEncoder();
343         return encoder.encodeToString(bytes);
344     }
345
346     /**
347      * Return SDC id and pw as a HTTP Basic Auth string (for example: Basic
348      * dGVzdDoxMjM0NTY=).
349      *
350      * @return
351      */
352     public static String getSdcBasicAuth(RefProp refProp) {
353         String sdcId = refProp.getStringValue("sdc.serviceUsername");
354         String sdcPw = refProp.getStringValue("sdc.servicePassword");
355         String idPw = base64Encode(sdcId + ":" + sdcPw);
356         return "Basic " + idPw;
357     }
358
359     /**
360      * Method to get yaml/template properties value from json
361      * 
362      * @param docText
363      * @return
364      * @throws IOException
365      */
366     public static String getYamlvalue(String docText) throws IOException {
367         ObjectMapper objectMapper = new ObjectMapper();
368         String yamlFileValue = "";
369         ObjectNode root = objectMapper.readValue(docText, ObjectNode.class);
370         Iterator<Entry<String, JsonNode>> entryItr = root.fields();
371         while (entryItr.hasNext()) {
372             Entry<String, JsonNode> entry = entryItr.next();
373             String key = entry.getKey();
374             if (key != null && key.equalsIgnoreCase("global")) {
375                 ArrayNode arrayNode = (ArrayNode) entry.getValue();
376                 for (JsonNode anArrayNode : arrayNode) {
377                     ObjectNode node = (ObjectNode) anArrayNode;
378                     ArrayNode arrayValueNode = (ArrayNode) node.get("value");
379                     JsonNode jsonNode = arrayValueNode.get(0);
380                     yamlFileValue = jsonNode.asText();
381                     logger.info("value:" + yamlFileValue);
382                 }
383                 break;
384             }
385         }
386         return yamlFileValue;
387     }
388 }