c76607af6d04792cb49bf2c171d5d8fdd7a1c426
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / sdc / SdcRequests.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 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.sdc;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.databind.JsonNode;
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import com.fasterxml.jackson.databind.node.ArrayNode;
31 import com.fasterxml.jackson.databind.node.ObjectNode;
32
33 import java.io.IOException;
34 import java.nio.charset.StandardCharsets;
35 import java.security.GeneralSecurityException;
36 import java.util.ArrayList;
37 import java.util.Base64;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Map.Entry;
41
42 import org.apache.commons.codec.DecoderException;
43 import org.onap.clamp.clds.client.req.tca.TcaRequestFormatter;
44 import org.onap.clamp.clds.config.ClampProperties;
45 import org.onap.clamp.clds.model.properties.Global;
46 import org.onap.clamp.clds.model.properties.ModelProperties;
47 import org.onap.clamp.clds.model.properties.Tca;
48 import org.onap.clamp.clds.model.sdc.SdcResource;
49 import org.onap.clamp.clds.model.sdc.SdcServiceDetail;
50 import org.onap.clamp.clds.util.JacksonUtils;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.stereotype.Component;
53
54 /**
55  * Construct a Sdc request given CLDS objects.
56  */
57 @Component
58 public class SdcRequests {
59
60     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcRequests.class);
61     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
62     @Autowired
63     private SdcCatalogServices sdcCatalogServices;
64     @Autowired
65     protected ClampProperties refProp;
66
67     /**
68      * Format the Blueprint from a Yaml
69      *
70      * @param prop
71      *            The ModelProperties describing the clds model
72      * @param docText
73      *            The Yaml file that must be converted
74      * @return A String containing the BluePrint
75      * @throws IOException
76      *             In case of issues
77      */
78     public String formatBlueprint(ModelProperties prop, String docText) throws IOException {
79         String yamlvalue = getYamlvalue(docText);
80         String updatedBlueprint = "";
81         Tca tca = prop.getType(Tca.class);
82         if (tca.isFound()) {
83             updatedBlueprint = TcaRequestFormatter.updatedBlueprintWithConfiguration(refProp, prop, yamlvalue);
84         }
85         logger.info("value of blueprint:" + updatedBlueprint);
86         return updatedBlueprint;
87     }
88
89     /**
90      * Format the SDC Locations Request in the JSON Format
91      *
92      * @param prop
93      *            The ModelProperties describing the clds model
94      * @param artifactName
95      *            The name of the artifact
96      * @return SDC Locations request in the JSON Format
97      */
98     public String formatSdcLocationsReq(ModelProperties prop, String artifactName) {
99         ObjectMapper objectMapper = JacksonUtils.getObjectMapperInstance();
100         Global global = prop.getGlobal();
101         List<String> locationsList = global.getLocation();
102         ArrayNode locationsArrayNode = objectMapper.createArrayNode();
103         ObjectNode locationObject = objectMapper.createObjectNode();
104         for (String currLocation : locationsList) {
105             locationsArrayNode.add(currLocation);
106         }
107         locationObject.put("artifactName", artifactName);
108         locationObject.putPOJO("locations", locationsArrayNode);
109         String locationJsonFormat = locationObject.toString();
110         logger.info("Value of location Json Artifact:" + locationsArrayNode);
111         return locationJsonFormat;
112     }
113
114     /**
115      * Format the SDC Request
116      *
117      * @param payloadData
118      *            The ModelProperties describing the clds model
119      * @param artifactName
120      *            The name of the artifact
121      * @param artifactLabel
122      *            The Label of the artifact
123      * @param artifactType
124      *            The type of the artifact
125      * @return formatted SDC Request
126      */
127     public String formatSdcReq(String payloadData, String artifactName, String artifactLabel, String artifactType) {
128         logger.info("artifact=" + payloadData);
129         String base64Artifact = Base64.getEncoder().encodeToString(payloadData.getBytes(StandardCharsets.UTF_8));
130         return "{ \n" + "\"payloadData\" : \"" + base64Artifact + "\",\n" + "\"artifactLabel\" : \"" + artifactLabel
131                 + "\",\n" + "\"artifactName\" :\"" + artifactName + "\",\n" + "\"artifactType\" : \"" + artifactType
132                 + "\",\n" + "\"artifactGroupType\" : \"DEPLOYMENT\",\n" + "\"description\" : \"from CLAMP Cockpit\"\n"
133                 + "} \n";
134     }
135
136     private List<String> filterVfResourceList(String serviceUuid, List<SdcResource> sdcResourcesList,
137             List<String> cldsResourceVfList) {
138         List<String> urlList = new ArrayList<>();
139         for (SdcResource cldsSdcResource : sdcResourcesList) {
140             if (cldsSdcResource != null && cldsSdcResource.getResoucreType() != null
141                     && cldsSdcResource.getResoucreType().equalsIgnoreCase("VF")
142                     && cldsResourceVfList.contains(cldsSdcResource.getResourceInvariantUUID())) {
143                 String normalizedResourceInstanceName = normalizeResourceInstanceName(
144                         cldsSdcResource.getResourceInstanceName());
145                 String svcUrl = createUrlForResource(normalizedResourceInstanceName, serviceUuid);
146                 urlList.add(svcUrl);
147             }
148         }
149         return urlList;
150     }
151
152     private String createUrlForResource(String normalizedResourceInstanceName, String serviceUuid) {
153         return refProp.getStringValue("sdc.serviceUrl") + "/" + serviceUuid + "/resourceInstances/"
154                 + normalizedResourceInstanceName + "/artifacts";
155     }
156
157     /**
158      * To get List of urls for all vfresources
159      *
160      * @param prop
161      *            The model properties JSON describing the closed loop flow
162      * @return A list of Service URL
163      * @throws GeneralSecurityException
164      *             In case of issues when decrypting the password
165      * @throws DecoderException
166      *             In case of issues when decoding the Hex String
167      */
168     public List<String> getSdcReqUrlsList(ModelProperties prop) throws GeneralSecurityException, DecoderException {
169         List<String> urlList = new ArrayList<>();
170         Global globalProps = prop.getGlobal();
171         if (globalProps != null && globalProps.getService() != null && globalProps.getResourceVf() != null) {
172             String serviceUuid = sdcCatalogServices.getServiceUuidFromServiceInvariantId(globalProps.getService());
173             SdcServiceDetail sdcServiceDetail = sdcCatalogServices
174                     .decodeCldsSdcServiceDetailFromJson(sdcCatalogServices.getSdcServicesInformation(serviceUuid));
175             if (sdcServiceDetail != null) {
176                 urlList = filterVfResourceList(serviceUuid, sdcServiceDetail.getResources(),
177                         globalProps.getResourceVf());
178             }
179         } else {
180             logger.warn("GlobalProperties json is empty, skipping getSdcReqUrlsList and returning empty list");
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 String normalizeResourceInstanceName(String inText) {
194         return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
195     }
196
197     /**
198      * Method to get yaml/template properties value from json.
199      *
200      * @param jsonGlobal
201      *            The Json containing a Yaml file
202      * @return The yaml extracted from the JSON
203      * @throws IOException
204      *             In case of issues with the Json parser
205      */
206     protected String getYamlvalue(String jsonGlobal) throws IOException {
207         String yamlFileValue = "";
208         ObjectNode root = JacksonUtils.getObjectMapperInstance().readValue(jsonGlobal, ObjectNode.class);
209         Iterator<Entry<String, JsonNode>> entryItr = root.fields();
210         while (entryItr.hasNext()) {
211             Entry<String, JsonNode> entry = entryItr.next();
212             String key = entry.getKey();
213             if (key != null && key.equalsIgnoreCase("global")) {
214                 ArrayNode arrayNode = (ArrayNode) entry.getValue();
215                 for (JsonNode anArrayNode : arrayNode) {
216                     ObjectNode node = (ObjectNode) anArrayNode;
217                     ArrayNode arrayValueNode = (ArrayNode) node.get("value");
218                     JsonNode jsonNode = arrayValueNode.get(0);
219                     yamlFileValue = jsonNode.asText();
220                     logger.info("value:" + yamlFileValue);
221                 }
222                 break;
223             }
224         }
225         return yamlFileValue;
226     }
227 }