2 * Copyright (c) 2018 Orange
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
14 package org.onap.nbi.apis.servicecatalog;
17 import java.io.FileInputStream;
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.sql.Timestamp;
21 import java.util.ArrayList;
22 import java.util.LinkedHashMap;
23 import java.util.List;
25 import java.util.Map.Entry;
27 import java.util.zip.ZipEntry;
28 import java.util.zip.ZipInputStream;
29 import org.apache.commons.collections.CollectionUtils;
30 import org.apache.commons.io.FileUtils;
31 import org.onap.nbi.exceptions.TechnicalException;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.stereotype.Service;
36 import com.fasterxml.jackson.databind.ObjectMapper;
37 import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
40 public class ToscaInfosProcessor {
45 final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); // jackson databind
47 private static final Logger LOGGER = LoggerFactory.getLogger(ToscaInfosProcessor.class);
49 public void buildResponseWithToscaInfos(LinkedHashMap toscaInfosTopologyTemplate,
50 LinkedHashMap serviceCatalogResponse) {
51 if (toscaInfosTopologyTemplate.get("inputs") != null) {
52 ArrayList serviceSpecCharacteristic = new ArrayList();
53 LinkedHashMap toscaInfos = (LinkedHashMap) toscaInfosTopologyTemplate.get("inputs");
54 Set<Entry<String, LinkedHashMap>> stringLinkedHashMapEntry = (Set<Entry<String, LinkedHashMap>>) toscaInfos
57 for (Map.Entry<String,LinkedHashMap> key :stringLinkedHashMapEntry) {
58 String keyString = key.getKey();
59 LinkedHashMap inputParameter = key.getValue();
60 LinkedHashMap mapParameter = new LinkedHashMap();
61 String parameterType = (String) inputParameter.get("type");
62 mapParameter.put("name", keyString);
63 mapParameter.put("description", inputParameter.get("description"));
64 mapParameter.put("valueType", parameterType);
65 mapParameter.put("@type", "ONAPserviceCharacteristic");
66 mapParameter.put("required", inputParameter.get("required"));
67 mapParameter.put("status", inputParameter.get("status"));
68 List<LinkedHashMap> serviceSpecCharacteristicValues =
69 buildServiceSpecCharacteristicsValues(inputParameter, parameterType);
70 mapParameter.put("serviceSpecCharacteristicValue", serviceSpecCharacteristicValues);
71 serviceSpecCharacteristic.add(mapParameter);
74 serviceCatalogResponse.put("serviceSpecCharacteristic", serviceSpecCharacteristic);
76 LinkedHashMap nodeTemplate = (LinkedHashMap) toscaInfosTopologyTemplate.get("node_templates");
78 List<LinkedHashMap> resourceSpecifications =
79 (List<LinkedHashMap>) serviceCatalogResponse.get("resourceSpecification");
80 for (LinkedHashMap resourceSpecification : resourceSpecifications) {
81 String id = (String) resourceSpecification.get("id");
82 LOGGER.debug("get tosca infos for service id: {0}", id);
83 LinkedHashMap toscaInfosFromResourceId = getToscaInfosFromResourceUUID(nodeTemplate, id);
84 if (toscaInfosFromResourceId != null) {
85 resourceSpecification.put("modelCustomizationId", toscaInfosFromResourceId.get("customizationUUID"));
91 private List<LinkedHashMap> buildServiceSpecCharacteristicsValues(LinkedHashMap parameter, String parameterType) {
92 List<LinkedHashMap> serviceSpecCharacteristicValues = new ArrayList<>();
93 if (!"map".equalsIgnoreCase(parameterType) && !"list".equalsIgnoreCase(parameterType)) {
94 LOGGER.debug("get tosca infos for serviceSpecCharacteristicValues of type map or string : {0}", parameter);
95 Object aDefault = parameter.get("default");
96 if (parameter.get("entry_schema") != null) {
97 ArrayList entrySchema = (ArrayList) parameter.get("entry_schema");
98 if (CollectionUtils.isNotEmpty(entrySchema)) {
99 buildCharacteristicValuesFormShema(parameterType, serviceSpecCharacteristicValues, aDefault,
104 return serviceSpecCharacteristicValues;
107 private void buildCharacteristicValuesFormShema(String parameterType,
108 List<LinkedHashMap> serviceSpecCharacteristicValues, Object aDefault, ArrayList entry_schema) {
109 LinkedHashMap constraints = (LinkedHashMap) entry_schema.get(0);
110 if (constraints != null) {
111 ArrayList constraintsList = (ArrayList) constraints.get("constraints");
112 if (CollectionUtils.isNotEmpty(constraintsList)) {
113 LinkedHashMap valuesMap = (LinkedHashMap) constraintsList.get(0);
114 if (valuesMap != null) {
115 List<Object> values = (List<Object>) valuesMap.get("valid_values");
116 for (Object value : values) {
117 String stringValue = value.toString();
118 LinkedHashMap serviceSpecCharacteristicValue = new LinkedHashMap();
119 serviceSpecCharacteristicValue.put("isDefault",
120 aDefault != null && aDefault.toString().equals(stringValue));
121 serviceSpecCharacteristicValue.put("value", stringValue);
122 serviceSpecCharacteristicValue.put("valueType", parameterType);
123 serviceSpecCharacteristicValues.add(serviceSpecCharacteristicValue);
131 private LinkedHashMap getToscaInfosFromResourceUUID(LinkedHashMap node_templates, String name) {
132 if(node_templates!=null) {
133 for (Object nodeTemplateObject : node_templates.values()) {
134 LinkedHashMap nodeTemplate = (LinkedHashMap) nodeTemplateObject;
135 LinkedHashMap metadata = (LinkedHashMap) nodeTemplate.get("metadata");
136 String metadataUUID = (String) metadata.get("UUID");
137 String metadataType = (String) metadata.get("type");
138 if ("VF".equalsIgnoreCase(metadataType) && name.equalsIgnoreCase(metadataUUID)) {
147 public LinkedHashMap getToscaInfos(LinkedHashMap sdcResponse) {
149 LinkedHashMap topologyTemplate = null;
151 String toscaModelUrl = (String) sdcResponse.get("toscaModelURL");
152 String serviceId = (String) sdcResponse.get("uuid");
153 File toscaFile = sdcClient.callGetWithAttachment(toscaModelUrl);
154 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
155 String tempFolderName = serviceId + timestamp;
156 File folderTemp = null;
159 unZipArchive(toscaFile.getName(), tempFolderName);
160 folderTemp = new File(tempFolderName);
161 LOGGER.debug("temp folder for tosca files : " + folderTemp.getName());
163 LinkedHashMap toscaMetaFileHashMap = parseToscaFile(tempFolderName + "/TOSCA-Metadata/TOSCA.meta");
164 topologyTemplate = getToscaTopologyTemplateNode(tempFolderName, toscaMetaFileHashMap);
165 return topologyTemplate;
166 } catch (TechnicalException e) {
167 LOGGER.error("unable to parse tosca file for id : " + serviceId, e);
168 return topologyTemplate;
171 deleteTempFiles(serviceId, toscaFile, folderTemp);
176 private LinkedHashMap getToscaTopologyTemplateNode(String tempFolderName,LinkedHashMap toscaMetaFileHashMap) {
177 LinkedHashMap topologyTemplate = null;
178 if (toscaMetaFileHashMap.get("Entry-Definitions") != null) {
179 String toscaFilePath = (String) toscaMetaFileHashMap.get("Entry-Definitions");
180 LinkedHashMap toscaFileHashMap = parseToscaFile(tempFolderName + "/" + toscaFilePath);
181 if (toscaFileHashMap.get("topology_template") != null) {
182 topologyTemplate = (LinkedHashMap) toscaFileHashMap.get("topology_template");
184 LOGGER.error("no Entry-Definitions node in TOSCA.meta");
187 LOGGER.error("no topology_template node in tosca file");
189 return topologyTemplate;
193 private void deleteTempFiles(String serviceId, File toscaFile, File folderTemp) {
195 if(folderTemp!=null){
196 LOGGER.debug("deleting temp folder for tosca files : " + folderTemp.getName());
197 FileUtils.deleteDirectory(folderTemp);
199 LOGGER.debug("deleting tosca archive : " + toscaFile.getName());
200 FileUtils.forceDelete(toscaFile);
201 } catch (IOException e) {
202 LOGGER.error("unable to delete temp directory tosca file for id : " + serviceId, e);
206 private LinkedHashMap parseToscaFile(String fileName) {
208 File toscaFile = new File(fileName);
209 if (!toscaFile.exists()) {
210 throw new TechnicalException("unable to find file : " + fileName);
213 return (LinkedHashMap) mapper.readValue(toscaFile, Object.class);
214 } catch (IOException e) {
215 LOGGER.warn("unable to parse tosca file : " + fileName, e);
216 throw new TechnicalException("Unable to parse tosca file : " + fileName);
218 } catch (NullPointerException e) {
219 LOGGER.warn("unable to find tosca file : " + fileName, e);
220 throw new TechnicalException("unable to find tosca file : " + fileName);
228 * @param zipFile input zip file
229 * @param outputFolder zip file output folder
231 private void unZipArchive(String zipFile, String outputFolder) {
233 byte[] buffer = new byte[1024];
237 // create output directory is not exists
238 File folder = new File(outputFolder);
239 if (!folder.exists()) {
243 // get the zip file content
244 try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
245 // get the zipped file list entry
246 ZipEntry ze = zis.getNextEntry();
250 String fileName = ze.getName();
251 File newFile = new File(outputFolder + File.separator + fileName);
253 LOGGER.debug("File to unzip : " + newFile.getAbsoluteFile());
255 // create all non exists folders
256 // else you will hit FileNotFoundException for compressed folder
257 new File(newFile.getParent()).mkdirs();
259 try (FileOutputStream fos = new FileOutputStream(newFile)) {
262 while ((len = zis.read(buffer)) > 0) {
263 fos.write(buffer, 0, len);
268 ze = zis.getNextEntry();
275 LOGGER.debug("Done");
277 } catch (IOException ex) {
278 LOGGER.error("Error while unzipping ToscaModel archive from ONAP", ex);
279 throw new TechnicalException("Error while unzipping ToscaModel archive from ONAP");