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 fj.data.Either;
24 import org.apache.commons.lang3.tuple.ImmutablePair;
25 import org.junit.Assert;
26 import org.junit.Before;
27 import org.junit.Test;
28 import org.mockito.InjectMocks;
29 import org.mockito.Mockito;
30 import org.mockito.MockitoAnnotations;
31 import org.openecomp.sdc.ElementOperationMock;
32 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
33 import org.openecomp.sdc.be.components.ArtifactsResolver;
34 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
35 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
36 import org.openecomp.sdc.be.components.csar.CsarInfo;
37 import org.openecomp.sdc.be.components.csar.YamlTemplateParsingHandler;
38 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
39 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
40 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
41 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
42 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
43 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
44 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
45 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
46 import org.openecomp.sdc.be.components.validation.UserValidations;
47 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
48 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
49 import org.openecomp.sdc.be.components.validation.component.ComponentFieldValidator;
50 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
51 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
52 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
53 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
54 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
55 import org.openecomp.sdc.be.config.ConfigurationManager;
56 import org.openecomp.sdc.be.dao.api.ActionStatus;
57 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
58 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
59 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
60 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
61 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
62 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
63 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
66 import org.openecomp.sdc.be.facade.operations.CatalogOperation;
67 import org.openecomp.sdc.be.impl.ComponentsUtils;
68 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
69 import org.openecomp.sdc.be.model.ArtifactDefinition;
70 import org.openecomp.sdc.be.model.Component;
71 import org.openecomp.sdc.be.model.ComponentInstance;
72 import org.openecomp.sdc.be.model.ComponentParametersView;
73 import org.openecomp.sdc.be.model.DataTypeDefinition;
74 import org.openecomp.sdc.be.model.GroupDefinition;
75 import org.openecomp.sdc.be.model.InputDefinition;
76 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
77 import org.openecomp.sdc.be.model.LifecycleStateEnum;
78 import org.openecomp.sdc.be.model.NodeTypeInfo;
79 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
80 import org.openecomp.sdc.be.model.PropertyDefinition;
81 import org.openecomp.sdc.be.model.RequirementDefinition;
82 import org.openecomp.sdc.be.model.Resource;
83 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
84 import org.openecomp.sdc.be.model.User;
85 import org.openecomp.sdc.be.model.VendorSoftwareProduct;
86 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
87 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
88 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
89 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
90 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTypeOperation;
91 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation;
92 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
93 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.OperationException;
94 import org.openecomp.sdc.be.model.operations.StorageException;
95 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
96 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
97 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
98 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
99 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
100 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
101 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
102 import org.openecomp.sdc.be.model.operations.impl.ArtifactTypeOperation;
103 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
104 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
105 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
106 import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
107 import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
108 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
109 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
110 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
111 import org.openecomp.sdc.be.tosca.CsarUtils;
112 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
113 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
114 import org.openecomp.sdc.be.user.Role;
115 import org.openecomp.sdc.be.user.UserBusinessLogic;
116 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
117 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
118 import org.openecomp.sdc.common.api.Constants;
119 import org.openecomp.sdc.common.impl.ExternalConfiguration;
120 import org.openecomp.sdc.common.impl.FSConfigurationSource;
121 import org.openecomp.sdc.common.util.GeneralUtility;
122 import org.openecomp.sdc.common.util.ValidationUtils;
123 import org.openecomp.sdc.common.zip.ZipUtils;
124 import org.openecomp.sdc.common.zip.exception.ZipException;
125 import org.openecomp.sdc.exception.ResponseFormat;
126 import org.springframework.web.context.WebApplicationContext;
128 import javax.servlet.ServletContext;
130 import java.io.IOException;
131 import java.lang.reflect.Method;
132 import java.net.URISyntaxException;
133 import java.util.ArrayList;
134 import java.util.Arrays;
135 import java.util.Collections;
136 import java.util.EnumMap;
137 import java.util.HashMap;
138 import java.util.List;
139 import java.util.Map;
140 import java.util.Map.Entry;
141 import java.util.Optional;
142 import java.util.stream.Collectors;
143 import java.util.stream.Stream;
145 import static org.assertj.core.api.Java6Assertions.assertThat;
146 import static org.junit.Assert.assertEquals;
147 import static org.junit.Assert.assertFalse;
148 import static org.junit.Assert.assertNotEquals;
149 import static org.junit.Assert.assertNotNull;
150 import static org.junit.Assert.assertThrows;
151 import static org.junit.Assert.assertTrue;
152 import static org.mockito.ArgumentMatchers.any;
153 import static org.mockito.ArgumentMatchers.anyList;
154 import static org.mockito.ArgumentMatchers.anyString;
155 import static org.mockito.ArgumentMatchers.eq;
156 import static org.mockito.Mockito.doAnswer;
157 import static org.mockito.Mockito.times;
158 import static org.mockito.Mockito.when;
160 public class ResourceBusinessLogicTest {
162 private final ConfigurationManager configurationManager = new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"));
163 private static final String RESOURCE_CATEGORY1 = "Network Layer 2-3";
164 private static final String RESOURCE_SUBCATEGORY = "Router";
166 private static final String UPDATED_SUBCATEGORY = "Gateway";
168 private static final String RESOURCE_NAME = "My-Resource_Name with space";
169 private static final String RESOURCE_TOSCA_NAME = "My-Resource_Tosca_Name";
170 private static final String GENERIC_ROOT_NAME = "tosca.nodes.Root";
171 private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
172 private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR";
173 private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
175 private final ServletContext servletContext = Mockito.mock(ServletContext.class);
176 IElementOperation mockElementDao;
177 private final JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class);
178 private final UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
179 private final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
180 private final NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
181 private final NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
182 private final TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
183 private final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
184 private final CatalogOperation catalogOperation = Mockito.mock(CatalogOperation.class);
185 private final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
186 private final PropertyOperation propertyOperation = Mockito.mock(PropertyOperation.class);
187 private final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class);
188 private final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
189 private final UserValidations userValidations = Mockito.mock(UserValidations.class);
190 private final WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
191 private final IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
192 private final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class);
193 private final IElementOperation elementDao = new ElementOperationMock();
195 private final CsarUtils csarUtils = Mockito.mock(CsarUtils.class);
196 private final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
197 private final IGroupOperation groupOperation = Mockito.mock(IGroupOperation.class);
198 private final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class);
199 private final IGroupTypeOperation groupTypeOperation = Mockito.mock(IGroupTypeOperation.class);
200 private final GroupBusinessLogic groupBusinessLogic = Mockito.mock(GroupBusinessLogic.class);
201 private final ModelBusinessLogic modelBusinessLogic = Mockito.mock(ModelBusinessLogic.class);
202 private final InterfaceOperation interfaceOperation = Mockito.mock(InterfaceOperation.class);
203 private final ArtifactsOperations artifactToscaOperation = Mockito.mock(ArtifactsOperations.class);
204 private final PropertyBusinessLogic propertyBusinessLogic = Mockito.mock(PropertyBusinessLogic.class);
205 private final ArtifactsResolver artifactsResolver = Mockito.mock(ArtifactsResolver.class);
206 private final InterfaceLifecycleOperation interfaceLifecycleTypeOperation = Mockito.mock(InterfaceLifecycleOperation.class);
207 private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class);
208 private final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
209 private final InputsBusinessLogic inputsBusinessLogic = Mockito.mock(InputsBusinessLogic.class);
210 private final OutputsBusinessLogic outputsBusinessLogic = Mockito.mock(OutputsBusinessLogic.class);
211 private final CompositionBusinessLogic compositionBusinessLogic = Mockito.mock(CompositionBusinessLogic.class);
212 private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic = Mockito.mock(ResourceDataMergeBusinessLogic.class);
213 private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic = Mockito.mock(CsarArtifactsAndGroupsBusinessLogic.class);
214 private final MergeInstanceUtils mergeInstanceUtils = Mockito.mock(MergeInstanceUtils.class);
215 private final UiComponentDataConverter uiComponentDataConverter = Mockito.mock(UiComponentDataConverter.class);
216 private final ToscaExportHandler toscaExportHandler = Mockito.mock(ToscaExportHandler.class);
217 private final PolicyTypeOperation policyTypeOperation = Mockito.mock(PolicyTypeOperation.class);
218 private final PolicyBusinessLogic policyBusinessLogic = Mockito.mock(PolicyBusinessLogic.class);
219 private final ArtifactTypeOperation artifactTypeOperation = Mockito.mock(ArtifactTypeOperation.class);
220 private final DataTypeBusinessLogic dataTypeBusinessLogic = Mockito.mock(DataTypeBusinessLogic.class);
221 private final PolicyTypeBusinessLogic policyTypeBusinessLogic = Mockito.mock(PolicyTypeBusinessLogic.class);
222 private final ModelOperation modelOperation = Mockito.mock(ModelOperation.class);
224 private YamlTemplateParsingHandler yamlTemplateParsingHandler = Mockito.mock(YamlTemplateParsingHandler.class);
226 ResponseFormatManager responseManager = null;
227 private final GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
229 Resource resourceResponse = null;
230 Resource genericVF = null;
231 Resource genericCR = null;
232 Resource genericVFC = null;
233 Resource genericPNF = null;
234 Resource rootType = null;
235 ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
236 ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(artifactCassandraDao, toscaExportHandler, csarUtils, lifecycleBl,
237 userBusinessLogic, artifactsResolver, elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
238 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation, artifactTypeOperation);
239 CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
241 CsarBusinessLogic csarBusinessLogic ;
242 Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
243 List<Resource> reslist;
244 private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
245 protected ComponentDescriptionValidator componentDescriptionValidator = new ComponentDescriptionValidator(componentsUtils);
246 protected ComponentProjectCodeValidator componentProjectCodeValidator = new ComponentProjectCodeValidator(componentsUtils);
247 protected ComponentIconValidator componentIconValidator = new ComponentIconValidator(componentsUtils);
248 protected ComponentContactIdValidator componentContactIdValidator = new ComponentContactIdValidator(componentsUtils);
249 protected ComponentTagsValidator componentTagsValidator = new ComponentTagsValidator(componentsUtils);
250 protected ComponentNameValidator componentNameValidator = new ComponentNameValidator(componentsUtils, toscaOperationFacade);
251 private ComponentValidator componentValidator = createComponentValidator();
252 private SoftwareInformationBusinessLogic softwareInformationBusinessLogic = Mockito.mock(SoftwareInformationBusinessLogic.class);
254 private ComponentValidator createComponentValidator() {
255 List<ComponentFieldValidator> componentFieldValidators = Arrays.asList(componentNameValidator,
256 componentDescriptionValidator, componentProjectCodeValidator,
257 componentIconValidator, componentContactIdValidator,
258 componentTagsValidator);
259 return new ComponentValidator(componentsUtils,componentFieldValidators);
262 ResourceBusinessLogic bl;
265 public void setup() {
266 MockitoAnnotations.openMocks(this);
267 Mockito.reset(propertyOperation);
270 mockElementDao = new ElementOperationMock();
273 // User data and management
275 user.setUserId("jh0003");
276 user.setFirstName("Jimmi");
277 user.setLastName("Hendrix");
278 user.setRole(Role.ADMIN.name());
280 when(mockUserAdmin.getUser("jh0003", false)).thenReturn(user);
281 when(userValidations.validateUserExists(user.getUserId())).thenReturn(user);
282 when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
283 // Servlet Context attributes
284 when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
285 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
286 .thenReturn(webAppContextWrapper);
287 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
288 when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
290 Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true);
291 when(toscaOperationFacade.validateComponentNameExists("tosca.nodes.Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
292 .thenReturn(eitherFalse);
295 Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
296 when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC,
297 ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist);
299 Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
300 when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class),
301 eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount);
302 Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
303 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
305 Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false);
306 when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
307 when(graphLockOperation.lockComponent(anyString(), eq(NodeTypeEnum.Resource)))
308 .thenReturn(StorageOperationStatus.OK);
309 when(graphLockOperation.lockComponentByName(anyString(), eq(NodeTypeEnum.Resource)))
310 .thenReturn(StorageOperationStatus.OK);
313 resourceResponse = createResourceObject(true);
314 Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
315 when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
316 when(catalogOperation.updateCatalog(Mockito.any(), Mockito.any())).thenReturn(ActionStatus.OK);
317 Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
318 when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(emptyDataTypes));
319 when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
320 when(policyTypeOperation.getLatestPolicyTypeByType(any(String.class), any(String.class)))
321 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
323 artifactManager.setNodeTemplateOperation(nodeTemplateOperation);
324 bl = new ResourceBusinessLogic(mockElementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
325 interfaceOperation, interfaceLifecycleTypeOperation, artifactManager, componentInstanceBusinessLogic,
326 resourceImportManager, inputsBusinessLogic, outputsBusinessLogic, compositionBusinessLogic, resourceDataMergeBusinessLogic,
327 csarArtifactsAndGroupsBusinessLogic, mergeInstanceUtils, uiComponentDataConverter, csarBusinessLogic,
328 artifactToscaOperation, propertyBusinessLogic, componentContactIdValidator, componentNameValidator,
329 componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator,
330 componentDescriptionValidator, policyBusinessLogic, modelBusinessLogic, dataTypeBusinessLogic, policyTypeBusinessLogic, modelOperation);
331 bl.setElementDao(mockElementDao);
332 bl.setUserAdmin(mockUserAdmin);
333 bl.setCapabilityTypeOperation(capabilityTypeOperation);
334 bl.setComponentsUtils(componentsUtils);
335 bl.setLifecycleManager(lifecycleBl);
336 bl.setArtifactsManager(artifactManager);
337 bl.setGraphLockOperation(graphLockOperation);
338 bl.setPropertyOperation(propertyOperation);
339 bl.setJanusGraphDao(mockJanusGraphDao);
340 bl.setApplicationDataTypeCache(applicationDataTypeCache);
341 bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
342 bl.setCatalogOperations(catalogOperation);
343 toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
344 csarBusinessLogic.setComponentsUtils(componentsUtils);
345 toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
346 bl.setToscaOperationFacade(toscaOperationFacade);
347 bl.setUserValidations(userValidations);
348 bl.setInterfaceTypeOperation(interfaceTypeOperation);
349 bl.setPolicyTypeOperation(policyTypeOperation);
351 csarBusinessLogic.setCsarOperation(csarOperation);
352 Resource resourceCsar = createResourceObjectCsar(true);
353 setCanWorkOnResource(resourceCsar);
354 Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
355 when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
356 responseManager = ResponseFormatManager.getInstance();
357 bl.setComponentIconValidator(componentIconValidator);
358 bl.setComponentNameValidator(componentNameValidator);
359 bl.setComponentDescriptionValidator(componentDescriptionValidator);
360 bl.setComponentTagsValidator(componentTagsValidator);
361 bl.setComponentContactIdValidator(componentContactIdValidator);
362 bl.setComponentProjectCodeValidator(componentProjectCodeValidator);
363 bl.setComponentValidator(componentValidator);
364 reslist = new ArrayList<>();
365 reslist.add(resourceResponse);
366 reslist.add(genericVF);
367 reslist.add(genericCR);
368 reslist.add(genericVFC);
369 reslist.add(genericPNF);
370 Either<List<Resource>, StorageOperationStatus> returneval= Either.left(reslist);
371 when(toscaOperationFacade.getAllCertifiedResources(true, true)).thenReturn(returneval);
372 when(toscaOperationFacade.validateComponentNameUniqueness("Resource", ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(true));
373 Either<List<Resource>, StorageOperationStatus> returnevalexception= Either.right(StorageOperationStatus.BAD_REQUEST);
374 when(toscaOperationFacade.getAllCertifiedResources(false, false)).thenReturn(returnevalexception);
377 @Test(expected = ComponentException.class)
378 public void createResourcesFromYamlNodeTypesList() throws IOException {
379 Map<String, Object> mappedToscaTemplate = new HashMap<>();
380 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
381 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
382 Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
383 bl.createResourcesFromYamlNodeTypesList(
388 nodeTypesArtifactsToHandle,
389 nodeTypesNewCreatedArtifacts,
391 new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"),true), "");
395 public void handleNodeTypeArtifactsTest() {
396 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = new HashMap<>();
397 List<ArtifactDefinition> defs = new ArrayList<>();
398 defs.add(new ArtifactDefinition());
399 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, defs);
400 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, defs);
401 assertTrue(bl.handleNodeTypeArtifacts(resourceResponse, nodeTypeArtifactsToHandle, new ArrayList<>(), user, true, true).isRight());
405 public void getUiComponentDataTransferByComponentIdTest() {
406 when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(genericCR));
407 assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isLeft());
408 when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.right(StorageOperationStatus.OK));
409 assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isRight());
413 public void shouldUpgradeToLatestDerivedTest() {
416 when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericCR)).thenReturn(Either.left(genericCR));
417 when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericVFC)).thenReturn(Either.right(StorageOperationStatus.OK));
418 assertTrue(bl.shouldUpgradeToLatestDerived(genericVF).isLeft());
419 assertTrue(bl.shouldUpgradeToLatestDerived(genericCR).isLeft());
422 private Resource createResourceObject(boolean afterCreate) {
423 Resource resource = new Resource();
424 resource.setName(RESOURCE_NAME);
425 resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
426 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
427 resource.setDescription("My short description");
428 List<String> tgs = new ArrayList<>();
430 tgs.add(resource.getName());
431 resource.setTags(tgs);
432 List<String> template = new ArrayList<>();
433 template.add("tosca.nodes.Root");
434 resource.setDerivedFrom(template);
435 resource.setVendorName("Motorola");
436 resource.setVendorRelease("1.0.0");
437 resource.setContactId("ya5467");
438 resource.setIcon("defaulticon");
441 resource.setName(resource.getName());
442 resource.setVersion("0.1");
443 resource.setUniqueId(resource.getName()
444 .toLowerCase() + ":" + resource.getVersion());
445 resource.setCreatorUserId(user.getUserId());
446 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
447 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
452 private Resource createResourceObjectWithModel(boolean afterCreate) {
453 Resource resource = new Resource();
454 resource.setName(RESOURCE_NAME);
455 resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
456 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
457 resource.setDescription("My short description");
458 List<String> tgs = new ArrayList<>();
460 tgs.add(resource.getName());
461 resource.setTags(tgs);
462 List<String> template = new ArrayList<>();
463 template.add("tosca.nodes.Root");
464 resource.setDerivedFrom(template);
465 resource.setVendorName("Motorola");
466 resource.setVendorRelease("1.0.0");
467 resource.setContactId("ya5467");
468 resource.setIcon("defaulticon");
469 resource.setModel("Test Model");
472 resource.setName(resource.getName());
473 resource.setVersion("0.1");
474 resource.setUniqueId(resource.getName()
475 .toLowerCase() + ":" + resource.getVersion());
476 resource.setCreatorUserId(user.getUserId());
477 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
478 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
483 private Resource createResourceObjectCsar(boolean afterCreate) {
484 Resource resource = new Resource();
485 resource.setName(RESOURCE_NAME);
486 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
487 resource.setDescription("My short description");
488 List<String> tgs = new ArrayList<>();
490 tgs.add(resource.getName());
491 resource.setTags(tgs);
492 List<String> template = new ArrayList<>();
493 template.add("tosca.nodes.Root");
494 resource.setDerivedFrom(template);
495 resource.setVendorName("Motorola");
496 resource.setVendorRelease("1.0.0");
497 resource.setResourceVendorModelNumber("");
498 resource.setContactId("ya5467");
499 resource.setIcon("MyIcon");
500 resource.setCsarUUID("valid_vf.csar");
501 resource.setCsarVersion("1");
504 resource.setName(resource.getName());
505 resource.setVersion("0.1");
507 resource.setUniqueId(resource.getName()
508 .toLowerCase() + ":" + resource.getVersion());
509 resource.setCreatorUserId(user.getUserId());
510 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
511 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
516 private Resource setCanWorkOnResource(Resource resource) {
517 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
518 resource.setLastUpdaterUserId(user.getUserId());
523 public void testHappyScenario() {
524 validateUserRoles(Role.ADMIN, Role.DESIGNER);
525 Resource resource = createResourceObject(false);
526 Resource createdResource = null;
528 when(toscaOperationFacade
529 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
530 .thenReturn(Either.left(false));
531 createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
532 assertThat(createResourceObject(true)).isEqualTo(createdResource);
533 } catch (ComponentException e) {
534 assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
540 public void testUpdateHappyScenario() {
541 Resource resource = createResourceObjectCsar(true);
542 setCanWorkOnResource(resource);
543 validateUserRoles(Role.ADMIN, Role.DESIGNER);
544 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource);
545 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes);
546 Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
547 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
548 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
549 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
550 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
551 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
553 assertThat(resource.getUniqueId()).isEqualTo(bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()).getUniqueId());
554 } catch (ComponentException e) {
555 assertThat(e.getResponseFormat().getStatus()).isEqualTo(200);
560 public void testUpdateUnhappyScenario() {
561 Resource resource = createResourceObjectCsar(true);
562 final var csarVersionId = "csarVersionId";
563 resource.setCsarVersionId(csarVersionId);
565 final var vendorSoftwareProduct = new VendorSoftwareProduct();
566 vendorSoftwareProduct.setFileMap(new HashMap<>());
567 vendorSoftwareProduct.setModelList(Collections.emptyList());
568 setCanWorkOnResource(resource);
569 validateUserRoles(Role.ADMIN, Role.DESIGNER);
571 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(Either.left(resource));
572 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(Either.left(true));
573 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(Either.left(setCanWorkOnResource(resource)));
574 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(Either.left(resource));
575 when(csarOperation.findVsp("valid_vf.csar", csarVersionId, user)).thenReturn(Optional.of(vendorSoftwareProduct));
578 Resource createdResource = bl.validateAndUpdateResourceFromCsar(resource, user, null, "", resource.getUniqueId());
579 assertThat(resource.getUniqueId()).isEqualTo(createdResource.getUniqueId());
580 } catch (ComponentException e) {
581 assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
584 resource.setCsarVersion("2");
585 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(Either.left(resource));
586 bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId());
587 } catch (ComponentException e) {
588 assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
591 /* CREATE validations - start ***********************/
592 // Resource name - start
595 public void testFailedResourceValidations() {
596 testResourceNameExist();
597 testResourceNameEmpty();
598 // testResourceNameExceedsLimit();
599 testResourceNameWrongFormat();
600 testResourceDescExceedsLimitCreate();
601 testResourceDescNotEnglish();
602 testResourceDescriptionEmpty();
603 testResourceDescriptionMissing();
604 testResourceIconMissing();
605 testResourceIconInvalid();
606 testResourceIconExceedsLimit();
607 testResourceTagNotExist();
608 testResourceTagEmpty();
609 testTagsExceedsLimitCreate();
610 testTagsNoServiceName();
613 testContactIdTooLong();
614 testContactIdWrongFormatCreate();
615 testResourceContactIdEmpty();
616 testResourceContactIdMissing();
617 testVendorNameExceedsLimit();
618 testVendorNameWrongFormatCreate();
619 testVendorReleaseWrongFormat();
620 testVendorReleaseExceedsLimitCreate();
621 testResourceVendorModelNumberExceedsLimit();
622 testResourceVendorNameMissing();
623 testResourceVendorReleaseMissing();
624 testResourceCategoryExist();
625 testResourceBadCategoryCreate();
626 testHappyScenarioCostLicenseType();
627 testCostWrongFormatCreate();
628 testLicenseTypeWrongFormatCreate();
629 testResourceTemplateNotExist();
630 testResourceTemplateEmpty();
631 testResourceTemplateInvalid();
634 private void testResourceNameExist() {
635 String resourceName = "alreadyExists";
636 Resource resourceExist = createResourceObject(false);
637 resourceExist.setName(resourceName);
638 resourceExist.getTags()
640 validateUserRoles(Role.ADMIN, Role.DESIGNER);
641 when(toscaOperationFacade
642 .validateComponentNameAndModelExists(resourceName, null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
643 .thenReturn(Either.left(true));
645 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
646 } catch (ComponentException e) {
647 assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
648 ComponentTypeEnum.RESOURCE.getValue(), resourceName);
652 private void testResourceNameEmpty() {
653 Resource resourceExist = createResourceObject(false);
654 resourceExist.setName(null);
657 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
658 } catch (ComponentException e) {
659 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
663 private void testResourceNameExceedsLimit() {
664 Resource resourceExccedsNameLimit = createResourceObject(false);
665 // 51 chars, the limit is 50
666 String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
667 resourceExccedsNameLimit.setName(tooLongResourceName);
670 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
671 } catch (ComponentException e) {
672 assertComponentException(e, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT,
673 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
677 private void testResourceNameWrongFormat() {
678 Resource resource = createResourceObject(false);
680 String nameWrongFormat = "ljg?fd";
681 resource.setName(nameWrongFormat);
684 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
685 } catch (ComponentException e) {
686 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
690 // Resource name - end
691 // Resource description - start
692 private void testResourceDescExceedsLimitCreate() {
693 Resource resourceExccedsDescLimit = createResourceObject(false);
694 // 1025 chars, the limit is 1024
695 String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
696 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
697 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
698 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
699 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
700 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
701 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
702 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
704 resourceExccedsDescLimit.setDescription(tooLongResourceDesc);
706 bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
707 } catch (ComponentException e) {
708 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
709 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
713 private void testResourceDescNotEnglish() {
714 Resource notEnglish = createResourceObject(false);
716 String notEnglishDesc = "\uC2B5";
717 notEnglish.setDescription(notEnglishDesc);
720 bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
721 } catch (ComponentException e) {
722 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION,
723 ComponentTypeEnum.RESOURCE.getValue());
727 private void testResourceDescriptionEmpty() {
728 Resource resourceExist = createResourceObject(false);
729 resourceExist.setDescription("");
732 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
733 } catch (ComponentException e) {
734 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
735 ComponentTypeEnum.RESOURCE.getValue());
739 private void testResourceDescriptionMissing() {
740 Resource resourceExist = createResourceObject(false);
741 resourceExist.setDescription(null);
744 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
745 } catch (ComponentException e) {
746 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
747 ComponentTypeEnum.RESOURCE.getValue());
750 // Resource description - end
751 // Resource icon start
753 private void testResourceIconMissing() {
754 Resource resourceExist = createResourceObject(false);
755 resourceExist.setIcon(null);
756 when(toscaOperationFacade
757 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
758 .thenReturn(Either.left(false));
760 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
761 } catch (ComponentException e) {
762 assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
766 private void testResourceIconInvalid() {
767 Resource resourceExist = createResourceObject(false);
768 resourceExist.setIcon("kjk3453^&");
771 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
772 } catch (ComponentException e) {
773 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
777 private void testResourceIconExceedsLimit() {
778 Resource resourceExist = createResourceObject(false);
779 resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
781 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
782 } catch (ComponentException e) {
783 assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT,
784 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
789 // Resource tags - start
790 private void testResourceTagNotExist() {
791 Resource resourceExist = createResourceObject(false);
792 resourceExist.setTags(null);
794 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
795 } catch (ComponentException e) {
796 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
800 private void testResourceTagEmpty() {
801 Resource resourceExist = createResourceObject(false);
802 resourceExist.setTags(new ArrayList<>());
804 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
805 } catch (ComponentException e) {
806 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
810 private void testTagsExceedsLimitCreate() {
811 Resource resourceExccedsNameLimit = createResourceObject(false);
812 String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
813 String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
814 String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
815 String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
816 String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
817 String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
818 String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
819 String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
820 String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
821 String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
822 String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
823 String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
824 String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
825 String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
826 String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
827 String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
828 String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
829 String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
830 String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
831 String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
832 String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
834 List<String> tagsList = new ArrayList<>();
856 tagsList.add(resourceExccedsNameLimit.getName());
858 resourceExccedsNameLimit.setTags(tagsList);
860 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
861 } catch (ComponentException e) {
862 assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
863 "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
867 private void testTagsSingleExceedsLimit() {
868 Resource resourceExccedsNameLimit = createResourceObject(false);
869 String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI";
870 String tag2 = resourceExccedsNameLimit.getName();
871 List<String> tagsList = new ArrayList<>();
875 resourceExccedsNameLimit.setTags(tagsList);
877 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
878 } catch (ComponentException e) {
879 assertComponentException(e, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT,
880 "" + ValidationUtils.TAG_MAX_LENGTH);
884 private void testTagsNoServiceName() {
885 Resource serviceExccedsNameLimit = createResourceObject(false);
886 String tag1 = "afzs2qLBb";
887 List<String> tagsList = new ArrayList<>();
889 serviceExccedsNameLimit.setTags(tagsList);
891 bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
892 } catch (ComponentException e) {
893 assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
897 private void testInvalidTag() {
898 Resource serviceExccedsNameLimit = createResourceObject(false);
899 String tag1 = "afzs2qLBb%#%";
900 List<String> tagsList = new ArrayList<>();
902 serviceExccedsNameLimit.setTags(tagsList);
904 bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
905 } catch (ComponentException e) {
906 assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Resource", "tag" });
910 // Resource tags - stop
911 // Resource contact start
913 private void testContactIdTooLong() {
914 Resource resourceContactId = createResourceObject(false);
915 // 59 chars instead of 50
916 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
917 resourceContactId.setContactId(contactIdTooLong);
920 bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
921 } catch (ComponentException e) {
922 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
926 private void testContactIdWrongFormatCreate() {
927 Resource resourceContactId = createResourceObject(false);
928 // 3 letters and 3 digits and special characters
929 String contactIdFormatWrong = "yrt134!!!";
930 resourceContactId.setContactId(contactIdFormatWrong);
932 bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
933 } catch (ComponentException e) {
934 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
938 private void testResourceContactIdEmpty() {
939 Resource resourceExist = createResourceObject(false);
940 resourceExist.setContactId("");
942 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
943 } catch (ComponentException e) {
944 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
948 private void testResourceContactIdMissing() {
949 Resource resourceExist = createResourceObject(false);
950 resourceExist.setContactId(null);
952 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
953 } catch (ComponentException e) {
954 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
958 private void testVendorNameExceedsLimit() {
959 Resource resourceExccedsVendorNameLimit = createResourceObject(false);
960 String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
961 resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
963 bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
964 } catch (ComponentException e) {
965 assertComponentException(e, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
966 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
970 private void testResourceVendorModelNumberExceedsLimit() {
971 Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
972 String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
973 resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
975 bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null,
977 } catch (ComponentException e) {
978 assertComponentException(e, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
979 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
983 private void testVendorNameWrongFormatCreate() {
984 Resource resource = createResourceObject(false);
986 String nameWrongFormat = "ljg*fd";
987 resource.setVendorName(nameWrongFormat);
989 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
990 } catch (ComponentException e) {
991 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
995 private void testVendorReleaseWrongFormat() {
996 Resource resource = createResourceObject(false);
998 String vendorReleaseWrongFormat = "1>2";
999 resource.setVendorRelease(vendorReleaseWrongFormat);
1001 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1002 } catch (ComponentException e) {
1003 assertComponentException(e, ActionStatus.INVALID_VENDOR_RELEASE, vendorReleaseWrongFormat);
1007 private void testVendorReleaseExceedsLimitCreate() {
1008 Resource resourceExccedsNameLimit = createResourceObject(false);
1009 String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
1010 resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
1012 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1013 } catch (ComponentException e) {
1014 assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
1015 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
1019 private void testResourceVendorNameMissing() {
1020 Resource resourceExist = createResourceObject(false);
1021 resourceExist.setVendorName(null);
1023 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1024 } catch (ComponentException e) {
1025 assertComponentException(e, ActionStatus.MISSING_VENDOR_NAME);
1029 private void testResourceVendorReleaseMissing() {
1030 Resource resourceExist = createResourceObject(false);
1031 resourceExist.setVendorRelease(null);
1033 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1034 } catch (ComponentException e) {
1035 assertComponentException(e, ActionStatus.MISSING_VENDOR_RELEASE);
1039 // Resource vendor name/release stop
1041 private void testResourceCategoryExist() {
1042 Resource resourceExist = createResourceObject(false);
1043 resourceExist.setCategories(null);
1045 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1046 } catch (ComponentException e) {
1047 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1051 private void testResourceBadCategoryCreate() {
1053 Resource resourceExist = createResourceObject(false);
1054 resourceExist.setCategories(null);
1055 resourceExist.addCategory("koko", "koko");
1057 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1058 } catch (ComponentException e) {
1059 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1065 private void testHappyScenarioCostLicenseType() {
1066 Resource createResourceObject = createResourceObject(false);
1067 Resource createResourceObjectAfterCreate = createResourceObject(true);
1068 // Adding cost and licenseType to basic mock
1069 Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate);
1070 when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
1072 String cost = "123.456";
1073 String licenseType = "User";
1074 createResourceObject.setCost(cost);
1075 createResourceObject.setLicenseType(licenseType);
1076 Resource createdResource;
1078 createdResource = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null,
1080 createResourceObjectAfterCreate.setCost(cost);
1081 createResourceObjectAfterCreate.setLicenseType(licenseType);
1082 assertThat(createResourceObjectAfterCreate).isEqualTo(createdResource);
1083 } catch (ComponentException e) {
1084 assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
1089 private void testCostWrongFormatCreate() {
1090 Resource resourceCost = createResourceObject(false);
1091 // Comma instead of fullstop
1092 String cost = "12356,464";
1093 resourceCost.setCost(cost);
1095 bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1096 } catch (ComponentException e) {
1097 assertComponentException(e, ActionStatus.INVALID_CONTENT);
1102 // License type start
1103 private void testLicenseTypeWrongFormatCreate() {
1104 Resource resourceLicenseType = createResourceObject(false);
1106 String licenseType = "cpu";
1107 resourceLicenseType.setLicenseType(licenseType);
1109 bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1110 } catch (ComponentException e) {
1111 assertComponentException(e, ActionStatus.INVALID_CONTENT);
1115 // License type stop
1116 // Derived from start
1117 private void testResourceTemplateNotExist() {
1118 Resource resourceExist = createResourceObject(false);
1119 List<String> list = null;
1120 resourceExist.setDerivedFrom(list);
1122 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1123 } catch (ComponentException e) {
1124 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1128 private void testResourceTemplateEmpty() {
1129 Resource resourceExist = createResourceObject(false);
1130 resourceExist.setDerivedFrom(new ArrayList<>());
1132 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1133 } catch (ComponentException e) {
1134 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1138 private void testResourceTemplateInvalid() {
1139 Resource resourceExist = createResourceObject(false);
1140 ArrayList<String> derivedFrom = new ArrayList<>();
1141 derivedFrom.add("kuku");
1142 resourceExist.setDerivedFrom(derivedFrom);
1144 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1145 } catch (ComponentException e) {
1146 assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
1150 // Derived from stop
1151 private void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) {
1152 ResponseFormat actualResponse = e.getResponseFormat() != null ? e.getResponseFormat()
1153 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1154 assertResponse(actualResponse, expectedStatus, variables);
1157 private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
1158 ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
1159 assertThat(expectedResponse.getStatus()).isEqualTo(actualResponse.getStatus());
1160 assertThat(expectedResponse.getFormattedMessage()).isEqualTo(actualResponse.getFormattedMessage());
1163 private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus,
1164 String... variables) {
1165 assertResponse(createResponse.right()
1166 .value(), expectedStatus, variables);
1169 // UPDATE tests - start
1172 public void testResourceNameWrongFormat_UPDATE() {
1173 Resource resource = createResourceObject(true);
1174 Resource updatedResource = createResourceObject(true);
1176 // this is in order to prevent failing with 403 earlier
1177 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1178 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1180 String nameWrongFormat = "ljg*fd";
1181 updatedResource.setName(nameWrongFormat);
1183 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1184 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1186 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1187 } catch (ComponentException e) {
1188 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
1193 public void testResourceNameAfterCertify_UPDATE() {
1194 Resource resource = createResourceObject(true);
1195 Resource updatedResource = createResourceObject(true);
1197 // this is in order to prevent failing with 403 earlier
1198 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1199 // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
1200 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1202 String name = "ljg";
1203 updatedResource.setName(name);
1204 resource.setVersion("1.0");
1206 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1207 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1209 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1210 } catch (ComponentException e) {
1211 assertComponentException(e, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1216 public void testResourceNameAlreadyExist_UPDATE() {
1217 Resource resource = createResourceObject(true);
1218 Resource updatedResource = createResourceObject(true);
1220 // this is in order to prevent failing with 403 earlier
1221 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1222 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1224 String resourceName = "alreadyExists";
1225 updatedResource.setName(resourceName);
1226 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
1227 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1229 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1230 } catch (ComponentException e) {
1231 assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
1232 ComponentTypeEnum.RESOURCE.getValue(), resourceName);
1239 public void testResourceDescExceedsLimit_UPDATE() {
1240 Resource resource = createResourceObject(true);
1241 Resource updatedResource = createResourceObject(true);
1243 // this is in order to prevent failing with 403 earlier
1244 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1245 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1247 // 1025 chars, the limit is 1024
1248 String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
1249 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
1250 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
1251 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
1252 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
1253 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
1254 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
1255 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
1256 updatedResource.setDescription(tooLongResourceDesc);
1257 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1258 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1260 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1261 } catch (ComponentException e) {
1262 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
1263 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
1268 public void testIconWrongFormat_UPDATE() {
1269 Resource resource = createResourceObject(true);
1270 Resource updatedResource = createResourceObject(true);
1272 // this is in order to prevent failing with 403 earlier
1273 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1274 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1277 String icon = "icon.jpg";
1278 updatedResource.setIcon(icon);
1279 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1280 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1282 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1283 } catch (ComponentException e) {
1284 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
1289 public void testIconAfterCertify_UPDATE() {
1290 Resource resource = createResourceObject(true);
1291 Resource updatedResource = createResourceObject(true);
1293 // this is in order to prevent failing with 403 earlier
1294 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1295 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1298 String icon = "icon";
1299 updatedResource.setIcon(icon);
1301 resource.setVersion("1.0");
1303 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1304 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1306 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1307 } catch (ComponentException e) {
1308 assertComponentException(e, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
1313 public void testTagsExceedsLimit_UPDATE() {
1314 Resource resource = createResourceObject(true);
1315 Resource updatedResource = createResourceObject(true);
1317 // this is in order to prevent failing with 403 earlier
1318 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1319 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1321 String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
1322 String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
1323 String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
1324 String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
1325 String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
1326 String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
1327 String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
1328 String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
1329 String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
1330 String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
1331 String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
1332 String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
1333 String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
1334 String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
1335 String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
1336 String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
1337 String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
1338 String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
1339 String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
1340 String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
1341 String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
1343 List<String> tagsList = new ArrayList<>();
1353 tagsList.add(tag10);
1354 tagsList.add(tag11);
1355 tagsList.add(tag12);
1356 tagsList.add(tag13);
1357 tagsList.add(tag14);
1358 tagsList.add(tag15);
1359 tagsList.add(tag16);
1360 tagsList.add(tag17);
1361 tagsList.add(tag18);
1362 tagsList.add(tag19);
1363 tagsList.add(tag20);
1364 tagsList.add(tag21);
1365 tagsList.add(resource.getName());
1367 updatedResource.setTags(tagsList);
1368 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1369 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1371 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1372 } catch (ComponentException e) {
1373 assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
1374 "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
1379 public void testVendorNameWrongFormat_UPDATE() {
1380 Resource resource = createResourceObject(true);
1381 Resource updatedResource = createResourceObject(true);
1383 // this is in order to prevent failing with 403 earlier
1384 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1385 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1388 String nameWrongFormat = "ljg*fd";
1389 updatedResource.setVendorName(nameWrongFormat);
1390 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1391 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1393 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1394 } catch (ComponentException e) {
1395 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
1400 public void testVendorNameWrongFormat() {
1401 Resource resource = createResourceObject(true);
1402 Resource updatedResource = createResourceObject(true);
1404 // this is in order to prevent failing with 403 earlier
1405 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1406 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1409 String nameWrongFormat = "ljg*fd";
1410 updatedResource.setVendorName(nameWrongFormat);
1411 resource.setVersion("1.0");
1413 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1414 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1416 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1417 } catch (ComponentException e) {
1418 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
1423 public void testVendorReleaseExceedsLimit_UPDATE() {
1424 Resource resource = createResourceObject(true);
1425 Resource updatedResource = createResourceObject(true);
1427 // this is in order to prevent failing with 403 earlier
1428 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1429 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1430 // 129 chars, the limit is 128
1431 String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy";
1432 updatedResource.setVendorRelease(tooLongVendorRelease);
1433 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1434 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1436 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1437 } catch (ComponentException e) {
1438 assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
1439 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
1444 public void testResourceBadCategory_UPDATE() {
1445 Resource resource = createResourceObject(true);
1446 Resource updatedResource = createResourceObject(true);
1448 // this is in order to prevent failing with 403 earlier
1449 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1450 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1452 String resourceId = resource.getUniqueId();
1453 String badCategory = "ddfds";
1454 updatedResource.setCategories(null);
1455 updatedResource.addCategory(badCategory, "fikt");
1456 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1457 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1459 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1460 } catch (ComponentException e) {
1461 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1465 @Test(expected = ComponentException.class)
1466 public void createResourceFromCsarTest() {
1467 bl.createResourceFromCsar(resourceResponse, user, new HashMap<>(), "");
1471 public void testCreateResourceFromCsarWithModel() throws URISyntaxException, ZipException {
1473 final File csarFile = new File(
1474 ResourceBusinessLogicTest.class.getClassLoader().getResource("csars/nonOnapCsar.csar").toURI());
1475 final Map<String, byte[]> csar = ZipUtils.readZip(csarFile, false);
1477 String resourceYml = new String(csar.get("Definitions/my_vnf.yaml"));
1479 YamlTemplateParsingHandler yamlTemplateParser = new YamlTemplateParsingHandler(mockJanusGraphDao, null, Mockito.mock(AnnotationBusinessLogic.class), null);
1480 final ParsedToscaYamlInfo parsedToscaYamlInfo = yamlTemplateParser.parseResourceInfoFromYAML("Definitions/my_vnf.yml", resourceYml, Collections.EMPTY_MAP, Collections.EMPTY_MAP, "myVnf", resourceResponse, "");
1482 when(propertyOperation.getDataTypeByName("tosca.datatypes.testDataType.FromMainTemplate", "testModel")).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1484 when(toscaOperationFacade.getLatestByToscaResourceName(anyString(), any())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1485 Resource vduCp = new Resource();
1486 vduCp.setToscaResourceName("tosca.nodes.nfv.VduCp");
1487 vduCp.setState(LifecycleStateEnum.CERTIFIED);
1488 vduCp.setUniqueId("tosca.nodes.nfv.VduCp");
1489 vduCp.setProperties(new ArrayList<>());
1490 Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
1491 RequirementDefinition req = new RequirementDefinition();
1492 req.setName("virtual_link");
1493 List<RequirementDefinition> listReqs = new ArrayList<>();
1495 requirements.put("tosca.nodes.nfv.VduCp", listReqs);
1496 vduCp.setRequirements(requirements);
1497 PropertyDefinition bitrateProp = new PropertyDefinition();
1498 bitrateProp.setName("bitrate_requirement");
1499 bitrateProp.setType("integer");
1500 vduCp.getProperties().add(bitrateProp);
1501 PropertyDefinition virtNiProp = new PropertyDefinition();
1502 virtNiProp.setName("virtual_network_interface_requirements");
1503 virtNiProp.setType("list");
1504 vduCp.getProperties().add(virtNiProp);
1505 PropertyDefinition descriptionProp = new PropertyDefinition();
1506 descriptionProp.setName("description");
1507 descriptionProp.setType("string");
1508 vduCp.getProperties().add(descriptionProp);
1509 PropertyDefinition roleProp = new PropertyDefinition();
1510 roleProp.setName("role");
1511 roleProp.setType("string");
1512 vduCp.getProperties().add(roleProp);
1513 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel("tosca.nodes.nfv.VduCp", "testModel_myVnf1.0")).thenReturn(Either.left(vduCp));
1515 when(yamlTemplateParsingHandler.parseResourceInfoFromYAML(any(), any(), any(), any(), any(), any(), any())).thenReturn(parsedToscaYamlInfo);
1517 UploadComponentInstanceInfo uploadComponentInstanceInfo = new UploadComponentInstanceInfo();
1518 uploadComponentInstanceInfo.setType("myType");
1519 resourceResponse.setUniqueId("myVnf");
1520 resourceResponse.setName("myVnf");
1521 resourceResponse.setSystemName("myVnf");
1522 resourceResponse.setModel("testModel");
1523 resourceResponse.setResourceType(ResourceTypeEnum.VF);
1524 resourceResponse.setProperties(new ArrayList<>());
1525 resourceResponse.setCsarVersion("1.0");
1527 Resource derivedFrom = new Resource();
1528 List<PropertyDefinition> properties = new ArrayList<>();
1529 PropertyDefinition baseTypeProp = new PropertyDefinition();
1530 baseTypeProp.setName("propInBase");
1531 baseTypeProp.setType("string");
1532 properties.add(baseTypeProp);
1533 derivedFrom.setProperties(properties );
1534 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(any(), eq("tosca.nodes.nfv.VNF"))).thenReturn(Either.left(derivedFrom));
1536 when(toscaOperationFacade
1537 .validateComponentNameAndModelExists("myVnf", "testModel_myVnf1.0", ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(false));
1539 when(toscaOperationFacade.addPropertyToComponent(any(), any(), any())).thenReturn(Either.left(new PropertyDefinition()));
1540 when(toscaOperationFacade.associateComponentInstancePropertiesToComponent(any(), any())).thenReturn(Either.left(Collections.emptyMap()));
1541 when(toscaOperationFacade.associateArtifactsToInstances(any(), any())).thenReturn(StorageOperationStatus.OK);
1542 when(toscaOperationFacade.associateDeploymentArtifactsToInstances(any(), any(), any())).thenReturn(StorageOperationStatus.OK);
1543 when(toscaOperationFacade.associateInstAttributeToComponentToInstances(any(), any())).thenReturn(StorageOperationStatus.OK);
1544 when(toscaOperationFacade.associateResourceInstances(any(Component.class), anyString(), anyList())).thenReturn(Either.left(Collections.EMPTY_LIST));
1545 when(applicationDataTypeCache.getAll("testModel_myVnf1.0")).thenReturn(Either.left(emptyDataTypes));
1547 doAnswer(invocation -> {
1548 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReqs = invocation.getArgument(1);
1549 for (final Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> m: instReqs.entrySet()) {
1550 m.getKey().setRequirements(m.getValue());
1552 return StorageOperationStatus.OK;
1554 when(toscaOperationFacade).associateOrAddCalculatedCapReq(any(), any(), any());
1556 when(toscaOperationFacade.updateCalculatedCapabilitiesRequirements(any(), any(), any())).thenReturn(StorageOperationStatus.OK);
1557 when(groupBusinessLogic.validateUpdateVfGroupNames(any(), any())).thenReturn(Either.left(Collections.EMPTY_MAP));
1559 ComponentInstance ci = new ComponentInstance();
1560 List<ComponentInstance> cis = new ArrayList<>();
1562 doAnswer(invocation -> {
1563 List<ComponentInstance> componentInstances = new ArrayList<ComponentInstance>(((Map<ComponentInstance, Resource>)invocation.getArgument(1)).keySet());
1564 ((Resource)invocation.getArgument(0)).setComponentInstances(componentInstances);
1566 }).when(toscaOperationFacade).associateComponentInstancesToComponent(any(), any(), eq(false), eq(false));
1568 doAnswer(invocation -> {
1569 return Either.left(invocation.getArgument(0));
1570 }).when(csarArtifactsAndGroupsBusinessLogic).deleteVFModules(any(Resource.class), any(CsarInfo.class), eq(true), eq(false));
1572 doAnswer(invocation -> {
1573 return Either.left(resourceResponse);
1574 }).when(toscaOperationFacade).getToscaFullElement("myVnf");
1576 Resource result = bl.createResourceFromCsar(resourceResponse, user, csar, "1234");
1578 assertEquals("myDomain.myVnf", result.getToscaResourceName());
1579 List<String> propIds = result.getProperties().stream().map(prop -> prop.getUniqueId()).collect(Collectors.toList());
1580 assertTrue(propIds.contains("myVnf.propInBase"));
1581 assertTrue(propIds.contains("myVnf.descriptor_id"));
1582 assertTrue(propIds.contains("myVnf.descriptor_version"));
1583 assertTrue(propIds.contains("myVnf.flavour_description"));
1584 assertTrue(propIds.contains("myVnf.flavour_id"));
1585 assertTrue(propIds.contains("myVnf.product_name"));
1586 assertTrue(propIds.contains("myVnf.provider"));
1587 assertTrue(propIds.contains("myVnf.software_version"));
1588 assertTrue(propIds.contains("myVnf.vnfm_info"));
1590 final List<String> reqsName = new ArrayList<>();
1592 final List<ComponentInstance> cisWithExtReq = result.getComponentInstances().stream().filter(instance -> instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).isExternal()).collect(Collectors.toList());
1593 cisWithExtReq.forEach(instance -> reqsName.add(instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).getExternalName()));
1594 assertEquals(3, cisWithExtReq.size());
1598 public void testResourceCategoryAfterCertify_UPDATE() {
1599 Resource resource = createResourceObject(true);
1600 Resource updatedResource = createResourceObject(true);
1602 // this is in order to prevent failing with 403 earlier
1603 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1604 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1606 String resourceId = resource.getUniqueId();
1607 updatedResource.setCategories(null);
1608 updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY);
1609 resource.setVersion("1.0");
1611 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1612 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1614 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1615 } catch (ComponentException e) {
1616 assertComponentException(e, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
1620 // Derived from start
1622 public void testResourceTemplateNotExist_UPDATE() {
1623 Resource resource = createResourceObject(true);
1624 Resource updatedResource = createResourceObject(true);
1626 // this is in order to prevent failing with 403 earlier
1627 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1628 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1629 String resourceId = resource.getUniqueId();
1631 List<String> list = null;
1632 updatedResource.setDerivedFrom(list);
1633 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1634 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1636 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1637 } catch (ComponentException e) {
1638 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1643 public void testResourceTemplateEmpty_UPDATE() {
1644 Resource resource = createResourceObject(true);
1645 Resource updatedResource = createResourceObject(true);
1646 String resourceId = resource.getUniqueId();
1648 // this is in order to prevent failing with 403 earlier
1649 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1650 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1652 updatedResource.setDerivedFrom(new ArrayList<>());
1653 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1654 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1656 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1657 } catch (ComponentException e) {
1658 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1663 public void testResourceTemplateInvalid_UPDATE() {
1664 Resource resource = createResourceObject(true);
1665 Resource updatedResource = createResourceObject(true);
1666 String resourceId = resource.getUniqueId();
1668 // this is in order to prevent failing with 403 earlier
1669 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1670 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1672 ArrayList<String> derivedFrom = new ArrayList<>();
1673 derivedFrom.add("kuku");
1674 updatedResource.setDerivedFrom(derivedFrom);
1675 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1676 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1678 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1679 } catch (ComponentException e) {
1680 assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
1685 public void testResourceTemplateCertify_UPDATE_HAPPY() {
1686 Resource resource = createResourceObject(true);
1687 Resource updatedResource = createResourceObject(true);
1688 String resourceId = resource.getUniqueId();
1690 // this is in order to prevent failing with 403 earlier
1691 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1692 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1694 Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true);
1695 when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
1696 .thenReturn(isToscaNameExtending);
1698 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
1699 .left(new HashMap<>());
1700 when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
1701 .thenReturn(findPropertiesOfNode);
1703 resource.setVersion("1.0");
1705 ArrayList<String> derivedFrom = new ArrayList<>();
1706 derivedFrom.add("tosca.nodes.Root");
1707 updatedResource.setDerivedFrom(derivedFrom);
1708 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
1709 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1710 Resource createdResource = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1711 assertThat(createdResource).isNotNull();
1715 public void testResourceTemplateCertify_UPDATE_SAD() {
1716 Resource resource = createResourceObject(true);
1717 Resource updatedResource = createResourceObject(true);
1718 String resourceId = resource.getUniqueId();
1720 // this is in order to prevent failing with 403 earlier
1721 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1722 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1724 Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false);
1725 when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
1726 .thenReturn(isToscaNameExtending);
1728 resource.setVersion("1.0");
1730 ArrayList<String> derivedFrom = new ArrayList<>();
1731 derivedFrom.add("tosca.nodes.Root");
1732 updatedResource.setDerivedFrom(derivedFrom);
1733 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1734 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1735 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
1736 .left(new HashMap<>());
1737 when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
1738 .thenReturn(findPropertiesOfNode);
1741 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1742 } catch (ComponentException e) {
1743 assertComponentException(e, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1746 // Derived from stop
1749 public void createOrUpdateResourceAlreadyCheckout() {
1751 Resource resourceExist = createResourceObject(false);
1752 validateUserRoles(Role.ADMIN, Role.DESIGNER);
1753 when(toscaOperationFacade
1754 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1755 .thenReturn(Either.left(false));
1756 Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
1758 createdResource.setLastUpdaterUserId(user.getUserId());
1759 assertThat(createdResource).isNotNull();
1760 Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
1761 Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
1762 when(toscaOperationFacade.getLatestByToscaResourceName(resourceExist.getToscaResourceName(), null))
1763 .thenReturn(getCompLatestResult);
1764 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
1765 .thenReturn(getCompLatestResult);
1766 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1767 .thenReturn(getLatestResult);
1769 Resource resourceToUpdtae = createResourceObject(false);
1771 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1772 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1773 assertNotNull(createOrUpdateResource);
1775 Mockito.verify(toscaOperationFacade, Mockito.times(1))
1776 .overrideComponent(any(Resource.class), any(Resource.class));
1777 Mockito.verify(lifecycleBl, Mockito.times(0))
1778 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1779 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1784 public void createOrUpdateResourceCertified() {
1786 Resource resourceExist = createResourceObject(false);
1787 when(toscaOperationFacade
1788 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1789 .thenReturn(Either.left(false));
1790 validateUserRoles(Role.ADMIN, Role.DESIGNER);
1791 Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
1794 assertThat(createdResource).isNotNull();
1795 createdResource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
1796 createdResource.setVersion("1.0");
1798 Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
1799 Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
1800 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
1801 .thenReturn(getCompLatestResult);
1802 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1803 .thenReturn(getLatestResult);
1805 when(lifecycleBl.changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1806 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()))
1807 .thenReturn(Either.left(createdResource));
1809 Resource resourceToUpdtae = createResourceObject(false);
1811 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1812 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1813 assertNotNull(createOrUpdateResource);
1815 Mockito.verify(toscaOperationFacade, Mockito.times(1))
1816 .overrideComponent(any(Resource.class), any(Resource.class));
1817 Mockito.verify(lifecycleBl, Mockito.times(1))
1818 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1819 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1824 public void createOrUpdateResourceNotExist() {
1825 Resource resourceToUpdtae = createResourceObject(false);
1827 Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
1828 when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName(), null)).thenReturn(getLatestResult);
1829 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdtae.getToscaResourceName(), null))
1830 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1831 when(toscaOperationFacade
1832 .validateComponentNameAndModelExists(resourceToUpdtae.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1833 .thenReturn(Either.left(false));
1835 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1836 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1837 assertThat(createOrUpdateResource).isNotNull();
1839 Mockito.verify(toscaOperationFacade, times(1))
1840 .createToscaComponent(resourceToUpdtae);
1841 Mockito.verify(toscaOperationFacade, Mockito.times(0))
1842 .overrideComponent(any(Resource.class), any(Resource.class));
1843 Mockito.verify(lifecycleBl, Mockito.times(0))
1844 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1845 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1850 public void testIfNodeTypeNameHasValidPrefix() {
1851 final List<String> definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager()
1852 .getConfiguration().getDefinedResourceNamespace();
1854 definedNodeTypeNamespaceList.parallelStream().forEach(validNodeTypePrefix -> {
1855 final String nodeName = validNodeTypePrefix + "." + "abc";
1856 final Optional<String> result = bl.validateNodeTypeNamePrefix(nodeName, definedNodeTypeNamespaceList);
1857 assertTrue(result.isPresent());
1862 public void updateNestedResource_typeIsNew() throws IOException {
1863 Resource resourceToUpdate = createResourceObject(false);
1864 String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
1865 String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
1866 CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
1868 String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
1869 .name(), csarInfo.getVfResourceName(), nodeName)
1871 when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
1872 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1873 when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
1874 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1875 when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
1876 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1878 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
1879 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1880 when(toscaOperationFacade
1881 .validateComponentNameAndModelExists(resourceToUpdate.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1882 .thenReturn(Either.left(false));
1884 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1885 .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
1886 assertThat(createOrUpdateResource).isNotNull();
1888 Mockito.verify(toscaOperationFacade, times(1))
1889 .createToscaComponent(resourceToUpdate);
1890 Mockito.verify(toscaOperationFacade, times(0))
1891 .overrideComponent(any(Resource.class), any(Resource.class));
1892 Mockito.verify(lifecycleBl, times(0))
1893 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1894 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1898 public void updateNestedResource_typeExists() throws IOException {
1900 Resource resourceToUpdate = createResourceObject(false);
1901 setCanWorkOnResource(resourceResponse);
1902 String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
1903 String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
1904 CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
1906 String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
1907 .name(), csarInfo.getVfResourceName(), nodeName)
1909 when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
1910 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1911 when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
1912 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1913 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
1914 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1915 when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
1916 .thenReturn(Either.left(resourceResponse));
1917 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1918 .thenReturn(Either.left(resourceResponse));
1920 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1921 .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
1922 assertThat(createOrUpdateResource).isNotNull();
1923 Mockito.verify(toscaOperationFacade, times(1))
1924 .overrideComponent(any(Resource.class), any(Resource.class));
1925 Mockito.verify(lifecycleBl, times(0))
1926 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1927 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1931 public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() {
1932 Resource basic = createResourceObject(true);
1934 Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1935 assertTrue(validatePropertiesDefaultValues);
1939 public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() {
1940 Resource basic = createResourceObject(true);
1941 PropertyDefinition property = new PropertyDefinition();
1942 property.setName("myProperty");
1943 property.setType(ToscaPropertyType.INTEGER.getType());
1944 property.setDefaultValue("1");
1945 List<PropertyDefinition> properties = new ArrayList<>();
1946 properties.add(property);
1947 basic.setProperties(properties);
1948 when(propertyOperation.isPropertyTypeValid(property, (String)null)).thenReturn(true);
1949 when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true);
1950 Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1951 assertTrue(validatePropertiesDefaultValues);
1954 @Test(expected = ComponentException.class)
1955 public void testValidatePropertiesDefaultValues_FailedWithProperties() {
1956 Resource basic = createResourceObject(true);
1957 PropertyDefinition property = new PropertyDefinition();
1958 property.setName("myProperty");
1959 property.setType(ToscaPropertyType.INTEGER.getType());
1960 property.setDefaultValue("1.5");
1961 List<PropertyDefinition> properties = new ArrayList<>();
1962 properties.add(property);
1963 basic.setProperties(properties);
1965 when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false);
1966 bl.validatePropertiesDefaultValues(basic);
1970 public void testDeleteMarkedResourcesNoResources() {
1971 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(new ArrayList<>());
1973 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
1975 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
1976 assertTrue(deleteMarkedResources.isLeft());
1977 assertTrue(deleteMarkedResources.left().value().isEmpty());
1981 public void testDeleteMarkedResources() {
1982 List<String> ids = new ArrayList<>();
1983 String resourceInUse = "123";
1984 String resourceFree = "456";
1985 ids.add(resourceInUse);
1986 ids.add(resourceFree);
1987 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
1988 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
1990 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
1991 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
1993 List<ArtifactDefinition> artifacts = new ArrayList<>();
1995 when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
1996 when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
1998 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new
2000 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
2002 List<String> deletedComponents = new ArrayList<>();
2003 deletedComponents.add(resourceFree);
2004 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents));
2006 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
2007 assertTrue(deleteMarkedResources.isLeft());
2008 List<String> resourceIdList = deleteMarkedResources.left().value();
2009 assertFalse(resourceIdList.isEmpty());
2010 assertTrue(resourceIdList.contains(resourceFree));
2011 assertFalse(resourceIdList.contains(resourceInUse));
2014 @SuppressWarnings("unchecked")
2016 public void testFindVfCsarArtifactsToHandle() {
2018 Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
2019 String methodName = "findVfCsarArtifactsToHandle";
2020 Resource resource = new Resource();
2021 String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml";
2022 String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml";
2023 String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml";
2025 String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml";
2026 String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml";
2027 String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml";
2028 String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml";
2030 byte[] oldPayloadData = "oldPayloadData".getBytes();
2031 byte[] newPayloadData = "newPayloadData".getBytes();
2032 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
2034 ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition();
2035 deploymentArtifactToUpdate.setMandatory(false);
2036 deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName);
2037 deploymentArtifactToUpdate.setArtifactType("SNMP_POLL");
2038 deploymentArtifactToUpdate.setPayload(oldPayloadData);
2039 deploymentArtifactToUpdate
2040 .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2042 ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition();
2043 deploymentArtifactToDelete.setMandatory(false);
2044 deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName);
2045 deploymentArtifactToDelete.setArtifactType("SNMP_TRAP");
2046 deploymentArtifactToDelete.setPayload(oldPayloadData);
2047 deploymentArtifactToDelete
2048 .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2050 ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition();
2052 deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()),
2053 deploymentArtifactToUpdate);
2054 deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()),
2055 deploymentArtifactToDelete);
2056 deploymentArtifacts.put("ignore", deploymentArtifactToIgnore);
2058 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
2060 ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
2061 artifactToUpdate.setMandatory(false);
2062 artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName);
2063 artifactToUpdate.setArtifactType("SNMP_POLL");
2064 artifactToUpdate.setPayload(oldPayloadData);
2065 artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2067 ArtifactDefinition artifactToDelete = new ArtifactDefinition();
2068 artifactToDelete.setMandatory(false);
2069 artifactToDelete.setArtifactName(artifactInfoToDeleteFileName);
2070 artifactToDelete.setArtifactType("SNMP_TRAP");
2071 artifactToDelete.setPayload(oldPayloadData);
2072 artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2073 artifactToDelete.setIsFromCsar(true);
2075 ArtifactDefinition artifactToNotDelete = new ArtifactDefinition();
2076 artifactToNotDelete.setMandatory(false);
2077 artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName);
2078 artifactToNotDelete.setArtifactType("SNMP_TRAP");
2079 artifactToNotDelete.setPayload(oldPayloadData);
2080 artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2081 artifactToNotDelete.setIsFromCsar(false);
2083 ArtifactDefinition artifactToIgnore = new ArtifactDefinition();
2085 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate);
2086 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete);
2087 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()),
2088 artifactToNotDelete);
2089 artifacts.put("ignore", artifactToIgnore);
2091 resource.setDeploymentArtifacts(deploymentArtifacts);
2092 resource.setArtifacts(artifacts);
2094 List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>();
2095 NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(
2096 deploymentArtifactToUpdate.getArtifactName(), null,
2097 deploymentArtifactToUpdate.getArtifactType(),
2098 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false);
2100 NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(
2101 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2102 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), false);
2104 NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
2105 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2106 ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData, artifactToUpdate.getArtifactName(), true);
2108 NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
2109 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2110 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), true);
2112 NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName,
2113 null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData,
2114 deploymentArtifactToCreateFileName, false);
2116 NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName,
2117 null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData,
2118 artifactInfoToCreateFileName, false);
2120 artifactPathAndNameList.add(deploymentArtifactInfoToUpdate);
2121 artifactPathAndNameList.add(informationalArtifactInfoToUpdate);
2122 artifactPathAndNameList.add(deploymentArtifactInfoToCreate);
2123 artifactPathAndNameList.add(informationalArtifactInfoToCreate);
2124 artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar);
2125 artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar);
2127 Object[] argObjects = { resource, artifactPathAndNameList, user };
2128 Class[] argClasses = { Resource.class, List.class, User.class };
2130 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
2131 method.setAccessible(true);
2132 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method
2133 .invoke(bl, argObjects);
2134 assertTrue(findVfCsarArtifactsToHandleRes.isLeft());
2135 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes
2138 assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.CREATE)
2140 assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.UPDATE)
2142 assertEquals(1, foundVfArtifacts.get(ArtifactOperationEnum.DELETE)
2145 } catch (Exception e) {
2146 e.printStackTrace();
2151 public void testVFGeneratedInputs() {
2152 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2153 Resource resource = createVF();
2154 List<InputDefinition> inputs = resource.getInputs();
2155 assertEquals(6, inputs.size());
2156 for (InputDefinition input : inputs) {
2157 assertThat(input.getOwnerId()).isNotNull();
2159 assertEquals(resource.getDerivedFromGenericType(), genericVF.getToscaResourceName());
2160 assertEquals(resource.getDerivedFromGenericVersion(), genericVF.getVersion());
2164 public void testCRGeneratedInputs() {
2165 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2166 Resource resource = createCR();
2167 List<InputDefinition> inputs = resource.getInputs();
2168 assertEquals(3, inputs.size());
2169 for (InputDefinition input : inputs) {
2170 assertThat(input.getOwnerId()).isNotNull();
2172 assertEquals(resource.getDerivedFromGenericType(), genericCR.getToscaResourceName());
2173 assertEquals(resource.getDerivedFromGenericVersion(), genericCR.getVersion());
2177 public void testVFUpdateGenericInputsToLatestOnCheckout() {
2178 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2179 // create a VF that is derived from generic version 1.0
2180 Resource resource = createVF();
2181 // create a new generic version without properties
2182 genericVF.setVersion("2.0");
2183 genericVF.setProperties(null);
2184 String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
2185 List<InputDefinition> currentInputs = resource.getInputs();
2186 // verify previous inputs ownerId fields exist - user may not delete
2188 assertEquals(6, currentInputs.stream()
2189 .filter(p -> null != p.getOwnerId())
2190 .collect(Collectors.toList())
2192 Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
2194 assertTrue(upgradeToLatestGeneric.isLeft());
2195 // verify update required and valid
2196 assertTrue(upgradeToLatestGeneric.left()
2198 // verify version was upgraded
2199 assertNotEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
2200 // verify inputs were not deleted
2201 assertEquals(6, resource.getInputs()
2203 // verify inputs ownerId fields were removed - user may delete/edit
2205 assertEquals(6, resource.getInputs()
2207 .filter(p -> null == p.getOwnerId())
2208 .collect(Collectors.toList())
2213 public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
2215 // create a VF that is derived from generic version 1.0
2216 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2217 Resource resource = createVF();
2219 // add an input to the VF
2220 PropertyDefinition newProp = new PropertyDefinition();
2221 newProp.setType("integer");
2222 newProp.setName("newProp");
2223 resource.getInputs()
2224 .add(new InputDefinition(newProp));
2226 // create a new generic version with a new property which has the same
2227 // name as a user defined input on the VF with a different type
2228 genericVF.setVersion("2.0");
2229 newProp.setType("string");
2230 genericVF.setProperties(new ArrayList<>());
2231 genericVF.getProperties()
2233 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
2234 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
2235 genericVF.getUniqueId())).thenCallRealMethod();
2236 String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
2237 assertEquals(6, resource.getInputs()
2239 .filter(p -> null != p.getOwnerId())
2240 .collect(Collectors.toList())
2242 Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
2244 assertTrue(upgradeToLatestGeneric.isLeft());
2245 // verify update is invalid an void
2246 assertFalse(upgradeToLatestGeneric.left()
2248 // verify version was not upgraded
2249 assertEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
2250 // verify inputs were not removed
2251 assertEquals(7, resource.getInputs()
2253 // verify user defined input exists
2254 assertEquals(1, resource.getInputs()
2256 .filter(p -> null == p.getOwnerId())
2257 .collect(Collectors.toList())
2259 assertEquals("integer", resource.getInputs()
2261 .filter(p -> null == p.getOwnerId())
2268 public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
2269 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2270 Resource resource = createPNF();
2271 List<InputDefinition> inputs = resource.getInputs();
2272 assertEquals(3, inputs.size());
2273 for (InputDefinition input : inputs) {
2274 assertThat(input.getOwnerId()).isNotNull();
2276 assertEquals(resource.getDerivedFromGenericType(), genericPNF.getToscaResourceName());
2277 assertEquals(resource.getDerivedFromGenericVersion(), genericPNF.getVersion());
2278 assertEquals(0, resource.getArtifacts()
2282 private Resource createVF() {
2284 genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
2285 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME))
2286 .thenReturn(Either.left(genericVF));
2287 Resource resource = createResourceObject(true);
2288 resource.setDerivedFrom(null);
2289 resource.setResourceType(ResourceTypeEnum.VF);
2290 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2291 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericVF));
2292 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod();
2293 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
2294 resource.getUniqueId())).thenCallRealMethod();
2295 when(toscaOperationFacade
2296 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE))
2297 .thenReturn(Either.left(false));
2298 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2299 assertThat(createdResource).isNotNull();
2300 return createdResource;
2303 private Resource createRoot() {
2304 rootType = setupGenericTypeMock(GENERIC_ROOT_NAME);
2305 when(toscaOperationFacade.getLatestByToscaResourceName(GENERIC_ROOT_NAME, null))
2306 .thenReturn(Either.left(rootType));
2310 private Resource createCR() {
2312 genericCR = setupGenericTypeMock(GENERIC_CR_NAME);
2313 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME))
2314 .thenReturn(Either.left(genericCR));
2315 Resource resource = createResourceObject(true);
2316 resource.setDerivedFrom(null);
2317 resource.setResourceType(ResourceTypeEnum.CR);
2318 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2319 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericCR));
2320 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod();
2321 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(),
2322 resource.getUniqueId())).thenCallRealMethod();
2323 when(toscaOperationFacade
2324 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE))
2325 .thenReturn(Either.left(false));
2326 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2327 assertThat(createdResource).isNotNull();
2328 return createdResource;
2331 private Resource createPNF() {
2333 genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
2334 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME))
2335 .thenReturn(Either.left(genericPNF));
2336 Resource resource = createResourceObject(true);
2337 resource.setDerivedFrom(null);
2338 resource.setResourceType(ResourceTypeEnum.PNF);
2339 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2340 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericPNF));
2341 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod();
2342 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(),
2343 resource.getUniqueId())).thenCallRealMethod();
2344 when(toscaOperationFacade
2345 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE))
2346 .thenReturn(Either.left(false));
2347 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2348 assertThat(createdResource).isNotNull();
2349 return createdResource;
2352 private Map<String, String> getGenericPropertiesByToscaName(String toscaName) {
2353 HashMap<String, String> PNFProps = new HashMap<String, String>() {
2355 put("nf_function", "string");
2356 put("nf_role", "string");
2357 put("nf_type", "string");
2361 HashMap<String, String> CRProps = new HashMap<String, String>() {
2363 put("cr_function", "string");
2364 put("cr_role", "string");
2365 put("cr_type", "string");
2369 HashMap<String, String> VFProps = new HashMap<String, String>() {
2372 put("availability_zone_max_count", "integer");
2373 put("min_instances", "integer");
2374 put("max_instances", "integer");
2378 if (toscaName.contains("PNF"))
2380 if (toscaName.contains("CR"))
2382 if (toscaName.contains("VF"))
2385 return new HashMap<>();
2388 private Resource setupGenericTypeMock(String toscaName) {
2390 Resource genericType = createResourceObject(true);
2391 genericType.setVersion("1.0");
2392 genericType.setToscaResourceName(toscaName);
2393 genericType.setAbstract(true);
2394 List<PropertyDefinition> genericProps = new ArrayList<>();
2395 Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName);
2396 genericPropsMap.forEach((name, type) -> {
2397 PropertyDefinition prop = new PropertyDefinition();
2400 genericProps.add(prop);
2403 genericType.setProperties(genericProps);
2407 private void validateUserRoles(Role... roles) {
2408 List<Role> listOfRoles = Stream.of(roles)
2409 .collect(Collectors.toList());
2413 public void testUpdateVolumeGroup() {
2414 Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
2415 bl.updateVolumeGroup(resource);
2416 assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(true));
2420 public void testUpdateVolumeGroupNull() {
2421 Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
2422 resource.setGroups(null);
2423 bl.updateVolumeGroup(resource);
2424 assertThat(resource.getGroups()).isNull();
2428 public void testUpdateVolumeGroupFail() {
2429 Resource resource = getResourceWithType("NON_EXIST_HEAT", "org.openecomp.groups.VfModule");
2430 bl.updateVolumeGroup(resource);
2431 assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(false));
2434 private Resource getResourceWithType(String artifactType, String groupDefinitionType) {
2435 ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
2436 List<GroupDefinition> groups = new ArrayList<>();
2437 GroupDefinition gd = new GroupDefinition();
2438 List<PropertyDataDefinition> properties = new ArrayList<>();
2439 PropertyDataDefinition pdd = new PropertyDataDefinition();
2440 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
2441 List<String> artifactsList = new ArrayList<>();
2443 artifactToUpdate.setArtifactType(artifactType);
2444 artifactToUpdate.setArtifactName(artifactType);
2445 artifactToUpdate.setUniqueId(artifactType);
2446 Resource resource = createResourceObjectCsar(true);
2447 artifactsList.add(artifactToUpdate.getArtifactName());
2450 pdd.setName("volume_group");
2451 pdd.setValue("true");
2452 pdd.setType(ToscaPropertyType.BOOLEAN.getType());
2454 artifacts.put(artifactToUpdate.getArtifactName(), artifactToUpdate);
2456 properties.add(pdd);
2457 gd.setType(groupDefinitionType);
2458 gd.setProperties(properties);
2459 gd.setArtifacts(artifactsList);
2462 resource.setGroups(groups);
2463 resource.setDeploymentArtifacts(artifacts);
2469 public void testgetAllCertifiedResources() throws Exception {
2470 List<Resource> list = bl.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, "USER");
2471 Assert.assertEquals(reslist,list);
2474 @Test(expected = StorageException.class)
2475 public void testgetAllCertifiedResources_exception() throws Exception {
2476 List<Resource> list = bl.getAllCertifiedResources(false, HighestFilterEnum.NON_HIGHEST_ONLY, "USER");
2477 Assert.assertEquals(reslist,list);
2481 public void testvalidateResourceNameExists() throws Exception {
2482 Either<Map<String, Boolean>, ResponseFormat> res = bl.validateResourceNameExists("Resource", ResourceTypeEnum.CR, "jh0003");
2483 Assert.assertEquals(true,res.isLeft());
2487 public void rollbackWithEitherAlwaysReturnARuntimeException() {
2488 JanusGraphDao janusGraphDao = mockJanusGraphDao;
2489 ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
2490 String params = "testName";
2492 Either<Object, RuntimeException> result =
2493 ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
2495 assertTrue(result.isRight());
2496 assertTrue(result.right().value() instanceof ByActionStatusComponentException);
2500 public void rollbackWithEitherWorksWithNullJanusGraphDao() {
2501 JanusGraphDao janusGraphDao = null;
2502 ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
2503 String params = "testName";
2505 Either<Object, RuntimeException> result =
2506 ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
2508 assertTrue(result.isRight());
2509 assertTrue(result.right().value() instanceof ByActionStatusComponentException);
2513 public void testDeleteResource_NotFound() {
2514 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
2515 ResponseFormat respFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), "");
2516 ResponseFormat actualResponseFormat = bl.deleteResource("1", user);
2517 assertEquals(respFormat.getStatus(), actualResponseFormat.getStatus());
2521 public void testDeleteResource_NotArchived() {
2522 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(resourceResponse));
2523 ComponentException actualComponentException = assertThrows(ComponentException.class, () -> bl.deleteResourceAllVersions(resourceResponse.getUniqueId(), user));
2524 assertEquals(ActionStatus.COMPONENT_NOT_ARCHIVED, actualComponentException.getActionStatus());
2525 assertEquals("my-resource_name with space:0.1", actualComponentException.getParams()[0]);
2529 public void testDeleteResource_IsInUse() {
2530 Resource resourceObject = createResourceObject(true);
2531 Mockito.when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(resourceObject));
2532 resourceObject.setArchived(true);
2533 OperationException oe = new OperationException(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, "resource_name");
2534 Mockito.when(toscaOperationFacade.deleteComponent(resourceObject.getInvariantUUID(), NodeTypeEnum.Resource, true)).thenThrow(oe);
2535 OperationException actualOperationException = assertThrows(OperationException.class, () -> bl.deleteResourceAllVersions(resourceResponse.getUniqueId(), user));
2536 assertEquals(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, actualOperationException.getActionStatus());
2537 assertEquals("resource_name", actualOperationException.getParams()[0]);