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