[SDC] rebase 1710 code
[sdc.git] / asdc-tests / src / main / java / org / openecomp / sdc / ci / tests / execute / imports / ExportToscaTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.ci.tests.execute.imports;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertNull;
26 import static org.junit.Assert.assertTrue;
27
28 import java.io.ByteArrayInputStream;
29 import java.io.InputStream;
30 import java.nio.file.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.stream.Collectors;
39 import java.util.Optional;
40
41 import org.apache.commons.codec.binary.Base64;
42 import org.junit.Rule;
43 import org.junit.rules.TestName;
44 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
45 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
46 import org.openecomp.sdc.be.model.ArtifactDefinition;
47 import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
48 import org.openecomp.sdc.be.model.Component;
49 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
50 import org.openecomp.sdc.be.model.ComponentInstance;
51 import org.openecomp.sdc.be.model.ComponentInstanceInput;
52 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
53 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
54 import org.openecomp.sdc.be.model.GroupDefinition;
55 import org.openecomp.sdc.be.model.GroupProperty;
56 import org.openecomp.sdc.be.model.InputDefinition;
57 import org.openecomp.sdc.be.model.Resource;
58 import org.openecomp.sdc.be.model.Service;
59 import org.openecomp.sdc.be.model.User;
60 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
61 import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
62 import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
63 import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
64 import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
65 import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
66 import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
67 import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
68 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
69 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
70 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
71 import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
72 import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
73 import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
74 import org.openecomp.sdc.ci.tests.utils.rest.InputsRestUtils;
75 import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
76 import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
77 import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
78 import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
79 import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils;
80 import org.openecomp.sdc.common.api.Constants;
81 import org.testng.annotations.DataProvider;
82 import org.testng.annotations.Test;
83 import org.yaml.snakeyaml.Yaml;
84
85 import com.google.gson.Gson;
86 import com.google.gson.JsonParser;
87 import com.google.gson.reflect.TypeToken;
88
89 public class ExportToscaTest extends ComponentBaseTest {
90         @Rule
91         public static TestName name = new TestName();
92         String rootPath = System.getProperty("user.dir");
93         private static final String CSARS_PATH = "/src/test/resources/CI/csars/";
94         public static String userDefinedNodeYaml = "CustomVL.yml";
95
96         public ExportToscaTest() {
97                 super(name, ExportToscaTest.class.getName());
98         }
99
100         @DataProvider(name = "vfModuleCsar")
101         public static Object[][] csarNames() {
102                  return new Object[][] { { "VSPPackage", true }, { "csar_1", true }, { "noArtifact", false }, {"noVfModule", false} };
103 //              return new Object[][] { { "VSPPackage", true }, { "csar_1", true }, { "noArtifact", false } };
104         }
105
106         @Test(dataProvider = "vfModuleCsar")
107         public void exportVfModuleTest(String csarname, boolean includeGroups) throws Exception {
108                 System.out.println("run for csar " + csarname);
109                 User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
110
111                 Resource createdResource = createVfFromCSAR(sdncModifierDetails, csarname);
112
113                 validateGroupsInResource(sdncModifierDetails, createdResource, includeGroups);
114         }
115
116         @Test(dataProvider = "vfModuleCsar")
117         public void exportVfModuleInstanceTest(String csarname, boolean includeGroups) throws Exception {
118                 System.out.println("run for csar " + csarname);
119                 User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
120
121                 // create resource
122                 Resource createdResource = createVfFromCSAR(sdncModifierDetails, csarname);
123
124                 // change state to check in
125                 RestResponse checkinState = LifecycleRestUtils.changeComponentState(createdResource, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
126                 BaseRestUtils.checkSuccess(checkinState);
127                 ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncModifierDetails.getUserId());
128
129                 // 2 create service
130                 RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifierDetails);
131                 ResourceRestUtils.checkCreateResponse(createServiceResponse);
132                 Service service = ResponseParser.parseToObjectUsingMapper(createServiceResponse.getResponse(), Service.class);
133
134                 // 3 create vf instance in service
135                 ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(createdResource);
136                 RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service);
137                 ResourceRestUtils.checkCreateResponse(createComponentInstance);
138
139                 RestResponse getService = ServiceRestUtils.getService(service.getUniqueId());
140                 BaseRestUtils.checkSuccess(getService);
141                 service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
142
143                 List<GroupDefinition> groupsInResource = createdResource.getGroups();
144                 int vfModuleCount = 0;
145                 List<GroupDefinition> vfModulesInRes = groupsInResource.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList());
146
147                 ComponentInstance componentInstance = service.getComponentInstances().get(0);
148                 String normalizedName = componentInstance.getNormalizedName();
149
150                 Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, service);
151                 assertNotNull(load);
152                 Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
153                 assertNotNull(topology_template);
154                 Map<String, Object> groups = (Map<String, Object>) topology_template.get("groups");
155                 if (includeGroups) {
156                         assertNotNull(vfModulesInRes);
157                         assertNotNull(groups);
158
159                         assertEquals("Validate count of vf module instances", vfModulesInRes.size(), groups.size());
160
161                         vfModulesInRes.forEach(modInRes -> {
162                                 validateVfModuleVsInstance(normalizedName, groups, modInRes);
163                         });
164                 }else{
165                         assertNull(groups);
166                 }
167         }
168
169         private void validateVfModuleVsInstance(String normalizedName, Map<String, Object> groups, GroupDefinition modInRes) {
170                 String instName = normalizedName + ".." + modInRes.getName();
171                 Map<String, Object> group = (Map<String, Object>) groups.get(instName);
172                 assertNotNull(group);
173
174                 String type = (String) group.get("type");
175                 assertNotNull(type);
176                 assertEquals("Validate group instance type", modInRes.getType(), type);
177
178                 Map<String, Object> metadata = (Map<String, Object>) group.get("metadata");
179                 assertNotNull(metadata);
180
181                 String invariantUUID = (String) metadata.get("vfModuleModelInvariantUUID");
182                 String name = (String) metadata.get("vfModuleModelName");
183                 String UUID = (String) metadata.get("vfModuleModelUUID");
184                 String version = (String) metadata.get("vfModuleModelVersion");
185
186                 String customizationUUID = (String) metadata.get("vfModuleModelCustomizationUUID");
187                 assertNotNull("Validate group instance customizationUUID", customizationUUID);
188
189                 assertEquals("Validate group instance InvariantUUID", modInRes.getInvariantUUID(), invariantUUID);
190                 assertEquals("Validate group instance name", modInRes.getName(), name);
191                 assertEquals("Validate group instance UUID", modInRes.getGroupUUID(), UUID);
192                 assertEquals("Validate group instance version", modInRes.getVersion(), version);
193
194                 Map<String, Object> propertiesInInst = (Map<String, Object>) group.get("properties");
195                 assertNotNull(propertiesInInst);
196
197                 List<GroupProperty> propertiesInGroup = modInRes.convertToGroupProperties();
198                 // property isBase not exist in tosca
199                 assertEquals("Validate group instance properties size", propertiesInGroup.size() - 1, propertiesInInst.size());
200                 propertiesInGroup.forEach(propInGroup -> {
201                         String propName = propInGroup.getName();
202                         if (!propName.equals("isBase")) {
203                                 Object propValue = propertiesInInst.get(propName);
204                                 String valueInGroup = propInGroup.getValue();
205                                 if (valueInGroup != null && !valueInGroup.isEmpty()) {
206                                         assertNotNull(propValue);
207                                         assertEquals("Validate group instance property value for " + propName, valueInGroup, propValue.toString());
208                                 } else {
209                                         assertNull(propValue);
210                                 }
211                         }
212                 });
213         }
214
215         private void validateGroupsInResource(User sdncModifierDetails, Resource createdResource, boolean includeGroups) throws Exception {
216                 Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
217                 assertNotNull(load);
218                 Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
219                 assertNotNull(topology_template);
220                 Map<String, Object> groups = (Map<String, Object>) topology_template.get("groups");
221                 if (includeGroups) {
222                         assertNotNull(groups);
223                         List<GroupDefinition> groupsOrigin = createdResource.getGroups();
224
225                         assertEquals("Validate groups size", groupsOrigin.size(), groups.size());
226                         for (GroupDefinition group : groupsOrigin) {
227                                 Map<String, Object> groupTosca = (Map<String, Object>) groups.get(group.getName());
228                                 assertNotNull(groupTosca);
229
230                                 Map<String, Object> metadata = (Map<String, Object>) groupTosca.get("metadata");
231                                 assertNotNull(metadata);
232
233                                 String invariantUUID;
234                                 String name;
235                                 String UUID;
236                                 String version;
237                                 Map<String, Object> properties = (Map<String, Object>) groupTosca.get("properties");
238
239                                 if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
240                                         invariantUUID = (String) metadata.get("vfModuleModelInvariantUUID");
241                                         name = (String) metadata.get("vfModuleModelName");
242                                         UUID = (String) metadata.get("vfModuleModelUUID");
243                                         version = (String) metadata.get("vfModuleModelVersion");
244                                         assertNotNull(properties);
245
246                                         validateVfModuleProperties(createdResource, group, properties);
247                                 } else {
248                                         invariantUUID = (String) metadata.get("invariantUUID");
249                                         name = (String) metadata.get("name");
250                                         UUID = (String) metadata.get("UUID");
251                                         version = (String) metadata.get("version");
252                                         assertNull(properties);
253
254                                 }
255                                 assertEquals("Validate InvariantUUID", group.getInvariantUUID(), invariantUUID);
256                                 assertEquals("Validate name", group.getName(), name);
257                                 assertEquals("Validate UUID", group.getGroupUUID(), UUID);
258                                 assertEquals("Validate version", group.getVersion(), version);
259                         }
260                 } else {
261                         assertEquals(null, groups);
262                 }
263         }
264
265         private void validateVfModuleProperties(Resource createdResource, GroupDefinition group, Map<String, Object> properties) {
266                 // vf_module_type
267                 String vf_module_type = (String) properties.get("vf_module_type");
268                 List<GroupProperty> props = group.convertToGroupProperties();
269
270                 GroupProperty isBaseProp = getGroupPropertyByName(group, Constants.IS_BASE);
271                 assertNotNull(isBaseProp);
272
273                 String value = isBaseProp.getValue() == null ? isBaseProp.getDefaultValue() : isBaseProp.getValue();
274                 boolean bvalue = Boolean.parseBoolean(value);
275                 if (bvalue) {
276                         assertEquals("Validate vf_module_type", "Base", vf_module_type);
277                 } else {
278                         assertEquals("Validate vf_module_type", "Expansion", vf_module_type);
279                 }
280
281                 // vf_module_description
282                 String vf_module_description = (String) properties.get("vf_module_description");
283                 assertEquals("Validate vf_module_description", group.getDescription(), vf_module_description);
284
285                 // volume_group
286                 Boolean volume_group = (Boolean) properties.get("volume_group");
287                 boolean isVolume = false;
288                 List<String> artifactsList = group.getArtifacts();
289                 List<ArtifactDefinition> artifacts = new ArrayList<>();
290                 if (artifactsList != null && !artifactsList.isEmpty()) {
291                         ArtifactDefinition masterArtifact = findMasterArtifact(createdResource.getDeploymentArtifacts(), artifacts, artifactsList);
292                         if (masterArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
293                                 isVolume = true;
294                         }
295                 }
296                 assertEquals("Validate volume_group", isVolume, volume_group);
297
298                 // min_vf_module_instances
299                 Integer min_vf_module_instances = (Integer) properties.get("min_vf_module_instances");
300                 GroupProperty minInstProp = getGroupPropertyByName(group, "min_vf_module_instances");
301                 assertNotNull(minInstProp);
302                 assertEquals("Validate min_vf_module_instances", minInstProp.getValue(), min_vf_module_instances.toString());
303
304                 // vf_module_label
305                 String vf_module_label = (String) properties.get("vf_module_label");
306                 GroupProperty labelProp = getGroupPropertyByName(group, "vf_module_label");
307                 assertNotNull(labelProp);
308                 assertEquals("Validate vf_module_label", labelProp.getValue(), vf_module_label);
309
310                 // vf_module_label
311                 Integer initial_count = (Integer) properties.get("initial_count");
312                 GroupProperty initCountProp = getGroupPropertyByName(group, "initial_count");
313                 assertNotNull(initCountProp);
314                 assertEquals("Validate initial_count", initCountProp.getValue(), initial_count.toString());
315
316                 // max_vf_module_instances
317                 Integer max_vf_module_instances = (Integer) properties.get("max_vf_module_instances");
318                 GroupProperty maxInstProp = getGroupPropertyByName(group, "max_vf_module_instances");
319                 assertNotNull(maxInstProp);
320                 if (max_vf_module_instances != null) {
321                         assertEquals("Validate max_vf_module_instances", maxInstProp.getValue(), max_vf_module_instances.toString());
322                 } else {
323                         assertEquals("Validate max_vf_module_instances", maxInstProp.getValue(), max_vf_module_instances);
324                 }
325         }
326
327         private GroupProperty getGroupPropertyByName(GroupDefinition group, String name) {
328                 List<GroupProperty> props = group.convertToGroupProperties();
329                 for (GroupProperty prop : props) {
330                         if (prop.getName().equals(name)) {
331                                 return prop;
332                         }
333                 }
334                 return null;
335         }
336
337         @Test(enabled = true)
338         public void exportCsarInputsTest() throws Exception {
339                 User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
340
341                 Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csar_1");
342                 Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
343                 assertNotNull(load);
344
345                 Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
346                 assertNotNull(topology_template);
347
348                 Map<String, Object> inputs = (Map<String, Object>) topology_template.get("inputs");
349                 assertNotNull(inputs);
350
351                 List<InputDefinition> inputsFromResource = createdResource.getInputs();
352                 assertEquals("validate inputs size", inputsFromResource.size(), inputs.size());
353                 for (InputDefinition inputDef : inputsFromResource) {
354                         Map<String, Object> inputInFile = (Map<String, Object>) inputs.get(inputDef.getName());
355                         assertNotNull(inputInFile);
356                         validateInput(inputDef, inputInFile);
357                 }
358                 List<ComponentInstance> componentInstances = createdResource.getComponentInstances();
359                 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = createdResource.getComponentInstancesProperties();
360                 Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
361                 assertNotNull(node_templates);
362
363                 JsonParser jsonParser = new JsonParser();
364
365                 for (Map.Entry<String, List<ComponentInstanceProperty>> entry : componentInstancesProperties.entrySet()) {
366
367                         Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(entry.getKey())).findFirst();
368                         assertTrue(findFirst.isPresent());
369                         String resourceName = findFirst.get().getName();
370                         Map<String, Object> instance = (Map<String, Object>) node_templates.get(resourceName);
371                         assertNotNull(instance);
372                         Map<String, Object> properties = (Map<String, Object>) instance.get("properties");
373
374                         for (ComponentInstanceProperty cip : entry.getValue()) {
375                                 if (cip.getValueUniqueUid() != null && !cip.getValueUniqueUid().isEmpty()) {
376                                         assertNotNull(properties);
377                                         if (cip.getValue().contains("get_input")) {
378                                                 Object prop = properties.get(cip.getName());
379                                                 assertNotNull(prop);
380
381                                                 Gson gson = new Gson();
382                                                 String json = gson.toJson(prop);
383                                                 assertEquals("validate json property", cip.getValue(), json);
384                                         }
385
386                                 }
387                         }
388
389                 }
390
391         }
392
393         @Test
394         public void importExportCsarWithJsonPropertyType() throws Exception {
395                 User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
396                 String payloadName = "jsonPropertyTypeTest.csar";
397                 ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
398                 String rootPath = System.getProperty("user.dir");
399                 Path path = null;
400                 byte[] data = null;
401                 String payloadData = null;
402                 path = Paths.get(rootPath + "/src/test/resources/CI/csars/jsonPropertyTypeTest.csar");
403                 data = Files.readAllBytes(path);
404                 payloadData = Base64.encodeBase64String(data);
405                 resourceDetails.setPayloadData(payloadData);
406                 resourceDetails.setCsarUUID(payloadName);
407                 resourceDetails.setPayloadName(payloadName);
408                 resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
409                 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
410                 BaseRestUtils.checkCreateResponse(createResource);
411                 Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
412                 ComponentInstance pmaaServer = resource.getComponentInstances().stream().filter(p -> p.getName().equals("pmaa_server_0")).findAny().get();
413                 ComponentInstanceProperty jsonProp = resource.getComponentInstancesProperties().get(pmaaServer.getUniqueId()).stream().filter(p -> p.getType().equals(ToscaPropertyType.JSON.getType())).findAny().get();
414                 String jsonValue = "{\"pmaa.sb_nic\":{\"address\":{\"get_input\":\"pmaa_dpu_fixed_ip\"},\"cidr\":{\"get_input\":\"pmaa_dpu_cidr\"},\"gateway\":{\"get_input\":\"pmaa_dpu_gateway\"}}}";
415                 assertEquals(jsonProp.getValue(), jsonValue);
416                 // download and compare
417                 Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, resource);
418                 assertNotNull(load);
419                 Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
420                 assertNotNull(topology_template);
421                 Map<String, Object> nodes = (Map<String, Object>) topology_template.get("node_templates");
422                 assertNotNull(nodes);
423                 Map<String, Object> pmaaServerObj = (Map<String, Object>) nodes.get("pmaa_server_0");
424                 assertNotNull(pmaaServerObj);
425                 Map<String, Object> props = (Map<String, Object>) pmaaServerObj.get("properties");
426                 assertNotNull(props);
427                 Map<String, Object> jsonPropObj = (Map<String, Object>) props.get("metadata");
428                 assertNotNull(jsonPropObj);
429                 Gson gson = new Gson();
430                 String json = gson.toJson(jsonPropObj);
431                 assertEquals(json, jsonValue);
432         }
433
434         @Test(enabled = true)
435         public void exportServiceInputValue() throws Exception {
436                 // 1 create vf as certified
437                 User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
438
439                 Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csar_1");
440                 RestResponse checkinState = LifecycleRestUtils.changeComponentState(createdResource, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
441                 BaseRestUtils.checkSuccess(checkinState);
442                 ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncModifierDetails.getUserId());
443
444                 // 2 create service
445                 RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifierDetails);
446                 ResourceRestUtils.checkCreateResponse(createServiceResponse);
447                 Service service = ResponseParser.parseToObjectUsingMapper(createServiceResponse.getResponse(), Service.class);
448
449                 // 3 create vf instance in service
450                 ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(createdResource);
451                 RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service);
452                 ResourceRestUtils.checkCreateResponse(createComponentInstance);
453
454                 RestResponse getService = ServiceRestUtils.getService(service.getUniqueId());
455                 BaseRestUtils.checkSuccess(getService);
456                 service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
457
458                 // 4 download tosca template
459                 Map<String, Object> tosca = downloadAndParseToscaTemplate(sdncModifierDetails, service);
460                 assertNotNull(tosca);
461                 Map<String, Object> topology_template = (Map<String, Object>) tosca.get("topology_template");
462                 assertNotNull(topology_template);
463
464                 // 5 validate no inputs in service
465                 Map<String, Object> inputs = (Map<String, Object>) tosca.get("inputs");
466                 assertNull(inputs);
467
468                 List<ComponentInstance> componentInstances = service.getComponentInstances();
469                 assertNotNull(componentInstances);
470                 assertEquals(1, componentInstances.size());
471                 ComponentInstance vfi = componentInstances.get(0);
472
473                 // 6 add instance inputs in service
474                 RestResponse getComponentInstanceInputsResponse = InputsRestUtils.getComponentInstanceInputs(service, vfi);
475                 BaseValidationUtils.checkSuccess(getComponentInstanceInputsResponse);
476                 List<ComponentInstancePropInput> instanceInputs = new Gson().fromJson(getComponentInstanceInputsResponse.getResponse(), new TypeToken<ArrayList<ComponentInstancePropInput>>() {
477                 }.getType());
478                 // Take only the 2 first inputs
479                 List<ComponentInstancePropInput> inputsToAdd = instanceInputs.stream().limit(2).collect(Collectors.toList());
480
481                 // 7 Build component instances input map to add to server
482                 ComponentInstInputsMap buildComponentInstInputsMap = buildComponentInstInputsMap(vfi.getUniqueId(), inputsToAdd);
483                 RestResponse addInputResponse = InputsRestUtils.addInput(service, buildComponentInstInputsMap, UserRoleEnum.DESIGNER);
484                 BaseValidationUtils.checkSuccess(addInputResponse);
485
486                 // 8 validate inputs in service
487                 // 8.1 download tosca template
488                 getService = ServiceRestUtils.getService(service.getUniqueId());
489                 BaseRestUtils.checkSuccess(getService);
490                 service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
491
492                 tosca = downloadAndParseToscaTemplate(sdncModifierDetails, service);
493                 assertNotNull(tosca);
494                 topology_template = (Map<String, Object>) tosca.get("topology_template");
495                 assertNotNull(topology_template);
496
497                 // 8.2 validate inputs in service
498                 inputs = (Map<String, Object>) topology_template.get("inputs");
499                 assertNotNull(inputs);
500                 assertEquals(2, inputs.size());
501
502                 // validate created inputs vs inputs in Tosca inputs section
503                 final Map<String, Object> inputsFinal = inputs;
504                 buildComponentInstInputsMap.getComponentInstanceInputsMap().values().forEach(listPerInstance -> {
505                         listPerInstance.forEach(input -> {
506                                 Map<String, Object> inputInMap = (Map<String, Object>) inputsFinal.get(input.getName());
507                                 assertNotNull(inputInMap);
508                         });
509                 });
510                 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = service.getComponentInstancesInputs();
511
512                 // validate created inputs vs inputs in Tosca instance input value
513                 List<ComponentInstanceInput> vfiInputs = componentInstancesInputs.get(vfi.getUniqueId());
514                 assertNotNull(vfiInputs);
515                 assertEquals(2, vfiInputs.size());
516
517                 Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
518                 assertNotNull(node_templates);
519
520                 Map<String, Object> instance = (Map<String, Object>) node_templates.get(vfi.getName());
521                 assertNotNull(instance);
522                 Map<String, Object> properties = (Map<String, Object>) instance.get("properties");
523                 assertNotNull(properties);
524
525                 vfiInputs.forEach(vfiInput -> {
526                         Map<String, Object> inputPropValueInTosca = (Map<String, Object>) properties.get(vfiInput.getName());
527                         assertNotNull(inputPropValueInTosca);
528                         String instaneInputName = (String) inputPropValueInTosca.get("get_input");
529                         assertNotNull(instaneInputName);
530                         Map<String, Object> inputInMap = (Map<String, Object>) inputsFinal.get(instaneInputName);
531                         assertNotNull(inputInMap);
532                 });
533
534         }
535
536         @Test(enabled = true)
537         public void exportComponentInstancesTest() throws Exception {
538                 User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
539
540                 Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csar_1");
541
542                 Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
543                 assertNotNull(load);
544                 Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
545                 assertNotNull(topology_template);
546
547                 Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
548                 assertNotNull(node_templates);
549
550                 RestResponse getResource = ResourceRestUtils.getResource(createdResource.getUniqueId());
551                 BaseRestUtils.checkSuccess(getResource);
552                 Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
553                 List<ComponentInstance> componentInstances = resource.getComponentInstances();
554
555                 assertEquals(componentInstances.size(), node_templates.size());
556
557                 for (ComponentInstance ci : componentInstances) {
558                         Map<String, Object> instance = (Map<String, Object>) node_templates.get(ci.getName());
559                         assertNotNull(instance);
560                         Map<String, Object> metadata = (Map<String, Object>) instance.get("metadata");
561                         assertNotNull(metadata);
562                         String customizationUUD = (String) metadata.get("customizationUUID");
563                         assertTrue(ci.getCustomizationUUID().equals(customizationUUD));
564                 }
565
566         }
567
568         @SuppressWarnings("unchecked")
569         @Test
570         public void extendNodeTemplateWithDefaultPropertyValuesTest() throws Exception {
571
572                 User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
573                 ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
574                 String payloadCsarName = "ToscaTemplateCsar.csar";
575                 Path path = Paths.get(rootPath + CSARS_PATH + "ToscaTemplateCsar.csar");
576                 byte[] data = Files.readAllBytes(path);
577                 String payloadData = Base64.encodeBase64String(data);
578                 resourceDetails.setPayloadData(payloadData);
579                 resourceDetails.setPayloadName(payloadCsarName);
580                 resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
581                 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
582                 BaseRestUtils.checkCreateResponse(createResource);
583                 Resource createdResource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
584
585                 Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
586                 assertNotNull(load);
587
588                 Map<String, Object> nodeTemplateProperties = findNodeTemplateProperties(load, "custom_vl");
589
590                 assertTrue(nodeTemplateProperties != null);
591                 assertTrue(nodeTemplateProperties.get("dhcp_enabled").equals(true));
592                 assertTrue(nodeTemplateProperties.get("ip_version").equals(4));
593                 assertTrue(nodeTemplateProperties.get("vl_name").equals("customvl"));
594         }
595
596         private Map<String, Object> findNodeTemplateProperties(Map<String, Object> load, String riName) {
597                 // find properties of node template (RI)
598                 return findToscaElement(
599                                 // find node template (RI) by name
600                                 findToscaElement(
601                                                 // find node templates
602                                                 findToscaElement(
603                                                                 // find topology template
604                                                                 findToscaElement(load, "topology_template"), "node_templates"),
605                                                 riName),
606                                 "properties");
607         }
608
609         @SuppressWarnings("unchecked")
610         private Map<String, Object> findToscaElement(Map<String, Object> load, String elementName) {
611                 return (Map<String, Object>) load.get(elementName);
612         }
613
614         // ----------------------------------------
615         private void validateInput(InputDefinition inputDef, Map<String, Object> inputInFile) {
616                 assertEquals("validate input type", inputDef.getType(), (String) inputInFile.get("type"));
617
618                 if (inputDef.getDefaultValue() == null) {
619                         assertNull(inputInFile.get("default"));
620                 } else {
621                         assertNotNull(inputInFile.get("default"));
622                         String value = inputDef.getDefaultValue().replace("\"", "");
623                         value = value.replace(" ", "");
624                         String expValue = inputInFile.get("default").toString().replace(" ", "");
625                         assertEquals("validate input default", value, expValue);
626                 }
627                 assertEquals("validate input description", inputDef.getDescription(), (String) inputInFile.get("description"));
628         }
629
630         private Map<String, Object> downloadAndParseToscaTemplate(User sdncModifierDetails, Component createdComponent) throws Exception {
631                 String artifactUniqeId = createdComponent.getToscaArtifacts().get("assettoscatemplate").getUniqueId();
632                 RestResponse toscaTemplate;
633
634                 if (createdComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
635                         toscaTemplate = ArtifactRestUtils.downloadResourceArtifactInternalApi(createdComponent.getUniqueId(), sdncModifierDetails, artifactUniqeId);
636
637                 } else {
638                         toscaTemplate = ArtifactRestUtils.downloadServiceArtifactInternalApi(createdComponent.getUniqueId(), sdncModifierDetails, artifactUniqeId);
639                 }
640                 BaseRestUtils.checkSuccess(toscaTemplate);
641
642                 ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(toscaTemplate.getResponse(), ArtifactUiDownloadData.class);
643                 byte[] fromUiDownload = artifactUiDownloadData.getBase64Contents().getBytes();
644                 byte[] decodeBase64 = Base64.decodeBase64(fromUiDownload);
645                 Yaml yaml = new Yaml();
646
647                 InputStream inputStream = new ByteArrayInputStream(decodeBase64);
648
649                 Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
650                 return load;
651         }
652
653         public ArtifactDefinition findMasterArtifact(Map<String, ArtifactDefinition> deplymentArtifact, List<ArtifactDefinition> artifacts, List<String> artifactsList) {
654                 for (String artifactUid : artifactsList) {
655                         for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
656                                 ArtifactDefinition artifact = entry.getValue();
657                                 if (artifactUid.equalsIgnoreCase(artifact.getUniqueId())) {
658                                         artifacts.add(artifact);
659                                 }
660
661                         }
662                 }
663                 ArtifactDefinition masterArtifact = null;
664                 for (ArtifactDefinition artifactInfo : artifacts) {
665                         String atrifactType = artifactInfo.getArtifactType();
666                         if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) {
667                                 masterArtifact = artifactInfo;
668                                 continue;
669                         }
670                         if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
671                                 masterArtifact = artifactInfo;
672                                 break;
673                         }
674                 }
675                 return masterArtifact;
676         }
677
678         private ComponentInstInputsMap buildComponentInstInputsMap(String addToInput, List<ComponentInstancePropInput> inputs) {
679                 Map<String, List<ComponentInstancePropInput>> map = new HashMap<>();
680                 map.put(addToInput, inputs);
681                 ComponentInstInputsMap componentInstInputsMap = new ComponentInstInputsMap();
682                 componentInstInputsMap.setComponentInstanceInputsMap(map);
683                 return componentInstInputsMap;
684         }
685
686 }