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.exception.SdcCommunicationException;
50 import org.onap.clamp.clds.model.CldsSdcResource;
51 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
52 import org.onap.clamp.clds.model.prop.Global;
53 import org.onap.clamp.clds.model.prop.ModelProperties;
54 import org.onap.clamp.clds.model.prop.StringMatch;
55 import org.onap.clamp.clds.model.prop.Tca;
56 import org.onap.clamp.clds.model.refprop.RefProp;
59 * Construct a Sdc request given CLDS objects.
62 protected static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcReq.class);
63 protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
66 * Format the Blueprint from a Yaml
69 * The RefProp instance containing the Clds config
71 * The ModelProperties describing the clds model
73 * The Yaml file that must be converted
75 * @return A String containing the BluePrint
76 * @throws JsonParseException
78 * @throws JsonMappingException
83 public static String formatBlueprint(RefProp refProp, ModelProperties prop, String docText)
84 throws JsonParseException, JsonMappingException, IOException {
86 Global globalProp = prop.getGlobal();
87 String service = globalProp.getService();
89 String yamlvalue = getYamlvalue(docText);
91 String updatedBlueprint = "";
92 StringMatch stringMatch = prop.getType(StringMatch.class);
93 Tca tca = prop.getType(Tca.class);
94 if (stringMatch.isFound()) {
95 prop.setCurrentModelElementId(stringMatch.getId());
96 ObjectMapper objectMapper = new ObjectMapper();
97 ObjectNode serviceConfigurations = objectMapper.createObjectNode();
99 StringMatchPolicyReq.appendServiceConfigurations(refProp, service, serviceConfigurations, stringMatch,
101 logger.info("Value of serviceConfigurations:" + serviceConfigurations);
102 ObjectNode servConfNode = (ObjectNode) serviceConfigurations.get("serviceConfigurations");
104 // get updated blueprint by attaching service Conf from
106 updatedBlueprint = getUpdatedBlueprintWithServiceConf(refProp, prop, yamlvalue, servConfNode);
107 } else if (tca.isFound()) {
108 prop.setCurrentModelElementId(tca.getId());
109 ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.template", service);
110 ObjectNode content = rootNode.with("content");
111 TcaMPolicyReq.appendSignatures(refProp, service, content, tca, prop);
112 logger.info("Value of content:" + content);
113 // ObjectNode servConfNode =
114 // (ObjectNode)signatures.get("signatures");
116 // get updated blueprint by attaching service Conf from
118 updatedBlueprint = getUpdatedBlueprintWithConfiguration(refProp, prop, yamlvalue, content);
121 logger.info("value of blueprint:" + updatedBlueprint);
122 return updatedBlueprint;
125 private static String getUpdatedBlueprintWithServiceConf(RefProp refProp, ModelProperties prop, String yamlValue,
126 ObjectNode serviceConf) throws IOException {
127 Yaml yaml = new Yaml();
129 // Serialiaze Yaml file
130 Map<String, Map> loadedYaml = (Map<String, Map>) yaml.load(yamlValue);
131 // Get node templates information from Yaml
132 Map<String, Map> nodeTemplates = loadedYaml.get("node_templates");
133 logger.info("value of NodeTemplates:" + nodeTemplates);
135 // Get StringMatch Object information from node templates of Yaml
136 Map<String, Map> smObject = nodeTemplates.get("SM");
137 logger.info("value of StringMatch:" + smObject);
139 // Get Properties Object information from stringmatch of Yaml
140 Map<String, String> propsObject = smObject.get("properties");
141 logger.info("value of PropsObject:" + propsObject);
143 String deploymentJsonObject = propsObject.get("deployment_JSON");
144 logger.info("value of deploymentJson:" + deploymentJsonObject);
146 ObjectMapper mapper = new ObjectMapper();
147 ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
148 ObjectNode configurationObjectNode = (ObjectNode) deployJsonNode.get("configuration");
150 // "policyName":"example_model06.ClosedLoop_FRWL_SIG_0538e6f2_8c1b_4656_9999_3501b3c59ad7_StringMatch_",
151 String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
152 String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
153 configurationObjectNode.put("policyName", policyName);
155 // "closedLoopControlName":"ClosedLoop-FRWL-SIG-0538e6f2-8c1b-4656-9999-3501b3c59ad7",
156 configurationObjectNode.put("closedLoopControlName", prop.getControlName());
157 configurationObjectNode.put("messageReaderConsumerGroup", prop.getModelName());
158 configurationObjectNode.set("serviceConfigurations", serviceConf);
159 propsObject.put("deployment_JSON", deployJsonNode.toString());
160 String blueprint = yaml.dump(loadedYaml);
161 logger.info("value of updated Yaml File:" + blueprint);
163 blueprint = yaml.dump(loadedYaml);
164 logger.info("value of updated Yaml File:" + blueprint);
169 private static String getUpdatedBlueprintWithConfiguration(RefProp refProp, ModelProperties prop, String yamlValue,
170 ObjectNode serviceConf) throws JsonProcessingException, IOException {
171 String blueprint = "";
172 Yaml yaml = new Yaml();
173 // Serialiaze Yaml file
174 Map<String, Map> loadedYaml = (Map<String, Map>) yaml.load(yamlValue);
175 // Get node templates information from Yaml
176 Map<String, Map> nodeTemplates = loadedYaml.get("node_templates");
177 logger.info("value of NodeTemplates:" + nodeTemplates);
178 // Get Tca Object information from node templates of Yaml
179 Map<String, Map> tcaObject = nodeTemplates.get("MTCA");
180 logger.info("value of Tca:" + tcaObject);
181 // Get Properties Object information from tca of Yaml
182 Map<String, String> propsObject = tcaObject.get("properties");
183 logger.info("value of PropsObject:" + propsObject);
184 String deploymentJsonObject = propsObject.get("deployment_JSON");
185 logger.info("value of deploymentJson:" + deploymentJsonObject);
187 ObjectMapper mapper = new ObjectMapper();
189 ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
191 // "policyName":"example_model06.ClosedLoop_FRWL_SIG_0538e6f2_8c1b_4656_9999_3501b3c59ad7_Tca_",
192 String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
193 String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
194 serviceConf.put("policyName", policyName);
196 deployJsonNode.set("configuration", serviceConf);
197 propsObject.put("deployment_JSON", deployJsonNode.toString());
198 blueprint = yaml.dump(loadedYaml);
199 logger.info("value of updated Yaml File:" + blueprint);
204 public static String formatSdcLocationsReq(ModelProperties prop, String artifactName) {
205 ObjectMapper objectMapper = new ObjectMapper();
206 Global global = prop.getGlobal();
207 List<String> locationsList = global.getLocation();
208 ArrayNode locationsArrayNode = objectMapper.createArrayNode();
209 ObjectNode locationObject = objectMapper.createObjectNode();
210 for (String currLocation : locationsList) {
211 locationsArrayNode.add(currLocation);
213 locationObject.put("artifactName", artifactName);
214 locationObject.putPOJO("locations", locationsArrayNode);
215 String locationJsonFormat = locationObject.toString();
216 logger.info("Value of locaation Json Artifact:" + locationsArrayNode);
217 return locationJsonFormat;
220 public static String formatSdcReq(String payloadData, String artifactName, String artifactLabel,
221 String artifactType) throws IOException {
222 logger.info("artifact=" + payloadData);
223 String base64Artifact = base64Encode(payloadData);
224 return "{ \n" + "\"payloadData\" : \"" + base64Artifact + "\",\n" + "\"artifactLabel\" : \"" + artifactLabel
225 + "\",\n" + "\"artifactName\" :\"" + artifactName + "\",\n" + "\"artifactType\" : \"" + artifactType
226 + "\",\n" + "\"artifactGroupType\" : \"DEPLOYMENT\",\n" + "\"description\" : \"from CLAMP Cockpit\"\n"
230 public static String getSdcReqUrl(ModelProperties prop, String url) {
231 Global globalProps = prop.getGlobal();
232 String serviceUUID = "";
233 String resourceInstanceName = "";
234 if (globalProps != null) {
235 List<String> resourceVf = globalProps.getResourceVf();
236 if (resourceVf != null && resourceVf.size() > 0) {
237 resourceInstanceName = resourceVf.get(0);
239 if (globalProps.getService() != null) {
240 serviceUUID = globalProps.getService();
243 String normalizedResourceInstanceName = normalizeResourceInstanceName(resourceInstanceName);
244 return url + "/" + serviceUUID + "/resourceInstances/" + normalizedResourceInstanceName + "/artifacts";
248 * To get List of urls for all vfresources
252 * @param sdcCatalogServices
256 public static List<String> getSdcReqUrlsList(ModelProperties prop, String baseUrl,
257 SdcCatalogServices sdcCatalogServices, DelegateExecution execution) {
258 // TODO : refact and regroup with very similar code
259 List<String> urlList = new ArrayList<>();
261 Global globalProps = prop.getGlobal();
262 if (globalProps != null) {
263 if (globalProps.getService() != null) {
264 String serviceInvariantUUID = globalProps.getService();
265 execution.setVariable("serviceInvariantUUID", serviceInvariantUUID);
266 List<String> resourceVfList = globalProps.getResourceVf();
267 String serviceUUID = sdcCatalogServices.getServiceUuidFromServiceInvariantId(serviceInvariantUUID);
268 String sdcServicesInformation = sdcCatalogServices.getSdcServicesInformation(serviceUUID);
269 CldsSdcServiceDetail CldsSdcServiceDetail = sdcCatalogServices
270 .getCldsSdcServiceDetailFromJson(sdcServicesInformation);
271 if (CldsSdcServiceDetail != null && resourceVfList != null) {
272 List<CldsSdcResource> CldsSdcResourcesList = CldsSdcServiceDetail.getResources();
273 if (CldsSdcResourcesList != null && CldsSdcResourcesList.size() > 0) {
274 for (CldsSdcResource CldsSdcResource : CldsSdcResourcesList) {
275 if (CldsSdcResource != null && CldsSdcResource.getResoucreType() != null
276 && CldsSdcResource.getResoucreType().equalsIgnoreCase("VF")) {
277 if (resourceVfList.contains(CldsSdcResource.getResourceInvariantUUID())) {
278 String normalizedResourceInstanceName = normalizeResourceInstanceName(
279 CldsSdcResource.getResourceInstanceName());
280 String svcUrl = baseUrl + "/" + serviceUUID + "/resourceInstances/"
281 + normalizedResourceInstanceName + "/artifacts";
290 } catch (IOException e) {
291 throw new SdcCommunicationException("Exception occurred during the SDC communication",e);
297 * "Normalize" the resource instance name: - Remove spaces, underscores,
298 * dashes, and periods. - make lower case This is required by SDC when using
299 * the resource instance name to upload an artifact.
304 public static String normalizeResourceInstanceName(String inText) {
305 return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
314 public static String calculateMD5ByString(String data) {
315 String calculatedMd5 = DigestUtils.md5Hex(data);
316 // encode base-64 result
317 return base64Encode(calculatedMd5.getBytes());
321 * Base 64 encode a String.
326 public static String base64Encode(String inText) {
327 return base64Encode(stringToByteArray(inText));
331 * Convert String to byte array.
336 public static byte[] stringToByteArray(String inText) {
337 return inText.getBytes(StandardCharsets.UTF_8);
341 * Base 64 encode a byte array.
346 public static String base64Encode(byte[] bytes) {
347 Base64.Encoder encoder = Base64.getEncoder();
348 return encoder.encodeToString(bytes);
352 * Return SDC id and pw as a HTTP Basic Auth string (for example: Basic
357 public static String getSdcBasicAuth(RefProp refProp) {
358 String sdcId = refProp.getStringValue("sdc.serviceUsername");
359 String sdcPw = refProp.getStringValue("sdc.servicePassword");
360 String idPw = base64Encode(sdcId + ":" + sdcPw);
361 return "Basic " + idPw;
365 * Method to get yaml/template properties value from json
369 * @throws IOException
371 public static String getYamlvalue(String docText) throws IOException {
372 ObjectMapper objectMapper = new ObjectMapper();
373 String yamlFileValue = "";
374 ObjectNode root = objectMapper.readValue(docText, ObjectNode.class);
375 Iterator<Entry<String, JsonNode>> entryItr = root.fields();
376 while (entryItr.hasNext()) {
377 Entry<String, JsonNode> entry = entryItr.next();
378 String key = entry.getKey();
379 if (key != null && key.equalsIgnoreCase("global")) {
380 ArrayNode arrayNode = (ArrayNode) entry.getValue();
381 for (JsonNode anArrayNode : arrayNode) {
382 ObjectNode node = (ObjectNode) anArrayNode;
383 ArrayNode arrayValueNode = (ArrayNode) node.get("value");
384 JsonNode jsonNode = arrayValueNode.get(0);
385 yamlFileValue = jsonNode.asText();
386 logger.info("value:" + yamlFileValue);
391 return yamlFileValue;