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