Preparing the request payload for calling SO macro flow.
[externalapi/nbi.git] / src / main / java / org / onap / nbi / apis / servicecatalog / ToscaInfosProcessor.java
1 /**
2  * Copyright (c) 2018 Orange
3  *
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
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
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
12  * the License.
13  */
14
15 package org.onap.nbi.apis.servicecatalog;
16
17 import java.nio.file.Path;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.LinkedHashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26
27 import org.onap.nbi.apis.serviceorder.model.consumer.VFModelInfo;
28 import org.onap.sdc.tosca.parser.api.IEntityDetails;
29 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
30 import org.onap.sdc.tosca.parser.elements.queries.EntityQuery;
31 import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery;
32 import org.onap.sdc.tosca.parser.enums.SdcTypes;
33 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
34 import org.onap.sdc.tosca.parser.impl.SdcPropertyNames;
35 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
36 import org.onap.sdc.toscaparser.api.NodeTemplate;
37 import org.onap.sdc.toscaparser.api.elements.Metadata;
38 import org.onap.sdc.toscaparser.api.parameters.Input;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.stereotype.Service;
43 import com.fasterxml.jackson.databind.ObjectMapper;
44 import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
45 import io.swagger.models.Model;
46 import io.swagger.models.ModelImpl;
47 import io.swagger.models.properties.Property;
48 import io.swagger.models.properties.PropertyBuilder;
49 import io.swagger.util.Json;
50
51 @Service
52 public class ToscaInfosProcessor {
53
54     @Autowired
55     SdcClient sdcClient;
56
57     @Autowired
58     private ServiceSpecificationDBManager serviceSpecificationDBManager;
59
60     private Set<String> vnfInstanceParams = new HashSet<String>(Arrays.asList("onap_private_net_id",
61         "onap_private_subnet_id", "pub_key", "sec_group", "install_script_version", "demo_artifacts_version",
62         "cloud_env", "public_net_id", "aic-cloud-region", "image_name", "flavor_name"));
63
64     final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); // jackson databind
65
66     private static final Logger LOGGER = LoggerFactory.getLogger(ToscaInfosProcessor.class);
67
68     public void buildResponseWithSdcToscaParser(Path path, Map serviceCatalogResponse) throws SdcToscaParserException {
69
70         SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();
71         ISdcCsarHelper sdcCsarHelper = factory.getSdcCsarHelper(path.toFile().getAbsolutePath(), false);
72         List<Input> inputs = sdcCsarHelper.getServiceInputs();
73         if (inputs != null && inputs.size() > 0) {
74             ArrayList serviceSpecCharacteristic = new ArrayList();
75             for (Input input : inputs) {
76                 LinkedHashMap mapParameter = new LinkedHashMap();
77                 mapParameter.put("name", input.getName());
78                 mapParameter.put("description", input.getDescription());
79                 mapParameter.put("valueType", input.getType());
80                 mapParameter.put("@type", "ONAPserviceCharacteristic");
81                 mapParameter.put("required", input.isRequired());
82                 mapParameter.put("status", null);
83                 mapParameter.put("serviceSpecCharacteristicValue", null);
84                 // If this Input has a default value, then put it in serviceSpecCharacteristicValue
85                 if (input.getDefault() != null) {
86                     List<LinkedHashMap> serviceSpecCharacteristicValues =
87                             buildServiceSpecCharacteristicsValuesFromSdc(input);
88                     mapParameter.put("serviceSpecCharacteristicValue", serviceSpecCharacteristicValues);
89                 }
90                 serviceSpecCharacteristic.add(mapParameter);
91             }
92             serviceCatalogResponse.put("serviceSpecCharacteristic", serviceSpecCharacteristic);
93         }
94         List<NodeTemplate> nodeTemplates = sdcCsarHelper.getServiceNodeTemplates();
95
96         List<LinkedHashMap> resourceSpecifications =
97                 (List<LinkedHashMap>) serviceCatalogResponse.get("resourceSpecification");
98         for (LinkedHashMap resourceSpecification : resourceSpecifications) {
99             if (resourceSpecification.get("id") != null) {
100                 String id = (String) resourceSpecification.get("id");
101                 LOGGER.debug("get tosca infos for service id: {}", id);
102                 NodeTemplate nodeTemplate = null;
103                 for (NodeTemplate node : nodeTemplates) {
104                     if (node.getMetaData().getValue("UUID").equals(id)) {
105                         nodeTemplate = node;
106                         break;
107                     }
108                 }
109                 if (nodeTemplate == null)
110                     continue;
111                 resourceSpecification.put("modelCustomizationId",
112                         sdcCsarHelper.getNodeTemplateCustomizationUuid(nodeTemplate));
113             }
114         }
115     }
116
117     private List<LinkedHashMap> buildServiceSpecCharacteristicsValuesFromSdc(Input input) {
118
119         List<LinkedHashMap> serviceSpecCharacteristicValues = new ArrayList<>();
120         LinkedHashMap serviceSpecCharacteristicValue = new LinkedHashMap();
121
122         serviceSpecCharacteristicValue.put("isDefault", true);
123         serviceSpecCharacteristicValue.put("value", input.getDefault());
124         serviceSpecCharacteristicValue.put("valueType", input.getType());
125         serviceSpecCharacteristicValues.add(serviceSpecCharacteristicValue);
126
127         return serviceSpecCharacteristicValues;
128     }
129
130     public void buildAndSaveResponseWithSdcToscaParser(Path path, Map serviceCatalogResponse)
131                         throws SdcToscaParserException {
132
133                 SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();
134                 ISdcCsarHelper sdcCsarHelper = factory.getSdcCsarHelper(path.toFile().getAbsolutePath(), false);
135                 List<Input> inputs = sdcCsarHelper.getServiceInputs();
136
137                 List<IEntityDetails> vfEntityList = sdcCsarHelper.getEntity(EntityQuery.newBuilder(SdcTypes.VF).build(),
138                                 TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build(), false);
139
140                 Map<String, String> listOfInstanceParameters = new HashMap<>();
141                 if (!vfEntityList.isEmpty()) {
142
143                         IEntityDetails iEntityDetails = vfEntityList.get(0);
144                         Map<String, org.onap.sdc.toscaparser.api.Property> groupProperties = iEntityDetails.getProperties();
145
146                         for (String key : groupProperties.keySet()) {
147                                 org.onap.sdc.toscaparser.api.Property property = groupProperties.get(key);
148                                 String paramName = property.getName();
149                                 if (paramName != null) {
150                                         if (vnfInstanceParams.stream()
151                                                         .filter(vnfInstanceParam -> vnfInstanceParam.equalsIgnoreCase(paramName)).findFirst()
152                                                         .isPresent()) {
153                                                 listOfInstanceParameters.put(paramName, property.getValue().toString());
154                                         }
155                                 }
156                         }
157
158                 }
159
160                 // it will build Entity as VfModules
161                 List<IEntityDetails> vfModuleEntityList = sdcCsarHelper.getEntity(
162                                 EntityQuery.newBuilder("org.openecomp.groups.VfModule").build(),
163                                 TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE)
164                                                 .customizationUUID(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID).build(),
165                                 false);
166                 List<VFModelInfo> listOfVfModelInfo = new ArrayList<>();
167
168                 if (!vfModuleEntityList.isEmpty()) {
169                         // Fetching vfModule metadata in a loop
170                         for (IEntityDetails vfModuleEntity : vfModuleEntityList) {
171                                 VFModelInfo vfModel = new VFModelInfo();
172                                 Metadata vfMetadata = vfModuleEntity.getMetadata();
173                                 // Preparing VFModel
174                                 vfModel.setModelInvariantUuid(
175                                                 testNull(vfMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)));
176                                 vfModel.setModelName(testNull(vfMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME)));
177                                 vfModel.setModelUuid(testNull(vfMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)));
178                                 vfModel.setModelVersion(
179                                                 testNull(vfMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION)));
180                                 vfModel.setModelCustomizationUuid(testNull(vfMetadata.getValue("vfModuleModelCustomizationUUID")));
181
182                                 // Adding it to the list
183                                 listOfVfModelInfo.add(vfModel);
184                         }
185                 }
186
187                 Map<String, Model> definitions = new HashMap<String, Model>();
188                 Model model = new ModelImpl();
189
190                 if (!inputs.isEmpty() && inputs.size() > 0) {
191                         for (Input input : inputs) {
192                                 Property property = null;
193                                 if (input.getType().equals("list") || input.getType().equals("map"))
194                                         property = PropertyBuilder.build("array", null, null);
195                                 else
196                                         property = PropertyBuilder.build(input.getType(), null, null);
197
198                                 property.setDescription(input.getDescription());
199                                 property.setRequired(input.isRequired());
200
201                                 if (input.getDefault() != null) {
202                                         property.setDefault(input.getDefault().toString());
203                                 }
204                                 ((ModelImpl) model).addProperty(input.getName(), property);
205                         }
206                         definitions.put("ServiceCharacteristics", model);
207
208                 }
209
210                 String svcCharacteristicsJson = Json.pretty(definitions);
211                 serviceSpecificationDBManager.saveSpecificationInputSchema(svcCharacteristicsJson, serviceCatalogResponse);
212
213                 Metadata serviceMetadata = sdcCsarHelper.getServiceMetadata();
214                 String instantationType = serviceMetadata.getValue("instantiationType");
215                 serviceCatalogResponse.put("instantiationType", instantationType);
216
217                 LinkedHashMap inputSchemaRef = new LinkedHashMap();
218                 // use object to match examples in Specifications
219                 inputSchemaRef.put("valueType", "object");
220                 inputSchemaRef.put("@schemaLocation",
221                                 "/serviceSpecification/" + serviceCatalogResponse.get("id") + "/specificationInputSchema");
222                 inputSchemaRef.put("@type", serviceCatalogResponse.get("name") + "_ServiceCharacteristic");
223
224                 LinkedHashMap serviceSpecCharacteristic = new LinkedHashMap();
225                 serviceSpecCharacteristic.put("name", serviceCatalogResponse.get("name") + "_ServiceCharacteristics");
226                 serviceSpecCharacteristic.put("description",
227                                 "This object describes all the inputs needed from the client to interact with the "
228                                                 + serviceCatalogResponse.get("name") + " Service Topology");
229                 serviceSpecCharacteristic.put("valueType", "object");
230                 serviceSpecCharacteristic.put("@type", "ONAPServiceCharacteristic");
231                 serviceSpecCharacteristic.put("@schemaLocation", "null");
232                 serviceSpecCharacteristic.put("serviceSpecCharacteristicValue", inputSchemaRef);
233
234                 serviceCatalogResponse.put("serviceSpecCharacteristic", serviceSpecCharacteristic);
235
236                 List<NodeTemplate> nodeTemplates = sdcCsarHelper.getServiceNodeTemplates();
237                 List<LinkedHashMap> resourceSpecifications = (List<LinkedHashMap>) serviceCatalogResponse
238                                 .get("resourceSpecification");
239                 for (LinkedHashMap resourceSpecification : resourceSpecifications) {
240                         if (resourceSpecification.get("id") != null) {
241                                 String id = (String) resourceSpecification.get("id");
242                                 LOGGER.debug("get tosca infos for service id: {}", id);
243                                 NodeTemplate nodeTemplate = null;
244                                 for (NodeTemplate node : nodeTemplates) {
245                                         if (node.getMetaData().getValue("UUID").equals(id)) {
246                                                 nodeTemplate = node;
247                                                 break;
248                                         }
249                                 }
250                                 if (nodeTemplate == null)
251                                         continue;
252                                 resourceSpecification.put("modelCustomizationId",
253                                                 sdcCsarHelper.getNodeTemplateCustomizationUuid(nodeTemplate));
254                                 if (!vfModuleEntityList.isEmpty()) {
255                                         resourceSpecification.put("childResourceSpecification", listOfVfModelInfo);
256                                 }
257                                 resourceSpecification.put("InstanceSpecification", listOfInstanceParameters);
258
259                         }
260                 }
261         }
262
263     private static String testNull(Object object) {
264         if (object == null) {
265           return "NULL";
266         } else if (object instanceof Integer) {
267           return object.toString();
268         } else if (object instanceof String) {
269           return (String) object;
270         } else {
271           return "Type not recognized";
272         }
273     }
274
275 }