2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.components.impl;
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;
38 import fj.data.Either;
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;
51 import java.util.HashSet;
52 import java.util.Map.Entry;
53 import java.util.Optional;
54 import java.util.stream.Collectors;
55 import java.util.stream.Stream;
56 import javax.servlet.ServletContext;
57 import org.apache.commons.lang3.tuple.ImmutablePair;
58 import org.hamcrest.MatcherAssert;
59 import org.junit.Assert;
60 import org.junit.jupiter.api.BeforeEach;
61 import org.junit.jupiter.api.Test;
62 import org.mockito.InjectMocks;
63 import org.mockito.Mockito;
64 import org.mockito.MockitoAnnotations;
65 import org.openecomp.sdc.ElementOperationMock;
66 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
67 import org.openecomp.sdc.be.components.ArtifactsResolver;
68 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
69 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
70 import org.openecomp.sdc.be.components.csar.CsarInfo;
71 import org.openecomp.sdc.be.components.csar.OnboardedCsarInfo;
72 import org.openecomp.sdc.be.components.csar.YamlTemplateParsingHandler;
73 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
74 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
75 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
76 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
77 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
78 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
79 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
80 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
81 import org.openecomp.sdc.be.components.validation.UserValidations;
82 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
83 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
84 import org.openecomp.sdc.be.components.validation.component.ComponentFieldValidator;
85 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
86 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
87 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
88 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
89 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
90 import org.openecomp.sdc.be.config.ConfigurationManager;
91 import org.openecomp.sdc.be.dao.api.ActionStatus;
92 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
93 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
94 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
95 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
96 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
97 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
98 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
99 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
100 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
101 import org.openecomp.sdc.be.facade.operations.CatalogOperation;
102 import org.openecomp.sdc.be.impl.ComponentsUtils;
103 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
104 import org.openecomp.sdc.be.model.ArtifactDefinition;
105 import org.openecomp.sdc.be.model.Component;
106 import org.openecomp.sdc.be.model.ComponentInstance;
107 import org.openecomp.sdc.be.model.ComponentParametersView;
108 import org.openecomp.sdc.be.model.DataTypeDefinition;
109 import org.openecomp.sdc.be.model.GroupDefinition;
110 import org.openecomp.sdc.be.model.InputDefinition;
111 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
112 import org.openecomp.sdc.be.model.LifecycleStateEnum;
113 import org.openecomp.sdc.be.model.NodeTypeInfo;
114 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
115 import org.openecomp.sdc.be.model.PropertyDefinition;
116 import org.openecomp.sdc.be.model.RequirementDefinition;
117 import org.openecomp.sdc.be.model.Resource;
118 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
119 import org.openecomp.sdc.be.model.User;
120 import org.openecomp.sdc.be.model.VendorSoftwareProduct;
121 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
122 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
123 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
124 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
125 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTypeOperation;
126 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation;
127 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
128 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.OperationException;
129 import org.openecomp.sdc.be.model.operations.StorageException;
130 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
131 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
132 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
133 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
134 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
135 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
136 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
137 import org.openecomp.sdc.be.model.operations.impl.ArtifactTypeOperation;
138 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
139 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
140 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
141 import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
142 import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
143 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
144 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
145 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
146 import org.openecomp.sdc.be.tosca.CsarUtils;
147 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
148 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
149 import org.openecomp.sdc.be.user.Role;
150 import org.openecomp.sdc.be.user.UserBusinessLogic;
151 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
152 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
153 import org.openecomp.sdc.common.api.Constants;
154 import org.openecomp.sdc.common.impl.ExternalConfiguration;
155 import org.openecomp.sdc.common.impl.FSConfigurationSource;
156 import org.openecomp.sdc.common.util.GeneralUtility;
157 import org.openecomp.sdc.common.util.ValidationUtils;
158 import org.openecomp.sdc.common.zip.ZipUtils;
159 import org.openecomp.sdc.common.zip.exception.ZipException;
160 import org.openecomp.sdc.exception.ResponseFormat;
161 import org.springframework.web.context.WebApplicationContext;
163 class ResourceBusinessLogicTest {
165 private final ConfigurationManager configurationManager = new ConfigurationManager(
166 new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"));
167 private static final String RESOURCE_CATEGORY1 = "Network Layer 2-3";
168 private static final String RESOURCE_SUBCATEGORY = "Router";
170 private static final String UPDATED_SUBCATEGORY = "Gateway";
172 private static final String RESOURCE_NAME = "My-Resource_Name with space";
173 private static final String RESOURCE_TOSCA_NAME = "My-Resource_Tosca_Name";
174 private static final String GENERIC_ROOT_NAME = "tosca.nodes.Root";
175 private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
176 private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR";
177 private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
178 private static final boolean MULTITENANCY_ENABLED = true;
179 private static final String TEST_TENANT = "test_tenant";
181 private final ServletContext servletContext = Mockito.mock(ServletContext.class);
182 private IElementOperation mockElementDao;
183 private final JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class);
184 private final UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
185 private final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
186 private final NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
187 private final NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
188 private final TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
189 private final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
190 private final CatalogOperation catalogOperation = Mockito.mock(CatalogOperation.class);
191 private final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
192 private final PropertyOperation propertyOperation = Mockito.mock(PropertyOperation.class);
193 private final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class);
194 private final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
195 private final UserValidations userValidations = Mockito.mock(UserValidations.class);
196 private final WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
197 private final IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
198 private final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class);
199 private final IElementOperation elementDao = new ElementOperationMock();
201 private final CsarUtils csarUtils = Mockito.mock(CsarUtils.class);
202 private final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
203 private final IGroupOperation groupOperation = Mockito.mock(IGroupOperation.class);
204 private final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class);
205 private final IGroupTypeOperation groupTypeOperation = Mockito.mock(IGroupTypeOperation.class);
206 private final GroupBusinessLogic groupBusinessLogic = Mockito.mock(GroupBusinessLogic.class);
207 private final ModelBusinessLogic modelBusinessLogic = Mockito.mock(ModelBusinessLogic.class);
208 private final InterfaceOperation interfaceOperation = Mockito.mock(InterfaceOperation.class);
209 private final ArtifactsOperations artifactToscaOperation = Mockito.mock(ArtifactsOperations.class);
210 private final PropertyBusinessLogic propertyBusinessLogic = Mockito.mock(PropertyBusinessLogic.class);
211 private final ArtifactsResolver artifactsResolver = Mockito.mock(ArtifactsResolver.class);
212 private final InterfaceLifecycleOperation interfaceLifecycleTypeOperation = Mockito.mock(InterfaceLifecycleOperation.class);
213 private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class);
214 private final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
215 private final InputsBusinessLogic inputsBusinessLogic = Mockito.mock(InputsBusinessLogic.class);
216 private final OutputsBusinessLogic outputsBusinessLogic = Mockito.mock(OutputsBusinessLogic.class);
217 private final CompositionBusinessLogic compositionBusinessLogic = Mockito.mock(CompositionBusinessLogic.class);
218 private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic = Mockito.mock(ResourceDataMergeBusinessLogic.class);
219 private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic = Mockito.mock(CsarArtifactsAndGroupsBusinessLogic.class);
220 private final MergeInstanceUtils mergeInstanceUtils = Mockito.mock(MergeInstanceUtils.class);
221 private final UiComponentDataConverter uiComponentDataConverter = Mockito.mock(UiComponentDataConverter.class);
222 private final ToscaExportHandler toscaExportHandler = Mockito.mock(ToscaExportHandler.class);
223 private final PolicyTypeOperation policyTypeOperation = Mockito.mock(PolicyTypeOperation.class);
224 private final PolicyBusinessLogic policyBusinessLogic = Mockito.mock(PolicyBusinessLogic.class);
225 private final ArtifactTypeOperation artifactTypeOperation = Mockito.mock(ArtifactTypeOperation.class);
226 private final DataTypeBusinessLogic dataTypeBusinessLogic = Mockito.mock(DataTypeBusinessLogic.class);
227 private final PolicyTypeBusinessLogic policyTypeBusinessLogic = Mockito.mock(PolicyTypeBusinessLogic.class);
228 private final ModelOperation modelOperation = Mockito.mock(ModelOperation.class);
230 private YamlTemplateParsingHandler yamlTemplateParsingHandler = Mockito.mock(YamlTemplateParsingHandler.class);
232 private ResponseFormatManager responseManager = null;
233 private final GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
234 private User user = null;
235 private Resource resourceResponse = null;
236 private Resource genericVF = null;
237 private Resource genericCR = null;
238 private Resource genericVFC = null;
239 private Resource genericPNF = null;
240 private Resource rootType = null;
241 private ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
242 private ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(artifactCassandraDao, toscaExportHandler, csarUtils, lifecycleBl,
243 userBusinessLogic, artifactsResolver, elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
244 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation, artifactTypeOperation);
245 private CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
247 private CsarBusinessLogic csarBusinessLogic;
248 private Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
249 private List<Resource> reslist;
250 private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
251 protected ComponentDescriptionValidator componentDescriptionValidator = new ComponentDescriptionValidator(componentsUtils);
252 protected ComponentProjectCodeValidator componentProjectCodeValidator = new ComponentProjectCodeValidator(componentsUtils);
253 protected ComponentIconValidator componentIconValidator = new ComponentIconValidator(componentsUtils);
254 protected ComponentContactIdValidator componentContactIdValidator = new ComponentContactIdValidator(componentsUtils);
255 protected ComponentTagsValidator componentTagsValidator = new ComponentTagsValidator(componentsUtils);
256 protected ComponentNameValidator componentNameValidator = new ComponentNameValidator(componentsUtils, toscaOperationFacade);
257 private ComponentValidator componentValidator = createComponentValidator();
258 private SoftwareInformationBusinessLogic softwareInformationBusinessLogic = Mockito.mock(SoftwareInformationBusinessLogic.class);
260 private ComponentValidator createComponentValidator() {
261 List<ComponentFieldValidator> componentFieldValidators = Arrays.asList(componentNameValidator,
262 componentDescriptionValidator, componentProjectCodeValidator,
263 componentIconValidator, componentContactIdValidator,
264 componentTagsValidator);
265 return new ComponentValidator(componentsUtils, componentFieldValidators);
268 private ResourceBusinessLogic bl;
271 public void setup() {
272 MockitoAnnotations.openMocks(this);
273 Mockito.reset(propertyOperation);
276 mockElementDao = new ElementOperationMock();
278 // User data and management
280 user.setUserId("jh0003");
281 user.setFirstName("Jimmi");
282 user.setLastName("Hendrix");
283 user.setRole(Role.ADMIN.name());
285 when(mockUserAdmin.getUser("jh0003", false)).thenReturn(user);
286 when(userValidations.validateUserExists(user.getUserId())).thenReturn(user);
287 when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
288 // Servlet Context attributes
289 when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
290 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
291 .thenReturn(webAppContextWrapper);
292 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
293 when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
295 Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true);
296 when(toscaOperationFacade.validateComponentNameExists("tosca.nodes.Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
297 .thenReturn(eitherFalse);
299 Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
300 when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC,
301 ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist);
303 Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
304 when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class),
305 eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount);
306 Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
307 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
309 Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false);
310 when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
311 when(graphLockOperation.lockComponent(anyString(), eq(NodeTypeEnum.Resource)))
312 .thenReturn(StorageOperationStatus.OK);
313 when(graphLockOperation.lockComponentByName(anyString(), eq(NodeTypeEnum.Resource)))
314 .thenReturn(StorageOperationStatus.OK);
317 resourceResponse = createResourceObject(true);
318 Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
319 when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
320 when(catalogOperation.updateCatalog(Mockito.any(), Mockito.any())).thenReturn(ActionStatus.OK);
321 Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
322 when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(emptyDataTypes));
323 when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
324 when(policyTypeOperation.getLatestPolicyTypeByType(any(String.class), any(String.class)))
325 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
327 artifactManager.setNodeTemplateOperation(nodeTemplateOperation);
328 bl = new ResourceBusinessLogic(mockElementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
329 interfaceOperation, interfaceLifecycleTypeOperation, artifactManager, componentInstanceBusinessLogic,
330 resourceImportManager, inputsBusinessLogic, outputsBusinessLogic, compositionBusinessLogic, resourceDataMergeBusinessLogic,
331 csarArtifactsAndGroupsBusinessLogic, uiComponentDataConverter, csarBusinessLogic,
332 artifactToscaOperation, propertyBusinessLogic, componentContactIdValidator, componentNameValidator,
333 componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator,
334 componentDescriptionValidator, policyBusinessLogic, modelBusinessLogic, dataTypeBusinessLogic, policyTypeBusinessLogic, modelOperation);
335 bl.setElementDao(mockElementDao);
336 bl.setUserAdmin(mockUserAdmin);
337 bl.setCapabilityTypeOperation(capabilityTypeOperation);
338 bl.setComponentsUtils(componentsUtils);
339 bl.setLifecycleManager(lifecycleBl);
340 bl.setArtifactsManager(artifactManager);
341 bl.setGraphLockOperation(graphLockOperation);
342 bl.setPropertyOperation(propertyOperation);
343 bl.setJanusGraphDao(mockJanusGraphDao);
344 bl.setApplicationDataTypeCache(applicationDataTypeCache);
345 bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
346 bl.setCatalogOperations(catalogOperation);
347 toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
348 csarBusinessLogic.setComponentsUtils(componentsUtils);
349 toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
350 bl.setToscaOperationFacade(toscaOperationFacade);
351 bl.setUserValidations(userValidations);
352 bl.setInterfaceTypeOperation(interfaceTypeOperation);
353 bl.setPolicyTypeOperation(policyTypeOperation);
355 csarBusinessLogic.setCsarOperation(csarOperation);
356 Resource resourceCsar = createResourceObjectCsar(true);
357 setCanWorkOnResource(resourceCsar);
358 Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
359 when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
360 responseManager = ResponseFormatManager.getInstance();
361 bl.setComponentIconValidator(componentIconValidator);
362 bl.setComponentNameValidator(componentNameValidator);
363 bl.setComponentDescriptionValidator(componentDescriptionValidator);
364 bl.setComponentTagsValidator(componentTagsValidator);
365 bl.setComponentContactIdValidator(componentContactIdValidator);
366 bl.setComponentProjectCodeValidator(componentProjectCodeValidator);
367 bl.setComponentValidator(componentValidator);
368 reslist = new ArrayList<>();
369 reslist.add(resourceResponse);
370 reslist.add(genericVF);
371 reslist.add(genericCR);
372 reslist.add(genericVFC);
373 reslist.add(genericPNF);
374 Either<List<Resource>, StorageOperationStatus> returneval = Either.left(reslist);
375 when(toscaOperationFacade.getAllCertifiedResources(true, true)).thenReturn(returneval);
376 when(toscaOperationFacade.validateComponentNameUniqueness("Resource", ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(
378 Either<List<Resource>, StorageOperationStatus> returnevalexception = Either.right(StorageOperationStatus.BAD_REQUEST);
379 when(toscaOperationFacade.getAllCertifiedResources(false, false)).thenReturn(returnevalexception);
383 void createResourcesFromYamlNodeTypesList() throws IOException {
384 Map<String, Object> mappedToscaTemplate = new HashMap<>();
385 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
386 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
387 Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
388 assertThrows(ComponentException.class, () -> {
389 bl.createResourcesFromYamlNodeTypesList(
394 nodeTypesArtifactsToHandle,
395 nodeTypesNewCreatedArtifacts,
397 new OnboardedCsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name",
398 ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"), true), "");
403 void handleNodeTypeArtifactsTest() {
404 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = new HashMap<>();
405 List<ArtifactDefinition> defs = new ArrayList<>();
406 defs.add(new ArtifactDefinition());
407 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, defs);
408 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, defs);
409 assertTrue(bl.handleNodeTypeArtifacts(resourceResponse, nodeTypeArtifactsToHandle, new ArrayList<>(), user, true, true).isRight());
413 void getUiComponentDataTransferByComponentIdTest() {
414 when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(genericCR));
415 assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isLeft());
416 when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(
417 Either.right(StorageOperationStatus.OK));
418 assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isRight());
422 void shouldUpgradeToLatestDerivedTest() {
425 when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericCR)).thenReturn(Either.left(genericCR));
426 when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericVFC)).thenReturn(Either.right(StorageOperationStatus.OK));
427 assertTrue(bl.shouldUpgradeToLatestDerived(genericVF).isLeft());
428 assertTrue(bl.shouldUpgradeToLatestDerived(genericCR).isLeft());
431 private Resource createResourceObject(boolean afterCreate) {
432 Resource resource = new Resource();
433 resource.setName(RESOURCE_NAME);
434 resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
435 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
436 resource.setDescription("My short description");
437 List<String> tgs = new ArrayList<>();
439 tgs.add(resource.getName());
440 resource.setTags(tgs);
441 List<String> template = new ArrayList<>();
442 template.add("tosca.nodes.Root");
443 resource.setDerivedFrom(template);
444 resource.setVendorName("Motorola");
445 resource.setVendorRelease("1.0.0");
446 resource.setContactId("ya5467");
447 resource.setIcon("defaulticon");
450 resource.setName(resource.getName());
451 resource.setVersion("0.1");
452 resource.setUniqueId(resource.getName()
453 .toLowerCase() + ":" + resource.getVersion());
454 resource.setCreatorUserId(user.getUserId());
455 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
456 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
461 private Resource createResourceObjectWithModel(boolean afterCreate) {
462 Resource resource = new Resource();
463 resource.setName(RESOURCE_NAME);
464 resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
465 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
466 resource.setDescription("My short description");
467 List<String> tgs = new ArrayList<>();
469 tgs.add(resource.getName());
470 resource.setTags(tgs);
471 List<String> template = new ArrayList<>();
472 template.add("tosca.nodes.Root");
473 resource.setDerivedFrom(template);
474 resource.setVendorName("Motorola");
475 resource.setVendorRelease("1.0.0");
476 resource.setContactId("ya5467");
477 resource.setIcon("defaulticon");
478 resource.setModel("Test Model");
481 resource.setName(resource.getName());
482 resource.setVersion("0.1");
483 resource.setUniqueId(resource.getName()
484 .toLowerCase() + ":" + resource.getVersion());
485 resource.setCreatorUserId(user.getUserId());
486 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
487 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
492 private Resource createResourceObjectCsar(boolean afterCreate) {
493 Resource resource = new Resource();
494 resource.setName(RESOURCE_NAME);
495 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
496 resource.setDescription("My short description");
497 List<String> tgs = new ArrayList<>();
499 tgs.add(resource.getName());
500 resource.setTags(tgs);
501 List<String> template = new ArrayList<>();
502 template.add("tosca.nodes.Root");
503 resource.setDerivedFrom(template);
504 resource.setVendorName("Motorola");
505 resource.setVendorRelease("1.0.0");
506 resource.setResourceVendorModelNumber("");
507 resource.setContactId("ya5467");
508 resource.setIcon("MyIcon");
509 resource.setCsarUUID("valid_vf.csar");
510 resource.setCsarVersion("1");
513 resource.setName(resource.getName());
514 resource.setVersion("0.1");
516 resource.setUniqueId(resource.getName()
517 .toLowerCase() + ":" + resource.getVersion());
518 resource.setCreatorUserId(user.getUserId());
519 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
520 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
525 private Resource setCanWorkOnResource(Resource resource) {
526 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
527 resource.setLastUpdaterUserId(user.getUserId());
532 void testHappyScenario() {
533 validateUserRoles(Role.ADMIN, Role.DESIGNER);
534 Resource resource = createResourceObject(false);
535 Resource createdResource = null;
537 when(toscaOperationFacade
538 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
539 .thenReturn(Either.left(false));
540 createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
541 assertThat(createResourceObject(true)).isEqualTo(createdResource);
542 } catch (ComponentException e) {
543 assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
549 void testUpdateHappyScenario() {
550 Resource resource = createResourceObjectCsar(true);
551 setCanWorkOnResource(resource);
552 validateUserRoles(Role.ADMIN, Role.DESIGNER);
553 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource);
554 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(),
555 resource.getSystemName())).thenReturn(resourceLinkedToCsarRes);
556 Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
557 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
558 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
559 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
560 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
561 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
563 assertThat(resource.getUniqueId()).isEqualTo(
564 bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()).getUniqueId());
565 } catch (ComponentException e) {
566 assertThat(e.getResponseFormat().getStatus()).isEqualTo(200);
571 void testUpdateUnhappyScenario() {
572 Resource resource = createResourceObjectCsar(true);
573 final var csarVersionId = "csarVersionId";
574 resource.setCsarVersionId(csarVersionId);
576 final var vendorSoftwareProduct = new VendorSoftwareProduct();
577 vendorSoftwareProduct.setFileMap(new HashMap<>());
578 vendorSoftwareProduct.setModelList(Collections.emptyList());
579 setCanWorkOnResource(resource);
580 validateUserRoles(Role.ADMIN, Role.DESIGNER);
582 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(),
583 resource.getSystemName())).thenReturn(Either.left(resource));
584 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(Either.left(true));
585 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(Either.left(setCanWorkOnResource(resource)));
586 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(Either.left(resource));
587 when(csarOperation.findVsp("valid_vf.csar", csarVersionId, user)).thenReturn(Optional.of(vendorSoftwareProduct));
590 Resource createdResource = bl.validateAndUpdateResourceFromCsar(resource, user, null, "", resource.getUniqueId());
591 assertThat(resource.getUniqueId()).isEqualTo(createdResource.getUniqueId());
592 } catch (ComponentException e) {
593 assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
596 resource.setCsarVersion("2");
597 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(),
598 resource.getSystemName())).thenReturn(Either.left(resource));
599 bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId());
600 } catch (ComponentException e) {
601 assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
604 /* CREATE validations - start ***********************/
605 // Resource name - start
608 void testFailedResourceValidations() {
609 testResourceNameExist();
610 testResourceNameEmpty();
611 // testResourceNameExceedsLimit();
612 testResourceNameWrongFormat();
613 testResourceDescExceedsLimitCreate();
614 testResourceDescNotEnglish();
615 testResourceDescriptionEmpty();
616 testResourceDescriptionMissing();
617 testResourceIconMissing();
618 testResourceIconInvalid();
619 testResourceIconExceedsLimit();
620 testResourceTagNotExist();
621 testResourceTagEmpty();
622 testTagsExceedsLimitCreate();
623 testTagsNoServiceName();
626 testContactIdTooLong();
627 testContactIdWrongFormatCreate();
628 testResourceContactIdEmpty();
629 testResourceContactIdMissing();
630 testVendorNameExceedsLimit();
631 testVendorNameWrongFormatCreate();
632 testVendorReleaseWrongFormat();
633 testVendorReleaseExceedsLimitCreate();
634 testResourceVendorModelNumberExceedsLimit();
635 testResourceVendorNameMissing();
636 testResourceVendorReleaseMissing();
637 testResourceCategoryExist();
638 testResourceBadCategoryCreate();
639 testHappyScenarioCostLicenseType();
640 testCostWrongFormatCreate();
641 testLicenseTypeWrongFormatCreate();
642 testResourceTemplateNotExist();
643 testResourceTemplateEmpty();
644 testResourceTemplateInvalid();
647 private void testResourceNameExist() {
648 String resourceName = "alreadyExists";
649 Resource resourceExist = createResourceObject(false);
650 resourceExist.setName(resourceName);
651 resourceExist.getTags()
653 validateUserRoles(Role.ADMIN, Role.DESIGNER);
654 when(toscaOperationFacade
655 .validateComponentNameAndModelExists(resourceName, null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
656 .thenReturn(Either.left(true));
658 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
659 } catch (ComponentException e) {
660 assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
661 ComponentTypeEnum.RESOURCE.getValue(), resourceName);
665 private void testResourceNameEmpty() {
666 Resource resourceExist = createResourceObject(false);
667 resourceExist.setName(null);
670 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
671 } catch (ComponentException e) {
672 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
676 private void testResourceNameExceedsLimit() {
677 Resource resourceExccedsNameLimit = createResourceObject(false);
678 // 51 chars, the limit is 50
679 String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
680 resourceExccedsNameLimit.setName(tooLongResourceName);
683 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
684 } catch (ComponentException e) {
685 assertComponentException(e, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT,
686 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
690 private void testResourceNameWrongFormat() {
691 Resource resource = createResourceObject(false);
693 String nameWrongFormat = "ljg?fd";
694 resource.setName(nameWrongFormat);
697 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
698 } catch (ComponentException e) {
699 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
703 // Resource name - end
704 // Resource description - start
705 private void testResourceDescExceedsLimitCreate() {
706 Resource resourceExccedsDescLimit = createResourceObject(false);
707 // 1025 chars, the limit is 1024
708 String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
709 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
710 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
711 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
712 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
713 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
714 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
715 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
717 resourceExccedsDescLimit.setDescription(tooLongResourceDesc);
719 bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
720 } catch (ComponentException e) {
721 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
722 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
726 private void testResourceDescNotEnglish() {
727 Resource notEnglish = createResourceObject(false);
729 String notEnglishDesc = "\uC2B5";
730 notEnglish.setDescription(notEnglishDesc);
733 bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
734 } catch (ComponentException e) {
735 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION,
736 ComponentTypeEnum.RESOURCE.getValue());
740 private void testResourceDescriptionEmpty() {
741 Resource resourceExist = createResourceObject(false);
742 resourceExist.setDescription("");
745 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
746 } catch (ComponentException e) {
747 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
748 ComponentTypeEnum.RESOURCE.getValue());
752 private void testResourceDescriptionMissing() {
753 Resource resourceExist = createResourceObject(false);
754 resourceExist.setDescription(null);
757 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
758 } catch (ComponentException e) {
759 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
760 ComponentTypeEnum.RESOURCE.getValue());
763 // Resource description - end
764 // Resource icon start
766 private void testResourceIconMissing() {
767 Resource resourceExist = createResourceObject(false);
768 resourceExist.setIcon(null);
769 when(toscaOperationFacade
770 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
771 .thenReturn(Either.left(false));
773 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
774 } catch (ComponentException e) {
775 assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
779 private void testResourceIconInvalid() {
780 Resource resourceExist = createResourceObject(false);
781 resourceExist.setIcon("kjk3453^&");
784 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
785 } catch (ComponentException e) {
786 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
790 private void testResourceIconExceedsLimit() {
791 Resource resourceExist = createResourceObject(false);
792 resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
794 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
795 } catch (ComponentException e) {
796 assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT,
797 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
802 // Resource tags - start
803 private void testResourceTagNotExist() {
804 Resource resourceExist = createResourceObject(false);
805 resourceExist.setTags(null);
807 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
808 } catch (ComponentException e) {
809 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
813 private void testResourceTagEmpty() {
814 Resource resourceExist = createResourceObject(false);
815 resourceExist.setTags(new ArrayList<>());
817 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
818 } catch (ComponentException e) {
819 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
823 private void testTagsExceedsLimitCreate() {
824 Resource resourceExccedsNameLimit = createResourceObject(false);
825 String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
826 String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
827 String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
828 String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
829 String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
830 String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
831 String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
832 String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
833 String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
834 String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
835 String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
836 String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
837 String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
838 String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
839 String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
840 String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
841 String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
842 String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
843 String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
844 String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
845 String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
847 List<String> tagsList = new ArrayList<>();
869 tagsList.add(resourceExccedsNameLimit.getName());
871 resourceExccedsNameLimit.setTags(tagsList);
873 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
874 } catch (ComponentException e) {
875 assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
876 "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
880 private void testTagsSingleExceedsLimit() {
881 Resource resourceExccedsNameLimit = createResourceObject(false);
882 String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI";
883 String tag2 = resourceExccedsNameLimit.getName();
884 List<String> tagsList = new ArrayList<>();
888 resourceExccedsNameLimit.setTags(tagsList);
890 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
891 } catch (ComponentException e) {
892 assertComponentException(e, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT,
893 "" + ValidationUtils.TAG_MAX_LENGTH);
897 private void testTagsNoServiceName() {
898 Resource serviceExccedsNameLimit = createResourceObject(false);
899 String tag1 = "afzs2qLBb";
900 List<String> tagsList = new ArrayList<>();
902 serviceExccedsNameLimit.setTags(tagsList);
904 bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
905 } catch (ComponentException e) {
906 assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
910 private void testInvalidTag() {
911 Resource serviceExccedsNameLimit = createResourceObject(false);
912 String tag1 = "afzs2qLBb%#%";
913 List<String> tagsList = new ArrayList<>();
915 serviceExccedsNameLimit.setTags(tagsList);
917 bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
918 } catch (ComponentException e) {
919 assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, new String[]{"Resource", "tag"});
923 // Resource tags - stop
924 // Resource contact start
926 private void testContactIdTooLong() {
927 Resource resourceContactId = createResourceObject(false);
928 // 59 chars instead of 50
929 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
930 resourceContactId.setContactId(contactIdTooLong);
933 bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
934 } catch (ComponentException e) {
935 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
939 private void testContactIdWrongFormatCreate() {
940 Resource resourceContactId = createResourceObject(false);
941 // 3 letters and 3 digits and special characters
942 String contactIdFormatWrong = "yrt134!!!";
943 resourceContactId.setContactId(contactIdFormatWrong);
945 bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
946 } catch (ComponentException e) {
947 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
951 private void testResourceContactIdEmpty() {
952 Resource resourceExist = createResourceObject(false);
953 resourceExist.setContactId("");
955 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
956 } catch (ComponentException e) {
957 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
961 private void testResourceContactIdMissing() {
962 Resource resourceExist = createResourceObject(false);
963 resourceExist.setContactId(null);
965 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
966 } catch (ComponentException e) {
967 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
971 private void testVendorNameExceedsLimit() {
972 Resource resourceExccedsVendorNameLimit = createResourceObject(false);
973 String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
974 resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
976 bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
977 } catch (ComponentException e) {
978 assertComponentException(e, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
979 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
983 private void testResourceVendorModelNumberExceedsLimit() {
984 Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
985 String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
986 resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
988 bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null,
990 } catch (ComponentException e) {
991 assertComponentException(e, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
992 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
996 private void testVendorNameWrongFormatCreate() {
997 Resource resource = createResourceObject(false);
999 String nameWrongFormat = "ljg*fd";
1000 resource.setVendorName(nameWrongFormat);
1002 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1003 } catch (ComponentException e) {
1004 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
1008 private void testVendorReleaseWrongFormat() {
1009 Resource resource = createResourceObject(false);
1011 String vendorReleaseWrongFormat = "1>2";
1012 resource.setVendorRelease(vendorReleaseWrongFormat);
1014 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1015 } catch (ComponentException e) {
1016 assertComponentException(e, ActionStatus.INVALID_VENDOR_RELEASE, vendorReleaseWrongFormat);
1020 private void testVendorReleaseExceedsLimitCreate() {
1021 Resource resourceExccedsNameLimit = createResourceObject(false);
1022 String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
1023 resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
1025 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1026 } catch (ComponentException e) {
1027 assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
1028 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
1032 private void testResourceVendorNameMissing() {
1033 Resource resourceExist = createResourceObject(false);
1034 resourceExist.setVendorName(null);
1036 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1037 } catch (ComponentException e) {
1038 assertComponentException(e, ActionStatus.MISSING_VENDOR_NAME);
1042 private void testResourceVendorReleaseMissing() {
1043 Resource resourceExist = createResourceObject(false);
1044 resourceExist.setVendorRelease(null);
1046 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1047 } catch (ComponentException e) {
1048 assertComponentException(e, ActionStatus.MISSING_VENDOR_RELEASE);
1052 // Resource vendor name/release stop
1054 private void testResourceCategoryExist() {
1055 Resource resourceExist = createResourceObject(false);
1056 resourceExist.setCategories(null);
1058 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1059 } catch (ComponentException e) {
1060 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1064 private void testResourceBadCategoryCreate() {
1066 Resource resourceExist = createResourceObject(false);
1067 resourceExist.setCategories(null);
1068 resourceExist.addCategory("koko", "koko");
1070 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1071 } catch (ComponentException e) {
1072 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1078 private void testHappyScenarioCostLicenseType() {
1079 Resource createResourceObject = createResourceObject(false);
1080 Resource createResourceObjectAfterCreate = createResourceObject(true);
1081 // Adding cost and licenseType to basic mock
1082 Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate);
1083 when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
1085 String cost = "123.456";
1086 String licenseType = "User";
1087 createResourceObject.setCost(cost);
1088 createResourceObject.setLicenseType(licenseType);
1089 Resource createdResource;
1091 createdResource = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null,
1093 createResourceObjectAfterCreate.setCost(cost);
1094 createResourceObjectAfterCreate.setLicenseType(licenseType);
1095 assertThat(createResourceObjectAfterCreate).isEqualTo(createdResource);
1096 } catch (ComponentException e) {
1097 assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
1102 private void testCostWrongFormatCreate() {
1103 Resource resourceCost = createResourceObject(false);
1104 // Comma instead of fullstop
1105 String cost = "12356,464";
1106 resourceCost.setCost(cost);
1108 bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1109 } catch (ComponentException e) {
1110 assertComponentException(e, ActionStatus.INVALID_CONTENT);
1115 // License type start
1116 private void testLicenseTypeWrongFormatCreate() {
1117 Resource resourceLicenseType = createResourceObject(false);
1119 String licenseType = "cpu";
1120 resourceLicenseType.setLicenseType(licenseType);
1122 bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1123 } catch (ComponentException e) {
1124 assertComponentException(e, ActionStatus.INVALID_CONTENT);
1128 // License type stop
1129 // Derived from start
1130 private void testResourceTemplateNotExist() {
1131 Resource resourceExist = createResourceObject(false);
1132 List<String> list = null;
1133 resourceExist.setDerivedFrom(list);
1135 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1136 } catch (ComponentException e) {
1137 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1141 private void testResourceTemplateEmpty() {
1142 Resource resourceExist = createResourceObject(false);
1143 resourceExist.setDerivedFrom(new ArrayList<>());
1145 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1146 } catch (ComponentException e) {
1147 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1151 private void testResourceTemplateInvalid() {
1152 Resource resourceExist = createResourceObject(false);
1153 ArrayList<String> derivedFrom = new ArrayList<>();
1154 derivedFrom.add("kuku");
1155 resourceExist.setDerivedFrom(derivedFrom);
1157 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1158 } catch (ComponentException e) {
1159 assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
1163 // Derived from stop
1164 private void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) {
1165 ResponseFormat actualResponse = e.getResponseFormat() != null ? e.getResponseFormat()
1166 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1167 assertResponse(actualResponse, expectedStatus, variables);
1170 private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
1171 ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
1172 assertThat(expectedResponse.getStatus()).isEqualTo(actualResponse.getStatus());
1173 assertThat(expectedResponse.getFormattedMessage()).isEqualTo(actualResponse.getFormattedMessage());
1176 private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus,
1177 String... variables) {
1178 assertResponse(createResponse.right()
1179 .value(), expectedStatus, variables);
1182 // UPDATE tests - start
1185 void testResourceNameWrongFormat_UPDATE() {
1186 Resource resource = createResourceObject(true);
1187 Resource updatedResource = createResourceObject(true);
1189 // this is in order to prevent failing with 403 earlier
1190 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1191 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1193 String nameWrongFormat = "ljg*fd";
1194 updatedResource.setName(nameWrongFormat);
1196 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1197 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1199 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1200 } catch (ComponentException e) {
1201 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
1206 void testResourceNameAfterCertify_UPDATE() {
1207 Resource resource = createResourceObject(true);
1208 Resource updatedResource = createResourceObject(true);
1210 // this is in order to prevent failing with 403 earlier
1211 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1212 // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
1213 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1215 String name = "ljg";
1216 updatedResource.setName(name);
1217 resource.setVersion("1.0");
1219 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1220 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1222 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1223 } catch (ComponentException e) {
1224 assertComponentException(e, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1229 void testResourceNameAlreadyExist_UPDATE() {
1230 Resource resource = createResourceObject(true);
1231 Resource updatedResource = createResourceObject(true);
1233 // this is in order to prevent failing with 403 earlier
1234 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1235 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1237 String resourceName = "alreadyExists";
1238 updatedResource.setName(resourceName);
1239 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
1240 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1242 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1243 } catch (ComponentException e) {
1244 assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
1245 ComponentTypeEnum.RESOURCE.getValue(), resourceName);
1250 void testResourceDescExceedsLimit_UPDATE() {
1251 Resource resource = createResourceObject(true);
1252 Resource updatedResource = createResourceObject(true);
1254 // this is in order to prevent failing with 403 earlier
1255 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1256 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1258 // 1025 chars, the limit is 1024
1259 String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
1260 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
1261 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
1262 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
1263 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
1264 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
1265 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
1266 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
1267 updatedResource.setDescription(tooLongResourceDesc);
1268 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1269 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1271 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1272 } catch (ComponentException e) {
1273 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
1274 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
1279 void testIconWrongFormat_UPDATE() {
1280 Resource resource = createResourceObject(true);
1281 Resource updatedResource = createResourceObject(true);
1283 // this is in order to prevent failing with 403 earlier
1284 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1285 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1288 String icon = "icon.jpg";
1289 updatedResource.setIcon(icon);
1290 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1291 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1293 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1294 } catch (ComponentException e) {
1295 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
1300 void testIconAfterCertify_UPDATE() {
1301 Resource resource = createResourceObject(true);
1302 Resource updatedResource = createResourceObject(true);
1304 // this is in order to prevent failing with 403 earlier
1305 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1306 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1309 String icon = "icon";
1310 updatedResource.setIcon(icon);
1312 resource.setVersion("1.0");
1314 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1315 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1317 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1318 } catch (ComponentException e) {
1319 assertComponentException(e, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
1324 void testTagsExceedsLimit_UPDATE() {
1325 Resource resource = createResourceObject(true);
1326 Resource updatedResource = createResourceObject(true);
1328 // this is in order to prevent failing with 403 earlier
1329 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1330 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1332 String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
1333 String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
1334 String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
1335 String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
1336 String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
1337 String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
1338 String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
1339 String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
1340 String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
1341 String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
1342 String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
1343 String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
1344 String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
1345 String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
1346 String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
1347 String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
1348 String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
1349 String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
1350 String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
1351 String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
1352 String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
1354 List<String> tagsList = new ArrayList<>();
1364 tagsList.add(tag10);
1365 tagsList.add(tag11);
1366 tagsList.add(tag12);
1367 tagsList.add(tag13);
1368 tagsList.add(tag14);
1369 tagsList.add(tag15);
1370 tagsList.add(tag16);
1371 tagsList.add(tag17);
1372 tagsList.add(tag18);
1373 tagsList.add(tag19);
1374 tagsList.add(tag20);
1375 tagsList.add(tag21);
1376 tagsList.add(resource.getName());
1378 updatedResource.setTags(tagsList);
1379 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1380 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1382 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1383 } catch (ComponentException e) {
1384 assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
1385 "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
1390 void testVendorNameWrongFormat_UPDATE() {
1391 Resource resource = createResourceObject(true);
1392 Resource updatedResource = createResourceObject(true);
1394 // this is in order to prevent failing with 403 earlier
1395 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1396 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1399 String nameWrongFormat = "ljg*fd";
1400 updatedResource.setVendorName(nameWrongFormat);
1401 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1402 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1404 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1405 } catch (ComponentException e) {
1406 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
1411 void testVendorNameWrongFormat() {
1412 Resource resource = createResourceObject(true);
1413 Resource updatedResource = createResourceObject(true);
1415 // this is in order to prevent failing with 403 earlier
1416 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1417 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1420 String nameWrongFormat = "ljg*fd";
1421 updatedResource.setVendorName(nameWrongFormat);
1422 resource.setVersion("1.0");
1424 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1425 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1427 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1428 } catch (ComponentException e) {
1429 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
1434 void testVendorReleaseExceedsLimit_UPDATE() {
1435 Resource resource = createResourceObject(true);
1436 Resource updatedResource = createResourceObject(true);
1438 // this is in order to prevent failing with 403 earlier
1439 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1440 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1441 // 129 chars, the limit is 128
1442 String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy";
1443 updatedResource.setVendorRelease(tooLongVendorRelease);
1444 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1445 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1447 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1448 } catch (ComponentException e) {
1449 assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
1450 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
1455 void testResourceBadCategory_UPDATE() {
1456 Resource resource = createResourceObject(true);
1457 Resource updatedResource = createResourceObject(true);
1459 // this is in order to prevent failing with 403 earlier
1460 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1461 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1463 String resourceId = resource.getUniqueId();
1464 String badCategory = "ddfds";
1465 updatedResource.setCategories(null);
1466 updatedResource.addCategory(badCategory, "fikt");
1467 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1468 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1470 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1471 } catch (ComponentException e) {
1472 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1477 void createResourceFromCsarTest() {
1478 assertThrows(ComponentException.class, () -> {
1479 bl.createResourceFromCsar(resourceResponse, user, new HashMap<>(), "");
1484 void testCreateResourceFromCsarWithModel() throws URISyntaxException, ZipException {
1486 final File csarFile = new File(
1487 ResourceBusinessLogicTest.class.getClassLoader().getResource("csars/nonOnapCsar.csar").toURI());
1488 final Map<String, byte[]> csar = ZipUtils.readZip(csarFile, false);
1490 String resourceYml = new String(csar.get("Definitions/my_vnf.yaml"));
1492 YamlTemplateParsingHandler yamlTemplateParser = new YamlTemplateParsingHandler(mockJanusGraphDao, null,
1493 Mockito.mock(AnnotationBusinessLogic.class), null, null, null);
1494 final ParsedToscaYamlInfo parsedToscaYamlInfo = yamlTemplateParser.parseResourceInfoFromYAML("Definitions/my_vnf.yml", resourceYml,
1495 Collections.EMPTY_MAP, Collections.EMPTY_MAP, "myVnf", resourceResponse, "");
1497 when(propertyOperation.getDataTypeByName("tosca.datatypes.testDataType.FromMainTemplate", "testModel")).thenReturn(
1498 Either.right(StorageOperationStatus.NOT_FOUND));
1500 when(toscaOperationFacade.getLatestByToscaResourceName(anyString(), any())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1501 Resource vduCp = new Resource();
1502 vduCp.setToscaResourceName("tosca.nodes.nfv.VduCp");
1503 vduCp.setState(LifecycleStateEnum.CERTIFIED);
1504 vduCp.setUniqueId("tosca.nodes.nfv.VduCp");
1505 vduCp.setProperties(new ArrayList<>());
1506 Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
1507 RequirementDefinition req = new RequirementDefinition();
1508 req.setName("virtual_link");
1509 List<RequirementDefinition> listReqs = new ArrayList<>();
1511 requirements.put("tosca.nodes.nfv.VduCp", listReqs);
1512 vduCp.setRequirements(requirements);
1513 PropertyDefinition bitrateProp = new PropertyDefinition();
1514 bitrateProp.setName("bitrate_requirement");
1515 bitrateProp.setType("integer");
1516 vduCp.getProperties().add(bitrateProp);
1517 PropertyDefinition virtNiProp = new PropertyDefinition();
1518 virtNiProp.setName("virtual_network_interface_requirements");
1519 virtNiProp.setType("list");
1520 vduCp.getProperties().add(virtNiProp);
1521 PropertyDefinition descriptionProp = new PropertyDefinition();
1522 descriptionProp.setName("description");
1523 descriptionProp.setType("string");
1524 vduCp.getProperties().add(descriptionProp);
1525 PropertyDefinition roleProp = new PropertyDefinition();
1526 roleProp.setName("role");
1527 roleProp.setType("string");
1528 vduCp.getProperties().add(roleProp);
1529 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel("tosca.nodes.nfv.VduCp", "testModel_myVnf1.0")).thenReturn(Either.left(vduCp));
1531 when(yamlTemplateParsingHandler.parseResourceInfoFromYAML(any(), any(), any(), any(), any(), any(), any())).thenReturn(parsedToscaYamlInfo);
1533 UploadComponentInstanceInfo uploadComponentInstanceInfo = new UploadComponentInstanceInfo();
1534 uploadComponentInstanceInfo.setType("myType");
1535 resourceResponse.setUniqueId("myVnf");
1536 resourceResponse.setName("myVnf");
1537 resourceResponse.setSystemName("myVnf");
1538 resourceResponse.setModel("testModel");
1539 resourceResponse.setResourceType(ResourceTypeEnum.VF);
1540 resourceResponse.setProperties(new ArrayList<>());
1541 resourceResponse.setCsarVersion("1.0");
1543 Resource derivedFrom = new Resource();
1544 List<PropertyDefinition> properties = new ArrayList<>();
1545 PropertyDefinition baseTypeProp = new PropertyDefinition();
1546 baseTypeProp.setName("propInBase");
1547 baseTypeProp.setType("string");
1548 properties.add(baseTypeProp);
1549 derivedFrom.setProperties(properties);
1550 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(any(), eq("tosca.nodes.nfv.VNF"))).thenReturn(Either.left(derivedFrom));
1552 when(toscaOperationFacade
1553 .validateComponentNameAndModelExists("myVnf", "testModel_myVnf1.0", ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(
1554 Either.left(false));
1556 when(toscaOperationFacade.addPropertyToComponent(any(), any())).thenReturn(Either.left(new PropertyDefinition()));
1557 when(toscaOperationFacade.associateComponentInstancePropertiesToComponent(any(), any())).thenReturn(Either.left(Collections.emptyMap()));
1558 when(toscaOperationFacade.associateArtifactsToInstances(any(), any())).thenReturn(StorageOperationStatus.OK);
1559 when(toscaOperationFacade.associateDeploymentArtifactsToInstances(any(), any(), any())).thenReturn(StorageOperationStatus.OK);
1560 when(toscaOperationFacade.associateInstAttributeToComponentToInstances(any(), any())).thenReturn(StorageOperationStatus.OK);
1561 when(toscaOperationFacade.associateResourceInstances(any(Component.class), anyString(), anyList())).thenReturn(
1562 Either.left(Collections.EMPTY_LIST));
1563 when(applicationDataTypeCache.getAll("testModel_myVnf1.0")).thenReturn(Either.left(emptyDataTypes));
1565 doAnswer(invocation -> {
1566 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReqs = invocation.getArgument(1);
1567 for (final Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> m : instReqs.entrySet()) {
1568 m.getKey().setRequirements(m.getValue());
1570 return StorageOperationStatus.OK;
1572 when(toscaOperationFacade).associateOrAddCalculatedCapReq(any(), any(), any());
1574 when(toscaOperationFacade.updateCalculatedCapabilitiesRequirements(any(), any(), any())).thenReturn(StorageOperationStatus.OK);
1575 when(groupBusinessLogic.validateUpdateVfGroupNames(any(), any())).thenReturn(Either.left(Collections.EMPTY_MAP));
1577 ComponentInstance ci = new ComponentInstance();
1578 List<ComponentInstance> cis = new ArrayList<>();
1580 doAnswer(invocation -> {
1581 List<ComponentInstance> componentInstances = new ArrayList<ComponentInstance>(
1582 ((Map<ComponentInstance, Resource>) invocation.getArgument(1)).keySet());
1583 ((Resource) invocation.getArgument(0)).setComponentInstances(componentInstances);
1585 }).when(toscaOperationFacade).associateComponentInstancesToComponent(any(), any(), eq(false), eq(false));
1587 doAnswer(invocation -> {
1588 return Either.left(invocation.getArgument(0));
1589 }).when(csarArtifactsAndGroupsBusinessLogic).deleteVFModules(any(Resource.class), any(CsarInfo.class), eq(true), eq(false));
1591 doAnswer(invocation -> {
1592 return Either.left(resourceResponse);
1593 }).when(toscaOperationFacade).getToscaFullElement("myVnf");
1595 Resource result = bl.createResourceFromCsar(resourceResponse, user, csar, "1234");
1597 assertEquals("myDomain.myVnf", result.getToscaResourceName());
1598 List<String> propIds = result.getProperties().stream().map(prop -> prop.getUniqueId()).collect(Collectors.toList());
1599 assertTrue(propIds.contains("myVnf.propInBase"));
1600 assertTrue(propIds.contains("myVnf.descriptor_id"));
1601 assertTrue(propIds.contains("myVnf.descriptor_version"));
1602 assertTrue(propIds.contains("myVnf.flavour_description"));
1603 assertTrue(propIds.contains("myVnf.flavour_id"));
1604 assertTrue(propIds.contains("myVnf.product_name"));
1605 assertTrue(propIds.contains("myVnf.provider"));
1606 assertTrue(propIds.contains("myVnf.software_version"));
1607 assertTrue(propIds.contains("myVnf.vnfm_info"));
1609 final List<String> reqsName = new ArrayList<>();
1611 final List<ComponentInstance> cisWithExtReq = result.getComponentInstances().stream()
1612 .filter(instance -> instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).isExternal()).collect(Collectors.toList());
1613 cisWithExtReq.forEach(instance -> reqsName.add(instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).getExternalName()));
1614 assertEquals(3, cisWithExtReq.size());
1618 void testResourceCategoryAfterCertify_UPDATE() {
1619 Resource resource = createResourceObject(true);
1620 Resource updatedResource = createResourceObject(true);
1622 // this is in order to prevent failing with 403 earlier
1623 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1624 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1626 String resourceId = resource.getUniqueId();
1627 updatedResource.setCategories(null);
1628 updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY);
1629 resource.setVersion("1.0");
1631 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1632 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1634 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1635 } catch (ComponentException e) {
1636 assertComponentException(e, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
1640 // Derived from start
1642 void testResourceTemplateNotExist_UPDATE() {
1643 Resource resource = createResourceObject(true);
1644 Resource updatedResource = createResourceObject(true);
1646 // this is in order to prevent failing with 403 earlier
1647 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1648 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1649 String resourceId = resource.getUniqueId();
1651 List<String> list = null;
1652 updatedResource.setDerivedFrom(list);
1653 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1654 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1656 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1657 } catch (ComponentException e) {
1658 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1663 void testResourceTemplateEmpty_UPDATE() {
1664 Resource resource = createResourceObject(true);
1665 Resource updatedResource = createResourceObject(true);
1666 String resourceId = resource.getUniqueId();
1668 // this is in order to prevent failing with 403 earlier
1669 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1670 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1672 updatedResource.setDerivedFrom(new ArrayList<>());
1673 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1674 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1676 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1677 } catch (ComponentException e) {
1678 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1683 void testResourceTemplateInvalid_UPDATE() {
1684 Resource resource = createResourceObject(true);
1685 Resource updatedResource = createResourceObject(true);
1686 String resourceId = resource.getUniqueId();
1688 // this is in order to prevent failing with 403 earlier
1689 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1690 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1692 ArrayList<String> derivedFrom = new ArrayList<>();
1693 derivedFrom.add("kuku");
1694 updatedResource.setDerivedFrom(derivedFrom);
1695 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1696 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1698 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1699 } catch (ComponentException e) {
1700 assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
1705 void testResourceTemplateCertify_UPDATE_HAPPY() {
1706 Resource resource = createResourceObject(true);
1707 Resource updatedResource = createResourceObject(true);
1708 String resourceId = resource.getUniqueId();
1710 // this is in order to prevent failing with 403 earlier
1711 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1712 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1714 Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true);
1715 when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
1716 .thenReturn(isToscaNameExtending);
1718 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
1719 .left(new HashMap<>());
1720 when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
1721 .thenReturn(findPropertiesOfNode);
1723 resource.setVersion("1.0");
1725 ArrayList<String> derivedFrom = new ArrayList<>();
1726 derivedFrom.add("tosca.nodes.Root");
1727 updatedResource.setDerivedFrom(derivedFrom);
1728 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
1729 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1730 Resource createdResource = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1731 assertThat(createdResource).isNotNull();
1735 void testResourceTemplateCertify_UPDATE_SAD() {
1736 Resource resource = createResourceObject(true);
1737 Resource updatedResource = createResourceObject(true);
1738 String resourceId = resource.getUniqueId();
1740 // this is in order to prevent failing with 403 earlier
1741 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1742 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1744 Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false);
1745 when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
1746 .thenReturn(isToscaNameExtending);
1748 resource.setVersion("1.0");
1750 ArrayList<String> derivedFrom = new ArrayList<>();
1751 derivedFrom.add("tosca.nodes.Root");
1752 updatedResource.setDerivedFrom(derivedFrom);
1753 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1754 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1755 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
1756 .left(new HashMap<>());
1757 when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
1758 .thenReturn(findPropertiesOfNode);
1761 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1762 } catch (ComponentException e) {
1763 assertComponentException(e, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1766 // Derived from stop
1769 void createOrUpdateResourceAlreadyCheckout() {
1771 Resource resourceExist = createResourceObject(false);
1772 validateUserRoles(Role.ADMIN, Role.DESIGNER);
1773 when(toscaOperationFacade
1774 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1775 .thenReturn(Either.left(false));
1776 Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
1778 createdResource.setLastUpdaterUserId(user.getUserId());
1779 assertThat(createdResource).isNotNull();
1780 Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
1781 Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
1782 when(toscaOperationFacade.getLatestByToscaResourceName(resourceExist.getToscaResourceName(), null))
1783 .thenReturn(getCompLatestResult);
1784 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
1785 .thenReturn(getCompLatestResult);
1786 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1787 .thenReturn(getLatestResult);
1789 Resource resourceToUpdtae = createResourceObject(false);
1791 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1792 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1793 assertNotNull(createOrUpdateResource);
1795 Mockito.verify(toscaOperationFacade, Mockito.times(1))
1796 .overrideComponent(any(Resource.class), any(Resource.class));
1797 Mockito.verify(lifecycleBl, Mockito.times(0))
1798 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1799 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1804 void createOrUpdateResourceCertified() {
1806 Resource resourceExist = createResourceObject(false);
1807 when(toscaOperationFacade
1808 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1809 .thenReturn(Either.left(false));
1810 validateUserRoles(Role.ADMIN, Role.DESIGNER);
1811 Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
1814 assertThat(createdResource).isNotNull();
1815 createdResource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
1816 createdResource.setVersion("1.0");
1818 Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
1819 Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
1820 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
1821 .thenReturn(getCompLatestResult);
1822 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1823 .thenReturn(getLatestResult);
1825 when(lifecycleBl.changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1826 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()))
1827 .thenReturn(Either.left(createdResource));
1829 Resource resourceToUpdtae = createResourceObject(false);
1831 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1832 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1833 assertNotNull(createOrUpdateResource);
1835 Mockito.verify(toscaOperationFacade, Mockito.times(1))
1836 .overrideComponent(any(Resource.class), any(Resource.class));
1837 Mockito.verify(lifecycleBl, Mockito.times(1))
1838 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1839 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1844 void createOrUpdateResourceNotExist() {
1845 Resource resourceToUpdtae = createResourceObject(false);
1847 Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
1848 when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName(), null)).thenReturn(getLatestResult);
1849 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdtae.getToscaResourceName(), null))
1850 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1851 when(toscaOperationFacade
1852 .validateComponentNameAndModelExists(resourceToUpdtae.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1853 .thenReturn(Either.left(false));
1855 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1856 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1857 assertThat(createOrUpdateResource).isNotNull();
1859 Mockito.verify(toscaOperationFacade, times(1))
1860 .createToscaComponent(resourceToUpdtae);
1861 Mockito.verify(toscaOperationFacade, Mockito.times(0))
1862 .overrideComponent(any(Resource.class), any(Resource.class));
1863 Mockito.verify(lifecycleBl, Mockito.times(0))
1864 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1865 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1870 void testIfNodeTypeNameHasValidPrefix() {
1871 final List<String> definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager()
1872 .getConfiguration().getDefinedResourceNamespace();
1874 definedNodeTypeNamespaceList.parallelStream().forEach(validNodeTypePrefix -> {
1875 final String nodeName = validNodeTypePrefix + "." + "abc";
1876 final Optional<String> result = bl.validateNodeTypeNamePrefix(nodeName, definedNodeTypeNamespaceList);
1877 assertTrue(result.isPresent());
1882 void updateNestedResource_typeIsNew() throws IOException {
1883 Resource resourceToUpdate = createResourceObject(false);
1884 String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
1885 String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
1886 CsarInfo csarInfo = new OnboardedCsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
1888 String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
1889 .name(), csarInfo.getVfResourceName(), nodeName)
1891 when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
1892 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1893 when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
1894 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1895 when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
1896 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1898 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
1899 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1900 when(toscaOperationFacade
1901 .validateComponentNameAndModelExists(resourceToUpdate.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1902 .thenReturn(Either.left(false));
1904 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1905 .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
1906 assertThat(createOrUpdateResource).isNotNull();
1908 Mockito.verify(toscaOperationFacade, times(1))
1909 .createToscaComponent(resourceToUpdate);
1910 Mockito.verify(toscaOperationFacade, times(0))
1911 .overrideComponent(any(Resource.class), any(Resource.class));
1912 Mockito.verify(lifecycleBl, times(0))
1913 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1914 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1918 void updateNestedResource_typeExists() throws IOException {
1920 Resource resourceToUpdate = createResourceObject(false);
1921 setCanWorkOnResource(resourceResponse);
1922 String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
1923 String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
1924 CsarInfo csarInfo = new OnboardedCsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
1926 String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
1927 .name(), csarInfo.getVfResourceName(), nodeName)
1929 when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
1930 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1931 when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
1932 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1933 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
1934 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1935 when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
1936 .thenReturn(Either.left(resourceResponse));
1937 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1938 .thenReturn(Either.left(resourceResponse));
1940 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1941 .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
1942 assertThat(createOrUpdateResource).isNotNull();
1943 Mockito.verify(toscaOperationFacade, times(1))
1944 .overrideComponent(any(Resource.class), any(Resource.class));
1945 Mockito.verify(lifecycleBl, times(0))
1946 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1947 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1951 void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() {
1952 Resource basic = createResourceObject(true);
1954 Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1955 assertTrue(validatePropertiesDefaultValues);
1959 void testValidatePropertiesDefaultValues_SuccessfullWithProperties() {
1960 Resource basic = createResourceObject(true);
1961 PropertyDefinition property = new PropertyDefinition();
1962 property.setName("myProperty");
1963 property.setType(ToscaPropertyType.INTEGER.getType());
1964 property.setDefaultValue("1");
1965 List<PropertyDefinition> properties = new ArrayList<>();
1966 properties.add(property);
1967 basic.setProperties(properties);
1968 when(propertyOperation.isPropertyTypeValid(property, (String) null)).thenReturn(true);
1969 when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true);
1970 Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1971 assertTrue(validatePropertiesDefaultValues);
1975 void testValidatePropertiesDefaultValues_FailedWithProperties() {
1976 Resource basic = createResourceObject(true);
1977 PropertyDefinition property = new PropertyDefinition();
1978 property.setName("myProperty");
1979 property.setType(ToscaPropertyType.INTEGER.getType());
1980 property.setDefaultValue("1.5");
1981 List<PropertyDefinition> properties = new ArrayList<>();
1982 properties.add(property);
1983 basic.setProperties(properties);
1985 when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false);
1986 assertThrows(ComponentException.class, () -> {
1987 bl.validatePropertiesDefaultValues(basic);
1992 void testDeleteMarkedResourcesNoResources() {
1993 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(new ArrayList<>());
1995 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
1997 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
1998 assertTrue(deleteMarkedResources.isLeft());
1999 assertTrue(deleteMarkedResources.left().value().isEmpty());
2003 void testDeleteMarkedResources() {
2004 List<String> ids = new ArrayList<>();
2005 String resourceInUse = "123";
2006 String resourceFree = "456";
2007 ids.add(resourceInUse);
2008 ids.add(resourceFree);
2009 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
2010 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
2012 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
2013 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
2015 List<ArtifactDefinition> artifacts = new ArrayList<>();
2017 when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
2018 when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
2020 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new
2022 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
2024 List<String> deletedComponents = new ArrayList<>();
2025 deletedComponents.add(resourceFree);
2026 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents));
2028 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
2029 assertTrue(deleteMarkedResources.isLeft());
2030 List<String> resourceIdList = deleteMarkedResources.left().value();
2031 assertFalse(resourceIdList.isEmpty());
2032 assertTrue(resourceIdList.contains(resourceFree));
2033 assertFalse(resourceIdList.contains(resourceInUse));
2036 @SuppressWarnings("unchecked")
2038 void testFindVfCsarArtifactsToHandle() {
2040 Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
2041 String methodName = "findVfCsarArtifactsToHandle";
2042 Resource resource = new Resource();
2043 String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml";
2044 String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml";
2045 String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml";
2047 String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml";
2048 String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml";
2049 String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml";
2050 String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml";
2052 byte[] oldPayloadData = "oldPayloadData".getBytes();
2053 byte[] newPayloadData = "newPayloadData".getBytes();
2054 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
2056 ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition();
2057 deploymentArtifactToUpdate.setMandatory(false);
2058 deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName);
2059 deploymentArtifactToUpdate.setArtifactType("SNMP_POLL");
2060 deploymentArtifactToUpdate.setPayload(oldPayloadData);
2061 deploymentArtifactToUpdate
2062 .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2064 ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition();
2065 deploymentArtifactToDelete.setMandatory(false);
2066 deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName);
2067 deploymentArtifactToDelete.setArtifactType("SNMP_TRAP");
2068 deploymentArtifactToDelete.setPayload(oldPayloadData);
2069 deploymentArtifactToDelete
2070 .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2072 ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition();
2074 deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()),
2075 deploymentArtifactToUpdate);
2076 deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()),
2077 deploymentArtifactToDelete);
2078 deploymentArtifacts.put("ignore", deploymentArtifactToIgnore);
2080 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
2082 ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
2083 artifactToUpdate.setMandatory(false);
2084 artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName);
2085 artifactToUpdate.setArtifactType("SNMP_POLL");
2086 artifactToUpdate.setPayload(oldPayloadData);
2087 artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2089 ArtifactDefinition artifactToDelete = new ArtifactDefinition();
2090 artifactToDelete.setMandatory(false);
2091 artifactToDelete.setArtifactName(artifactInfoToDeleteFileName);
2092 artifactToDelete.setArtifactType("SNMP_TRAP");
2093 artifactToDelete.setPayload(oldPayloadData);
2094 artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2095 artifactToDelete.setIsFromCsar(true);
2097 ArtifactDefinition artifactToNotDelete = new ArtifactDefinition();
2098 artifactToNotDelete.setMandatory(false);
2099 artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName);
2100 artifactToNotDelete.setArtifactType("SNMP_TRAP");
2101 artifactToNotDelete.setPayload(oldPayloadData);
2102 artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2103 artifactToNotDelete.setIsFromCsar(false);
2105 ArtifactDefinition artifactToIgnore = new ArtifactDefinition();
2107 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate);
2108 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete);
2109 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()),
2110 artifactToNotDelete);
2111 artifacts.put("ignore", artifactToIgnore);
2113 resource.setDeploymentArtifacts(deploymentArtifacts);
2114 resource.setArtifacts(artifacts);
2116 List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>();
2117 NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(
2118 deploymentArtifactToUpdate.getArtifactName(), null,
2119 deploymentArtifactToUpdate.getArtifactType(),
2120 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false);
2122 NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(
2123 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2124 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), false);
2126 NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
2127 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2128 ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData, artifactToUpdate.getArtifactName(), true);
2130 NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
2131 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2132 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), true);
2134 NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName,
2135 null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData,
2136 deploymentArtifactToCreateFileName, false);
2138 NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName,
2139 null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData,
2140 artifactInfoToCreateFileName, false);
2142 artifactPathAndNameList.add(deploymentArtifactInfoToUpdate);
2143 artifactPathAndNameList.add(informationalArtifactInfoToUpdate);
2144 artifactPathAndNameList.add(deploymentArtifactInfoToCreate);
2145 artifactPathAndNameList.add(informationalArtifactInfoToCreate);
2146 artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar);
2147 artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar);
2149 Object[] argObjects = {resource, artifactPathAndNameList, user};
2150 Class[] argClasses = {Resource.class, List.class, User.class};
2152 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
2153 method.setAccessible(true);
2154 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method
2155 .invoke(bl, argObjects);
2156 assertTrue(findVfCsarArtifactsToHandleRes.isLeft());
2157 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes
2160 assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.CREATE)
2162 assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.UPDATE)
2164 assertEquals(1, foundVfArtifacts.get(ArtifactOperationEnum.DELETE)
2167 } catch (Exception e) {
2168 e.printStackTrace();
2173 void testVFGeneratedInputs() {
2174 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2175 Resource resource = createVF();
2176 List<InputDefinition> inputs = resource.getInputs();
2177 assertEquals(6, inputs.size());
2178 for (InputDefinition input : inputs) {
2179 assertThat(input.getOwnerId()).isNotNull();
2181 assertEquals(resource.getDerivedFromGenericType(), genericVF.getToscaResourceName());
2182 assertEquals(resource.getDerivedFromGenericVersion(), genericVF.getVersion());
2186 void testCRGeneratedInputs() {
2187 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2188 Resource resource = createCR();
2189 List<InputDefinition> inputs = resource.getInputs();
2190 assertEquals(3, inputs.size());
2191 for (InputDefinition input : inputs) {
2192 assertThat(input.getOwnerId()).isNotNull();
2194 assertEquals(resource.getDerivedFromGenericType(), genericCR.getToscaResourceName());
2195 assertEquals(resource.getDerivedFromGenericVersion(), genericCR.getVersion());
2199 void testVFUpdateGenericInputsToLatestOnCheckout() {
2200 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2201 // create a VF that is derived from generic version 1.0
2202 Resource resource = createVF();
2203 // create a new generic version without properties
2204 genericVF.setVersion("2.0");
2205 genericVF.setProperties(null);
2206 String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
2207 List<InputDefinition> currentInputs = resource.getInputs();
2208 // verify previous inputs ownerId fields exist - user may not delete
2210 assertEquals(6, currentInputs.stream()
2211 .filter(p -> null != p.getOwnerId())
2212 .collect(Collectors.toList())
2214 Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
2216 assertTrue(upgradeToLatestGeneric.isLeft());
2217 // verify update required and valid
2218 assertTrue(upgradeToLatestGeneric.left()
2220 // verify version was upgraded
2221 assertNotEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
2222 // verify inputs were not deleted
2223 assertEquals(6, resource.getInputs()
2225 // verify inputs ownerId fields were removed - user may delete/edit
2227 assertEquals(6, resource.getInputs()
2229 .filter(p -> null == p.getOwnerId())
2230 .collect(Collectors.toList())
2235 void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
2237 // create a VF that is derived from generic version 1.0
2238 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2239 Resource resource = createVF();
2241 // add an input to the VF
2242 PropertyDefinition newProp = new PropertyDefinition();
2243 newProp.setType("integer");
2244 newProp.setName("newProp");
2245 resource.getInputs()
2246 .add(new InputDefinition(newProp));
2248 // create a new generic version with a new property which has the same
2249 // name as a user defined input on the VF with a different type
2250 genericVF.setVersion("2.0");
2251 newProp.setType("string");
2252 genericVF.setProperties(new ArrayList<>());
2253 genericVF.getProperties()
2255 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
2256 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
2257 genericVF.getUniqueId())).thenCallRealMethod();
2258 String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
2259 assertEquals(6, resource.getInputs()
2261 .filter(p -> null != p.getOwnerId())
2262 .collect(Collectors.toList())
2264 Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
2266 assertTrue(upgradeToLatestGeneric.isLeft());
2267 // verify update is invalid an void
2268 assertFalse(upgradeToLatestGeneric.left().value());
2269 // verify version was not upgraded
2270 assertEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
2271 // verify inputs were not removed
2272 assertEquals(7, resource.getInputs().size());
2273 // verify user defined input exists
2274 assertEquals(1, resource.getInputs()
2276 .filter(p -> null == p.getOwnerId())
2277 .collect(Collectors.toList())
2279 assertEquals("integer", resource.getInputs()
2281 .filter(p -> null == p.getOwnerId())
2288 void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
2289 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2290 Resource resource = createPNF();
2291 List<InputDefinition> inputs = resource.getInputs();
2292 assertEquals(3, inputs.size());
2293 for (InputDefinition input : inputs) {
2294 assertThat(input.getOwnerId()).isNotNull();
2296 assertEquals(resource.getDerivedFromGenericType(), genericPNF.getToscaResourceName());
2297 assertEquals(resource.getDerivedFromGenericVersion(), genericPNF.getVersion());
2298 assertEquals(0, resource.getArtifacts()
2302 private Resource createVF() {
2304 genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
2305 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME))
2306 .thenReturn(Either.left(genericVF));
2307 Resource resource = createResourceObject(true);
2308 resource.setDerivedFrom(null);
2309 resource.setResourceType(ResourceTypeEnum.VF);
2310 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2311 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericVF));
2312 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod();
2313 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
2314 resource.getUniqueId())).thenCallRealMethod();
2315 when(toscaOperationFacade
2316 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE))
2317 .thenReturn(Either.left(false));
2318 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2319 assertThat(createdResource).isNotNull();
2320 return createdResource;
2323 private Resource createRoot() {
2324 rootType = setupGenericTypeMock(GENERIC_ROOT_NAME);
2325 when(toscaOperationFacade.getLatestByToscaResourceName(GENERIC_ROOT_NAME, null))
2326 .thenReturn(Either.left(rootType));
2330 private Resource createCR() {
2332 genericCR = setupGenericTypeMock(GENERIC_CR_NAME);
2333 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME))
2334 .thenReturn(Either.left(genericCR));
2335 Resource resource = createResourceObject(true);
2336 resource.setDerivedFrom(null);
2337 resource.setResourceType(ResourceTypeEnum.CR);
2338 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2339 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericCR));
2340 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod();
2341 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(),
2342 resource.getUniqueId())).thenCallRealMethod();
2343 when(toscaOperationFacade
2344 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE))
2345 .thenReturn(Either.left(false));
2346 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2347 assertThat(createdResource).isNotNull();
2348 return createdResource;
2351 private Resource createPNF() {
2353 genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
2354 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME))
2355 .thenReturn(Either.left(genericPNF));
2356 Resource resource = createResourceObject(true);
2357 resource.setDerivedFrom(null);
2358 resource.setResourceType(ResourceTypeEnum.PNF);
2359 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2360 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericPNF));
2361 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod();
2362 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(),
2363 resource.getUniqueId())).thenCallRealMethod();
2364 when(toscaOperationFacade
2365 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE))
2366 .thenReturn(Either.left(false));
2367 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2368 assertThat(createdResource).isNotNull();
2369 return createdResource;
2372 private Map<String, String> getGenericPropertiesByToscaName(String toscaName) {
2373 HashMap<String, String> PNFProps = new HashMap<String, String>() {
2375 put("nf_function", "string");
2376 put("nf_role", "string");
2377 put("nf_type", "string");
2381 HashMap<String, String> CRProps = new HashMap<String, String>() {
2383 put("cr_function", "string");
2384 put("cr_role", "string");
2385 put("cr_type", "string");
2389 HashMap<String, String> VFProps = new HashMap<String, String>() {
2392 put("availability_zone_max_count", "integer");
2393 put("min_instances", "integer");
2394 put("max_instances", "integer");
2398 if (toscaName.contains("PNF")) {
2401 if (toscaName.contains("CR")) {
2404 if (toscaName.contains("VF")) {
2408 return new HashMap<>();
2411 private Resource setupGenericTypeMock(String toscaName) {
2413 Resource genericType = createResourceObject(true);
2414 genericType.setVersion("1.0");
2415 genericType.setToscaResourceName(toscaName);
2416 genericType.setAbstract(true);
2417 List<PropertyDefinition> genericProps = new ArrayList<>();
2418 Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName);
2419 genericPropsMap.forEach((name, type) -> {
2420 PropertyDefinition prop = new PropertyDefinition();
2423 genericProps.add(prop);
2426 genericType.setProperties(genericProps);
2430 private void validateUserRoles(Role... roles) {
2431 List<Role> listOfRoles = Stream.of(roles)
2432 .collect(Collectors.toList());
2436 void testUpdateVolumeGroup() {
2437 Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
2438 bl.updateVolumeGroup(resource);
2439 assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(true));
2443 void testUpdateVolumeGroupNull() {
2444 Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
2445 resource.setGroups(null);
2446 bl.updateVolumeGroup(resource);
2447 assertThat(resource.getGroups()).isNull();
2451 void testUpdateVolumeGroupFail() {
2452 Resource resource = getResourceWithType("NON_EXIST_HEAT", "org.openecomp.groups.VfModule");
2453 bl.updateVolumeGroup(resource);
2454 assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(false));
2457 private Resource getResourceWithType(String artifactType, String groupDefinitionType) {
2458 ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
2459 List<GroupDefinition> groups = new ArrayList<>();
2460 GroupDefinition gd = new GroupDefinition();
2461 List<PropertyDataDefinition> properties = new ArrayList<>();
2462 PropertyDataDefinition pdd = new PropertyDataDefinition();
2463 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
2464 List<String> artifactsList = new ArrayList<>();
2466 artifactToUpdate.setArtifactType(artifactType);
2467 artifactToUpdate.setArtifactName(artifactType);
2468 artifactToUpdate.setUniqueId(artifactType);
2469 Resource resource = createResourceObjectCsar(true);
2470 artifactsList.add(artifactToUpdate.getArtifactName());
2472 pdd.setName("volume_group");
2473 pdd.setValue("true");
2474 pdd.setType(ToscaPropertyType.BOOLEAN.getType());
2476 artifacts.put(artifactToUpdate.getArtifactName(), artifactToUpdate);
2478 properties.add(pdd);
2479 gd.setType(groupDefinitionType);
2480 gd.setProperties(properties);
2481 gd.setArtifacts(artifactsList);
2484 resource.setGroups(groups);
2485 resource.setDeploymentArtifacts(artifacts);
2490 void testGetAllCertifiedResources() {
2491 List<Resource> list = bl.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, "USER");
2492 assertEquals(reslist, list);
2496 void testGetAllCertifiedResources_exception() {
2497 assertThrows(StorageException.class, () -> {
2498 List<Resource> list = bl.getAllCertifiedResources(false, HighestFilterEnum.NON_HIGHEST_ONLY, "USER");
2499 assertEquals(reslist, list);
2504 void testValidateResourceNameExists() {
2505 Either<Map<String, Boolean>, ResponseFormat> res = bl.validateResourceNameExists("Resource", ResourceTypeEnum.CR, "jh0003");
2506 assertEquals(true, res.isLeft());
2510 void rollbackWithEitherAlwaysReturnARuntimeException() {
2511 JanusGraphDao janusGraphDao = mockJanusGraphDao;
2512 ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
2513 String params = "testName";
2515 Either<Object, RuntimeException> result =
2516 ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
2518 assertTrue(result.isRight());
2519 assertTrue(result.right().value() instanceof ByActionStatusComponentException);
2523 void rollbackWithEitherWorksWithNullJanusGraphDao() {
2524 JanusGraphDao janusGraphDao = null;
2525 ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
2526 String params = "testName";
2528 Either<Object, RuntimeException> result =
2529 ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
2531 assertTrue(result.isRight());
2532 assertTrue(result.right().value() instanceof ByActionStatusComponentException);
2536 void testDeleteResource_NotFound() {
2537 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
2538 ResponseFormat respFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND),
2540 ResponseFormat actualResponseFormat = bl.deleteResource("1", user);
2541 assertEquals(respFormat.getStatus(), actualResponseFormat.getStatus());
2545 void testDeleteResource_NotArchived() {
2546 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(resourceResponse));
2547 ComponentException actualComponentException = assertThrows(ComponentException.class,
2548 () -> bl.deleteResourceAllVersions(resourceResponse.getUniqueId(), user));
2549 assertEquals(ActionStatus.COMPONENT_NOT_ARCHIVED, actualComponentException.getActionStatus());
2550 assertEquals("my-resource_name with space:0.1", actualComponentException.getParams()[0]);
2554 void testDeleteResource_IsInUse() {
2555 Resource resourceObject = createResourceObject(true);
2556 Mockito.when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(resourceObject));
2557 resourceObject.setArchived(true);
2558 OperationException oe = new OperationException(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, "resource_name");
2559 Mockito.when(toscaOperationFacade.deleteComponent(resourceObject.getInvariantUUID(), NodeTypeEnum.Resource, true)).thenThrow(oe);
2560 OperationException actualOperationException = assertThrows(OperationException.class,
2561 () -> bl.deleteResourceAllVersions(resourceResponse.getUniqueId(), user));
2562 assertEquals(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, actualOperationException.getActionStatus());
2563 assertEquals("resource_name", actualOperationException.getParams()[0]);
2568 void testCreateResource_withMultitenancyWithTenant_Success() {
2569 Assert.assertTrue(MULTITENANCY_ENABLED);
2570 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2571 Resource resource = createResourceObject(false);
2572 resource.setTenant(TEST_TENANT);
2573 Resource createdResource = null;
2575 when(toscaOperationFacade
2576 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
2577 .thenReturn(Either.left(false));
2578 createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2579 assertThat(createResourceObject(true)).isEqualTo(createdResource);
2580 MatcherAssert.assertThat("Unauthorized Tenant", getTestRoles().contains(resource.getTenant()));
2581 } catch (ComponentException e) {
2582 assertThat(Integer.valueOf(200)).isEqualTo(e.getResponseFormat()
2588 void testCreateResource_withMultitenancyWithInvalidTenant_Failure() {
2589 Assert.assertTrue(MULTITENANCY_ENABLED);
2590 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2591 Resource resource = createResourceObject(false);
2592 resource.setTenant("invalid_tenant");
2593 Resource createdResource = null;
2595 MatcherAssert.assertThat("Unauthorized Tenant", !getTestRoles().contains(resource.getTenant()));
2596 when(toscaOperationFacade
2597 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
2598 .thenReturn(Either.left(false));
2599 createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2601 assertThat(createResourceObject(true)).isEqualTo(createdResource);
2602 MatcherAssert.assertThat("Unauthorized Tenant", !getTestRoles().contains(resource.getTenant()));
2603 } catch (ComponentException e) {
2604 assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
2609 private Set<String> getTestRoles(){
2610 Set<String> roles = new HashSet<>();
2611 roles.add("test_admin");
2612 roles.add("test_tenant");