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