re base code
[sdc.git] / test-apis-ci / src / main / java / org / openecomp / sdc / ci / tests / api / ComponentInstanceBaseTest.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.api;
22
23 import org.apache.commons.lang3.tuple.ImmutablePair;
24 import org.junit.rules.TestName;
25 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
26 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
27 import org.openecomp.sdc.be.model.*;
28 import org.openecomp.sdc.ci.tests.datatypes.*;
29 import org.openecomp.sdc.ci.tests.datatypes.enums.*;
30 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
31 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
32 import org.openecomp.sdc.ci.tests.utils.rest.*;
33 import org.testng.Assert;
34
35 import java.io.IOException;
36 import java.util.*;
37 import java.util.Map.Entry;
38 import java.util.function.Function;
39 import java.util.stream.Collectors;
40
41 import static org.testng.AssertJUnit.*;
42
43 public class ComponentInstanceBaseTest extends ComponentBaseTest {
44         public static final String acceptHeaderData = "application/json";
45         // Req/cap of container component
46         protected Map<String, List<CapabilityDefinition>> expectedContainerCapabilities;
47         protected Map<String, List<RequirementDefinition>> expectedContainerRequirements;
48         protected Map<String, Map<String, List<RequirementDefinition>>> removedRequirements;
49         protected Map<String, ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>> expectedContInstReqCap;
50
51         protected User sdncPsDetails1;
52         protected User sdncPsDetails2;
53         protected User sdncPmDetails1;
54         protected User sdncPmDetails2;
55         protected User sdncDesignerDetails;
56         protected User sdncAdminDetails;
57         protected User sdncTesterDetails;
58         protected ResourceReqDetails resourceDetailsVFC_01;
59         protected ResourceReqDetails resourceDetailsVFC_02;
60         protected ResourceReqDetails resourceDetailsVF_01;
61         protected ResourceReqDetails resourceDetailsVF_02;
62         protected ResourceReqDetails resourceDetailsCP_01;
63         protected ResourceReqDetails resourceDetailsCP_02;
64         protected ResourceReqDetails resourceDetailsVL_01;
65         protected ResourceReqDetails resourceDetailsVL_02;
66         protected ServiceReqDetails serviceDetails_01;
67         protected ServiceReqDetails serviceDetails_02;
68         protected ServiceReqDetails serviceDetails_03;
69         protected ProductReqDetails productDetails_01;
70         protected ProductReqDetails productDetails_02;
71
72         public void init() {
73                 // Req/caps of inner componentInstances
74                 expectedContainerCapabilities = new LinkedHashMap<String, List<CapabilityDefinition>>();
75                 expectedContainerRequirements = new LinkedHashMap<String, List<RequirementDefinition>>();
76                 removedRequirements = new HashMap<>();
77                 expectedContInstReqCap = new HashMap<>();
78
79                 sdncPsDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1);
80                 sdncPsDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST2);
81                 sdncPmDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
82                 sdncPmDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER2);
83                 sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
84                 sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
85                 sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
86                 resourceDetailsVFC_01 = ElementFactory.getDefaultResourceByType("ciVFC100", NormativeTypesEnum.SOFTWARE_COMPONENT, ResourceCategoryEnum.GENERIC_DATABASE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VFC.toString()); // resourceType = VFC
87                 resourceDetailsVFC_02 = ElementFactory.getDefaultResourceByType("ciVFC200", NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VFC.toString());
88                 resourceDetailsVF_01 = ElementFactory.getDefaultResourceByType("ciVF100", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
89                 resourceDetailsVF_02 = ElementFactory.getDefaultResourceByType("ciVF200", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
90                 resourceDetailsCP_01 = ElementFactory.getDefaultResourceByType("ciCP100", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
91                 resourceDetailsCP_02 = ElementFactory.getDefaultResourceByType("ciCP200", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_DATABASE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
92                 resourceDetailsVL_01 = ElementFactory.getDefaultResourceByType("ciVL100", NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VL.toString());
93                 resourceDetailsVL_02 = ElementFactory.getDefaultResourceByType("ciVL200", NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VL.toString());
94                 serviceDetails_01 = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId(), ServiceInstantiationType.A_LA_CARTE.getValue());
95                 serviceDetails_02 = ElementFactory.getDefaultService("ciNewtestservice2", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId(), ServiceInstantiationType.A_LA_CARTE.getValue());
96                 serviceDetails_03 = ElementFactory.getDefaultService("ciNewtestservice3", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId(), ServiceInstantiationType.A_LA_CARTE.getValue());
97                 productDetails_01 = ElementFactory.getDefaultProduct("ciProduct01");
98                 productDetails_02 = ElementFactory.getDefaultProduct("ciProduct02");
99         }
100
101         public ComponentInstanceBaseTest(TestName testName, String className) {
102                 super(testName, className);
103         }
104
105         public void verifyVFReqCap(String componentId) throws Exception {
106                 RestResponse restResponse = ResourceRestUtils.getResource(componentId);
107                 Resource resource = ResponseParser.parseToObject(restResponse.getResponse(), Resource.class);
108                 verifyReqCap(resource);
109         }
110
111         public void verifyServiceReqCap(String componentId) throws Exception {
112                 RestResponse restResponse = ServiceRestUtils.getService(componentId, sdncDesignerDetails);
113                 Service service = ResponseParser.parseToObject(restResponse.getResponse(), Service.class);
114                 verifyReqCap(service);
115         }
116
117         public void verifyProductReqCap(String componentId) throws Exception {
118                 RestResponse restResponse = ProductRestUtils.getProduct(componentId, sdncPsDetails1.getUserId());
119                 Product product = ResponseParser.parseToObject(restResponse.getResponse(), Product.class);
120                 verifyReqCap(product);
121         }
122
123         public void verifyReqCap(Component actualComponent) {
124                 verifyContainerReqCap(actualComponent);
125                 verifyCompInstReqCap(actualComponent);
126         }
127
128         public RestResponse changeServiceInstanceVersion(String componentUniqueId, String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType, boolean isHighestLevel) throws Exception {
129                 RestResponse changeResourceInstanceVersion = ProductRestUtils.changeServiceInstanceVersion(componentUniqueId, serviceInstanceToReplaceUniqueId, serviceUniqueId, sdncModifierDetails, componentType);
130                 if (changeResourceInstanceVersion.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS) && isHighestLevel) {
131                         /*
132                          * // Add RI Capabilities and Requirements to expected MAP --> expectedVfCapabilities and expectedVfRequirements
133                          * 
134                          * ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper( changeResourceInstanceVersion.getResponse(), ComponentInstance.class); addCompInstReqCapToExpected(componentInstance, componentType);
135                          */
136                 }
137                 return changeResourceInstanceVersion;
138         }
139
140         protected void updateExpectedReqCapAfterChangeLifecycleState(String oldContainerUniqueIdToReplace, String newContainerUniqueId) {
141
142                 // Update of container req/cap
143
144                 Set<String> compInstKeysToChange = new HashSet<>();
145
146                 for (String expKey : expectedContainerCapabilities.keySet()) {
147                         List<CapabilityDefinition> expCapList = expectedContainerCapabilities.get(expKey);
148                         for (CapabilityDefinition cap : expCapList) {
149                                 String ownerId = cap.getOwnerId();
150
151                                 if (ownerId.contains(oldContainerUniqueIdToReplace)) {
152                                         compInstKeysToChange.add(ownerId);
153                                         cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
154                                 }
155                         }
156                 }
157
158                 for (String expKey : expectedContainerRequirements.keySet()) {
159                         List<RequirementDefinition> expCapList = expectedContainerRequirements.get(expKey);
160                         for (RequirementDefinition cap : expCapList) {
161                                 String ownerId = cap.getOwnerId();
162                                 if (ownerId.contains(oldContainerUniqueIdToReplace)) {
163                                         compInstKeysToChange.add(ownerId);
164                                         cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
165                                 }
166                         }
167                 }
168
169                 // Update of internal comp instances req/cap
170                 for (String oldKey : compInstKeysToChange) {
171                         ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> immutablePair = expectedContInstReqCap.get(oldKey);
172                         if (immutablePair != null) {
173                                 expectedContInstReqCap.remove(oldKey);
174                                 String newKey = oldKey.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId);
175                                 expectedContInstReqCap.put(newKey, immutablePair);
176                         }
177                 }
178
179                 // Update of removed req
180                 for (String oldKey : compInstKeysToChange) {
181                         Map<String, List<RequirementDefinition>> map = removedRequirements.get(oldKey);
182                         if (map != null) {
183                                 removedRequirements.remove(oldKey);
184                                 String newKey = oldKey.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId);
185                                 Collection<List<RequirementDefinition>> values = map.values();
186                                 if (values != null) {
187                                         for (List<RequirementDefinition> list : values) {
188                                                 for (RequirementDefinition reqDef : list) {
189                                                         reqDef.setOwnerId(reqDef.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
190                                                 }
191                                         }
192                                 }
193                                 removedRequirements.put(newKey, map);
194                         }
195                 }
196         }
197
198         private void verifyCompInstReqCap(Component actualComponent) {
199                 List<ComponentInstance> componentInstances = actualComponent.getComponentInstances();
200                 if (componentInstances != null) {
201                         assertEquals(expectedContInstReqCap.size(), componentInstances.size());
202                         for (ComponentInstance compInst : componentInstances) {
203                                 String uniqueId = compInst.getUniqueId();
204                                 // System.out.println("Verifying req/cap of component instance
205                                 // "+ uniqueId);
206                                 Map<String, List<RequirementDefinition>> actualCompInstReq = compInst.getRequirements();
207                                 if (actualCompInstReq == null) {
208                                         actualCompInstReq = new HashMap<>();
209                                 }
210                                 Map<String, List<CapabilityDefinition>> actualCompInstCap = compInst.getCapabilities();
211                                 if (actualCompInstCap == null) {
212                                         actualCompInstCap = new HashMap<>();
213                                 }
214                                 ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> expReqCap = expectedContInstReqCap.get(uniqueId);
215                                 assertNotNull(expReqCap);
216                                 // System.out.println("expected instance requirements:
217                                 // "+expReqCap.right);
218                                 // System.out.println("expected instance capabilities:
219                                 // "+expReqCap.left);
220                                 // System.out.println("actual instance requirements:
221                                 // "+actualCompInstReq);
222                                 // System.out.println("actual instance capabilities:
223                                 // "+actualCompInstCap);
224
225                                 // REQ comparison
226                                 compareReqCapMaps(expReqCap.right, actualCompInstReq);
227
228                                 // CAP comparison
229                                 compareReqCapMaps(expReqCap.left, actualCompInstCap);
230                         }
231
232                 } else {
233                         assertTrue(expectedContInstReqCap.isEmpty());
234                 }
235         }
236
237         private void verifyContainerReqCap(Component actualComponent) {
238                 Map<String, List<RequirementDefinition>> actualContainerRequirements = actualComponent.getRequirements();
239                 if (actualContainerRequirements == null) {
240                         actualContainerRequirements = new HashMap<>();
241                 }
242                 Map<String, List<CapabilityDefinition>> actualContainerCapabilities = actualComponent.getCapabilities();
243                 if (actualContainerCapabilities == null) {
244                         actualContainerCapabilities = new HashMap<>();
245                 }
246                 // System.out.println("Verifying req/cap of container component "+
247                 // actualComponent.getUniqueId());
248                 // System.out.println("expected container requirements:
249                 // "+expectedContainerRequirements);
250                 // System.out.println("expected container capabilities:
251                 // "+expectedContainerCapabilities);
252                 // System.out.println("actual container requirements:
253                 // "+actualContainerRequirements);
254                 // System.out.println("actual container capabilities:
255                 // "+actualContainerCapabilities);
256
257                 // REQ comparison
258                 compareReqCapMaps(expectedContainerRequirements, actualContainerRequirements);
259
260                 // CAP comparison
261                 compareReqCapMaps(expectedContainerCapabilities, actualContainerCapabilities);
262         }
263
264         private <T> void compareReqCapMaps(Map<String, List<T>> expectedMap, Map<String, List<T>> actualMap) {
265                 assertEquals(expectedMap.size(), actualMap.size());
266                 for (String expKey : expectedMap.keySet()) {
267                         List<?> expCapList = expectedMap.get(expKey);
268                         List<?> actCapList = actualMap.get(expKey);
269                         assertEquals(expCapList.size(), actCapList.size());
270                         assertEquals(new HashSet<>(expCapList), new HashSet<>(actCapList));
271                 }
272         }
273
274         public void addCompInstReqCapToExpected(ComponentInstance componentInstance, ComponentTypeEnum containerComponentType) throws Exception {
275                 String uniqueId = componentInstance.getUniqueId();
276                 String name = componentInstance.getName();
277                 String originComponentId = componentInstance.getComponentUid();
278                 RestResponse getResponse = null;
279                 ComponentTypeEnum compInstType = getCompInstTypeByContainerType(containerComponentType);
280                 Component component = null;
281                 if (compInstType == ComponentTypeEnum.RESOURCE) {
282                         getResponse = ResourceRestUtils.getResource(sdncDesignerDetails, originComponentId);
283                         ResourceRestUtils.checkSuccess(getResponse);
284                         component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
285                 } else if (compInstType == ComponentTypeEnum.SERVICE) {
286                         getResponse = ServiceRestUtils.getService(originComponentId, sdncDesignerDetails);
287                         ResourceRestUtils.checkSuccess(getResponse);
288                         component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
289                 } else {
290                         Assert.fail("Unsupported type - " + containerComponentType);
291                 }
292
293                 Map<String, List<RequirementDefinition>> resourceRequirements = component.getRequirements();
294                 if (resourceRequirements == null) {
295                         resourceRequirements = new HashMap<>();
296                 }
297                 
298                 Function<Entry<String, List<RequirementDefinition>>, List<RequirementDefinition>> requirementDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new RequirementDefinition(item)).collect(Collectors.toList()));
299                 Map<String, List<RequirementDefinition>> reqCopy = resourceRequirements.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), requirementDefinitionMapper));
300                 
301                 Map<String, List<CapabilityDefinition>> resourceCapabilities = component.getCapabilities();
302                 if (resourceCapabilities == null) {
303                         resourceCapabilities = new HashMap<>();
304                 }
305                 
306                 Function<? super Entry<String, List<CapabilityDefinition>>, List<CapabilityDefinition>> capabilityDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new CapabilityDefinition(item)).collect(Collectors.toList()));
307                 Map<String, List<CapabilityDefinition>> capCopy = resourceCapabilities.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), capabilityDefinitionMapper));
308                 
309                 setupContainerExpectedReqCap(uniqueId, name, resourceRequirements, resourceCapabilities);
310                 if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE) && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) {
311                         setupConstInstExpectedReqCap(uniqueId, name, reqCopy, capCopy);
312                 }
313
314                 // adding entry for expected componentInstance
315                 ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> compInstReqCapPair = new ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>(capCopy, reqCopy);
316                 expectedContInstReqCap.put(uniqueId, compInstReqCapPair);
317         }
318
319         private void setupContainerExpectedReqCap(String uniqueId, String name, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
320                 for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
321                         List<RequirementDefinition> reqListToAdd = resReq.getValue();
322                         for (RequirementDefinition requirementDefinition : reqListToAdd) {
323                                 requirementDefinition.setOwnerId(uniqueId);
324                                 requirementDefinition.setOwnerName(name);
325                         }
326                         List<RequirementDefinition> expectedReqList = expectedContainerRequirements.get(resReq.getKey());
327                         if (expectedReqList == null) {
328                                 expectedReqList = reqListToAdd;
329                         } else {
330                                 expectedReqList.addAll(reqListToAdd);
331                         }
332                         expectedContainerRequirements.put(resReq.getKey(), expectedReqList);
333                 }
334
335                 for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
336                         List<CapabilityDefinition> capListToAdd = resCap.getValue();
337                         for (CapabilityDefinition capDefinition : capListToAdd) {
338                                 capDefinition.setOwnerId(uniqueId);
339                                 capDefinition.setOwnerName(name);
340                         }
341                         List<CapabilityDefinition> expectedCapList = expectedContainerCapabilities.get(resCap.getKey());
342                         if (expectedCapList == null) {
343                                 expectedCapList = capListToAdd;
344                         } else {
345                                 expectedCapList.addAll(capListToAdd);
346                         }
347                         expectedContainerCapabilities.put(resCap.getKey(), expectedCapList);
348                 }
349         }
350
351         private void setupConstInstExpectedReqCap(String uniqueId, String name, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
352                 for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
353                         List<RequirementDefinition> reqListToAdd = resReq.getValue();
354                         for (RequirementDefinition requirementDefinition : reqListToAdd) {
355                                 requirementDefinition.setOwnerId(uniqueId);
356                                 requirementDefinition.setOwnerName(name);
357                         }
358                 }
359
360                 for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
361                         List<CapabilityDefinition> capListToAdd = resCap.getValue();
362                         for (CapabilityDefinition capDefinition : capListToAdd) {
363                                 capDefinition.setOwnerId(uniqueId);
364                                 capDefinition.setOwnerName(name);
365                         }
366                 }
367         }
368
369         private ComponentTypeEnum getCompInstTypeByContainerType(ComponentTypeEnum componentType) {
370                 switch (componentType) {
371                 case RESOURCE:
372                         return ComponentTypeEnum.RESOURCE;
373                 case SERVICE:
374                         return ComponentTypeEnum.RESOURCE;
375                 case PRODUCT:
376                         return ComponentTypeEnum.SERVICE;
377                 default:
378                         break;
379                 }
380                 return null;
381         }
382
383         public void deleteCompInstReqCapFromExpected(String componentInstanceId) {
384                 List<String> entriesRequirementsToRemove = new ArrayList<>();
385                 List<String> entriesCapabilitiesToRemove = new ArrayList<>();
386                 for (Entry<String, List<RequirementDefinition>> reqEntry : expectedContainerRequirements.entrySet()) {
387                         List<RequirementDefinition> reqList = reqEntry.getValue();
388                         List<RequirementDefinition> reqListToDelete = new ArrayList<>();
389                         for (RequirementDefinition requirementDefinition : reqList) {
390                                 if (requirementDefinition.getOwnerId().equals(componentInstanceId)) {
391                                         reqListToDelete.add(requirementDefinition);
392                                 }
393                         }
394                         reqList.removeAll(reqListToDelete);
395                         if (reqList.isEmpty()) {
396                                 entriesRequirementsToRemove.add(reqEntry.getKey());
397                         }
398                 }
399
400                 for (String ekey : entriesRequirementsToRemove) {
401                         expectedContainerRequirements.remove(ekey);
402                 }
403
404                 for (Entry<String, List<CapabilityDefinition>> capEntry : expectedContainerCapabilities.entrySet()) {
405                         List<CapabilityDefinition> capList = capEntry.getValue();
406                         List<CapabilityDefinition> capListToDelete = new ArrayList<>();
407                         for (CapabilityDefinition capabilityDefinition : capList) {
408                                 if (capabilityDefinition.getOwnerId().equals(componentInstanceId)) {
409                                         capListToDelete.add(capabilityDefinition);
410                                 }
411                         }
412                         capList.removeAll(capListToDelete);
413                         if (capList.isEmpty()) {
414                                 entriesCapabilitiesToRemove.add(capEntry.getKey());
415                         }
416                 }
417                 for (String ekey : entriesCapabilitiesToRemove) {
418                         expectedContainerCapabilities.remove(ekey);
419                 }
420
421                 expectedContInstReqCap.remove(componentInstanceId);
422
423         }
424
425         // Automatically updates the expected req/cap of the container
426         protected RestResponse createAtomicInstanceForVF(ResourceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
427                 return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE, true);
428         }
429
430         // Automatically updates the expected req/cap of the container
431         protected RestResponse createAtomicInstanceForService(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
432                 return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, true);
433         }
434
435         // Automatically updates the expected req/cap of the container
436         protected RestResponse createVFInstance(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
437                 return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, true);
438         }
439
440         // Automatically updates the expected req/cap of the container
441         protected RestResponse createServiceInstance(ProductReqDetails containerDetails, ServiceReqDetails compInstOriginDetails, User modifier) throws Exception {
442                 return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT, true);
443         }
444
445         // Automatically updates the expected req/cap of the container
446         protected RestResponse deleteAtomicInstanceForVF(String compInstUniqueId, ResourceReqDetails containerDetails, User modifier) throws IOException, Exception {
447                 return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, true);
448         }
449
450         // Automatically updates the expected req/cap of the container
451         protected RestResponse deleteAtomicInstanceForService(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception {
452                 return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true);
453         }
454
455         // Automatically updates the expected req/cap of the container
456         protected RestResponse deleteVFInstance(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception {
457                 return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true);
458
459         }
460
461         // Automatically updates the expected req/cap of the container
462         protected RestResponse deleteServiceInstance(String compInstUniqueId, ProductReqDetails containerDetails, User modifier) throws IOException, Exception {
463                 return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, true);
464         }
465
466         // Setup of lower components - Doesn't affect req/cap of the container (for
467         // example, setup of VF for testing a Product)
468         protected RestResponse createAtomicInstanceForVFDuringSetup(ResourceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
469                 return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE, false);
470         }
471
472         // Setup of lower components - Doesn't affect req/cap of the container (for
473         // example, setup of VF for testing a Product)
474         protected RestResponse createAtomicInstanceForServiceDuringSetup(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
475                 return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, false);
476         }
477
478         // Setup of lower components - Doesn't affect req/cap of the container (for
479         // example, setup of VF for testing a Product)
480         protected RestResponse createVFInstanceDuringSetup(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
481                 return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, false);
482         }
483
484         // Setup of lower components - Doesn't affect req/cap of the container (for
485         // example, setup of VF for testing a Product)
486         protected RestResponse createServiceInstanceDuringSetup(ProductReqDetails containerDetails, ServiceReqDetails compInstOriginDetails, User modifier) throws Exception {
487                 return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT, false);
488         }
489
490         // Setup of lower components - Doesn't affect req/cap of the container (for
491         // example, setup of VF for testing a Product)
492         protected RestResponse deleteAtomicInstanceForVFDuringSetup(String compInstUniqueId, ResourceReqDetails containerDetails, User modifier) throws IOException, Exception {
493                 return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, false);
494         }
495
496         // Setup of lower components - Doesn't affect req/cap of the container (for
497         // example, setup of VF for testing a Product)
498         protected RestResponse deleteAtomicInstanceForServiceDuringSetup(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception {
499                 return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false);
500         }
501
502         // Setup of lower components - Doesn't affect req/cap of the container (for
503         // example, setup of VF for testing a Product)
504         protected RestResponse deleteVFInstanceDuringSetup(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception {
505                 return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false);
506
507         }
508
509         // Setup of lower components - Doesn't affect req/cap of the container (for
510         // example, setup of VF for testing a Product)
511         protected RestResponse deleteServiceInstanceDuringSetup(String compInstUniqueId, ProductReqDetails containerDetails, User modifier) throws IOException, Exception {
512                 return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, false);
513         }
514
515         protected Component getComponentAndValidateRIs(ComponentReqDetails componentDetails, int numberOfRIs, int numberOfRelations) throws IOException, Exception {
516
517                 RestResponse getResponse = null;
518                 Component component = null;
519                 if (componentDetails instanceof ResourceReqDetails) {
520                         getResponse = ResourceRestUtils.getResource(sdncAdminDetails, componentDetails.getUniqueId());
521                         component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
522                 } else if (componentDetails instanceof ServiceReqDetails) {
523                         getResponse = ServiceRestUtils.getService((ServiceReqDetails) componentDetails, sdncAdminDetails);
524                         component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
525                 } else if (componentDetails instanceof ProductReqDetails) {
526                         getResponse = ProductRestUtils.getProduct(componentDetails.getUniqueId(), sdncAdminDetails.getUserId());
527                         component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Product.class);
528                 } else {
529                         Assert.fail("Unsupported type of componentDetails - " + componentDetails.getClass().getSimpleName());
530                 }
531                 ResourceRestUtils.checkSuccess(getResponse);
532                 int numberOfActualRIs = component.getComponentInstances() != null ? component.getComponentInstances().size() : 0;
533                 int numberOfActualRelations = component.getComponentInstancesRelations() != null ? component.getComponentInstancesRelations().size() : 0;
534                 assertEquals("Check number of RIs meet the expected number", numberOfRIs, numberOfActualRIs);
535                 assertEquals("Check number of RI relations meet the expected number", numberOfRelations, numberOfActualRelations);
536                 verifyReqCap(component);
537
538                 return component;
539         }
540
541         protected void getComponentAndValidateRIsAfterChangeLifecycleState(String oldComponentUniqueIdToReplace, ComponentReqDetails componentDetails, int numOfRIs, int numOfRelations) throws IOException, Exception {
542                 updateExpectedReqCapAfterChangeLifecycleState(oldComponentUniqueIdToReplace, componentDetails.getUniqueId());
543                 getComponentAndValidateRIs(componentDetails, numOfRIs, numOfRelations);
544         }
545
546         private RestResponse createComponentInstance(ComponentReqDetails containerDetails, ComponentReqDetails compInstOriginDetails, User modifier, ComponentTypeEnum containerComponentTypeEnum, boolean isHighestLevel) throws IOException, Exception {
547                 ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getComponentResourceInstance(compInstOriginDetails);
548                 RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, modifier, containerDetails.getUniqueId(), containerComponentTypeEnum);
549                 if (createResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_CREATED) && isHighestLevel) {
550                         // Add RI Capabilities and Requirements to expected MAP -->
551                         // expectedVfCapabilities and expectedVfRequirements
552                         ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
553                         addCompInstReqCapToExpected(componentInstance, containerComponentTypeEnum);
554                 }
555                 return createResourceInstanceResponse;
556         }
557
558         private RestResponse deleteComponentInstance(String compInstUniqueId, ComponentReqDetails containerDetails, User modifier, ComponentTypeEnum componentTypeEnum, boolean isHighestLevel) throws Exception {
559                 RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(modifier, containerDetails.getUniqueId(), compInstUniqueId, componentTypeEnum);
560                 if (deleteResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_DELETE) && isHighestLevel) {
561                         deleteCompInstReqCapFromExpected(compInstUniqueId);
562                 }
563                 return deleteResourceInstanceResponse;
564         }
565
566         // Create Atomic resource ( VFC/CP/VL)
567         protected void createAtomicResource(ResourceReqDetails resourceDetails) throws Exception {
568                 RestResponse createResourceResponse = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails);
569                 ResourceRestUtils.checkCreateResponse(createResourceResponse);
570
571         }
572
573         protected void createVF(ResourceReqDetails resourceDetails) throws Exception {
574                 createVF(resourceDetails, sdncDesignerDetails);
575
576         }
577
578         protected void createVF(ResourceReqDetails resourceDetails, User sdncModifier) throws Exception {
579                 RestResponse createVfResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifier);
580                 ResourceRestUtils.checkCreateResponse(createVfResponse);
581         }
582
583         protected void createService(ServiceReqDetails serviceDetails) throws Exception {
584                 createService(serviceDetails, sdncDesignerDetails);
585         }
586
587         protected void createService(ServiceReqDetails serviceDetails, User sdncModifier) throws Exception {
588                 RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifier);
589                 ResourceRestUtils.checkCreateResponse(createServiceResponse);
590         }
591
592         protected void createProduct(ProductReqDetails productDetails) throws Exception {
593                 createProduct(productDetails, sdncPmDetails1);
594         }
595
596         protected void createProduct(ProductReqDetails productDetails, User sdncModifier) throws Exception {
597                 RestResponse createProductResponse = ProductRestUtils.createProduct(productDetails, sdncModifier);
598                 ResourceRestUtils.checkCreateResponse(createProductResponse);
599         }
600
601         protected RestResponse associateComponentInstancesForService(RequirementCapabilityRelDef requirementDef, ComponentReqDetails containerDetails, User user) throws IOException {
602
603                 RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, user, containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
604                 ResourceRestUtils.checkSuccess(associateInstances);
605                 deleteAssociatedFromExpected(requirementDef);
606
607                 return associateInstances;
608         }
609
610         private void deleteAssociatedFromExpected(RequirementCapabilityRelDef requirementDef) {
611                 // removing from requirements
612                 RelationshipInfo relationship = requirementDef.getRelationships().get(0).getRelation();
613                 String type = relationship.getRelationship().getType();
614                 String fromId = requirementDef.getFromNode();
615                 List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
616                 List<CapabilityDefinition> capList = expectedContainerCapabilities.get(type);
617                 RequirementDefinition toDelete = null;
618                 if (reqList != null) {
619                         for (RequirementDefinition reqDef : reqList) {
620                                 if (reqDef.getOwnerId().equals(fromId)) {
621                                         toDelete = reqDef;
622                                 }
623                         }
624                         if (toDelete != null) {
625                                 reqList.remove(toDelete);
626                                 if (reqList.isEmpty()) {
627                                         expectedContainerRequirements.remove(type);
628                                 }
629                                 String ownerId = toDelete.getOwnerId();
630                                 Map<String, List<RequirementDefinition>> map = removedRequirements.get(ownerId);
631                                 if (map == null) {
632                                         map = new HashMap<>();
633                                         removedRequirements.put(ownerId, map);
634                                 }
635                                 List<RequirementDefinition> list = map.get(type);
636                                 if (list == null) {
637                                         list = new ArrayList<>();
638                                         map.put(type, list);
639                                 }
640                                 list.add(toDelete);
641                         }
642                 }
643
644                 for (CapabilityDefinition capabilityDefinition : capList) {
645                         if (capabilityDefinition.getType().equals(type)) {
646                                 int minOccurrences = Integer.parseInt(capabilityDefinition.getMinOccurrences()) - 1;
647                                 if (minOccurrences < 0)
648                                         minOccurrences = 0;
649                                 String minOccurrencesString = Integer.toString(minOccurrences);
650                                 capabilityDefinition.setMinOccurrences(minOccurrencesString);
651                                 if (!capabilityDefinition.getMaxOccurrences().equals("UNBOUNDED")) {
652                                         int maxOccurrences = Integer.parseInt(capabilityDefinition.getMaxOccurrences()) - 1;
653                                         if (maxOccurrences < 0)
654                                                 maxOccurrences = 0;
655                                         String maxOccurrencesString = Integer.toString(maxOccurrences);
656                                         capabilityDefinition.setMaxOccurrences(maxOccurrencesString);
657                                 }
658                         }
659                 }
660                 expectedContainerCapabilities.put(type, capList);
661         }
662
663         protected void dissociateComponentInstancesForService(RequirementCapabilityRelDef requirementDef, ComponentReqDetails containerDetails, User user) throws IOException {
664
665                 RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, user, containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
666                 ResourceRestUtils.checkSuccess(dissociateInstances);
667                 addDissociatedToExpected(requirementDef);
668         }
669
670         protected void fulfillCpRequirement(ComponentReqDetails component, String cpCompInstId, String cpReqFulfillerCompInstId, String cpReqFulfillerOwnerId, User user, ComponentTypeEnum containerCompType) throws IOException {
671                 // Fulfilling cp's "binding" requirement - US626240
672                 String requirementName = "binding";
673                 String capType = "tosca.capabilities.network.Bindable";
674                 RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(user, component);
675                 ResourceRestUtils.checkSuccess(getResourceResponse);
676                 CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
677                 List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
678                 List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
679                 RequirementCapabilityRelDef reqCapRelation = ElementFactory.getReqCapRelation(cpCompInstId, cpReqFulfillerCompInstId, cpCompInstId, cpReqFulfillerOwnerId, capType, requirementName, capList, reqList);
680                 RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(reqCapRelation, user, component.getUniqueId(), containerCompType);
681                 ResourceRestUtils.checkSuccess(associateInstances);
682         }
683
684         protected void consumeVlCapability(ComponentReqDetails component, String vlCapConsumerCompInstId, String vlCompInstId, String vlCapConsumerOwnerId, User user, ComponentTypeEnum containerCompType) throws IOException {
685                 // Consuming vl's "link" capability - US626240
686                 String requirementName = "link";
687                 String capType = "tosca.capabilities.network.Linkable";
688                 RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(user, component);
689                 ResourceRestUtils.checkSuccess(getResourceResponse);
690                 CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
691                 List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
692                 List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
693                 RequirementCapabilityRelDef reqCapRelation = ElementFactory.getReqCapRelation(vlCapConsumerCompInstId, vlCompInstId, vlCapConsumerOwnerId, vlCompInstId, capType, requirementName, capList, reqList);
694                 RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(reqCapRelation, user, component.getUniqueId(), containerCompType);
695                 ResourceRestUtils.checkSuccess(associateInstances);
696         }
697
698         private void addDissociatedToExpected(RequirementCapabilityRelDef requirementDef) {
699                 // adding to requirements
700                 RelationshipInfo relationship = requirementDef.getRelationships().get(0).getRelation();
701                 String type = relationship.getRelationship().getType();
702                 String fromId = requirementDef.getFromNode();
703                 Map<String, List<RequirementDefinition>> map = removedRequirements.get(fromId);
704                 if (map != null) {
705                         List<RequirementDefinition> list = map.get(type);
706                         if (list != null && !list.isEmpty()) {
707                                 List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
708                                 if (reqList == null) {
709                                         reqList = new ArrayList<>();
710                                         expectedContainerRequirements.put(type, reqList);
711                                 }
712                                 reqList.add(list.remove(0));
713                         }
714                 }
715
716                 List<CapabilityDefinition> capList = expectedContainerCapabilities.get(type);
717
718                 for (CapabilityDefinition capabilityDefinition : capList) {
719                         if (capabilityDefinition.getType().equals(type)) {
720                                 int minOccurrences = Integer.parseInt(capabilityDefinition.getMinOccurrences()) + 1;
721                                 String minOccurrencesString = Integer.toString(minOccurrences);
722                                 capabilityDefinition.setMinOccurrences(minOccurrencesString);
723                                 if (!capabilityDefinition.getMaxOccurrences().equals("UNBOUNDED")) {
724                                         int maxOccurrences = Integer.parseInt(capabilityDefinition.getMaxOccurrences()) + 1;
725                                         String maxOccurrencesString = Integer.toString(maxOccurrences);
726                                         capabilityDefinition.setMaxOccurrences(maxOccurrencesString);
727                                 }
728                         }
729                 }
730                 expectedContainerCapabilities.put(type, capList);
731         }
732 }