Revert "Interface operation feature enhancements"
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / impl / ResourceBusinessLogicTest.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.be.components.impl;
22
23 import fj.data.Either;
24 import org.apache.commons.lang3.tuple.ImmutablePair;
25 import org.junit.Assert;
26 import org.junit.Before;
27 import org.junit.Test;
28 import org.mockito.InjectMocks;
29 import org.mockito.Mockito;
30 import org.mockito.MockitoAnnotations;
31 import org.openecomp.sdc.ElementOperationMock;
32 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
33 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
34 import org.openecomp.sdc.be.model.operations.StorageException;
35 import org.openecomp.sdc.test.utils.InterfaceOperationTestUtils;
36 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
37 import org.openecomp.sdc.be.components.csar.CsarInfo;
38 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
39 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
40 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
41 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
42 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
43 import org.openecomp.sdc.be.components.validation.UserValidations;
44 import org.openecomp.sdc.be.config.ConfigurationManager;
45 import org.openecomp.sdc.be.dao.api.ActionStatus;
46 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
47 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
48 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
49 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
51 import org.openecomp.sdc.be.impl.ComponentsUtils;
52 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
53 import org.openecomp.sdc.be.model.ArtifactDefinition;
54 import org.openecomp.sdc.be.model.Component;
55 import org.openecomp.sdc.be.model.DataTypeDefinition;
56 import org.openecomp.sdc.be.model.InputDefinition;
57 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
58 import org.openecomp.sdc.be.model.LifecycleStateEnum;
59 import org.openecomp.sdc.be.model.PropertyDefinition;
60 import org.openecomp.sdc.be.model.Resource;
61 import org.openecomp.sdc.be.model.User;
62 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
63 import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
64 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
65 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation;
66 import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
67 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
68 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
69 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
70 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
71 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
72 import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
73 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
74 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
75 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
76 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
77 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
78 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
79 import org.openecomp.sdc.be.user.Role;
80 import org.openecomp.sdc.be.user.UserBusinessLogic;
81 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
82 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
83 import org.openecomp.sdc.common.api.ConfigurationSource;
84 import org.openecomp.sdc.common.api.Constants;
85 import org.openecomp.sdc.common.impl.ExternalConfiguration;
86 import org.openecomp.sdc.common.impl.FSConfigurationSource;
87 import org.openecomp.sdc.common.util.GeneralUtility;
88 import org.openecomp.sdc.common.util.ValidationUtils;
89 import org.openecomp.sdc.exception.ResponseFormat;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
92 import org.springframework.web.context.WebApplicationContext;
93
94 import javax.servlet.ServletContext;
95 import java.io.IOException;
96 import java.lang.reflect.Method;
97 import java.util.ArrayList;
98 import java.util.EnumMap;
99 import java.util.HashMap;
100 import java.util.List;
101 import java.util.Map;
102 import java.util.stream.Collectors;
103 import java.util.stream.Stream;
104
105 import static org.junit.Assert.assertEquals;
106 import static org.junit.Assert.assertFalse;
107 import static org.junit.Assert.assertNotNull;
108 import static org.junit.Assert.assertTrue;
109 import static org.mockito.ArgumentMatchers.any;
110 import static org.mockito.ArgumentMatchers.anyObject;
111 import static org.mockito.ArgumentMatchers.anyString;
112 import static org.mockito.ArgumentMatchers.eq;
113 import static org.mockito.Mockito.when;
114
115 import static org.assertj.core.api.Java6Assertions.assertThat;
116 import static org.junit.Assert.assertEquals;
117 import static org.junit.Assert.assertFalse;
118 import static org.junit.Assert.assertNotEquals;
119 import static org.junit.Assert.assertNotNull;
120 import static org.junit.Assert.assertTrue;
121 import static org.mockito.ArgumentMatchers.any;
122 import static org.mockito.ArgumentMatchers.eq;
123 import static org.mockito.Mockito.times;
124
125 public class ResourceBusinessLogicTest {
126
127     private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class);
128     private static final String RESOURCE_CATEGORY1 = "Network Layer 2-3";
129     private static final String RESOURCE_SUBCATEGORY = "Router";
130
131     private static final String UPDATED_SUBCATEGORY = "Gateway";
132
133     private String resourceId = "resourceId1";
134     private String operationId = "uniqueId1";
135     Resource resourceUpdate;
136
137     private static final String RESOURCE_NAME = "My-Resource_Name with   space";
138     private static final String RESOURCE_TOSCA_NAME = "My-Resource_Tosca_Name";
139     private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
140     private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR";
141     private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
142
143     final ServletContext servletContext = Mockito.mock(ServletContext.class);
144     IElementOperation mockElementDao;
145     TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
146     UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
147     ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
148     NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
149     NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
150     TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
151     final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
152     final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
153     final PropertyOperation propertyOperation = Mockito.mock(PropertyOperation.class);
154     final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class);
155     WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
156     UserValidations userValidations = Mockito.mock(UserValidations.class);
157     WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
158     IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
159     InterfaceOperation interfaceOperation = Mockito.mock(InterfaceOperation.class);
160     InterfaceOperationBusinessLogic interfaceOperationBl = Mockito.mock(InterfaceOperationBusinessLogic.class);
161
162     @InjectMocks
163     ResourceBusinessLogic bl = new ResourceBusinessLogic();
164     ResponseFormatManager responseManager = null;
165     GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
166     User user = null;
167     Resource resourceResponse = null;
168     Resource genericVF = null;
169     Resource genericCR = null;
170     Resource genericVFC = null;
171     Resource genericPNF = null;
172     ComponentsUtils componentsUtils;
173     ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic();
174     CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
175     @InjectMocks
176     CsarBusinessLogic csarBusinessLogic = new CsarBusinessLogic();
177     Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
178     private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
179     CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
180     List<Resource> reslist;
181
182     public ResourceBusinessLogicTest() {
183     }
184
185     @Before
186     public void setup() {
187         MockitoAnnotations.initMocks(this);
188         Mockito.reset(propertyOperation);
189
190         ExternalConfiguration.setAppName("catalog-be");
191
192         // init Configuration
193         String appConfigDir = "src/test/resources/config/catalog-be";
194         ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
195         ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
196         componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
197
198         // Elements
199         mockElementDao = new ElementOperationMock();
200
201         // User data and management
202         user = new User();
203         user.setUserId("jh0003");
204         user.setFirstName("Jimmi");
205         user.setLastName("Hendrix");
206         user.setRole(Role.ADMIN.name());
207
208         Either<User, ActionStatus> eitherGetUser = Either.left(user);
209         when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
210         when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), eq(false))).thenReturn(user);
211         when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
212         // Servlet Context attributes
213         when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
214         when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
215         when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
216         when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
217
218         Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1);
219         Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true);
220         when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse);
221
222
223         Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
224         when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist);
225
226         Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
227         when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class), eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount);
228         /*when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
229         when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
230         when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);*/
231         when(interfaceOperation.updateInterface(anyString(), anyObject())).thenReturn(Either.left(InterfaceOperationTestUtils.mockInterfaceDefinitionToReturn(RESOURCE_NAME)));
232         Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
233         when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists);
234
235         Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false);
236         when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
237         when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK);
238         when(graphLockOperation.lockComponentByName(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK);
239
240         // createResource
241         resourceResponse = createResourceObject(true);
242         Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
243         Either<Integer, StorageOperationStatus> eitherValidate = Either.left(null);
244         when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
245         Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
246         when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes));
247         when(mockTitanDao.commit()).thenReturn(TitanOperationStatus.OK);
248         when(interfaceOperationBl.validateComponentNameAndUpdateInterfaces(any(Component.class), any(Component.class))).thenReturn(Either.left(true));
249
250         // BL object
251         artifactManager.setNodeTemplateOperation(nodeTemplateOperation);
252         bl = new ResourceBusinessLogic();
253         bl.setElementDao(mockElementDao);
254         bl.setUserAdmin(mockUserAdmin);
255         bl.setCapabilityTypeOperation(capabilityTypeOperation);
256         bl.setComponentsUtils(componentsUtils);
257         bl.setLifecycleManager(lifecycleBl);
258         bl.setGraphLockOperation(graphLockOperation);
259         bl.setArtifactsManager(artifactManager);
260         bl.setPropertyOperation(propertyOperation);
261         bl.setTitanGenericDao(mockTitanDao);
262         bl.setApplicationDataTypeCache(applicationDataTypeCache);
263         bl.setCacheManagerOperation(cacheManager);
264         bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
265         toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
266         toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
267         bl.setToscaOperationFacade(toscaOperationFacade);
268         bl.setUserValidations(userValidations);
269         bl.setInterfaceTypeOperation(interfaceTypeOperation);
270         bl.setInterfaceOperation(interfaceOperation);
271         bl.setInterfaceOperationBusinessLogic(interfaceOperationBl);
272
273         csarBusinessLogic.setCsarOperation(csarOperation);
274         Resource resourceCsar = createResourceObjectCsar(true);
275         setCanWorkOnResource(resourceCsar);
276         Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
277         when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
278         responseManager = ResponseFormatManager.getInstance();
279
280         reslist = new ArrayList<Resource>();
281         reslist.add(resourceResponse);
282         reslist.add(genericVF);
283         reslist.add(genericCR);
284         reslist.add(genericVFC);
285         reslist.add(genericPNF);
286         Either<List<Resource>, StorageOperationStatus> returneval= Either.left(reslist);
287         when(toscaOperationFacade.getAllCertifiedResources(true, true)).thenReturn(returneval);
288         when(toscaOperationFacade.validateComponentNameUniqueness("Resource", ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(true));
289         Either<List<Resource>, StorageOperationStatus> returnevalexception= Either.right(StorageOperationStatus.BAD_REQUEST);
290         when(toscaOperationFacade.getAllCertifiedResources(false, false)).thenReturn(returnevalexception);
291
292     }
293
294     private Resource createResourceObject(boolean afterCreate) {
295         Resource resource = new Resource();
296         resource.setName(RESOURCE_NAME);
297         resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
298         resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
299         resource.setDescription("My short description");
300         List<String> tgs = new ArrayList<>();
301         tgs.add("test");
302         tgs.add(resource.getName());
303         resource.setTags(tgs);
304         List<String> template = new ArrayList<>();
305         template.add("Root");
306         resource.setDerivedFrom(template);
307         resource.setVendorName("Motorola");
308         resource.setVendorRelease("1.0.0");
309         resource.setContactId("ya5467");
310         resource.setIcon("MyIcon");
311
312         if (afterCreate) {
313             resource.setName(resource.getName());
314             resource.setVersion("0.1");
315             resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion());
316             resource.setCreatorUserId(user.getUserId());
317             resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
318             resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
319         }
320         return resource;
321     }
322
323     private Resource createResourceObjectCsar(boolean afterCreate) {
324         Resource resource = new Resource();
325         resource.setName(RESOURCE_NAME);
326         resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
327         resource.setDescription("My short description");
328         List<String> tgs = new ArrayList<>();
329         tgs.add("test");
330         tgs.add(resource.getName());
331         resource.setTags(tgs);
332         List<String> template = new ArrayList<>();
333         template.add("Root");
334         resource.setDerivedFrom(template);
335         resource.setVendorName("Motorola");
336         resource.setVendorRelease("1.0.0");
337         resource.setResourceVendorModelNumber("");
338         resource.setContactId("ya5467");
339         resource.setIcon("MyIcon");
340         resource.setCsarUUID("valid_vf.csar");
341         resource.setCsarVersion("1");
342
343         if (afterCreate) {
344             resource.setName(resource.getName());
345             resource.setVersion("0.1");
346
347             resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion());
348             resource.setCreatorUserId(user.getUserId());
349             resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
350             resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
351         }
352         return resource;
353     }
354
355     private Resource setCanWorkOnResource(Resource resource) {
356         resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
357         resource.setLastUpdaterUserId(user.getUserId());
358         return resource;
359     }
360
361     @Test
362     public void testHappyScenario() {
363         validateUserRoles(Role.ADMIN, Role.DESIGNER);
364         Resource resource = createResourceObject(false);
365         Resource createdResource = null;
366         try{
367             createdResource= bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
368             assertThat(createResourceObject(true)).isEqualTo(createdResource);
369         } catch(ComponentException e){
370             assertThat(new Integer(200)).isEqualTo(e.getResponseFormat().getStatus());
371         }
372     }
373
374     @Test
375     public void testUpdateHappyScenario() {
376         Resource resource = createResourceObjectCsar(true);
377         setCanWorkOnResource(resource);
378         validateUserRoles(Role.ADMIN, Role.DESIGNER);
379         Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource);
380         when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes);
381         Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
382         when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists);
383         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
384         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
385         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
386         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
387         Resource createdResource = null;
388         try{
389             createdResource= bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId());
390             assertThat(resource.getUniqueId()).isEqualTo(createdResource.getUniqueId());
391         } catch(ComponentException e){
392             assertThat(new Integer(200)).isEqualTo(e.getResponseFormat().getStatus());
393         }
394     }
395
396
397     @Test
398     public void testFailedResourceValidations() {
399         testResourceNameExist();
400         testResourceNameEmpty();
401         // testResourceNameExceedsLimit();
402         testResourceNameWrongFormat();
403         testResourceDescExceedsLimitCreate();
404         testResourceDescNotEnglish();
405         testResourceDescriptionEmpty();
406         testResourceDescriptionMissing();
407         testResourceIconMissing();
408         testResourceIconInvalid();
409         testResourceIconExceedsLimit();
410         testResourceTagNotExist();
411         testResourceTagEmpty();
412         testTagsExceedsLimitCreate();
413         testTagsNoServiceName();
414         testInvalidTag();
415
416         testContactIdTooLong();
417         testContactIdWrongFormatCreate();
418         testResourceContactIdEmpty();
419         testResourceContactIdMissing();
420         testVendorNameExceedsLimit();
421         testVendorNameWrongFormatCreate();
422         testVendorReleaseWrongFormat();
423         testVendorReleaseExceedsLimitCreate();
424         testResourceVendorModelNumberExceedsLimit();
425         testResourceVendorNameMissing();
426         testResourceVendorReleaseMissing();
427         testResourceCategoryExist();
428         testResourceBadCategoryCreate();
429         testHappyScenarioCostLicenseType();
430         testCostWrongFormatCreate();
431         testLicenseTypeWrongFormatCreate();
432         testResourceTemplateNotExist();
433         testResourceTemplateEmpty();
434         testResourceTemplateInvalid();
435     }
436
437     private void testResourceNameExist() {
438         String resourceName = "alreadyExists";
439         Resource resourceExist = createResourceObject(false);
440         resourceExist.setName(resourceName);
441         resourceExist.getTags().add(resourceName);
442         validateUserRoles(Role.ADMIN, Role.DESIGNER);
443         try {
444             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
445         } catch (ComponentException e) {
446             assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName);
447         }
448     }
449
450     private void testResourceNameEmpty() {
451         Resource resourceExist = createResourceObject(false);
452         resourceExist.setName(null);
453
454         try {
455             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
456         } catch (ComponentException e) {
457             assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
458         }
459     }
460
461     private void testResourceNameExceedsLimit() {
462         Resource resourceExccedsNameLimit = createResourceObject(false);
463         // 51 chars, the limit is 50
464         String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
465         resourceExccedsNameLimit.setName(tooLongResourceName);
466
467         try {
468             bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
469         } catch (ComponentException e) {
470             assertComponentException(e, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
471         }
472     }
473
474     private void testResourceNameWrongFormat() {
475         Resource resource = createResourceObject(false);
476         // contains :
477         String nameWrongFormat = "ljg?fd";
478         resource.setName(nameWrongFormat);
479
480         try {
481             bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
482         } catch (ComponentException e) {
483             assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
484         }
485     }
486
487     // Resource name - end
488     // Resource description - start
489     private void testResourceDescExceedsLimitCreate() {
490         Resource resourceExccedsDescLimit = createResourceObject(false);
491         // 1025 chars, the limit is 1024
492         String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
493                 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
494                 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
495                 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
496                 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
497                 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
498                 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
499                 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
500
501         resourceExccedsDescLimit.setDescription(tooLongResourceDesc);
502         try {
503             bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
504         } catch (ComponentException e) {
505             assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
506         }
507     }
508
509     private void testResourceDescNotEnglish() {
510         Resource notEnglish = createResourceObject(false);
511         // Not english
512         String notEnglishDesc = "\uC2B5";
513         notEnglish.setDescription(notEnglishDesc);
514
515         try {
516             bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
517         } catch (ComponentException e) {
518             assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
519         }
520     }
521
522     private void testResourceDescriptionEmpty() {
523         Resource resourceExist = createResourceObject(false);
524         resourceExist.setDescription("");
525
526         try {
527             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
528         } catch (ComponentException e) {
529             assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
530         }
531     }
532
533     private void testResourceDescriptionMissing() {
534         Resource resourceExist = createResourceObject(false);
535         resourceExist.setDescription(null);
536
537         try {
538             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
539         } catch (ComponentException e) {
540             assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
541         }
542     }
543     // Resource description - end
544     // Resource icon start
545
546     private void testResourceIconMissing() {
547         Resource resourceExist = createResourceObject(false);
548         resourceExist.setIcon(null);
549
550         try {
551             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
552         } catch (ComponentException e) {
553             assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
554         }
555     }
556
557     private void testResourceIconInvalid() {
558         Resource resourceExist = createResourceObject(false);
559         resourceExist.setIcon("kjk3453^&");
560
561         try {
562             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
563         } catch (ComponentException e) {
564             assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
565         }
566     }
567
568     private void testResourceIconExceedsLimit() {
569         Resource resourceExist = createResourceObject(false);
570         resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
571         try {
572             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
573         } catch (ComponentException e) {
574             assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
575         }
576     }
577
578     // Resource icon end
579     // Resource tags - start
580     private void testResourceTagNotExist() {
581         Resource resourceExist = createResourceObject(false);
582         resourceExist.setTags(null);
583         try {
584             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
585         } catch (ComponentException e) {
586             assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
587         }
588     }
589
590     private void testResourceTagEmpty() {
591         Resource resourceExist = createResourceObject(false);
592         resourceExist.setTags(new ArrayList<>());
593         try {
594             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
595         } catch (ComponentException e) {
596             assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
597         }
598     }
599
600     private void testTagsExceedsLimitCreate() {
601         Resource resourceExccedsNameLimit = createResourceObject(false);
602         String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
603         String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
604         String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
605         String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
606         String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
607         String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
608         String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
609         String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
610         String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
611         String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
612         String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
613         String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
614         String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
615         String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
616         String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
617         String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
618         String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
619         String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
620         String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
621         String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
622         String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
623
624         List<String> tagsList = new ArrayList<>();
625         tagsList.add(tag1);
626         tagsList.add(tag2);
627         tagsList.add(tag3);
628         tagsList.add(tag4);
629         tagsList.add(tag5);
630         tagsList.add(tag6);
631         tagsList.add(tag7);
632         tagsList.add(tag8);
633         tagsList.add(tag9);
634         tagsList.add(tag10);
635         tagsList.add(tag11);
636         tagsList.add(tag12);
637         tagsList.add(tag13);
638         tagsList.add(tag14);
639         tagsList.add(tag15);
640         tagsList.add(tag16);
641         tagsList.add(tag17);
642         tagsList.add(tag18);
643         tagsList.add(tag19);
644         tagsList.add(tag20);
645         tagsList.add(tag21);
646         tagsList.add(resourceExccedsNameLimit.getName());
647
648         resourceExccedsNameLimit.setTags(tagsList);
649         try {
650             bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
651         } catch (ComponentException e) {
652             assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
653         }
654     }
655
656     private void testTagsSingleExceedsLimit() {
657         Resource resourceExccedsNameLimit = createResourceObject(false);
658         String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI";
659         String tag2 = resourceExccedsNameLimit.getName();
660         List<String> tagsList = new ArrayList<>();
661         tagsList.add(tag1);
662         tagsList.add(tag2);
663
664         resourceExccedsNameLimit.setTags(tagsList);
665         try {
666             bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
667         } catch (ComponentException e) {
668             assertComponentException(e, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH);
669         }
670     }
671
672     private void testTagsNoServiceName() {
673         Resource serviceExccedsNameLimit = createResourceObject(false);
674         String tag1 = "afzs2qLBb";
675         List<String> tagsList = new ArrayList<>();
676         tagsList.add(tag1);
677         serviceExccedsNameLimit.setTags(tagsList);
678         try {
679             bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
680         } catch (ComponentException e) {
681             assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
682         }
683     }
684
685     private void testInvalidTag() {
686         Resource serviceExccedsNameLimit = createResourceObject(false);
687         String tag1 = "afzs2qLBb%#%";
688         List<String> tagsList = new ArrayList<>();
689         tagsList.add(tag1);
690         serviceExccedsNameLimit.setTags(tagsList);
691         try {
692             bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
693         } catch (ComponentException e) {
694             assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, new String[]{"Resource", "tag"});
695         }
696     }
697
698     // Resource tags - stop
699     // Resource contact start
700
701     private void testContactIdTooLong() {
702         Resource resourceContactId = createResourceObject(false);
703         // 59 chars instead of 50
704         String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
705         resourceContactId.setContactId(contactIdTooLong);
706
707         try {
708             bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
709         } catch (ComponentException e) {
710             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
711         }
712     }
713
714     private void testContactIdWrongFormatCreate() {
715         Resource resourceContactId = createResourceObject(false);
716         // 3 letters and 3 digits and special characters
717         String contactIdFormatWrong = "yrt134!!!";
718         resourceContactId.setContactId(contactIdFormatWrong);
719         try {
720             bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
721         } catch (ComponentException e) {
722             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
723         }
724     }
725
726     private void testResourceContactIdEmpty() {
727         Resource resourceExist = createResourceObject(false);
728         resourceExist.setContactId("");
729         try {
730             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
731         } catch (ComponentException e) {
732             assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
733         }
734     }
735
736     private void testResourceContactIdMissing() {
737         Resource resourceExist = createResourceObject(false);
738         resourceExist.setContactId(null);
739         try {
740             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
741         } catch (ComponentException e) {
742             assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
743         }
744     }
745
746     private void testVendorNameExceedsLimit() {
747         Resource resourceExccedsVendorNameLimit = createResourceObject(false);
748         String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
749         resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
750         try {
751             bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
752         } catch (ComponentException e) {
753             assertComponentException(e, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
754         }
755     }
756
757     private void testResourceVendorModelNumberExceedsLimit() {
758         Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
759         String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
760         resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
761         try {
762             bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
763         } catch (ComponentException e) {
764             assertComponentException(e, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
765         }
766     }
767
768     private void testVendorNameWrongFormatCreate() {
769         Resource resource = createResourceObject(false);
770         // contains *
771         String nameWrongFormat = "ljg*fd";
772         resource.setVendorName(nameWrongFormat);
773         try {
774             bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
775         } catch (ComponentException e) {
776             assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME);
777         }
778     }
779
780     private void testVendorReleaseWrongFormat() {
781         Resource resource = createResourceObject(false);
782         // contains >
783         String nameWrongFormat = "1>2";
784         resource.setVendorRelease(nameWrongFormat);
785         try {
786             bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
787         } catch (ComponentException e) {
788             assertComponentException(e, ActionStatus.INVALID_VENDOR_RELEASE);
789         }
790     }
791
792     private void testVendorReleaseExceedsLimitCreate() {
793         Resource resourceExccedsNameLimit = createResourceObject(false);
794         String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
795         resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
796         try {
797             bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
798         } catch (ComponentException e) {
799             assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
800         }
801     }
802
803     private void testResourceVendorNameMissing() {
804         Resource resourceExist = createResourceObject(false);
805         resourceExist.setVendorName(null);
806         try {
807             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
808         } catch (ComponentException e) {
809             assertComponentException(e, ActionStatus.MISSING_VENDOR_NAME);
810         }
811     }
812
813     private void testResourceVendorReleaseMissing() {
814         Resource resourceExist = createResourceObject(false);
815         resourceExist.setVendorRelease(null);
816         try {
817             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
818         } catch (ComponentException e) {
819             assertComponentException(e, ActionStatus.MISSING_VENDOR_RELEASE);
820         }
821     }
822
823     // Resource vendor name/release stop
824     // Category start
825     private void testResourceCategoryExist() {
826         Resource resourceExist = createResourceObject(false);
827         resourceExist.setCategories(null);
828         try {
829             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
830         } catch (ComponentException e) {
831             assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
832         }
833     }
834
835     private void testResourceBadCategoryCreate() {
836
837         Resource resourceExist = createResourceObject(false);
838         resourceExist.setCategories(null);
839         resourceExist.addCategory("koko", "koko");
840         try {
841             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
842         } catch (ComponentException e) {
843             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
844         }
845     }
846
847     // Category stop
848     // Cost start
849     private void testHappyScenarioCostLicenseType() {
850         Resource createResourceObject = createResourceObject(false);
851         Resource createResourceObjectAfterCreate = createResourceObject(true);
852         // Adding cost and licenseType to basic mock
853         Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate);
854         when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
855
856         String cost = "123.456";
857         String licenseType = "User";
858         createResourceObject.setCost(cost);
859         createResourceObject.setLicenseType(licenseType);
860         Resource createdResource;
861         try{
862             createdResource = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
863             createResourceObjectAfterCreate.setCost(cost);
864             createResourceObjectAfterCreate.setLicenseType(licenseType);
865             assertThat(createResourceObjectAfterCreate).isEqualTo(createdResource);
866         }catch(ComponentException e){
867             assertThat(new Integer(200)).isEqualTo(e.getResponseFormat().getStatus());
868         }
869     }
870
871     private void testCostWrongFormatCreate() {
872         Resource resourceCost = createResourceObject(false);
873         // Comma instead of fullstop
874         String cost = "12356,464";
875         resourceCost.setCost(cost);
876         try {
877             bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
878         } catch (ComponentException e) {
879             assertComponentException(e, ActionStatus.INVALID_CONTENT);
880         }
881     }
882
883     // Cost stop
884     // License type start
885     private void testLicenseTypeWrongFormatCreate() {
886         Resource resourceLicenseType = createResourceObject(false);
887         // lowcase
888         String licenseType = "cpu";
889         resourceLicenseType.setLicenseType(licenseType);
890         try {
891             bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
892         } catch (ComponentException e) {
893             assertComponentException(e, ActionStatus.INVALID_CONTENT);
894         }
895     }
896
897     // License type stop
898     // Derived from start
899     private void testResourceTemplateNotExist() {
900         Resource resourceExist = createResourceObject(false);
901         List<String> list = null;
902         resourceExist.setDerivedFrom(list);
903         try {
904             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
905         } catch (ComponentException e) {
906             assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
907         }
908     }
909
910     private void testResourceTemplateEmpty() {
911         Resource resourceExist = createResourceObject(false);
912         resourceExist.setDerivedFrom(new ArrayList<>());
913         try {
914             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
915         } catch (ComponentException e) {
916             assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
917         }
918     }
919
920     private void testResourceTemplateInvalid() {
921         Resource resourceExist = createResourceObject(false);
922         ArrayList<String> derivedFrom = new ArrayList<>();
923         derivedFrom.add("kuku");
924         resourceExist.setDerivedFrom(derivedFrom);
925         try {
926             bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
927         } catch (ComponentException e) {
928             assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
929         }
930     }
931     // Derived from stop
932     private void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) {
933         ResponseFormat actualResponse = e.getResponseFormat() != null ?
934                 e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
935         assertResponse(actualResponse, expectedStatus, variables);
936     }
937
938     private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
939         ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
940         assertThat(expectedResponse.getStatus()).isEqualTo(actualResponse.getStatus());
941         assertThat(expectedResponse.getFormattedMessage()).isEqualTo(actualResponse.getFormattedMessage());
942     }
943
944     private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
945         assertResponse(createResponse.right().value(), expectedStatus, variables);
946     }
947
948     // UPDATE tests - start
949     // Resource name
950     @Test
951     public void testResourceNameWrongFormat_UPDATE() {
952         Resource resource = createResourceObject(true);
953         resource.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinition(RESOURCE_NAME));
954         Resource updatedResource = createResourceObject(true);
955
956         // this is in order to prevent failing with 403 earlier
957         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
958         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
959         // contains *
960         String nameWrongFormat = "ljg*fd";
961         updatedResource.setName(nameWrongFormat);
962
963         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
964         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
965         try {
966             bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
967         } catch (ComponentException e) {
968             assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
969         }
970     }
971
972     @Test
973     public void testResourceNameAfterCertify_UPDATE() {
974         Resource resource = createResourceObject(true);
975         resource.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinition(RESOURCE_NAME));
976         Resource updatedResource = createResourceObject(true);
977
978         // this is in order to prevent failing with 403 earlier
979         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
980         // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
981         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
982
983         String name = "ljg";
984         updatedResource.setName(name);
985         resource.setVersion("1.0");
986
987         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
988         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
989         try {
990             bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
991         } catch (ComponentException e) {
992             assertComponentException(e, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
993         }
994     }
995
996     @Test
997     public void testResourceNameAlreadyExist_UPDATE() {
998         Resource resource = createResourceObject(true);
999         resource.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinition(RESOURCE_NAME));
1000         Resource updatedResource = createResourceObject(true);
1001
1002         // this is in order to prevent failing with 403 earlier
1003         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1004         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1005
1006         String resourceName = "alreadyExists";
1007         updatedResource.setName(resourceName);
1008         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
1009         when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1010         try {
1011             bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1012         } catch (ComponentException e) {
1013             assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName);
1014         }
1015     }
1016
1017     //
1018
1019     @Test
1020     public void testResourceDescExceedsLimit_UPDATE() {
1021         Resource resource = createResourceObject(true);
1022         Resource updatedResource = createResourceObject(true);
1023
1024         // this is in order to prevent failing with 403 earlier
1025         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1026         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1027
1028         // 1025 chars, the limit is 1024
1029         String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
1030                 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
1031                 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
1032                 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
1033                 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
1034                 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
1035                 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
1036                 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
1037         updatedResource.setDescription(tooLongResourceDesc);
1038         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1039         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1040         try {
1041             bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1042         } catch (ComponentException e) {
1043             assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
1044         }
1045     }
1046
1047     @Test
1048     public void testIconWrongFormat_UPDATE() {
1049         Resource resource = createResourceObject(true);
1050         Resource updatedResource = createResourceObject(true);
1051
1052         // this is in order to prevent failing with 403 earlier
1053         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1054         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1055
1056         // contains .
1057         String icon = "icon.jpg";
1058         updatedResource.setIcon(icon);
1059         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1060         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1061         try {
1062             bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1063         } catch (ComponentException e) {
1064             assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
1065         }
1066     }
1067
1068     @Test
1069     public void testIconAfterCertify_UPDATE() {
1070         Resource resource = createResourceObject(true);
1071         Resource updatedResource = createResourceObject(true);
1072
1073         // this is in order to prevent failing with 403 earlier
1074         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1075         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1076
1077         // contains
1078         String icon = "icon";
1079         updatedResource.setIcon(icon);
1080
1081         resource.setVersion("1.0");
1082         ;
1083         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1084         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1085         try {
1086             bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1087         } catch (ComponentException e) {
1088             assertComponentException(e, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
1089         }
1090     }
1091
1092     @Test
1093     public void testTagsExceedsLimit_UPDATE() {
1094         Resource resource = createResourceObject(true);
1095         Resource updatedResource = createResourceObject(true);
1096
1097         // this is in order to prevent failing with 403 earlier
1098         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1099         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1100
1101         String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
1102         String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
1103         String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
1104         String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
1105         String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
1106         String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
1107         String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
1108         String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
1109         String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
1110         String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
1111         String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
1112         String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
1113         String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
1114         String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
1115         String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
1116         String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
1117         String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
1118         String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
1119         String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
1120         String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
1121         String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
1122
1123         List<String> tagsList = new ArrayList<>();
1124         tagsList.add(tag1);
1125         tagsList.add(tag2);
1126         tagsList.add(tag3);
1127         tagsList.add(tag4);
1128         tagsList.add(tag5);
1129         tagsList.add(tag6);
1130         tagsList.add(tag7);
1131         tagsList.add(tag8);
1132         tagsList.add(tag9);
1133         tagsList.add(tag10);
1134         tagsList.add(tag11);
1135         tagsList.add(tag12);
1136         tagsList.add(tag13);
1137         tagsList.add(tag14);
1138         tagsList.add(tag15);
1139         tagsList.add(tag16);
1140         tagsList.add(tag17);
1141         tagsList.add(tag18);
1142         tagsList.add(tag19);
1143         tagsList.add(tag20);
1144         tagsList.add(tag21);
1145         tagsList.add(resource.getName());
1146
1147         updatedResource.setTags(tagsList);
1148         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1149         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1150         try {
1151             bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1152         } catch (ComponentException e) {
1153             assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
1154         }
1155     }
1156
1157     @Test
1158     public void testVendorNameWrongFormat_UPDATE() {
1159         Resource resource = createResourceObject(true);
1160         Resource updatedResource = createResourceObject(true);
1161
1162         // this is in order to prevent failing with 403 earlier
1163         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1164         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1165
1166         // contains *
1167         String nameWrongFormat = "ljg*fd";
1168         updatedResource.setVendorName(nameWrongFormat);
1169         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1170         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1171         try {
1172             bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1173         } catch (ComponentException e) {
1174             assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME);
1175         }
1176     }
1177
1178     @Test
1179     public void testVendorNameWrongFormat() {
1180         Resource resource = createResourceObject(true);
1181         Resource updatedResource = createResourceObject(true);
1182
1183         // this is in order to prevent failing with 403 earlier
1184         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1185         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1186
1187         // contains *
1188         String nameWrongFormat = "ljg*fd";
1189         updatedResource.setVendorName(nameWrongFormat);
1190         resource.setVersion("1.0");
1191         ;
1192         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1193         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1194         try {
1195             bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1196         } catch (ComponentException e) {
1197             assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME);
1198         }
1199     }
1200
1201     @Test
1202     public void testVendorReleaseExceedsLimit_UPDATE() {
1203         Resource resource = createResourceObject(true);
1204         Resource updatedResource = createResourceObject(true);
1205
1206         // this is in order to prevent failing with 403 earlier
1207         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1208         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1209         // 129 chars, the limit is 128
1210         String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy";
1211         updatedResource.setVendorRelease(tooLongVendorRelease);
1212         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1213         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1214         try {
1215             bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1216         } catch (ComponentException e) {
1217             assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
1218         }
1219     }
1220
1221     @Test
1222     public void testResourceBadCategory_UPDATE() {
1223         Resource resource = createResourceObject(true);
1224         Resource updatedResource = createResourceObject(true);
1225
1226         // this is in order to prevent failing with 403 earlier
1227         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1228         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1229
1230         String resourceId = resource.getUniqueId();
1231         String badCategory = "ddfds";
1232         updatedResource.setCategories(null);
1233         updatedResource.addCategory(badCategory, "fikt");
1234         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1235         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1236         try {
1237             bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1238         } catch (ComponentException e) {
1239             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1240         }
1241     }
1242
1243     @Test
1244     public void testResourceCategoryAfterCertify_UPDATE() {
1245         Resource resource = createResourceObject(true);
1246         Resource updatedResource = createResourceObject(true);
1247
1248         // this is in order to prevent failing with 403 earlier
1249         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1250         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1251
1252         String resourceId = resource.getUniqueId();
1253         updatedResource.setCategories(null);
1254         updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY);
1255         resource.setVersion("1.0");
1256         ;
1257         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1258         when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1259         try {
1260             bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1261         } catch (ComponentException e) {
1262             assertComponentException(e, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
1263         }
1264     }
1265
1266     // Derived from start
1267     @Test
1268     public void testResourceTemplateNotExist_UPDATE() {
1269         Resource resource = createResourceObject(true);
1270         Resource updatedResource = createResourceObject(true);
1271
1272         // this is in order to prevent failing with 403 earlier
1273         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1274         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1275         String resourceId = resource.getUniqueId();
1276
1277         List<String> list = null;
1278         updatedResource.setDerivedFrom(list);
1279         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1280         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1281         try {
1282             bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1283         } catch (ComponentException e) {
1284             assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1285         }
1286     }
1287
1288     @Test
1289     public void testResourceTemplateEmpty_UPDATE() {
1290         Resource resource = createResourceObject(true);
1291         Resource updatedResource = createResourceObject(true);
1292         String resourceId = resource.getUniqueId();
1293
1294         // this is in order to prevent failing with 403 earlier
1295         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1296         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1297
1298         updatedResource.setDerivedFrom(new ArrayList<>());
1299         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1300         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1301         try {
1302             bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1303         } catch (ComponentException e) {
1304             assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1305         }
1306     }
1307
1308     @Test
1309     public void testResourceTemplateInvalid_UPDATE() {
1310         Resource resource = createResourceObject(true);
1311         Resource updatedResource = createResourceObject(true);
1312         String resourceId = resource.getUniqueId();
1313
1314         // this is in order to prevent failing with 403 earlier
1315         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1316         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1317
1318         ArrayList<String> derivedFrom = new ArrayList<>();
1319         derivedFrom.add("kuku");
1320         updatedResource.setDerivedFrom(derivedFrom);
1321         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1322         when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1323         try {
1324             bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1325         } catch (ComponentException e) {
1326             assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
1327         }
1328     }
1329
1330     @Test
1331     public void testResourceTemplateCertify_UPDATE_HAPPY() {
1332         Resource resource = createResourceObject(true);
1333         Resource updatedResource = createResourceObject(true);
1334         String resourceId = resource.getUniqueId();
1335
1336         // this is in order to prevent failing with 403 earlier
1337         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1338         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1339
1340         Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true);
1341         when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending);
1342
1343         Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>());
1344         when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode);
1345
1346         resource.setVersion("1.0");
1347
1348         ArrayList<String> derivedFrom = new ArrayList<>();
1349         derivedFrom.add("tosca.nodes.Root");
1350         updatedResource.setDerivedFrom(derivedFrom);
1351         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
1352         when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1353         Resource createdResource = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1354         assertThat(createdResource).isNotNull();
1355     }
1356
1357     @Test
1358     public void testResourceTemplateCertify_UPDATE_SAD() {
1359         Resource resource = createResourceObject(true);
1360         Resource updatedResource = createResourceObject(true);
1361         String resourceId = resource.getUniqueId();
1362
1363         // this is in order to prevent failing with 403 earlier
1364         Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1365         when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1366
1367         Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false);
1368         when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString()))
1369                 .thenReturn(isToscaNameExtending);
1370
1371         resource.setVersion("1.0");
1372
1373         ArrayList<String> derivedFrom = new ArrayList<>();
1374         derivedFrom.add("tosca.nodes.Root");
1375         updatedResource.setDerivedFrom(derivedFrom);
1376         Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1377         when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1378         Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>());
1379         when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode);
1380
1381         try {
1382             bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1383         } catch (ComponentException e) {
1384             assertComponentException(e, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1385         }
1386     }
1387     // Derived from stop
1388
1389     @Test
1390     public void createOrUpdateResourceAlreadyCheckout() {
1391         Resource resourceExist = createResourceObject(false);
1392         validateUserRoles(Role.ADMIN, Role.DESIGNER);
1393         Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1394         createdResource.setLastUpdaterUserId(user.getUserId());
1395         assertThat(createdResource).isNotNull();
1396         Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
1397         Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
1398         when(toscaOperationFacade.getLatestByToscaResourceName(resourceExist.getToscaResourceName())).thenReturn(getCompLatestResult);
1399         when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult);
1400
1401         Resource resourceToUpdtae = createResourceObject(false);
1402
1403         ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1404         assertNotNull(createOrUpdateResource);
1405
1406         Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class));
1407         Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1408
1409     }
1410
1411     @Test
1412     public void createOrUpdateResourceCertified() {
1413         Resource resourceExist = createResourceObject(false);
1414         validateUserRoles(Role.ADMIN, Role.DESIGNER);
1415         Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1416
1417         assertThat(createdResource).isNotNull();
1418         createdResource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
1419         createdResource.setVersion("1.0");
1420
1421         Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
1422         Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
1423         when(toscaOperationFacade.getLatestByToscaResourceName(resourceExist.getToscaResourceName())).thenReturn(getCompLatestResult);        when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult);
1424
1425         when(lifecycleBl.changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(Either.left(createdResource));
1426
1427         Resource resourceToUpdtae = createResourceObject(false);
1428
1429         ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1430         assertNotNull(createOrUpdateResource);
1431
1432         Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class));
1433         Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1434
1435     }
1436
1437     @Test
1438     public void createOrUpdateResourceNotExist() {
1439         Resource resourceToUpdtae = createResourceObject(false);
1440
1441         Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
1442         when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult);
1443
1444         Either<Component, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND);
1445         when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult);
1446
1447         ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1448         assertThat(createOrUpdateResource).isNotNull();
1449
1450         Mockito.verify(toscaOperationFacade, times(1)).createToscaComponent(eq(resourceToUpdtae));
1451         Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(any(Resource.class), any(Resource.class));
1452         Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1453
1454     }
1455
1456     @Test
1457     public void updateNestedResource_typeIsNew() throws IOException {
1458         Resource resourceToUpdate = createResourceObject(false);
1459         String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
1460         String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
1461         CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(),
1462                 RESOURCE_NAME, "template name", jsonContent, true);
1463         String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight();
1464         when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1465         when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1466         when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName)).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1467
1468         ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo,
1469                 nodeName, false);
1470         assertThat(createOrUpdateResource).isNotNull();
1471
1472         Mockito.verify(toscaOperationFacade, times(1)).createToscaComponent(eq(resourceToUpdate));
1473         Mockito.verify(toscaOperationFacade, times(0)).overrideComponent(any(Resource.class), any(Resource.class));
1474         Mockito.verify(lifecycleBl, times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1475     }
1476
1477     @Test
1478     public void updateNestedResource_typeExists() throws IOException {
1479         Resource resourceToUpdate = createResourceObject(false);
1480         setCanWorkOnResource(resourceResponse);
1481         String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
1482         String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
1483         CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(),
1484                 RESOURCE_NAME, "template name", jsonContent, true);
1485         String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight();
1486         when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1487         when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1488         when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName)).thenReturn(Either.left(resourceResponse));
1489         when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(Either.left(resourceResponse));
1490
1491         ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo,
1492                 nodeName, false);
1493         assertThat(createOrUpdateResource).isNotNull();
1494         Mockito.verify(toscaOperationFacade, times(1)).overrideComponent(any(Resource.class), any(Resource.class));
1495         Mockito.verify(lifecycleBl, times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1496     }
1497
1498     @Test
1499     public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() {
1500         Resource basic = createResourceObject(true);
1501
1502         Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1503         assertTrue(validatePropertiesDefaultValues.isLeft());
1504     }
1505
1506     @Test
1507     public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() {
1508         Resource basic = createResourceObject(true);
1509         PropertyDefinition property = new PropertyDefinition();
1510         property.setName("myProperty");
1511         property.setType(ToscaPropertyType.INTEGER.getType());
1512         property.setDefaultValue("1");
1513         List<PropertyDefinition> properties = new ArrayList<>();
1514         properties.add(property);
1515         basic.setProperties(properties);
1516         when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true);
1517         when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true);
1518         Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1519         assertTrue(validatePropertiesDefaultValues.isLeft());
1520     }
1521
1522     @Test
1523     public void testValidatePropertiesDefaultValues_FailedWithProperties() {
1524         Resource basic = createResourceObject(true);
1525         PropertyDefinition property = new PropertyDefinition();
1526         property.setName("myProperty");
1527         property.setType(ToscaPropertyType.INTEGER.getType());
1528         property.setDefaultValue("1.5");
1529         List<PropertyDefinition> properties = new ArrayList<>();
1530         properties.add(property);
1531         basic.setProperties(properties);
1532
1533         when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false);
1534         Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1535         assertTrue(validatePropertiesDefaultValues.isRight());
1536     }
1537
1538
1539     @SuppressWarnings("unchecked")
1540     @Test
1541     public void testFindVfCsarArtifactsToHandle() {
1542
1543         Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
1544         String methodName = "findVfCsarArtifactsToHandle";
1545         Resource resource = new Resource();
1546         String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml";
1547         String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml";
1548         String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml";
1549
1550         String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml";
1551         String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml";
1552         String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml";
1553         String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml";
1554
1555         byte[] oldPayloadData = "oldPayloadData".getBytes();
1556         byte[] newPayloadData = "newPayloadData".getBytes();
1557         Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
1558
1559         ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition();
1560         deploymentArtifactToUpdate.setMandatory(false);
1561         deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName);
1562         deploymentArtifactToUpdate.setArtifactType("SNMP_POLL");
1563         deploymentArtifactToUpdate.setPayload(oldPayloadData);
1564         deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
1565
1566         ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition();
1567         deploymentArtifactToDelete.setMandatory(false);
1568         deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName);
1569         deploymentArtifactToDelete.setArtifactType("SNMP_TRAP");
1570         deploymentArtifactToDelete.setPayload(oldPayloadData);
1571         deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
1572
1573         ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition();
1574
1575         deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate);
1576         deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete);
1577         deploymentArtifacts.put("ignore", deploymentArtifactToIgnore);
1578
1579         Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1580
1581         ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
1582         artifactToUpdate.setMandatory(false);
1583         artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName);
1584         artifactToUpdate.setArtifactType("SNMP_POLL");
1585         artifactToUpdate.setPayload(oldPayloadData);
1586         artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
1587
1588         ArtifactDefinition artifactToDelete = new ArtifactDefinition();
1589         artifactToDelete.setMandatory(false);
1590         artifactToDelete.setArtifactName(artifactInfoToDeleteFileName);
1591         artifactToDelete.setArtifactType("SNMP_TRAP");
1592         artifactToDelete.setPayload(oldPayloadData);
1593         artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
1594         artifactToDelete.setIsFromCsar(true);
1595
1596         ArtifactDefinition artifactToNotDelete = new ArtifactDefinition();
1597         artifactToNotDelete.setMandatory(false);
1598         artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName);
1599         artifactToNotDelete.setArtifactType("SNMP_TRAP");
1600         artifactToNotDelete.setPayload(oldPayloadData);
1601         artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
1602         artifactToNotDelete.setIsFromCsar(false);
1603
1604         ArtifactDefinition artifactToIgnore = new ArtifactDefinition();
1605
1606         artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate);
1607         artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete);
1608         artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()), artifactToNotDelete);
1609         artifacts.put("ignore", artifactToIgnore);
1610
1611         resource.setDeploymentArtifacts(deploymentArtifacts);
1612         resource.setArtifacts(artifacts);
1613
1614         List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>();
1615         NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null,
1616                 ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT,
1617                 newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false);
1618
1619         NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null,
1620                 ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT,
1621                 newPayloadData, artifactToUpdate.getArtifactName(), false);
1622
1623         NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null,
1624                 ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.INFORMATIONAL,
1625                 newPayloadData, artifactToUpdate.getArtifactName(), true);
1626
1627         NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null,
1628                 ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT,
1629                 newPayloadData, artifactToUpdate.getArtifactName(), true);
1630
1631         NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null,
1632                 ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName, false);
1633
1634         NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null,
1635                 ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.INFORMATIONAL,
1636                 newPayloadData, artifactInfoToCreateFileName, false);
1637
1638         artifactPathAndNameList.add(deploymentArtifactInfoToUpdate);
1639         artifactPathAndNameList.add(informationalArtifactInfoToUpdate);
1640         artifactPathAndNameList.add(deploymentArtifactInfoToCreate);
1641         artifactPathAndNameList.add(informationalArtifactInfoToCreate);
1642         artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar);
1643         artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar);
1644
1645         Object[] argObjects = {resource, artifactPathAndNameList, user};
1646         Class[] argClasses = {Resource.class, List.class, User.class};
1647         try {
1648             Method method = targetClass.getDeclaredMethod(methodName, argClasses);
1649             method.setAccessible(true);
1650             Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes =
1651                     (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method.invoke(bl, argObjects);
1652             assertTrue(findVfCsarArtifactsToHandleRes.isLeft());
1653             EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value();
1654             assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.CREATE).size());
1655             assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.UPDATE).size());
1656             assertEquals(1, foundVfArtifacts.get(ArtifactOperationEnum.DELETE).size());
1657
1658         } catch (Exception e) {
1659             e.printStackTrace();
1660         }
1661     }
1662
1663     @Test
1664     public void testVFGeneratedInputs() {
1665         validateUserRoles(Role.ADMIN, Role.DESIGNER);
1666         Resource resource = createVF();
1667         List<InputDefinition> inputs = resource.getInputs();
1668         assertEquals(6, inputs.size());
1669         for (InputDefinition input : inputs) {
1670             assertThat(input.getOwnerId()).isNotNull();
1671         }
1672         assertEquals(resource.getDerivedFromGenericType(), genericVF.getToscaResourceName());
1673         assertEquals(resource.getDerivedFromGenericVersion(), genericVF.getVersion());
1674     }
1675
1676     @Test
1677     public void testCRGeneratedInputs() {
1678         validateUserRoles(Role.ADMIN, Role.DESIGNER);
1679         Resource resource = createCR();
1680         List<InputDefinition> inputs = resource.getInputs();
1681         assertEquals(3, inputs.size());
1682         for (InputDefinition input : inputs) {
1683             assertThat(input.getOwnerId()).isNotNull();
1684         }
1685         assertEquals(resource.getDerivedFromGenericType(), genericCR.getToscaResourceName());
1686         assertEquals(resource.getDerivedFromGenericVersion(), genericCR.getVersion());
1687     }
1688
1689     @Test
1690     public void testVFUpdateGenericInputsToLatestOnCheckout() {
1691         validateUserRoles(Role.ADMIN, Role.DESIGNER);
1692         //create a VF that is derived from generic version 1.0
1693         Resource resource = createVF();
1694         // create a new generic version without properties
1695         genericVF.setVersion("2.0");
1696         genericVF.setProperties(null);
1697         String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
1698         List<InputDefinition> currentInputs = resource.getInputs();
1699         //verify previous inputs ownerId fields exist - user may not delete generated inputs
1700         assertEquals(6, currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size());
1701         Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
1702         //verify success
1703         assertTrue(upgradeToLatestGeneric.isLeft());
1704         //verify update required and valid
1705         assertTrue(upgradeToLatestGeneric.left().value());
1706         //verify version was upgraded
1707         assertNotEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
1708         //verify inputs were not deleted
1709         assertEquals(6, resource.getInputs().size());
1710         //verify inputs ownerId fields were removed - user may delete/edit inputs
1711         assertEquals(6, resource.getInputs()
1712                                 .stream()
1713                                 .filter(p -> null == p.getOwnerId())
1714                                 .collect(Collectors.toList())
1715                                 .size());
1716     }
1717
1718
1719     @Test
1720     public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
1721
1722         //create a VF that is derived from generic version 1.0
1723         validateUserRoles(Role.ADMIN, Role.DESIGNER);
1724         Resource resource = createVF();
1725
1726         //add an input to the VF
1727         PropertyDefinition newProp = new PropertyDefinition();
1728         newProp.setType("integer");
1729         newProp.setName("newProp");
1730         resource.getInputs().add(new InputDefinition(newProp));
1731
1732         //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type
1733         genericVF.setVersion("2.0");
1734         newProp.setType("string");
1735         genericVF.setProperties(new ArrayList<>());
1736         genericVF.getProperties().add(newProp);
1737         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
1738         when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod();
1739         String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
1740         assertEquals(6, resource.getInputs()
1741                                 .stream()
1742                                 .filter(p -> null != p.getOwnerId())
1743                                 .collect(Collectors.toList())
1744                                 .size());
1745         Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
1746         //verify success
1747         assertTrue(upgradeToLatestGeneric.isLeft());
1748         //verify update is invalid an void
1749         assertFalse(upgradeToLatestGeneric.left().value());
1750         //verify version was not upgraded
1751         assertEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
1752         //verify inputs were not removed
1753         assertEquals(7, resource.getInputs().size());
1754         //verify user defined input exists
1755         assertEquals(1, resource.getInputs()
1756                                 .stream()
1757                                 .filter(p -> null == p.getOwnerId())
1758                                 .collect(Collectors.toList())
1759                                 .size());
1760         assertEquals("integer", resource.getInputs()
1761                                         .stream()
1762                                         .filter(p -> null == p.getOwnerId())
1763                                         .findAny()
1764                                         .get()
1765                                         .getType());
1766     }
1767
1768     @Test
1769     public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
1770         validateUserRoles(Role.ADMIN, Role.DESIGNER);
1771         Resource resource = createPNF();
1772         List<InputDefinition> inputs = resource.getInputs();
1773         assertEquals(3, inputs.size());
1774         for (InputDefinition input : inputs) {
1775             assertThat(input.getOwnerId()).isNotNull();
1776         }
1777         assertEquals(resource.getDerivedFromGenericType(), genericPNF.getToscaResourceName());
1778         assertEquals(resource.getDerivedFromGenericVersion(), genericPNF.getVersion());
1779         assertEquals(0, resource.getArtifacts().size());
1780     }
1781
1782
1783     private Resource createVF() {
1784
1785         genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
1786         when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF));
1787         Resource resource = createResourceObject(true);
1788         resource.setDerivedFrom(null);
1789         resource.setResourceType(ResourceTypeEnum.VF);
1790         when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
1791         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
1792         when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod();
1793         when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod();
1794         Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1795         assertThat(createdResource).isNotNull();
1796         return createdResource;
1797     }
1798
1799
1800     private Resource createCR() {
1801
1802         genericCR = setupGenericTypeMock(GENERIC_CR_NAME);
1803         when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME)).thenReturn(Either.left(genericCR));
1804         Resource resource = createResourceObject(true);
1805         resource.setDerivedFrom(null);
1806         resource.setResourceType(ResourceTypeEnum.CR);
1807         when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
1808         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericCR));
1809         when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod();
1810         when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(), resource.getUniqueId())).thenCallRealMethod();
1811         Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1812         assertThat(createdResource).isNotNull();
1813         return createdResource;
1814     }
1815
1816     private Resource createPNF() {
1817
1818         genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
1819         when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF));
1820         Resource resource = createResourceObject(true);
1821         resource.setDerivedFrom(null);
1822         resource.setResourceType(ResourceTypeEnum.PNF);
1823         when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
1824         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF));
1825         when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod();
1826         when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod();
1827         Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1828         assertThat(createdResource).isNotNull();
1829         return createdResource;
1830     }
1831
1832
1833     private Map<String, String> getGenericPropertiesByToscaName(String toscaName) {
1834         HashMap<String, String> PNFProps = new HashMap<String, String>() {{
1835             put("nf_function", "string");
1836             put("nf_role", "string");
1837             put("nf_type", "string");
1838         }};
1839
1840         HashMap<String, String> CRProps = new HashMap<String, String>() {{
1841             put("cr_function", "string");
1842             put("cr_role", "string");
1843             put("cr_type", "string");
1844         }};
1845
1846         HashMap<String, String> VFProps = new HashMap<String, String>() {{
1847             putAll(CRProps);
1848             put("availability_zone_max_count", "integer");
1849             put("min_instances", "integer");
1850             put("max_instances", "integer");
1851         }};
1852
1853         if (toscaName.contains("PNF")) return PNFProps;
1854         if (toscaName.contains("CR")) return CRProps;
1855         if (toscaName.contains("VF")) return VFProps;
1856
1857         return new HashMap<>();
1858     }
1859
1860
1861     private Resource setupGenericTypeMock(String toscaName) {
1862
1863         Resource genericType = createResourceObject(true);
1864         genericType.setVersion("1.0");
1865         genericType.setToscaResourceName(toscaName);
1866         List<PropertyDefinition> genericProps = new ArrayList<>();
1867         Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName);
1868         genericPropsMap.forEach((name, type) -> {
1869             PropertyDefinition prop = new PropertyDefinition();
1870             prop.setName(name);
1871             prop.setType(type);
1872             genericProps.add(prop);
1873         });
1874
1875         genericType.setProperties(genericProps);
1876         return genericType;
1877     }
1878
1879     private void validateUserRoles(Role... roles) {
1880         List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
1881     }
1882
1883
1884     @Test
1885     public void testgetAllCertifiedResources() throws Exception {
1886         List<Resource> list = bl.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, "USER");
1887         Assert.assertEquals(reslist,list);
1888     }
1889
1890     @Test(expected = StorageException.class)
1891     public void testgetAllCertifiedResources_exception() throws Exception {
1892         List<Resource> list = bl.getAllCertifiedResources(false, HighestFilterEnum.NON_HIGHEST_ONLY, "USER");
1893         Assert.assertEquals(reslist,list);
1894     }
1895
1896     @Test
1897     public void testvalidateResourceNameExists() throws Exception {
1898         Either<Map<String, Boolean>, ResponseFormat> res = bl.validateResourceNameExists("Resource", ResourceTypeEnum.CR, "jh0003");
1899         Assert.assertEquals(true,res.isLeft());
1900     }
1901
1902
1903 }