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