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