640d3b0cdf520ae77166e5e394f9e4b3be34e5be
[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     public static String formatSdcLocationsReq(ModelProperties prop, String artifactName) {
98         ObjectMapper objectMapper = new ObjectMapper();
99         Global global = prop.getGlobal();
100         List<String> locationsList = global.getLocation();
101         ArrayNode locationsArrayNode = objectMapper.createArrayNode();
102         ObjectNode locationObject = objectMapper.createObjectNode();
103         for (String currLocation : locationsList) {
104             locationsArrayNode.add(currLocation);
105         }
106         locationObject.put("artifactName", artifactName);
107         locationObject.putPOJO("locations", locationsArrayNode);
108         String locationJsonFormat = locationObject.toString();
109         logger.info("Value of locaation Json Artifact:" + locationsArrayNode);
110         return locationJsonFormat;
111     }
112
113     public static String formatSdcReq(String payloadData, String artifactName, String artifactLabel,
114             String artifactType) throws IOException {
115         logger.info("artifact=" + payloadData);
116         String base64Artifact = base64Encode(payloadData);
117         return "{ \n" + "\"payloadData\" : \"" + base64Artifact + "\",\n" + "\"artifactLabel\" : \"" + artifactLabel
118                 + "\",\n" + "\"artifactName\" :\"" + artifactName + "\",\n" + "\"artifactType\" : \"" + artifactType
119                 + "\",\n" + "\"artifactGroupType\" : \"DEPLOYMENT\",\n" + "\"description\" : \"from CLAMP Cockpit\"\n"
120                 + "} \n";
121     }
122
123     public static String getSdcReqUrl(ModelProperties prop, String url) {
124         Global globalProps = prop.getGlobal();
125         String serviceUUID = "";
126         String resourceInstanceName = "";
127         if (globalProps != null) {
128             List<String> resourceVf = globalProps.getResourceVf();
129             if (resourceVf != null && !resourceVf.isEmpty()) {
130                 resourceInstanceName = resourceVf.get(0);
131             }
132             if (globalProps.getService() != null) {
133                 serviceUUID = globalProps.getService();
134             }
135         }
136         String normalizedResourceInstanceName = normalizeResourceInstanceName(resourceInstanceName);
137         return url + "/" + serviceUUID + "/resourceInstances/" + normalizedResourceInstanceName + "/artifacts";
138     }
139
140     /**
141      * To get List of urls for all vfresources
142      *
143      * @param prop
144      * @param baseUrl
145      * @param sdcCatalogServices
146      * @return
147      */
148     public static List<String> getSdcReqUrlsList(ModelProperties prop, String baseUrl,
149             SdcCatalogServices sdcCatalogServices, DelegateExecution execution) {
150         // TODO : refact and regroup with very similar code
151         List<String> urlList = new ArrayList<>();
152
153         Global globalProps = prop.getGlobal();
154         if (globalProps != null) {
155             if (globalProps.getService() != null) {
156                 String serviceInvariantUUID = globalProps.getService();
157                 execution.setVariable("serviceInvariantUUID", serviceInvariantUUID);
158                 List<String> resourceVfList = globalProps.getResourceVf();
159                 String serviceUUID = sdcCatalogServices.getServiceUuidFromServiceInvariantId(serviceInvariantUUID);
160                 String sdcServicesInformation = sdcCatalogServices.getSdcServicesInformation(serviceUUID);
161                 CldsSdcServiceDetail cldsSdcServiceDetail = sdcCatalogServices
162                         .getCldsSdcServiceDetailFromJson(sdcServicesInformation);
163                 if (cldsSdcServiceDetail != null && resourceVfList != null) {
164                     List<CldsSdcResource> cldsSdcResourcesList = cldsSdcServiceDetail.getResources();
165                     if (cldsSdcResourcesList != null && !cldsSdcResourcesList.isEmpty()) {
166                         for (CldsSdcResource CldsSdcResource : cldsSdcResourcesList) {
167                             if (CldsSdcResource != null && CldsSdcResource.getResoucreType() != null
168                                     && CldsSdcResource.getResoucreType().equalsIgnoreCase("VF")
169                                     && resourceVfList.contains(CldsSdcResource.getResourceInvariantUUID())) {
170                                 String normalizedResourceInstanceName = normalizeResourceInstanceName(
171                                         CldsSdcResource.getResourceInstanceName());
172                                 String svcUrl = baseUrl + "/" + serviceUUID + "/resourceInstances/"
173                                         + normalizedResourceInstanceName + "/artifacts";
174                                 urlList.add(svcUrl);
175                             }
176                         }
177                     }
178                 }
179             }
180         }
181
182         return urlList;
183     }
184
185     /**
186      * "Normalize" the resource instance name: - Remove spaces, underscores,
187      * dashes, and periods. - make lower case This is required by SDC when using
188      * the resource instance name to upload an artifact.
189      *
190      * @param inText
191      * @return
192      */
193     public static String normalizeResourceInstanceName(String inText) {
194         return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
195     }
196
197     /**
198      * from michael
199      *
200      * @param data
201      * @return
202      */
203     public static String calculateMD5ByString(String data) {
204         String calculatedMd5 = DigestUtils.md5Hex(data);
205         // encode base-64 result
206         return base64Encode(calculatedMd5.getBytes());
207     }
208
209     /**
210      * Base 64 encode a String.
211      *
212      * @param inText
213      * @return
214      */
215     public static String base64Encode(String inText) {
216         return base64Encode(stringToByteArray(inText));
217     }
218
219     /**
220      * Convert String to byte array.
221      *
222      * @param inText
223      * @return
224      */
225     public static byte[] stringToByteArray(String inText) {
226         return inText.getBytes(StandardCharsets.UTF_8);
227     }
228
229     /**
230      * Base 64 encode a byte array.
231      *
232      * @param bytes
233      * @return
234      */
235     public static String base64Encode(byte[] bytes) {
236         Base64.Encoder encoder = Base64.getEncoder();
237         return encoder.encodeToString(bytes);
238     }
239
240     /**
241      * Return SDC id and pw as a HTTP Basic Auth string (for example: Basic
242      * dGVzdDoxMjM0NTY=).
243      *
244      * @return
245      */
246     public static String getSdcBasicAuth(RefProp refProp) {
247         String sdcId = refProp.getStringValue("sdc.serviceUsername");
248         String sdcPw = refProp.getStringValue("sdc.servicePassword");
249         String idPw = base64Encode(sdcId + ":" + sdcPw);
250         return "Basic " + idPw;
251     }
252
253     /**
254      * Method to get yaml/template properties value from json
255      *
256      * @param docText
257      * @return
258      * @throws IOException
259      */
260     public static String getYamlvalue(String docText) throws IOException {
261         ObjectMapper objectMapper = new ObjectMapper();
262         String yamlFileValue = "";
263         ObjectNode root = objectMapper.readValue(docText, ObjectNode.class);
264         Iterator<Entry<String, JsonNode>> entryItr = root.fields();
265         while (entryItr.hasNext()) {
266             Entry<String, JsonNode> entry = entryItr.next();
267             String key = entry.getKey();
268             if (key != null && key.equalsIgnoreCase("global")) {
269                 ArrayNode arrayNode = (ArrayNode) entry.getValue();
270                 for (JsonNode anArrayNode : arrayNode) {
271                     ObjectNode node = (ObjectNode) anArrayNode;
272                     ArrayNode arrayValueNode = (ArrayNode) node.get("value");
273                     JsonNode jsonNode = arrayValueNode.get(0);
274                     yamlFileValue = jsonNode.asText();
275                     logger.info("value:" + yamlFileValue);
276                 }
277                 break;
278             }
279         }
280         return yamlFileValue;
281     }
282 }