Remove Camunda and replace by Camel
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / sdc / SdcReq.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.model.CldsSdcResource;
45 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
46 import org.onap.clamp.clds.model.prop.Global;
47 import org.onap.clamp.clds.model.prop.ModelProperties;
48 import org.onap.clamp.clds.model.prop.Tca;
49 import org.onap.clamp.clds.model.refprop.RefProp;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.stereotype.Component;
52
53 /**
54  * Construct a Sdc request given CLDS objects.
55  */
56 @Component
57 public class SdcReq {
58
59     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcReq.class);
60     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
61     @Autowired
62     private SdcCatalogServices sdcCatalogServices;
63     @Autowired
64     protected RefProp refProp;
65
66     /**
67      * Format the Blueprint from a Yaml
68      *
69      * @param prop
70      *            The ModelProperties describing the clds model
71      * @param docText
72      *            The Yaml file that must be converted
73      * @return A String containing the BluePrint
74      * @throws IOException
75      *             In case of issues
76      */
77     public String formatBlueprint(ModelProperties prop, String docText) throws IOException {
78         String yamlvalue = getYamlvalue(docText);
79         String updatedBlueprint = "";
80         Tca tca = prop.getType(Tca.class);
81         if (tca.isFound()) {
82             updatedBlueprint = TcaRequestFormatter.updatedBlueprintWithConfiguration(refProp, prop, yamlvalue);
83         }
84         logger.info("value of blueprint:" + updatedBlueprint);
85         return updatedBlueprint;
86     }
87
88     /**
89      * Format the SDC Locations Request in the JSON Format
90      *
91      * @param prop
92      *            The ModelProperties describing the clds model
93      * @param artifactName
94      *            The name of the artifact
95      * @return SDC Locations request in the JSON Format
96      */
97     public 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 location Json Artifact:" + locationsArrayNode);
110         return locationJsonFormat;
111     }
112
113     /**
114      * Format the SDC Request
115      *
116      * @param payloadData
117      *            The ModelProperties describing the clds model
118      * @param artifactName
119      *            The name of the artifact
120      * @param artifactLabel
121      *            The Label of the artifact
122      * @param artifactType
123      *            The type of the artifact
124      * @return formatted SDC Request
125      */
126     public String formatSdcReq(String payloadData, String artifactName, String artifactLabel, String artifactType) {
127         logger.info("artifact=" + payloadData);
128         String base64Artifact = Base64.getEncoder().encodeToString(payloadData.getBytes(StandardCharsets.UTF_8));
129         return "{ \n" + "\"payloadData\" : \"" + base64Artifact + "\",\n" + "\"artifactLabel\" : \"" + artifactLabel
130                 + "\",\n" + "\"artifactName\" :\"" + artifactName + "\",\n" + "\"artifactType\" : \"" + artifactType
131                 + "\",\n" + "\"artifactGroupType\" : \"DEPLOYMENT\",\n" + "\"description\" : \"from CLAMP Cockpit\"\n"
132                 + "} \n";
133     }
134
135     /**
136      * To get List of urls for all vfresources
137      *
138      * @param prop
139      *            The model properties JSON describing the closed loop flow
140      * @param baseUrl
141      *            The URL to trigger
142      * @return A list of Service URL
143      * @throws GeneralSecurityException
144      *             In case of issues when decrypting the password
145      * @throws DecoderException
146      *             In case of issues when decoding the Hex String
147      */
148     public List<String> getSdcReqUrlsList(ModelProperties prop, String baseUrl)
149             throws GeneralSecurityException, DecoderException {
150         List<String> urlList = new ArrayList<>();
151         Global globalProps = prop.getGlobal();
152         if (globalProps != null && globalProps.getService() != null) {
153             String serviceInvariantUUID = globalProps.getService();
154             List<String> resourceVfList = globalProps.getResourceVf();
155             String serviceUUID = sdcCatalogServices.getServiceUuidFromServiceInvariantId(serviceInvariantUUID);
156             CldsSdcServiceDetail cldsSdcServiceDetail = sdcCatalogServices
157                     .getCldsSdcServiceDetailFromJson(sdcCatalogServices.getSdcServicesInformation(serviceUUID));
158             if (cldsSdcServiceDetail != null && resourceVfList != null) {
159                 List<CldsSdcResource> cldsSdcResourcesList = cldsSdcServiceDetail.getResources();
160                 if (cldsSdcResourcesList != null && !cldsSdcResourcesList.isEmpty()) {
161                     for (CldsSdcResource cldsSdcResource : cldsSdcResourcesList) {
162                         if (cldsSdcResource != null && cldsSdcResource.getResoucreType() != null
163                                 && cldsSdcResource.getResoucreType().equalsIgnoreCase("VF")
164                                 && resourceVfList.contains(cldsSdcResource.getResourceInvariantUUID())) {
165                             String normalizedResourceInstanceName = normalizeResourceInstanceName(
166                                     cldsSdcResource.getResourceInstanceName());
167                             String svcUrl = baseUrl + "/" + serviceUUID + "/resourceInstances/"
168                                     + normalizedResourceInstanceName + "/artifacts";
169                             urlList.add(svcUrl);
170                         } else {
171                             logger.warn("The VF Resource invariant UUID (" + cldsSdcResource.getResourceInvariantUUID()
172                                     + ") has not been found in the Service (Invariant ID:" + serviceInvariantUUID
173                                     + ")VF resource list");
174                         }
175                     }
176                 }
177             }
178         } else {
179             logger.warn("GlobalProperties json is empty, skipping getSdcReqUrlsList and returning empty list");
180         }
181         return urlList;
182     }
183
184     /**
185      * "Normalize" the resource instance name: - Remove spaces, underscores,
186      * dashes, and periods. - make lower case This is required by SDC when using
187      * the resource instance name to upload an artifact.
188      *
189      * @param inText
190      * @return
191      */
192     public String normalizeResourceInstanceName(String inText) {
193         return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
194     }
195
196     /**
197      * Method to get yaml/template properties value from json.
198      *
199      * @param jsonGlobal
200      *            The Json containing a Yaml file
201      * @return The yaml extracted from the JSON
202      * @throws IOException
203      *             In case of issues with the Json parser
204      */
205     protected String getYamlvalue(String jsonGlobal) throws IOException {
206         ObjectMapper objectMapper = new ObjectMapper();
207         String yamlFileValue = "";
208         ObjectNode root = objectMapper.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 }