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;
50 import java.util.Map.Entry;
51 import java.util.Optional;
52 import java.util.stream.Collectors;
53 import java.util.stream.Stream;
54 import javax.servlet.ServletContext;
55 import org.apache.commons.lang3.tuple.ImmutablePair;
56 import org.junit.jupiter.api.BeforeEach;
57 import org.junit.jupiter.api.Test;
58 import org.mockito.InjectMocks;
59 import org.mockito.Mockito;
60 import org.mockito.MockitoAnnotations;
61 import org.openecomp.sdc.ElementOperationMock;
62 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
63 import org.openecomp.sdc.be.components.ArtifactsResolver;
64 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
65 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
66 import org.openecomp.sdc.be.components.csar.CsarInfo;
67 import org.openecomp.sdc.be.components.csar.YamlTemplateParsingHandler;
68 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
69 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
70 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
71 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
72 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
73 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
74 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
75 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
76 import org.openecomp.sdc.be.components.validation.UserValidations;
77 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
78 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
79 import org.openecomp.sdc.be.components.validation.component.ComponentFieldValidator;
80 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
81 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
82 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
83 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
84 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
85 import org.openecomp.sdc.be.config.ConfigurationManager;
86 import org.openecomp.sdc.be.dao.api.ActionStatus;
87 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
88 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
89 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
90 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
91 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
92 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
93 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
94 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
95 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
96 import org.openecomp.sdc.be.facade.operations.CatalogOperation;
97 import org.openecomp.sdc.be.impl.ComponentsUtils;
98 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
99 import org.openecomp.sdc.be.model.ArtifactDefinition;
100 import org.openecomp.sdc.be.model.Component;
101 import org.openecomp.sdc.be.model.ComponentInstance;
102 import org.openecomp.sdc.be.model.ComponentParametersView;
103 import org.openecomp.sdc.be.model.DataTypeDefinition;
104 import org.openecomp.sdc.be.model.GroupDefinition;
105 import org.openecomp.sdc.be.model.InputDefinition;
106 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
107 import org.openecomp.sdc.be.model.LifecycleStateEnum;
108 import org.openecomp.sdc.be.model.NodeTypeInfo;
109 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
110 import org.openecomp.sdc.be.model.PropertyDefinition;
111 import org.openecomp.sdc.be.model.RequirementDefinition;
112 import org.openecomp.sdc.be.model.Resource;
113 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
114 import org.openecomp.sdc.be.model.User;
115 import org.openecomp.sdc.be.model.VendorSoftwareProduct;
116 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
117 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
118 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
119 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
120 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTypeOperation;
121 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation;
122 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
123 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.OperationException;
124 import org.openecomp.sdc.be.model.operations.StorageException;
125 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
126 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
127 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
128 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
129 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
130 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
131 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
132 import org.openecomp.sdc.be.model.operations.impl.ArtifactTypeOperation;
133 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
134 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
135 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
136 import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
137 import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
138 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
139 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
140 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
141 import org.openecomp.sdc.be.tosca.CsarUtils;
142 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
143 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
144 import org.openecomp.sdc.be.user.Role;
145 import org.openecomp.sdc.be.user.UserBusinessLogic;
146 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
147 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
148 import org.openecomp.sdc.common.api.Constants;
149 import org.openecomp.sdc.common.impl.ExternalConfiguration;
150 import org.openecomp.sdc.common.impl.FSConfigurationSource;
151 import org.openecomp.sdc.common.util.GeneralUtility;
152 import org.openecomp.sdc.common.util.ValidationUtils;
153 import org.openecomp.sdc.common.zip.ZipUtils;
154 import org.openecomp.sdc.common.zip.exception.ZipException;
155 import org.openecomp.sdc.exception.ResponseFormat;
156 import org.springframework.web.context.WebApplicationContext;
158 class ResourceBusinessLogicTest {
160 private final ConfigurationManager configurationManager = new ConfigurationManager(
161 new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"));
162 private static final String RESOURCE_CATEGORY1 = "Network Layer 2-3";
163 private static final String RESOURCE_SUBCATEGORY = "Router";
165 private static final String UPDATED_SUBCATEGORY = "Gateway";
167 private static final String RESOURCE_NAME = "My-Resource_Name with space";
168 private static final String RESOURCE_TOSCA_NAME = "My-Resource_Tosca_Name";
169 private static final String GENERIC_ROOT_NAME = "tosca.nodes.Root";
170 private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
171 private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR";
172 private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
174 private final ServletContext servletContext = Mockito.mock(ServletContext.class);
175 private IElementOperation mockElementDao;
176 private final JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class);
177 private final UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
178 private final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
179 private final NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
180 private final NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
181 private final TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
182 private final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
183 private final CatalogOperation catalogOperation = Mockito.mock(CatalogOperation.class);
184 private final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
185 private final PropertyOperation propertyOperation = Mockito.mock(PropertyOperation.class);
186 private final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class);
187 private final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
188 private final UserValidations userValidations = Mockito.mock(UserValidations.class);
189 private final WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
190 private final IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
191 private final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class);
192 private final IElementOperation elementDao = new ElementOperationMock();
194 private final CsarUtils csarUtils = Mockito.mock(CsarUtils.class);
195 private final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
196 private final IGroupOperation groupOperation = Mockito.mock(IGroupOperation.class);
197 private final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class);
198 private final IGroupTypeOperation groupTypeOperation = Mockito.mock(IGroupTypeOperation.class);
199 private final GroupBusinessLogic groupBusinessLogic = Mockito.mock(GroupBusinessLogic.class);
200 private final ModelBusinessLogic modelBusinessLogic = Mockito.mock(ModelBusinessLogic.class);
201 private final InterfaceOperation interfaceOperation = Mockito.mock(InterfaceOperation.class);
202 private final ArtifactsOperations artifactToscaOperation = Mockito.mock(ArtifactsOperations.class);
203 private final PropertyBusinessLogic propertyBusinessLogic = Mockito.mock(PropertyBusinessLogic.class);
204 private final ArtifactsResolver artifactsResolver = Mockito.mock(ArtifactsResolver.class);
205 private final InterfaceLifecycleOperation interfaceLifecycleTypeOperation = Mockito.mock(InterfaceLifecycleOperation.class);
206 private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class);
207 private final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
208 private final InputsBusinessLogic inputsBusinessLogic = Mockito.mock(InputsBusinessLogic.class);
209 private final OutputsBusinessLogic outputsBusinessLogic = Mockito.mock(OutputsBusinessLogic.class);
210 private final CompositionBusinessLogic compositionBusinessLogic = Mockito.mock(CompositionBusinessLogic.class);
211 private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic = Mockito.mock(ResourceDataMergeBusinessLogic.class);
212 private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic = Mockito.mock(CsarArtifactsAndGroupsBusinessLogic.class);
213 private final MergeInstanceUtils mergeInstanceUtils = Mockito.mock(MergeInstanceUtils.class);
214 private final UiComponentDataConverter uiComponentDataConverter = Mockito.mock(UiComponentDataConverter.class);
215 private final ToscaExportHandler toscaExportHandler = Mockito.mock(ToscaExportHandler.class);
216 private final PolicyTypeOperation policyTypeOperation = Mockito.mock(PolicyTypeOperation.class);
217 private final PolicyBusinessLogic policyBusinessLogic = Mockito.mock(PolicyBusinessLogic.class);
218 private final ArtifactTypeOperation artifactTypeOperation = Mockito.mock(ArtifactTypeOperation.class);
219 private final DataTypeBusinessLogic dataTypeBusinessLogic = Mockito.mock(DataTypeBusinessLogic.class);
220 private final PolicyTypeBusinessLogic policyTypeBusinessLogic = Mockito.mock(PolicyTypeBusinessLogic.class);
221 private final ModelOperation modelOperation = Mockito.mock(ModelOperation.class);
223 private YamlTemplateParsingHandler yamlTemplateParsingHandler = Mockito.mock(YamlTemplateParsingHandler.class);
225 private ResponseFormatManager responseManager = null;
226 private final GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
227 private User user = null;
228 private Resource resourceResponse = null;
229 private Resource genericVF = null;
230 private Resource genericCR = null;
231 private Resource genericVFC = null;
232 private Resource genericPNF = null;
233 private Resource rootType = null;
234 private ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
235 private ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(artifactCassandraDao, toscaExportHandler, csarUtils, lifecycleBl,
236 userBusinessLogic, artifactsResolver, elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
237 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation, artifactTypeOperation);
238 private CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
240 private CsarBusinessLogic csarBusinessLogic;
241 private Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
242 private List<Resource> reslist;
243 private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
244 protected ComponentDescriptionValidator componentDescriptionValidator = new ComponentDescriptionValidator(componentsUtils);
245 protected ComponentProjectCodeValidator componentProjectCodeValidator = new ComponentProjectCodeValidator(componentsUtils);
246 protected ComponentIconValidator componentIconValidator = new ComponentIconValidator(componentsUtils);
247 protected ComponentContactIdValidator componentContactIdValidator = new ComponentContactIdValidator(componentsUtils);
248 protected ComponentTagsValidator componentTagsValidator = new ComponentTagsValidator(componentsUtils);
249 protected ComponentNameValidator componentNameValidator = new ComponentNameValidator(componentsUtils, toscaOperationFacade);
250 private ComponentValidator componentValidator = createComponentValidator();
251 private SoftwareInformationBusinessLogic softwareInformationBusinessLogic = Mockito.mock(SoftwareInformationBusinessLogic.class);
253 private ComponentValidator createComponentValidator() {
254 List<ComponentFieldValidator> componentFieldValidators = Arrays.asList(componentNameValidator,
255 componentDescriptionValidator, componentProjectCodeValidator,
256 componentIconValidator, componentContactIdValidator,
257 componentTagsValidator);
258 return new ComponentValidator(componentsUtils, componentFieldValidators);
261 private ResourceBusinessLogic bl;
264 public void setup() {
265 MockitoAnnotations.openMocks(this);
266 Mockito.reset(propertyOperation);
269 mockElementDao = new ElementOperationMock();
271 // User data and management
273 user.setUserId("jh0003");
274 user.setFirstName("Jimmi");
275 user.setLastName("Hendrix");
276 user.setRole(Role.ADMIN.name());
278 when(mockUserAdmin.getUser("jh0003", false)).thenReturn(user);
279 when(userValidations.validateUserExists(user.getUserId())).thenReturn(user);
280 when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
281 // Servlet Context attributes
282 when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
283 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
284 .thenReturn(webAppContextWrapper);
285 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
286 when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
288 Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true);
289 when(toscaOperationFacade.validateComponentNameExists("tosca.nodes.Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
290 .thenReturn(eitherFalse);
292 Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
293 when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC,
294 ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist);
296 Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
297 when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class),
298 eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount);
299 Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
300 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
302 Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false);
303 when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
304 when(graphLockOperation.lockComponent(anyString(), eq(NodeTypeEnum.Resource)))
305 .thenReturn(StorageOperationStatus.OK);
306 when(graphLockOperation.lockComponentByName(anyString(), eq(NodeTypeEnum.Resource)))
307 .thenReturn(StorageOperationStatus.OK);
310 resourceResponse = createResourceObject(true);
311 Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
312 when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
313 when(catalogOperation.updateCatalog(Mockito.any(), Mockito.any())).thenReturn(ActionStatus.OK);
314 Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
315 when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(emptyDataTypes));
316 when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
317 when(policyTypeOperation.getLatestPolicyTypeByType(any(String.class), any(String.class)))
318 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
320 artifactManager.setNodeTemplateOperation(nodeTemplateOperation);
321 bl = new ResourceBusinessLogic(mockElementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
322 interfaceOperation, interfaceLifecycleTypeOperation, artifactManager, componentInstanceBusinessLogic,
323 resourceImportManager, inputsBusinessLogic, outputsBusinessLogic, compositionBusinessLogic, resourceDataMergeBusinessLogic,
324 csarArtifactsAndGroupsBusinessLogic, mergeInstanceUtils, uiComponentDataConverter, csarBusinessLogic,
325 artifactToscaOperation, propertyBusinessLogic, componentContactIdValidator, componentNameValidator,
326 componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator,
327 componentDescriptionValidator, policyBusinessLogic, modelBusinessLogic, dataTypeBusinessLogic, policyTypeBusinessLogic, modelOperation);
328 bl.setElementDao(mockElementDao);
329 bl.setUserAdmin(mockUserAdmin);
330 bl.setCapabilityTypeOperation(capabilityTypeOperation);
331 bl.setComponentsUtils(componentsUtils);
332 bl.setLifecycleManager(lifecycleBl);
333 bl.setArtifactsManager(artifactManager);
334 bl.setGraphLockOperation(graphLockOperation);
335 bl.setPropertyOperation(propertyOperation);
336 bl.setJanusGraphDao(mockJanusGraphDao);
337 bl.setApplicationDataTypeCache(applicationDataTypeCache);
338 bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
339 bl.setCatalogOperations(catalogOperation);
340 toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
341 csarBusinessLogic.setComponentsUtils(componentsUtils);
342 toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
343 bl.setToscaOperationFacade(toscaOperationFacade);
344 bl.setUserValidations(userValidations);
345 bl.setInterfaceTypeOperation(interfaceTypeOperation);
346 bl.setPolicyTypeOperation(policyTypeOperation);
348 csarBusinessLogic.setCsarOperation(csarOperation);
349 Resource resourceCsar = createResourceObjectCsar(true);
350 setCanWorkOnResource(resourceCsar);
351 Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
352 when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
353 responseManager = ResponseFormatManager.getInstance();
354 bl.setComponentIconValidator(componentIconValidator);
355 bl.setComponentNameValidator(componentNameValidator);
356 bl.setComponentDescriptionValidator(componentDescriptionValidator);
357 bl.setComponentTagsValidator(componentTagsValidator);
358 bl.setComponentContactIdValidator(componentContactIdValidator);
359 bl.setComponentProjectCodeValidator(componentProjectCodeValidator);
360 bl.setComponentValidator(componentValidator);
361 reslist = new ArrayList<>();
362 reslist.add(resourceResponse);
363 reslist.add(genericVF);
364 reslist.add(genericCR);
365 reslist.add(genericVFC);
366 reslist.add(genericPNF);
367 Either<List<Resource>, StorageOperationStatus> returneval = Either.left(reslist);
368 when(toscaOperationFacade.getAllCertifiedResources(true, true)).thenReturn(returneval);
369 when(toscaOperationFacade.validateComponentNameUniqueness("Resource", ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(
371 Either<List<Resource>, StorageOperationStatus> returnevalexception = Either.right(StorageOperationStatus.BAD_REQUEST);
372 when(toscaOperationFacade.getAllCertifiedResources(false, false)).thenReturn(returnevalexception);
376 void createResourcesFromYamlNodeTypesList() throws IOException {
377 Map<String, Object> mappedToscaTemplate = new HashMap<>();
378 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
379 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
380 Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
381 assertThrows(ComponentException.class, () -> {
382 bl.createResourcesFromYamlNodeTypesList(
387 nodeTypesArtifactsToHandle,
388 nodeTypesNewCreatedArtifacts,
390 new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name",
391 ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"), true), "");
396 void handleNodeTypeArtifactsTest() {
397 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = new HashMap<>();
398 List<ArtifactDefinition> defs = new ArrayList<>();
399 defs.add(new ArtifactDefinition());
400 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, defs);
401 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, defs);
402 assertTrue(bl.handleNodeTypeArtifacts(resourceResponse, nodeTypeArtifactsToHandle, new ArrayList<>(), user, true, true).isRight());
406 void getUiComponentDataTransferByComponentIdTest() {
407 when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(genericCR));
408 assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isLeft());
409 when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(
410 Either.right(StorageOperationStatus.OK));
411 assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isRight());
415 void shouldUpgradeToLatestDerivedTest() {
418 when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericCR)).thenReturn(Either.left(genericCR));
419 when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericVFC)).thenReturn(Either.right(StorageOperationStatus.OK));
420 assertTrue(bl.shouldUpgradeToLatestDerived(genericVF).isLeft());
421 assertTrue(bl.shouldUpgradeToLatestDerived(genericCR).isLeft());
424 private Resource createResourceObject(boolean afterCreate) {
425 Resource resource = new Resource();
426 resource.setName(RESOURCE_NAME);
427 resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
428 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
429 resource.setDescription("My short description");
430 List<String> tgs = new ArrayList<>();
432 tgs.add(resource.getName());
433 resource.setTags(tgs);
434 List<String> template = new ArrayList<>();
435 template.add("tosca.nodes.Root");
436 resource.setDerivedFrom(template);
437 resource.setVendorName("Motorola");
438 resource.setVendorRelease("1.0.0");
439 resource.setContactId("ya5467");
440 resource.setIcon("defaulticon");
443 resource.setName(resource.getName());
444 resource.setVersion("0.1");
445 resource.setUniqueId(resource.getName()
446 .toLowerCase() + ":" + resource.getVersion());
447 resource.setCreatorUserId(user.getUserId());
448 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
449 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
454 private Resource createResourceObjectWithModel(boolean afterCreate) {
455 Resource resource = new Resource();
456 resource.setName(RESOURCE_NAME);
457 resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
458 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
459 resource.setDescription("My short description");
460 List<String> tgs = new ArrayList<>();
462 tgs.add(resource.getName());
463 resource.setTags(tgs);
464 List<String> template = new ArrayList<>();
465 template.add("tosca.nodes.Root");
466 resource.setDerivedFrom(template);
467 resource.setVendorName("Motorola");
468 resource.setVendorRelease("1.0.0");
469 resource.setContactId("ya5467");
470 resource.setIcon("defaulticon");
471 resource.setModel("Test Model");
474 resource.setName(resource.getName());
475 resource.setVersion("0.1");
476 resource.setUniqueId(resource.getName()
477 .toLowerCase() + ":" + resource.getVersion());
478 resource.setCreatorUserId(user.getUserId());
479 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
480 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
485 private Resource createResourceObjectCsar(boolean afterCreate) {
486 Resource resource = new Resource();
487 resource.setName(RESOURCE_NAME);
488 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
489 resource.setDescription("My short description");
490 List<String> tgs = new ArrayList<>();
492 tgs.add(resource.getName());
493 resource.setTags(tgs);
494 List<String> template = new ArrayList<>();
495 template.add("tosca.nodes.Root");
496 resource.setDerivedFrom(template);
497 resource.setVendorName("Motorola");
498 resource.setVendorRelease("1.0.0");
499 resource.setResourceVendorModelNumber("");
500 resource.setContactId("ya5467");
501 resource.setIcon("MyIcon");
502 resource.setCsarUUID("valid_vf.csar");
503 resource.setCsarVersion("1");
506 resource.setName(resource.getName());
507 resource.setVersion("0.1");
509 resource.setUniqueId(resource.getName()
510 .toLowerCase() + ":" + resource.getVersion());
511 resource.setCreatorUserId(user.getUserId());
512 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
513 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
518 private Resource setCanWorkOnResource(Resource resource) {
519 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
520 resource.setLastUpdaterUserId(user.getUserId());
525 void testHappyScenario() {
526 validateUserRoles(Role.ADMIN, Role.DESIGNER);
527 Resource resource = createResourceObject(false);
528 Resource createdResource = null;
530 when(toscaOperationFacade
531 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
532 .thenReturn(Either.left(false));
533 createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
534 assertThat(createResourceObject(true)).isEqualTo(createdResource);
535 } catch (ComponentException e) {
536 assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
542 void testUpdateHappyScenario() {
543 Resource resource = createResourceObjectCsar(true);
544 setCanWorkOnResource(resource);
545 validateUserRoles(Role.ADMIN, Role.DESIGNER);
546 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource);
547 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(),
548 resource.getSystemName())).thenReturn(resourceLinkedToCsarRes);
549 Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
550 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
551 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
552 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
553 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
554 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
556 assertThat(resource.getUniqueId()).isEqualTo(
557 bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()).getUniqueId());
558 } catch (ComponentException e) {
559 assertThat(e.getResponseFormat().getStatus()).isEqualTo(200);
564 void testUpdateUnhappyScenario() {
565 Resource resource = createResourceObjectCsar(true);
566 final var csarVersionId = "csarVersionId";
567 resource.setCsarVersionId(csarVersionId);
569 final var vendorSoftwareProduct = new VendorSoftwareProduct();
570 vendorSoftwareProduct.setFileMap(new HashMap<>());
571 vendorSoftwareProduct.setModelList(Collections.emptyList());
572 setCanWorkOnResource(resource);
573 validateUserRoles(Role.ADMIN, Role.DESIGNER);
575 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(),
576 resource.getSystemName())).thenReturn(Either.left(resource));
577 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(Either.left(true));
578 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(Either.left(setCanWorkOnResource(resource)));
579 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(Either.left(resource));
580 when(csarOperation.findVsp("valid_vf.csar", csarVersionId, user)).thenReturn(Optional.of(vendorSoftwareProduct));
583 Resource createdResource = bl.validateAndUpdateResourceFromCsar(resource, user, null, "", resource.getUniqueId());
584 assertThat(resource.getUniqueId()).isEqualTo(createdResource.getUniqueId());
585 } catch (ComponentException e) {
586 assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
589 resource.setCsarVersion("2");
590 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(),
591 resource.getSystemName())).thenReturn(Either.left(resource));
592 bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId());
593 } catch (ComponentException e) {
594 assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
597 /* CREATE validations - start ***********************/
598 // Resource name - start
601 void testFailedResourceValidations() {
602 testResourceNameExist();
603 testResourceNameEmpty();
604 // testResourceNameExceedsLimit();
605 testResourceNameWrongFormat();
606 testResourceDescExceedsLimitCreate();
607 testResourceDescNotEnglish();
608 testResourceDescriptionEmpty();
609 testResourceDescriptionMissing();
610 testResourceIconMissing();
611 testResourceIconInvalid();
612 testResourceIconExceedsLimit();
613 testResourceTagNotExist();
614 testResourceTagEmpty();
615 testTagsExceedsLimitCreate();
616 testTagsNoServiceName();
619 testContactIdTooLong();
620 testContactIdWrongFormatCreate();
621 testResourceContactIdEmpty();
622 testResourceContactIdMissing();
623 testVendorNameExceedsLimit();
624 testVendorNameWrongFormatCreate();
625 testVendorReleaseWrongFormat();
626 testVendorReleaseExceedsLimitCreate();
627 testResourceVendorModelNumberExceedsLimit();
628 testResourceVendorNameMissing();
629 testResourceVendorReleaseMissing();
630 testResourceCategoryExist();
631 testResourceBadCategoryCreate();
632 testHappyScenarioCostLicenseType();
633 testCostWrongFormatCreate();
634 testLicenseTypeWrongFormatCreate();
635 testResourceTemplateNotExist();
636 testResourceTemplateEmpty();
637 testResourceTemplateInvalid();
640 private void testResourceNameExist() {
641 String resourceName = "alreadyExists";
642 Resource resourceExist = createResourceObject(false);
643 resourceExist.setName(resourceName);
644 resourceExist.getTags()
646 validateUserRoles(Role.ADMIN, Role.DESIGNER);
647 when(toscaOperationFacade
648 .validateComponentNameAndModelExists(resourceName, null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
649 .thenReturn(Either.left(true));
651 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
652 } catch (ComponentException e) {
653 assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
654 ComponentTypeEnum.RESOURCE.getValue(), resourceName);
658 private void testResourceNameEmpty() {
659 Resource resourceExist = createResourceObject(false);
660 resourceExist.setName(null);
663 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
664 } catch (ComponentException e) {
665 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
669 private void testResourceNameExceedsLimit() {
670 Resource resourceExccedsNameLimit = createResourceObject(false);
671 // 51 chars, the limit is 50
672 String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
673 resourceExccedsNameLimit.setName(tooLongResourceName);
676 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
677 } catch (ComponentException e) {
678 assertComponentException(e, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT,
679 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
683 private void testResourceNameWrongFormat() {
684 Resource resource = createResourceObject(false);
686 String nameWrongFormat = "ljg?fd";
687 resource.setName(nameWrongFormat);
690 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
691 } catch (ComponentException e) {
692 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
696 // Resource name - end
697 // Resource description - start
698 private void testResourceDescExceedsLimitCreate() {
699 Resource resourceExccedsDescLimit = createResourceObject(false);
700 // 1025 chars, the limit is 1024
701 String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
702 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
703 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
704 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
705 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
706 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
707 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
708 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
710 resourceExccedsDescLimit.setDescription(tooLongResourceDesc);
712 bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
713 } catch (ComponentException e) {
714 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
715 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
719 private void testResourceDescNotEnglish() {
720 Resource notEnglish = createResourceObject(false);
722 String notEnglishDesc = "\uC2B5";
723 notEnglish.setDescription(notEnglishDesc);
726 bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
727 } catch (ComponentException e) {
728 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION,
729 ComponentTypeEnum.RESOURCE.getValue());
733 private void testResourceDescriptionEmpty() {
734 Resource resourceExist = createResourceObject(false);
735 resourceExist.setDescription("");
738 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
739 } catch (ComponentException e) {
740 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
741 ComponentTypeEnum.RESOURCE.getValue());
745 private void testResourceDescriptionMissing() {
746 Resource resourceExist = createResourceObject(false);
747 resourceExist.setDescription(null);
750 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
751 } catch (ComponentException e) {
752 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
753 ComponentTypeEnum.RESOURCE.getValue());
756 // Resource description - end
757 // Resource icon start
759 private void testResourceIconMissing() {
760 Resource resourceExist = createResourceObject(false);
761 resourceExist.setIcon(null);
762 when(toscaOperationFacade
763 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
764 .thenReturn(Either.left(false));
766 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
767 } catch (ComponentException e) {
768 assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
772 private void testResourceIconInvalid() {
773 Resource resourceExist = createResourceObject(false);
774 resourceExist.setIcon("kjk3453^&");
777 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
778 } catch (ComponentException e) {
779 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
783 private void testResourceIconExceedsLimit() {
784 Resource resourceExist = createResourceObject(false);
785 resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
787 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
788 } catch (ComponentException e) {
789 assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT,
790 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
795 // Resource tags - start
796 private void testResourceTagNotExist() {
797 Resource resourceExist = createResourceObject(false);
798 resourceExist.setTags(null);
800 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
801 } catch (ComponentException e) {
802 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
806 private void testResourceTagEmpty() {
807 Resource resourceExist = createResourceObject(false);
808 resourceExist.setTags(new ArrayList<>());
810 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
811 } catch (ComponentException e) {
812 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
816 private void testTagsExceedsLimitCreate() {
817 Resource resourceExccedsNameLimit = createResourceObject(false);
818 String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
819 String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
820 String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
821 String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
822 String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
823 String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
824 String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
825 String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
826 String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
827 String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
828 String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
829 String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
830 String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
831 String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
832 String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
833 String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
834 String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
835 String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
836 String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
837 String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
838 String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
840 List<String> tagsList = new ArrayList<>();
862 tagsList.add(resourceExccedsNameLimit.getName());
864 resourceExccedsNameLimit.setTags(tagsList);
866 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
867 } catch (ComponentException e) {
868 assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
869 "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
873 private void testTagsSingleExceedsLimit() {
874 Resource resourceExccedsNameLimit = createResourceObject(false);
875 String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI";
876 String tag2 = resourceExccedsNameLimit.getName();
877 List<String> tagsList = new ArrayList<>();
881 resourceExccedsNameLimit.setTags(tagsList);
883 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
884 } catch (ComponentException e) {
885 assertComponentException(e, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT,
886 "" + ValidationUtils.TAG_MAX_LENGTH);
890 private void testTagsNoServiceName() {
891 Resource serviceExccedsNameLimit = createResourceObject(false);
892 String tag1 = "afzs2qLBb";
893 List<String> tagsList = new ArrayList<>();
895 serviceExccedsNameLimit.setTags(tagsList);
897 bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
898 } catch (ComponentException e) {
899 assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
903 private void testInvalidTag() {
904 Resource serviceExccedsNameLimit = createResourceObject(false);
905 String tag1 = "afzs2qLBb%#%";
906 List<String> tagsList = new ArrayList<>();
908 serviceExccedsNameLimit.setTags(tagsList);
910 bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
911 } catch (ComponentException e) {
912 assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, new String[]{"Resource", "tag"});
916 // Resource tags - stop
917 // Resource contact start
919 private void testContactIdTooLong() {
920 Resource resourceContactId = createResourceObject(false);
921 // 59 chars instead of 50
922 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
923 resourceContactId.setContactId(contactIdTooLong);
926 bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
927 } catch (ComponentException e) {
928 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
932 private void testContactIdWrongFormatCreate() {
933 Resource resourceContactId = createResourceObject(false);
934 // 3 letters and 3 digits and special characters
935 String contactIdFormatWrong = "yrt134!!!";
936 resourceContactId.setContactId(contactIdFormatWrong);
938 bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
939 } catch (ComponentException e) {
940 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
944 private void testResourceContactIdEmpty() {
945 Resource resourceExist = createResourceObject(false);
946 resourceExist.setContactId("");
948 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
949 } catch (ComponentException e) {
950 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
954 private void testResourceContactIdMissing() {
955 Resource resourceExist = createResourceObject(false);
956 resourceExist.setContactId(null);
958 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
959 } catch (ComponentException e) {
960 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
964 private void testVendorNameExceedsLimit() {
965 Resource resourceExccedsVendorNameLimit = createResourceObject(false);
966 String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
967 resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
969 bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
970 } catch (ComponentException e) {
971 assertComponentException(e, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
972 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
976 private void testResourceVendorModelNumberExceedsLimit() {
977 Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
978 String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
979 resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
981 bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null,
983 } catch (ComponentException e) {
984 assertComponentException(e, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
985 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
989 private void testVendorNameWrongFormatCreate() {
990 Resource resource = createResourceObject(false);
992 String nameWrongFormat = "ljg*fd";
993 resource.setVendorName(nameWrongFormat);
995 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
996 } catch (ComponentException e) {
997 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
1001 private void testVendorReleaseWrongFormat() {
1002 Resource resource = createResourceObject(false);
1004 String vendorReleaseWrongFormat = "1>2";
1005 resource.setVendorRelease(vendorReleaseWrongFormat);
1007 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1008 } catch (ComponentException e) {
1009 assertComponentException(e, ActionStatus.INVALID_VENDOR_RELEASE, vendorReleaseWrongFormat);
1013 private void testVendorReleaseExceedsLimitCreate() {
1014 Resource resourceExccedsNameLimit = createResourceObject(false);
1015 String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
1016 resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
1018 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1019 } catch (ComponentException e) {
1020 assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
1021 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
1025 private void testResourceVendorNameMissing() {
1026 Resource resourceExist = createResourceObject(false);
1027 resourceExist.setVendorName(null);
1029 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1030 } catch (ComponentException e) {
1031 assertComponentException(e, ActionStatus.MISSING_VENDOR_NAME);
1035 private void testResourceVendorReleaseMissing() {
1036 Resource resourceExist = createResourceObject(false);
1037 resourceExist.setVendorRelease(null);
1039 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1040 } catch (ComponentException e) {
1041 assertComponentException(e, ActionStatus.MISSING_VENDOR_RELEASE);
1045 // Resource vendor name/release stop
1047 private void testResourceCategoryExist() {
1048 Resource resourceExist = createResourceObject(false);
1049 resourceExist.setCategories(null);
1051 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1052 } catch (ComponentException e) {
1053 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1057 private void testResourceBadCategoryCreate() {
1059 Resource resourceExist = createResourceObject(false);
1060 resourceExist.setCategories(null);
1061 resourceExist.addCategory("koko", "koko");
1063 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1064 } catch (ComponentException e) {
1065 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1071 private void testHappyScenarioCostLicenseType() {
1072 Resource createResourceObject = createResourceObject(false);
1073 Resource createResourceObjectAfterCreate = createResourceObject(true);
1074 // Adding cost and licenseType to basic mock
1075 Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate);
1076 when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
1078 String cost = "123.456";
1079 String licenseType = "User";
1080 createResourceObject.setCost(cost);
1081 createResourceObject.setLicenseType(licenseType);
1082 Resource createdResource;
1084 createdResource = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null,
1086 createResourceObjectAfterCreate.setCost(cost);
1087 createResourceObjectAfterCreate.setLicenseType(licenseType);
1088 assertThat(createResourceObjectAfterCreate).isEqualTo(createdResource);
1089 } catch (ComponentException e) {
1090 assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
1095 private void testCostWrongFormatCreate() {
1096 Resource resourceCost = createResourceObject(false);
1097 // Comma instead of fullstop
1098 String cost = "12356,464";
1099 resourceCost.setCost(cost);
1101 bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1102 } catch (ComponentException e) {
1103 assertComponentException(e, ActionStatus.INVALID_CONTENT);
1108 // License type start
1109 private void testLicenseTypeWrongFormatCreate() {
1110 Resource resourceLicenseType = createResourceObject(false);
1112 String licenseType = "cpu";
1113 resourceLicenseType.setLicenseType(licenseType);
1115 bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1116 } catch (ComponentException e) {
1117 assertComponentException(e, ActionStatus.INVALID_CONTENT);
1121 // License type stop
1122 // Derived from start
1123 private void testResourceTemplateNotExist() {
1124 Resource resourceExist = createResourceObject(false);
1125 List<String> list = null;
1126 resourceExist.setDerivedFrom(list);
1128 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1129 } catch (ComponentException e) {
1130 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1134 private void testResourceTemplateEmpty() {
1135 Resource resourceExist = createResourceObject(false);
1136 resourceExist.setDerivedFrom(new ArrayList<>());
1138 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1139 } catch (ComponentException e) {
1140 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1144 private void testResourceTemplateInvalid() {
1145 Resource resourceExist = createResourceObject(false);
1146 ArrayList<String> derivedFrom = new ArrayList<>();
1147 derivedFrom.add("kuku");
1148 resourceExist.setDerivedFrom(derivedFrom);
1150 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1151 } catch (ComponentException e) {
1152 assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
1156 // Derived from stop
1157 private void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) {
1158 ResponseFormat actualResponse = e.getResponseFormat() != null ? e.getResponseFormat()
1159 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1160 assertResponse(actualResponse, expectedStatus, variables);
1163 private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
1164 ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
1165 assertThat(expectedResponse.getStatus()).isEqualTo(actualResponse.getStatus());
1166 assertThat(expectedResponse.getFormattedMessage()).isEqualTo(actualResponse.getFormattedMessage());
1169 private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus,
1170 String... variables) {
1171 assertResponse(createResponse.right()
1172 .value(), expectedStatus, variables);
1175 // UPDATE tests - start
1178 void testResourceNameWrongFormat_UPDATE() {
1179 Resource resource = createResourceObject(true);
1180 Resource updatedResource = createResourceObject(true);
1182 // this is in order to prevent failing with 403 earlier
1183 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1184 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1186 String nameWrongFormat = "ljg*fd";
1187 updatedResource.setName(nameWrongFormat);
1189 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1190 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1192 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1193 } catch (ComponentException e) {
1194 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
1199 void testResourceNameAfterCertify_UPDATE() {
1200 Resource resource = createResourceObject(true);
1201 Resource updatedResource = createResourceObject(true);
1203 // this is in order to prevent failing with 403 earlier
1204 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1205 // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
1206 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1208 String name = "ljg";
1209 updatedResource.setName(name);
1210 resource.setVersion("1.0");
1212 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1213 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1215 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1216 } catch (ComponentException e) {
1217 assertComponentException(e, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1222 void testResourceNameAlreadyExist_UPDATE() {
1223 Resource resource = createResourceObject(true);
1224 Resource updatedResource = createResourceObject(true);
1226 // this is in order to prevent failing with 403 earlier
1227 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1228 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1230 String resourceName = "alreadyExists";
1231 updatedResource.setName(resourceName);
1232 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
1233 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1235 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1236 } catch (ComponentException e) {
1237 assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
1238 ComponentTypeEnum.RESOURCE.getValue(), resourceName);
1243 void testResourceDescExceedsLimit_UPDATE() {
1244 Resource resource = createResourceObject(true);
1245 Resource updatedResource = createResourceObject(true);
1247 // this is in order to prevent failing with 403 earlier
1248 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1249 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1251 // 1025 chars, the limit is 1024
1252 String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
1253 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
1254 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
1255 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
1256 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
1257 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
1258 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
1259 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
1260 updatedResource.setDescription(tooLongResourceDesc);
1261 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1262 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1264 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1265 } catch (ComponentException e) {
1266 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
1267 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
1272 void testIconWrongFormat_UPDATE() {
1273 Resource resource = createResourceObject(true);
1274 Resource updatedResource = createResourceObject(true);
1276 // this is in order to prevent failing with 403 earlier
1277 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1278 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1281 String icon = "icon.jpg";
1282 updatedResource.setIcon(icon);
1283 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1284 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1286 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1287 } catch (ComponentException e) {
1288 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
1293 void testIconAfterCertify_UPDATE() {
1294 Resource resource = createResourceObject(true);
1295 Resource updatedResource = createResourceObject(true);
1297 // this is in order to prevent failing with 403 earlier
1298 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1299 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1302 String icon = "icon";
1303 updatedResource.setIcon(icon);
1305 resource.setVersion("1.0");
1307 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1308 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1310 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1311 } catch (ComponentException e) {
1312 assertComponentException(e, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
1317 void testTagsExceedsLimit_UPDATE() {
1318 Resource resource = createResourceObject(true);
1319 Resource updatedResource = createResourceObject(true);
1321 // this is in order to prevent failing with 403 earlier
1322 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1323 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1325 String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
1326 String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
1327 String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
1328 String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
1329 String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
1330 String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
1331 String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
1332 String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
1333 String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
1334 String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
1335 String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
1336 String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
1337 String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
1338 String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
1339 String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
1340 String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
1341 String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
1342 String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
1343 String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
1344 String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
1345 String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
1347 List<String> tagsList = new ArrayList<>();
1357 tagsList.add(tag10);
1358 tagsList.add(tag11);
1359 tagsList.add(tag12);
1360 tagsList.add(tag13);
1361 tagsList.add(tag14);
1362 tagsList.add(tag15);
1363 tagsList.add(tag16);
1364 tagsList.add(tag17);
1365 tagsList.add(tag18);
1366 tagsList.add(tag19);
1367 tagsList.add(tag20);
1368 tagsList.add(tag21);
1369 tagsList.add(resource.getName());
1371 updatedResource.setTags(tagsList);
1372 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1373 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1375 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1376 } catch (ComponentException e) {
1377 assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
1378 "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
1383 void testVendorNameWrongFormat_UPDATE() {
1384 Resource resource = createResourceObject(true);
1385 Resource updatedResource = createResourceObject(true);
1387 // this is in order to prevent failing with 403 earlier
1388 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1389 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1392 String nameWrongFormat = "ljg*fd";
1393 updatedResource.setVendorName(nameWrongFormat);
1394 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1395 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1397 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1398 } catch (ComponentException e) {
1399 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
1404 void testVendorNameWrongFormat() {
1405 Resource resource = createResourceObject(true);
1406 Resource updatedResource = createResourceObject(true);
1408 // this is in order to prevent failing with 403 earlier
1409 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1410 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1413 String nameWrongFormat = "ljg*fd";
1414 updatedResource.setVendorName(nameWrongFormat);
1415 resource.setVersion("1.0");
1417 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1418 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1420 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1421 } catch (ComponentException e) {
1422 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
1427 void testVendorReleaseExceedsLimit_UPDATE() {
1428 Resource resource = createResourceObject(true);
1429 Resource updatedResource = createResourceObject(true);
1431 // this is in order to prevent failing with 403 earlier
1432 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1433 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1434 // 129 chars, the limit is 128
1435 String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy";
1436 updatedResource.setVendorRelease(tooLongVendorRelease);
1437 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1438 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1440 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1441 } catch (ComponentException e) {
1442 assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
1443 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
1448 void testResourceBadCategory_UPDATE() {
1449 Resource resource = createResourceObject(true);
1450 Resource updatedResource = createResourceObject(true);
1452 // this is in order to prevent failing with 403 earlier
1453 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1454 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1456 String resourceId = resource.getUniqueId();
1457 String badCategory = "ddfds";
1458 updatedResource.setCategories(null);
1459 updatedResource.addCategory(badCategory, "fikt");
1460 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1461 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1463 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1464 } catch (ComponentException e) {
1465 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1470 void createResourceFromCsarTest() {
1471 assertThrows(ComponentException.class, () -> {
1472 bl.createResourceFromCsar(resourceResponse, user, new HashMap<>(), "");
1477 void testCreateResourceFromCsarWithModel() throws URISyntaxException, ZipException {
1479 final File csarFile = new File(
1480 ResourceBusinessLogicTest.class.getClassLoader().getResource("csars/nonOnapCsar.csar").toURI());
1481 final Map<String, byte[]> csar = ZipUtils.readZip(csarFile, false);
1483 String resourceYml = new String(csar.get("Definitions/my_vnf.yaml"));
1485 YamlTemplateParsingHandler yamlTemplateParser = new YamlTemplateParsingHandler(mockJanusGraphDao, null,
1486 Mockito.mock(AnnotationBusinessLogic.class), null, null);
1487 final ParsedToscaYamlInfo parsedToscaYamlInfo = yamlTemplateParser.parseResourceInfoFromYAML("Definitions/my_vnf.yml", resourceYml,
1488 Collections.EMPTY_MAP, Collections.EMPTY_MAP, "myVnf", resourceResponse, "");
1490 when(propertyOperation.getDataTypeByName("tosca.datatypes.testDataType.FromMainTemplate", "testModel")).thenReturn(
1491 Either.right(StorageOperationStatus.NOT_FOUND));
1493 when(toscaOperationFacade.getLatestByToscaResourceName(anyString(), any())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1494 Resource vduCp = new Resource();
1495 vduCp.setToscaResourceName("tosca.nodes.nfv.VduCp");
1496 vduCp.setState(LifecycleStateEnum.CERTIFIED);
1497 vduCp.setUniqueId("tosca.nodes.nfv.VduCp");
1498 vduCp.setProperties(new ArrayList<>());
1499 Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
1500 RequirementDefinition req = new RequirementDefinition();
1501 req.setName("virtual_link");
1502 List<RequirementDefinition> listReqs = new ArrayList<>();
1504 requirements.put("tosca.nodes.nfv.VduCp", listReqs);
1505 vduCp.setRequirements(requirements);
1506 PropertyDefinition bitrateProp = new PropertyDefinition();
1507 bitrateProp.setName("bitrate_requirement");
1508 bitrateProp.setType("integer");
1509 vduCp.getProperties().add(bitrateProp);
1510 PropertyDefinition virtNiProp = new PropertyDefinition();
1511 virtNiProp.setName("virtual_network_interface_requirements");
1512 virtNiProp.setType("list");
1513 vduCp.getProperties().add(virtNiProp);
1514 PropertyDefinition descriptionProp = new PropertyDefinition();
1515 descriptionProp.setName("description");
1516 descriptionProp.setType("string");
1517 vduCp.getProperties().add(descriptionProp);
1518 PropertyDefinition roleProp = new PropertyDefinition();
1519 roleProp.setName("role");
1520 roleProp.setType("string");
1521 vduCp.getProperties().add(roleProp);
1522 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel("tosca.nodes.nfv.VduCp", "testModel_myVnf1.0")).thenReturn(Either.left(vduCp));
1524 when(yamlTemplateParsingHandler.parseResourceInfoFromYAML(any(), any(), any(), any(), any(), any(), any())).thenReturn(parsedToscaYamlInfo);
1526 UploadComponentInstanceInfo uploadComponentInstanceInfo = new UploadComponentInstanceInfo();
1527 uploadComponentInstanceInfo.setType("myType");
1528 resourceResponse.setUniqueId("myVnf");
1529 resourceResponse.setName("myVnf");
1530 resourceResponse.setSystemName("myVnf");
1531 resourceResponse.setModel("testModel");
1532 resourceResponse.setResourceType(ResourceTypeEnum.VF);
1533 resourceResponse.setProperties(new ArrayList<>());
1534 resourceResponse.setCsarVersion("1.0");
1536 Resource derivedFrom = new Resource();
1537 List<PropertyDefinition> properties = new ArrayList<>();
1538 PropertyDefinition baseTypeProp = new PropertyDefinition();
1539 baseTypeProp.setName("propInBase");
1540 baseTypeProp.setType("string");
1541 properties.add(baseTypeProp);
1542 derivedFrom.setProperties(properties);
1543 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(any(), eq("tosca.nodes.nfv.VNF"))).thenReturn(Either.left(derivedFrom));
1545 when(toscaOperationFacade
1546 .validateComponentNameAndModelExists("myVnf", "testModel_myVnf1.0", ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(
1547 Either.left(false));
1549 when(toscaOperationFacade.addPropertyToComponent(any(), any())).thenReturn(Either.left(new PropertyDefinition()));
1550 when(toscaOperationFacade.associateComponentInstancePropertiesToComponent(any(), any())).thenReturn(Either.left(Collections.emptyMap()));
1551 when(toscaOperationFacade.associateArtifactsToInstances(any(), any())).thenReturn(StorageOperationStatus.OK);
1552 when(toscaOperationFacade.associateDeploymentArtifactsToInstances(any(), any(), any())).thenReturn(StorageOperationStatus.OK);
1553 when(toscaOperationFacade.associateInstAttributeToComponentToInstances(any(), any())).thenReturn(StorageOperationStatus.OK);
1554 when(toscaOperationFacade.associateResourceInstances(any(Component.class), anyString(), anyList())).thenReturn(
1555 Either.left(Collections.EMPTY_LIST));
1556 when(applicationDataTypeCache.getAll("testModel_myVnf1.0")).thenReturn(Either.left(emptyDataTypes));
1558 doAnswer(invocation -> {
1559 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReqs = invocation.getArgument(1);
1560 for (final Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> m : instReqs.entrySet()) {
1561 m.getKey().setRequirements(m.getValue());
1563 return StorageOperationStatus.OK;
1565 when(toscaOperationFacade).associateOrAddCalculatedCapReq(any(), any(), any());
1567 when(toscaOperationFacade.updateCalculatedCapabilitiesRequirements(any(), any(), any())).thenReturn(StorageOperationStatus.OK);
1568 when(groupBusinessLogic.validateUpdateVfGroupNames(any(), any())).thenReturn(Either.left(Collections.EMPTY_MAP));
1570 ComponentInstance ci = new ComponentInstance();
1571 List<ComponentInstance> cis = new ArrayList<>();
1573 doAnswer(invocation -> {
1574 List<ComponentInstance> componentInstances = new ArrayList<ComponentInstance>(
1575 ((Map<ComponentInstance, Resource>) invocation.getArgument(1)).keySet());
1576 ((Resource) invocation.getArgument(0)).setComponentInstances(componentInstances);
1578 }).when(toscaOperationFacade).associateComponentInstancesToComponent(any(), any(), eq(false), eq(false));
1580 doAnswer(invocation -> {
1581 return Either.left(invocation.getArgument(0));
1582 }).when(csarArtifactsAndGroupsBusinessLogic).deleteVFModules(any(Resource.class), any(CsarInfo.class), eq(true), eq(false));
1584 doAnswer(invocation -> {
1585 return Either.left(resourceResponse);
1586 }).when(toscaOperationFacade).getToscaFullElement("myVnf");
1588 Resource result = bl.createResourceFromCsar(resourceResponse, user, csar, "1234");
1590 assertEquals("myDomain.myVnf", result.getToscaResourceName());
1591 List<String> propIds = result.getProperties().stream().map(prop -> prop.getUniqueId()).collect(Collectors.toList());
1592 assertTrue(propIds.contains("myVnf.propInBase"));
1593 assertTrue(propIds.contains("myVnf.descriptor_id"));
1594 assertTrue(propIds.contains("myVnf.descriptor_version"));
1595 assertTrue(propIds.contains("myVnf.flavour_description"));
1596 assertTrue(propIds.contains("myVnf.flavour_id"));
1597 assertTrue(propIds.contains("myVnf.product_name"));
1598 assertTrue(propIds.contains("myVnf.provider"));
1599 assertTrue(propIds.contains("myVnf.software_version"));
1600 assertTrue(propIds.contains("myVnf.vnfm_info"));
1602 final List<String> reqsName = new ArrayList<>();
1604 final List<ComponentInstance> cisWithExtReq = result.getComponentInstances().stream()
1605 .filter(instance -> instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).isExternal()).collect(Collectors.toList());
1606 cisWithExtReq.forEach(instance -> reqsName.add(instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).getExternalName()));
1607 assertEquals(3, cisWithExtReq.size());
1611 void testResourceCategoryAfterCertify_UPDATE() {
1612 Resource resource = createResourceObject(true);
1613 Resource updatedResource = createResourceObject(true);
1615 // this is in order to prevent failing with 403 earlier
1616 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1617 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1619 String resourceId = resource.getUniqueId();
1620 updatedResource.setCategories(null);
1621 updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY);
1622 resource.setVersion("1.0");
1624 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1625 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1627 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1628 } catch (ComponentException e) {
1629 assertComponentException(e, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
1633 // Derived from start
1635 void testResourceTemplateNotExist_UPDATE() {
1636 Resource resource = createResourceObject(true);
1637 Resource updatedResource = createResourceObject(true);
1639 // this is in order to prevent failing with 403 earlier
1640 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1641 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1642 String resourceId = resource.getUniqueId();
1644 List<String> list = null;
1645 updatedResource.setDerivedFrom(list);
1646 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1647 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1649 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1650 } catch (ComponentException e) {
1651 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1656 void testResourceTemplateEmpty_UPDATE() {
1657 Resource resource = createResourceObject(true);
1658 Resource updatedResource = createResourceObject(true);
1659 String resourceId = resource.getUniqueId();
1661 // this is in order to prevent failing with 403 earlier
1662 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1663 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1665 updatedResource.setDerivedFrom(new ArrayList<>());
1666 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1667 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1669 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1670 } catch (ComponentException e) {
1671 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1676 void testResourceTemplateInvalid_UPDATE() {
1677 Resource resource = createResourceObject(true);
1678 Resource updatedResource = createResourceObject(true);
1679 String resourceId = resource.getUniqueId();
1681 // this is in order to prevent failing with 403 earlier
1682 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1683 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1685 ArrayList<String> derivedFrom = new ArrayList<>();
1686 derivedFrom.add("kuku");
1687 updatedResource.setDerivedFrom(derivedFrom);
1688 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1689 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1691 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1692 } catch (ComponentException e) {
1693 assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
1698 void testResourceTemplateCertify_UPDATE_HAPPY() {
1699 Resource resource = createResourceObject(true);
1700 Resource updatedResource = createResourceObject(true);
1701 String resourceId = resource.getUniqueId();
1703 // this is in order to prevent failing with 403 earlier
1704 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1705 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1707 Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true);
1708 when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
1709 .thenReturn(isToscaNameExtending);
1711 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
1712 .left(new HashMap<>());
1713 when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
1714 .thenReturn(findPropertiesOfNode);
1716 resource.setVersion("1.0");
1718 ArrayList<String> derivedFrom = new ArrayList<>();
1719 derivedFrom.add("tosca.nodes.Root");
1720 updatedResource.setDerivedFrom(derivedFrom);
1721 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
1722 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1723 Resource createdResource = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1724 assertThat(createdResource).isNotNull();
1728 void testResourceTemplateCertify_UPDATE_SAD() {
1729 Resource resource = createResourceObject(true);
1730 Resource updatedResource = createResourceObject(true);
1731 String resourceId = resource.getUniqueId();
1733 // this is in order to prevent failing with 403 earlier
1734 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1735 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1737 Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false);
1738 when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
1739 .thenReturn(isToscaNameExtending);
1741 resource.setVersion("1.0");
1743 ArrayList<String> derivedFrom = new ArrayList<>();
1744 derivedFrom.add("tosca.nodes.Root");
1745 updatedResource.setDerivedFrom(derivedFrom);
1746 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1747 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1748 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
1749 .left(new HashMap<>());
1750 when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
1751 .thenReturn(findPropertiesOfNode);
1754 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1755 } catch (ComponentException e) {
1756 assertComponentException(e, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1759 // Derived from stop
1762 void createOrUpdateResourceAlreadyCheckout() {
1764 Resource resourceExist = createResourceObject(false);
1765 validateUserRoles(Role.ADMIN, Role.DESIGNER);
1766 when(toscaOperationFacade
1767 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1768 .thenReturn(Either.left(false));
1769 Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
1771 createdResource.setLastUpdaterUserId(user.getUserId());
1772 assertThat(createdResource).isNotNull();
1773 Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
1774 Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
1775 when(toscaOperationFacade.getLatestByToscaResourceName(resourceExist.getToscaResourceName(), null))
1776 .thenReturn(getCompLatestResult);
1777 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
1778 .thenReturn(getCompLatestResult);
1779 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1780 .thenReturn(getLatestResult);
1782 Resource resourceToUpdtae = createResourceObject(false);
1784 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1785 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1786 assertNotNull(createOrUpdateResource);
1788 Mockito.verify(toscaOperationFacade, Mockito.times(1))
1789 .overrideComponent(any(Resource.class), any(Resource.class));
1790 Mockito.verify(lifecycleBl, Mockito.times(0))
1791 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1792 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1797 void createOrUpdateResourceCertified() {
1799 Resource resourceExist = createResourceObject(false);
1800 when(toscaOperationFacade
1801 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1802 .thenReturn(Either.left(false));
1803 validateUserRoles(Role.ADMIN, Role.DESIGNER);
1804 Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
1807 assertThat(createdResource).isNotNull();
1808 createdResource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
1809 createdResource.setVersion("1.0");
1811 Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
1812 Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
1813 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
1814 .thenReturn(getCompLatestResult);
1815 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1816 .thenReturn(getLatestResult);
1818 when(lifecycleBl.changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1819 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()))
1820 .thenReturn(Either.left(createdResource));
1822 Resource resourceToUpdtae = createResourceObject(false);
1824 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1825 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1826 assertNotNull(createOrUpdateResource);
1828 Mockito.verify(toscaOperationFacade, Mockito.times(1))
1829 .overrideComponent(any(Resource.class), any(Resource.class));
1830 Mockito.verify(lifecycleBl, Mockito.times(1))
1831 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1832 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1837 void createOrUpdateResourceNotExist() {
1838 Resource resourceToUpdtae = createResourceObject(false);
1840 Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
1841 when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName(), null)).thenReturn(getLatestResult);
1842 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdtae.getToscaResourceName(), null))
1843 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1844 when(toscaOperationFacade
1845 .validateComponentNameAndModelExists(resourceToUpdtae.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1846 .thenReturn(Either.left(false));
1848 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1849 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1850 assertThat(createOrUpdateResource).isNotNull();
1852 Mockito.verify(toscaOperationFacade, times(1))
1853 .createToscaComponent(resourceToUpdtae);
1854 Mockito.verify(toscaOperationFacade, Mockito.times(0))
1855 .overrideComponent(any(Resource.class), any(Resource.class));
1856 Mockito.verify(lifecycleBl, Mockito.times(0))
1857 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1858 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1863 void testIfNodeTypeNameHasValidPrefix() {
1864 final List<String> definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager()
1865 .getConfiguration().getDefinedResourceNamespace();
1867 definedNodeTypeNamespaceList.parallelStream().forEach(validNodeTypePrefix -> {
1868 final String nodeName = validNodeTypePrefix + "." + "abc";
1869 final Optional<String> result = bl.validateNodeTypeNamePrefix(nodeName, definedNodeTypeNamespaceList);
1870 assertTrue(result.isPresent());
1875 void updateNestedResource_typeIsNew() throws IOException {
1876 Resource resourceToUpdate = createResourceObject(false);
1877 String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
1878 String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
1879 CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
1881 String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
1882 .name(), csarInfo.getVfResourceName(), nodeName)
1884 when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
1885 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1886 when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
1887 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1888 when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
1889 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1891 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
1892 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1893 when(toscaOperationFacade
1894 .validateComponentNameAndModelExists(resourceToUpdate.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1895 .thenReturn(Either.left(false));
1897 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1898 .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
1899 assertThat(createOrUpdateResource).isNotNull();
1901 Mockito.verify(toscaOperationFacade, times(1))
1902 .createToscaComponent(resourceToUpdate);
1903 Mockito.verify(toscaOperationFacade, times(0))
1904 .overrideComponent(any(Resource.class), any(Resource.class));
1905 Mockito.verify(lifecycleBl, times(0))
1906 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1907 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1911 void updateNestedResource_typeExists() throws IOException {
1913 Resource resourceToUpdate = createResourceObject(false);
1914 setCanWorkOnResource(resourceResponse);
1915 String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
1916 String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
1917 CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
1919 String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
1920 .name(), csarInfo.getVfResourceName(), nodeName)
1922 when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
1923 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1924 when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
1925 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1926 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
1927 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1928 when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
1929 .thenReturn(Either.left(resourceResponse));
1930 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1931 .thenReturn(Either.left(resourceResponse));
1933 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1934 .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
1935 assertThat(createOrUpdateResource).isNotNull();
1936 Mockito.verify(toscaOperationFacade, times(1))
1937 .overrideComponent(any(Resource.class), any(Resource.class));
1938 Mockito.verify(lifecycleBl, times(0))
1939 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1940 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1944 void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() {
1945 Resource basic = createResourceObject(true);
1947 Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1948 assertTrue(validatePropertiesDefaultValues);
1952 void testValidatePropertiesDefaultValues_SuccessfullWithProperties() {
1953 Resource basic = createResourceObject(true);
1954 PropertyDefinition property = new PropertyDefinition();
1955 property.setName("myProperty");
1956 property.setType(ToscaPropertyType.INTEGER.getType());
1957 property.setDefaultValue("1");
1958 List<PropertyDefinition> properties = new ArrayList<>();
1959 properties.add(property);
1960 basic.setProperties(properties);
1961 when(propertyOperation.isPropertyTypeValid(property, (String) null)).thenReturn(true);
1962 when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true);
1963 Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1964 assertTrue(validatePropertiesDefaultValues);
1968 void testValidatePropertiesDefaultValues_FailedWithProperties() {
1969 Resource basic = createResourceObject(true);
1970 PropertyDefinition property = new PropertyDefinition();
1971 property.setName("myProperty");
1972 property.setType(ToscaPropertyType.INTEGER.getType());
1973 property.setDefaultValue("1.5");
1974 List<PropertyDefinition> properties = new ArrayList<>();
1975 properties.add(property);
1976 basic.setProperties(properties);
1978 when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false);
1979 assertThrows(ComponentException.class, () -> {
1980 bl.validatePropertiesDefaultValues(basic);
1985 void testDeleteMarkedResourcesNoResources() {
1986 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(new ArrayList<>());
1988 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
1990 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
1991 assertTrue(deleteMarkedResources.isLeft());
1992 assertTrue(deleteMarkedResources.left().value().isEmpty());
1996 void testDeleteMarkedResources() {
1997 List<String> ids = new ArrayList<>();
1998 String resourceInUse = "123";
1999 String resourceFree = "456";
2000 ids.add(resourceInUse);
2001 ids.add(resourceFree);
2002 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
2003 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
2005 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
2006 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
2008 List<ArtifactDefinition> artifacts = new ArrayList<>();
2010 when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
2011 when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
2013 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new
2015 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
2017 List<String> deletedComponents = new ArrayList<>();
2018 deletedComponents.add(resourceFree);
2019 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents));
2021 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
2022 assertTrue(deleteMarkedResources.isLeft());
2023 List<String> resourceIdList = deleteMarkedResources.left().value();
2024 assertFalse(resourceIdList.isEmpty());
2025 assertTrue(resourceIdList.contains(resourceFree));
2026 assertFalse(resourceIdList.contains(resourceInUse));
2029 @SuppressWarnings("unchecked")
2031 void testFindVfCsarArtifactsToHandle() {
2033 Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
2034 String methodName = "findVfCsarArtifactsToHandle";
2035 Resource resource = new Resource();
2036 String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml";
2037 String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml";
2038 String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml";
2040 String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml";
2041 String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml";
2042 String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml";
2043 String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml";
2045 byte[] oldPayloadData = "oldPayloadData".getBytes();
2046 byte[] newPayloadData = "newPayloadData".getBytes();
2047 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
2049 ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition();
2050 deploymentArtifactToUpdate.setMandatory(false);
2051 deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName);
2052 deploymentArtifactToUpdate.setArtifactType("SNMP_POLL");
2053 deploymentArtifactToUpdate.setPayload(oldPayloadData);
2054 deploymentArtifactToUpdate
2055 .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2057 ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition();
2058 deploymentArtifactToDelete.setMandatory(false);
2059 deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName);
2060 deploymentArtifactToDelete.setArtifactType("SNMP_TRAP");
2061 deploymentArtifactToDelete.setPayload(oldPayloadData);
2062 deploymentArtifactToDelete
2063 .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2065 ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition();
2067 deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()),
2068 deploymentArtifactToUpdate);
2069 deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()),
2070 deploymentArtifactToDelete);
2071 deploymentArtifacts.put("ignore", deploymentArtifactToIgnore);
2073 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
2075 ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
2076 artifactToUpdate.setMandatory(false);
2077 artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName);
2078 artifactToUpdate.setArtifactType("SNMP_POLL");
2079 artifactToUpdate.setPayload(oldPayloadData);
2080 artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2082 ArtifactDefinition artifactToDelete = new ArtifactDefinition();
2083 artifactToDelete.setMandatory(false);
2084 artifactToDelete.setArtifactName(artifactInfoToDeleteFileName);
2085 artifactToDelete.setArtifactType("SNMP_TRAP");
2086 artifactToDelete.setPayload(oldPayloadData);
2087 artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2088 artifactToDelete.setIsFromCsar(true);
2090 ArtifactDefinition artifactToNotDelete = new ArtifactDefinition();
2091 artifactToNotDelete.setMandatory(false);
2092 artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName);
2093 artifactToNotDelete.setArtifactType("SNMP_TRAP");
2094 artifactToNotDelete.setPayload(oldPayloadData);
2095 artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2096 artifactToNotDelete.setIsFromCsar(false);
2098 ArtifactDefinition artifactToIgnore = new ArtifactDefinition();
2100 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate);
2101 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete);
2102 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()),
2103 artifactToNotDelete);
2104 artifacts.put("ignore", artifactToIgnore);
2106 resource.setDeploymentArtifacts(deploymentArtifacts);
2107 resource.setArtifacts(artifacts);
2109 List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>();
2110 NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(
2111 deploymentArtifactToUpdate.getArtifactName(), null,
2112 deploymentArtifactToUpdate.getArtifactType(),
2113 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false);
2115 NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(
2116 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2117 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), false);
2119 NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
2120 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2121 ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData, artifactToUpdate.getArtifactName(), true);
2123 NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
2124 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2125 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), true);
2127 NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName,
2128 null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData,
2129 deploymentArtifactToCreateFileName, false);
2131 NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName,
2132 null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData,
2133 artifactInfoToCreateFileName, false);
2135 artifactPathAndNameList.add(deploymentArtifactInfoToUpdate);
2136 artifactPathAndNameList.add(informationalArtifactInfoToUpdate);
2137 artifactPathAndNameList.add(deploymentArtifactInfoToCreate);
2138 artifactPathAndNameList.add(informationalArtifactInfoToCreate);
2139 artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar);
2140 artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar);
2142 Object[] argObjects = {resource, artifactPathAndNameList, user};
2143 Class[] argClasses = {Resource.class, List.class, User.class};
2145 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
2146 method.setAccessible(true);
2147 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method
2148 .invoke(bl, argObjects);
2149 assertTrue(findVfCsarArtifactsToHandleRes.isLeft());
2150 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes
2153 assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.CREATE)
2155 assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.UPDATE)
2157 assertEquals(1, foundVfArtifacts.get(ArtifactOperationEnum.DELETE)
2160 } catch (Exception e) {
2161 e.printStackTrace();
2166 void testVFGeneratedInputs() {
2167 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2168 Resource resource = createVF();
2169 List<InputDefinition> inputs = resource.getInputs();
2170 assertEquals(6, inputs.size());
2171 for (InputDefinition input : inputs) {
2172 assertThat(input.getOwnerId()).isNotNull();
2174 assertEquals(resource.getDerivedFromGenericType(), genericVF.getToscaResourceName());
2175 assertEquals(resource.getDerivedFromGenericVersion(), genericVF.getVersion());
2179 void testCRGeneratedInputs() {
2180 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2181 Resource resource = createCR();
2182 List<InputDefinition> inputs = resource.getInputs();
2183 assertEquals(3, inputs.size());
2184 for (InputDefinition input : inputs) {
2185 assertThat(input.getOwnerId()).isNotNull();
2187 assertEquals(resource.getDerivedFromGenericType(), genericCR.getToscaResourceName());
2188 assertEquals(resource.getDerivedFromGenericVersion(), genericCR.getVersion());
2192 void testVFUpdateGenericInputsToLatestOnCheckout() {
2193 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2194 // create a VF that is derived from generic version 1.0
2195 Resource resource = createVF();
2196 // create a new generic version without properties
2197 genericVF.setVersion("2.0");
2198 genericVF.setProperties(null);
2199 String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
2200 List<InputDefinition> currentInputs = resource.getInputs();
2201 // verify previous inputs ownerId fields exist - user may not delete
2203 assertEquals(6, currentInputs.stream()
2204 .filter(p -> null != p.getOwnerId())
2205 .collect(Collectors.toList())
2207 Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
2209 assertTrue(upgradeToLatestGeneric.isLeft());
2210 // verify update required and valid
2211 assertTrue(upgradeToLatestGeneric.left()
2213 // verify version was upgraded
2214 assertNotEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
2215 // verify inputs were not deleted
2216 assertEquals(6, resource.getInputs()
2218 // verify inputs ownerId fields were removed - user may delete/edit
2220 assertEquals(6, resource.getInputs()
2222 .filter(p -> null == p.getOwnerId())
2223 .collect(Collectors.toList())
2228 void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
2230 // create a VF that is derived from generic version 1.0
2231 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2232 Resource resource = createVF();
2234 // add an input to the VF
2235 PropertyDefinition newProp = new PropertyDefinition();
2236 newProp.setType("integer");
2237 newProp.setName("newProp");
2238 resource.getInputs()
2239 .add(new InputDefinition(newProp));
2241 // create a new generic version with a new property which has the same
2242 // name as a user defined input on the VF with a different type
2243 genericVF.setVersion("2.0");
2244 newProp.setType("string");
2245 genericVF.setProperties(new ArrayList<>());
2246 genericVF.getProperties()
2248 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
2249 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
2250 genericVF.getUniqueId())).thenCallRealMethod();
2251 String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
2252 assertEquals(6, resource.getInputs()
2254 .filter(p -> null != p.getOwnerId())
2255 .collect(Collectors.toList())
2257 Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
2259 assertTrue(upgradeToLatestGeneric.isLeft());
2260 // verify update is invalid an void
2261 assertFalse(upgradeToLatestGeneric.left().value());
2262 // verify version was not upgraded
2263 assertEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
2264 // verify inputs were not removed
2265 assertEquals(7, resource.getInputs().size());
2266 // verify user defined input exists
2267 assertEquals(1, resource.getInputs()
2269 .filter(p -> null == p.getOwnerId())
2270 .collect(Collectors.toList())
2272 assertEquals("integer", resource.getInputs()
2274 .filter(p -> null == p.getOwnerId())
2281 void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
2282 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2283 Resource resource = createPNF();
2284 List<InputDefinition> inputs = resource.getInputs();
2285 assertEquals(3, inputs.size());
2286 for (InputDefinition input : inputs) {
2287 assertThat(input.getOwnerId()).isNotNull();
2289 assertEquals(resource.getDerivedFromGenericType(), genericPNF.getToscaResourceName());
2290 assertEquals(resource.getDerivedFromGenericVersion(), genericPNF.getVersion());
2291 assertEquals(0, resource.getArtifacts()
2295 private Resource createVF() {
2297 genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
2298 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME))
2299 .thenReturn(Either.left(genericVF));
2300 Resource resource = createResourceObject(true);
2301 resource.setDerivedFrom(null);
2302 resource.setResourceType(ResourceTypeEnum.VF);
2303 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2304 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericVF));
2305 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod();
2306 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
2307 resource.getUniqueId())).thenCallRealMethod();
2308 when(toscaOperationFacade
2309 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE))
2310 .thenReturn(Either.left(false));
2311 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2312 assertThat(createdResource).isNotNull();
2313 return createdResource;
2316 private Resource createRoot() {
2317 rootType = setupGenericTypeMock(GENERIC_ROOT_NAME);
2318 when(toscaOperationFacade.getLatestByToscaResourceName(GENERIC_ROOT_NAME, null))
2319 .thenReturn(Either.left(rootType));
2323 private Resource createCR() {
2325 genericCR = setupGenericTypeMock(GENERIC_CR_NAME);
2326 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME))
2327 .thenReturn(Either.left(genericCR));
2328 Resource resource = createResourceObject(true);
2329 resource.setDerivedFrom(null);
2330 resource.setResourceType(ResourceTypeEnum.CR);
2331 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2332 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericCR));
2333 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod();
2334 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(),
2335 resource.getUniqueId())).thenCallRealMethod();
2336 when(toscaOperationFacade
2337 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE))
2338 .thenReturn(Either.left(false));
2339 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2340 assertThat(createdResource).isNotNull();
2341 return createdResource;
2344 private Resource createPNF() {
2346 genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
2347 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME))
2348 .thenReturn(Either.left(genericPNF));
2349 Resource resource = createResourceObject(true);
2350 resource.setDerivedFrom(null);
2351 resource.setResourceType(ResourceTypeEnum.PNF);
2352 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2353 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericPNF));
2354 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod();
2355 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(),
2356 resource.getUniqueId())).thenCallRealMethod();
2357 when(toscaOperationFacade
2358 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE))
2359 .thenReturn(Either.left(false));
2360 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2361 assertThat(createdResource).isNotNull();
2362 return createdResource;
2365 private Map<String, String> getGenericPropertiesByToscaName(String toscaName) {
2366 HashMap<String, String> PNFProps = new HashMap<String, String>() {
2368 put("nf_function", "string");
2369 put("nf_role", "string");
2370 put("nf_type", "string");
2374 HashMap<String, String> CRProps = new HashMap<String, String>() {
2376 put("cr_function", "string");
2377 put("cr_role", "string");
2378 put("cr_type", "string");
2382 HashMap<String, String> VFProps = new HashMap<String, String>() {
2385 put("availability_zone_max_count", "integer");
2386 put("min_instances", "integer");
2387 put("max_instances", "integer");
2391 if (toscaName.contains("PNF")) {
2394 if (toscaName.contains("CR")) {
2397 if (toscaName.contains("VF")) {
2401 return new HashMap<>();
2404 private Resource setupGenericTypeMock(String toscaName) {
2406 Resource genericType = createResourceObject(true);
2407 genericType.setVersion("1.0");
2408 genericType.setToscaResourceName(toscaName);
2409 genericType.setAbstract(true);
2410 List<PropertyDefinition> genericProps = new ArrayList<>();
2411 Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName);
2412 genericPropsMap.forEach((name, type) -> {
2413 PropertyDefinition prop = new PropertyDefinition();
2416 genericProps.add(prop);
2419 genericType.setProperties(genericProps);
2423 private void validateUserRoles(Role... roles) {
2424 List<Role> listOfRoles = Stream.of(roles)
2425 .collect(Collectors.toList());
2429 void testUpdateVolumeGroup() {
2430 Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
2431 bl.updateVolumeGroup(resource);
2432 assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(true));
2436 void testUpdateVolumeGroupNull() {
2437 Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
2438 resource.setGroups(null);
2439 bl.updateVolumeGroup(resource);
2440 assertThat(resource.getGroups()).isNull();
2444 void testUpdateVolumeGroupFail() {
2445 Resource resource = getResourceWithType("NON_EXIST_HEAT", "org.openecomp.groups.VfModule");
2446 bl.updateVolumeGroup(resource);
2447 assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(false));
2450 private Resource getResourceWithType(String artifactType, String groupDefinitionType) {
2451 ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
2452 List<GroupDefinition> groups = new ArrayList<>();
2453 GroupDefinition gd = new GroupDefinition();
2454 List<PropertyDataDefinition> properties = new ArrayList<>();
2455 PropertyDataDefinition pdd = new PropertyDataDefinition();
2456 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
2457 List<String> artifactsList = new ArrayList<>();
2459 artifactToUpdate.setArtifactType(artifactType);
2460 artifactToUpdate.setArtifactName(artifactType);
2461 artifactToUpdate.setUniqueId(artifactType);
2462 Resource resource = createResourceObjectCsar(true);
2463 artifactsList.add(artifactToUpdate.getArtifactName());
2465 pdd.setName("volume_group");
2466 pdd.setValue("true");
2467 pdd.setType(ToscaPropertyType.BOOLEAN.getType());
2469 artifacts.put(artifactToUpdate.getArtifactName(), artifactToUpdate);
2471 properties.add(pdd);
2472 gd.setType(groupDefinitionType);
2473 gd.setProperties(properties);
2474 gd.setArtifacts(artifactsList);
2477 resource.setGroups(groups);
2478 resource.setDeploymentArtifacts(artifacts);
2483 void testGetAllCertifiedResources() {
2484 List<Resource> list = bl.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, "USER");
2485 assertEquals(reslist, list);
2489 void testGetAllCertifiedResources_exception() {
2490 assertThrows(StorageException.class, () -> {
2491 List<Resource> list = bl.getAllCertifiedResources(false, HighestFilterEnum.NON_HIGHEST_ONLY, "USER");
2492 assertEquals(reslist, list);
2497 void testValidateResourceNameExists() {
2498 Either<Map<String, Boolean>, ResponseFormat> res = bl.validateResourceNameExists("Resource", ResourceTypeEnum.CR, "jh0003");
2499 assertEquals(true, res.isLeft());
2503 void rollbackWithEitherAlwaysReturnARuntimeException() {
2504 JanusGraphDao janusGraphDao = mockJanusGraphDao;
2505 ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
2506 String params = "testName";
2508 Either<Object, RuntimeException> result =
2509 ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
2511 assertTrue(result.isRight());
2512 assertTrue(result.right().value() instanceof ByActionStatusComponentException);
2516 void rollbackWithEitherWorksWithNullJanusGraphDao() {
2517 JanusGraphDao janusGraphDao = null;
2518 ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
2519 String params = "testName";
2521 Either<Object, RuntimeException> result =
2522 ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
2524 assertTrue(result.isRight());
2525 assertTrue(result.right().value() instanceof ByActionStatusComponentException);
2529 void testDeleteResource_NotFound() {
2530 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
2531 ResponseFormat respFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND),
2533 ResponseFormat actualResponseFormat = bl.deleteResource("1", user);
2534 assertEquals(respFormat.getStatus(), actualResponseFormat.getStatus());
2538 void testDeleteResource_NotArchived() {
2539 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(resourceResponse));
2540 ComponentException actualComponentException = assertThrows(ComponentException.class,
2541 () -> bl.deleteResourceAllVersions(resourceResponse.getUniqueId(), user));
2542 assertEquals(ActionStatus.COMPONENT_NOT_ARCHIVED, actualComponentException.getActionStatus());
2543 assertEquals("my-resource_name with space:0.1", actualComponentException.getParams()[0]);
2547 void testDeleteResource_IsInUse() {
2548 Resource resourceObject = createResourceObject(true);
2549 Mockito.when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(resourceObject));
2550 resourceObject.setArchived(true);
2551 OperationException oe = new OperationException(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, "resource_name");
2552 Mockito.when(toscaOperationFacade.deleteComponent(resourceObject.getInvariantUUID(), NodeTypeEnum.Resource, true)).thenThrow(oe);
2553 OperationException actualOperationException = assertThrows(OperationException.class,
2554 () -> bl.deleteResourceAllVersions(resourceResponse.getUniqueId(), user));
2555 assertEquals(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, actualOperationException.getActionStatus());
2556 assertEquals("resource_name", actualOperationException.getParams()[0]);