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