2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 package org.onap.clamp.clds.client.req;
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;
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;
44 import java.util.Map.Entry;
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;
58 * Construct a Sdc request given CLDS objects.
61 protected static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcReq.class);
62 protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
65 * Format the Blueprint from a Yaml
68 * The RefProp instance containing the Clds config
70 * The ModelProperties describing the clds model
72 * The Yaml file that must be converted
74 * @return A String containing the BluePrint
75 * @throws JsonParseException
77 * @throws JsonMappingException
82 public static String formatBlueprint(RefProp refProp, ModelProperties prop, String docText)
83 throws JsonParseException, JsonMappingException, IOException {
85 Global globalProp = prop.getGlobal();
86 String service = globalProp.getService();
88 String yamlvalue = getYamlvalue(docText);
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();
98 StringMatchPolicyReq.appendServiceConfigurations(refProp, service, serviceConfigurations, stringMatch,
100 logger.info("Value of serviceConfigurations:" + serviceConfigurations);
101 ObjectNode servConfNode = (ObjectNode) serviceConfigurations.get("serviceConfigurations");
103 // get updated blueprint by attaching service Conf from
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");
115 // get updated blueprint by attaching service Conf from
117 updatedBlueprint = getUpdatedBlueprintWithConfiguration(refProp, prop, yamlvalue, content);
120 logger.info("value of blueprint:" + updatedBlueprint);
121 return updatedBlueprint;
124 private static String getUpdatedBlueprintWithServiceConf(RefProp refProp, ModelProperties prop, String yamlValue,
125 ObjectNode serviceConf) throws IOException {
126 Yaml yaml = new Yaml();
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);
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);
138 // Get Properties Object information from stringmatch of Yaml
139 Map<String, String> propsObject = smObject.get("properties");
140 logger.info("value of PropsObject:" + propsObject);
142 String deploymentJsonObject = propsObject.get("deployment_JSON");
143 logger.info("value of deploymentJson:" + deploymentJsonObject);
145 ObjectMapper mapper = new ObjectMapper();
146 ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
147 ObjectNode configurationObjectNode = (ObjectNode) deployJsonNode.get("configuration");
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);
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);
162 blueprint = yaml.dump(loadedYaml);
163 logger.info("value of updated Yaml File:" + blueprint);
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);
186 ObjectMapper mapper = new ObjectMapper();
188 ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
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);
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);
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);
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;
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"
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);
238 if (globalProps.getService() != null) {
239 serviceUUID = globalProps.getService();
242 String normalizedResourceInstanceName = normalizeResourceInstanceName(resourceInstanceName);
243 return url + "/" + serviceUUID + "/resourceInstances/" + normalizedResourceInstanceName + "/artifacts";
247 * To get List of urls for all vfresources
251 * @param sdcCatalogServices
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<>();
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";
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.
300 public static String normalizeResourceInstanceName(String inText) {
301 return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
310 public static String calculateMD5ByString(String data) {
311 String calculatedMd5 = DigestUtils.md5Hex(data);
312 // encode base-64 result
313 return base64Encode(calculatedMd5.getBytes());
317 * Base 64 encode a String.
322 public static String base64Encode(String inText) {
323 return base64Encode(stringToByteArray(inText));
327 * Convert String to byte array.
332 public static byte[] stringToByteArray(String inText) {
333 return inText.getBytes(StandardCharsets.UTF_8);
337 * Base 64 encode a byte array.
342 public static String base64Encode(byte[] bytes) {
343 Base64.Encoder encoder = Base64.getEncoder();
344 return encoder.encodeToString(bytes);
348 * Return SDC id and pw as a HTTP Basic Auth string (for example: Basic
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;
361 * Method to get yaml/template properties value from json
365 * @throws IOException
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);
387 return yamlFileValue;