2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import static org.assertj.core.api.Java6Assertions.assertThat;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertFalse;
26 import static org.junit.Assert.assertNotEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertTrue;
29 import static org.mockito.ArgumentMatchers.any;
30 import static org.mockito.ArgumentMatchers.anyList;
31 import static org.mockito.ArgumentMatchers.anyString;
32 import static org.mockito.ArgumentMatchers.eq;
33 import static org.mockito.Mockito.doAnswer;
34 import static org.mockito.Mockito.times;
35 import static org.mockito.Mockito.when;
37 import fj.data.Either;
39 import java.io.IOException;
40 import java.lang.reflect.Method;
41 import java.net.URISyntaxException;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collections;
45 import java.util.EnumMap;
46 import java.util.HashMap;
47 import java.util.List;
49 import java.util.Map.Entry;
50 import java.util.Optional;
51 import java.util.stream.Collectors;
52 import java.util.stream.Stream;
53 import javax.servlet.ServletContext;
54 import org.apache.commons.lang3.tuple.ImmutablePair;
55 import org.junit.Assert;
56 import org.junit.Before;
57 import org.junit.Test;
58 import org.mockito.InjectMocks;
59 import org.mockito.Mockito;
60 import org.mockito.MockitoAnnotations;
61 import org.openecomp.sdc.ElementOperationMock;
62 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
63 import org.openecomp.sdc.be.components.ArtifactsResolver;
64 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
65 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
66 import org.openecomp.sdc.be.components.csar.CsarInfo;
67 import org.openecomp.sdc.be.components.csar.YamlTemplateParsingHandler;
68 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
69 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
70 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
71 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
72 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
73 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
74 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
75 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
76 import org.openecomp.sdc.be.components.validation.UserValidations;
77 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
78 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
79 import org.openecomp.sdc.be.components.validation.component.ComponentFieldValidator;
80 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
81 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
82 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
83 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
84 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
85 import org.openecomp.sdc.be.config.ConfigurationManager;
86 import org.openecomp.sdc.be.dao.api.ActionStatus;
87 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
88 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
89 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
90 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
91 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
92 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
93 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
94 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
95 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
96 import org.openecomp.sdc.be.facade.operations.CatalogOperation;
97 import org.openecomp.sdc.be.impl.ComponentsUtils;
98 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
99 import org.openecomp.sdc.be.model.ArtifactDefinition;
100 import org.openecomp.sdc.be.model.Component;
101 import org.openecomp.sdc.be.model.ComponentInstance;
102 import org.openecomp.sdc.be.model.ComponentParametersView;
103 import org.openecomp.sdc.be.model.DataTypeDefinition;
104 import org.openecomp.sdc.be.model.GroupDefinition;
105 import org.openecomp.sdc.be.model.InputDefinition;
106 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
107 import org.openecomp.sdc.be.model.LifecycleStateEnum;
108 import org.openecomp.sdc.be.model.NodeTypeInfo;
109 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
110 import org.openecomp.sdc.be.model.PropertyDefinition;
111 import org.openecomp.sdc.be.model.RequirementDefinition;
112 import org.openecomp.sdc.be.model.Resource;
113 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
114 import org.openecomp.sdc.be.model.User;
115 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
116 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
117 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
118 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
119 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTypeOperation;
120 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation;
121 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
122 import org.openecomp.sdc.be.model.operations.StorageException;
123 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
124 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
125 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
126 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
127 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
128 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
129 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
130 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
131 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
132 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
133 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
134 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
135 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
136 import org.openecomp.sdc.be.tosca.CsarUtils;
137 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
138 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
139 import org.openecomp.sdc.be.user.Role;
140 import org.openecomp.sdc.be.user.UserBusinessLogic;
141 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
142 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
143 import org.openecomp.sdc.common.api.Constants;
144 import org.openecomp.sdc.common.impl.ExternalConfiguration;
145 import org.openecomp.sdc.common.impl.FSConfigurationSource;
146 import org.openecomp.sdc.common.util.GeneralUtility;
147 import org.openecomp.sdc.common.util.ValidationUtils;
148 import org.openecomp.sdc.common.zip.ZipUtils;
149 import org.openecomp.sdc.common.zip.exception.ZipException;
150 import org.openecomp.sdc.exception.ResponseFormat;
151 import org.springframework.web.context.WebApplicationContext;
153 public class ResourceBusinessLogicTest {
155 private final ConfigurationManager configurationManager = new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"));
156 private static final String RESOURCE_CATEGORY1 = "Network Layer 2-3";
157 private static final String RESOURCE_SUBCATEGORY = "Router";
159 private static final String UPDATED_SUBCATEGORY = "Gateway";
161 private static final String RESOURCE_NAME = "My-Resource_Name with space";
162 private static final String RESOURCE_TOSCA_NAME = "My-Resource_Tosca_Name";
163 private static final String GENERIC_ROOT_NAME = "tosca.nodes.Root";
164 private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
165 private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR";
166 private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
168 private final ServletContext servletContext = Mockito.mock(ServletContext.class);
169 IElementOperation mockElementDao;
170 private final JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class);
171 private final UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
172 private final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
173 private final NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
174 private final NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
175 private final TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
176 private final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
177 private final CatalogOperation catalogOperation = Mockito.mock(CatalogOperation.class);
178 private final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
179 private final PropertyOperation propertyOperation = Mockito.mock(PropertyOperation.class);
180 private final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class);
181 private final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
182 private final UserValidations userValidations = Mockito.mock(UserValidations.class);
183 private final WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
184 private final IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
185 private final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class);
186 private final IElementOperation elementDao = new ElementOperationMock();
188 private final CsarUtils csarUtils = Mockito.mock(CsarUtils.class);
189 private final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
190 private final IGroupOperation groupOperation = Mockito.mock(IGroupOperation.class);
191 private final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class);
192 private final IGroupTypeOperation groupTypeOperation = Mockito.mock(IGroupTypeOperation.class);
193 private final GroupBusinessLogic groupBusinessLogic = Mockito.mock(GroupBusinessLogic.class);
194 private final ModelBusinessLogic modelBusinessLogic = Mockito.mock(ModelBusinessLogic.class);
195 private final InterfaceOperation interfaceOperation = Mockito.mock(InterfaceOperation.class);
196 private final ArtifactsOperations artifactToscaOperation = Mockito.mock(ArtifactsOperations.class);
197 private final PropertyBusinessLogic propertyBusinessLogic = Mockito.mock(PropertyBusinessLogic.class);
198 private final ArtifactsResolver artifactsResolver = Mockito.mock(ArtifactsResolver.class);
199 private final InterfaceLifecycleOperation interfaceLifecycleTypeOperation = Mockito.mock(InterfaceLifecycleOperation.class);
200 private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class);
201 private final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
202 private final InputsBusinessLogic inputsBusinessLogic = Mockito.mock(InputsBusinessLogic.class);
203 private final OutputsBusinessLogic outputsBusinessLogic = Mockito.mock(OutputsBusinessLogic.class);
204 private final CompositionBusinessLogic compositionBusinessLogic = Mockito.mock(CompositionBusinessLogic.class);
205 private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic = Mockito.mock(ResourceDataMergeBusinessLogic.class);
206 private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic = Mockito.mock(CsarArtifactsAndGroupsBusinessLogic.class);
207 private final MergeInstanceUtils mergeInstanceUtils = Mockito.mock(MergeInstanceUtils.class);
208 private final UiComponentDataConverter uiComponentDataConverter = Mockito.mock(UiComponentDataConverter.class);
209 private final ToscaExportHandler toscaExportHandler = Mockito.mock(ToscaExportHandler.class);
210 private final PolicyBusinessLogic policyBusinessLogic = Mockito.mock(PolicyBusinessLogic.class);
212 private YamlTemplateParsingHandler yamlTemplateParsingHandler = Mockito.mock(YamlTemplateParsingHandler.class);
214 ResponseFormatManager responseManager = null;
215 private final GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
217 Resource resourceResponse = null;
218 Resource genericVF = null;
219 Resource genericCR = null;
220 Resource genericVFC = null;
221 Resource genericPNF = null;
222 Resource rootType = null;
223 ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
224 ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(artifactCassandraDao, toscaExportHandler, csarUtils, lifecycleBl,
225 userBusinessLogic, artifactsResolver, elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
226 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
227 CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
229 CsarBusinessLogic csarBusinessLogic ;
230 Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
231 List<Resource> reslist;
232 private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
233 protected ComponentDescriptionValidator componentDescriptionValidator = new ComponentDescriptionValidator(componentsUtils);
234 protected ComponentProjectCodeValidator componentProjectCodeValidator = new ComponentProjectCodeValidator(componentsUtils);
235 protected ComponentIconValidator componentIconValidator = new ComponentIconValidator(componentsUtils);
236 protected ComponentContactIdValidator componentContactIdValidator = new ComponentContactIdValidator(componentsUtils);
237 protected ComponentTagsValidator componentTagsValidator = new ComponentTagsValidator(componentsUtils);
238 protected ComponentNameValidator componentNameValidator = new ComponentNameValidator(componentsUtils, toscaOperationFacade);
239 private ComponentValidator componentValidator = createComponentValidator();
240 private SoftwareInformationBusinessLogic softwareInformationBusinessLogic = Mockito.mock(SoftwareInformationBusinessLogic.class);
242 private ComponentValidator createComponentValidator() {
243 List<ComponentFieldValidator> componentFieldValidators = Arrays.asList(componentNameValidator,
244 componentDescriptionValidator, componentProjectCodeValidator,
245 componentIconValidator, componentContactIdValidator,
246 componentTagsValidator);
247 return new ComponentValidator(componentsUtils,componentFieldValidators);
250 ResourceBusinessLogic bl;
253 public void setup() {
254 MockitoAnnotations.initMocks(this);
255 Mockito.reset(propertyOperation);
258 mockElementDao = new ElementOperationMock();
261 // User data and management
263 user.setUserId("jh0003");
264 user.setFirstName("Jimmi");
265 user.setLastName("Hendrix");
266 user.setRole(Role.ADMIN.name());
268 when(mockUserAdmin.getUser("jh0003", false)).thenReturn(user);
269 when(userValidations.validateUserExists(user.getUserId())).thenReturn(user);
270 when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
271 // Servlet Context attributes
272 when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
273 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
274 .thenReturn(webAppContextWrapper);
275 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
276 when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
278 Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true);
279 when(toscaOperationFacade.validateComponentNameExists("tosca.nodes.Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
280 .thenReturn(eitherFalse);
283 Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
284 when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC,
285 ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist);
287 Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
288 when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class),
289 eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount);
290 Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
291 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
293 Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false);
294 when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
295 when(graphLockOperation.lockComponent(anyString(), eq(NodeTypeEnum.Resource)))
296 .thenReturn(StorageOperationStatus.OK);
297 when(graphLockOperation.lockComponentByName(anyString(), eq(NodeTypeEnum.Resource)))
298 .thenReturn(StorageOperationStatus.OK);
301 resourceResponse = createResourceObject(true);
302 Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
303 when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
304 when(catalogOperation.updateCatalog(Mockito.any(), Mockito.any())).thenReturn(ActionStatus.OK);
305 Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
306 when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(emptyDataTypes));
307 when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
310 artifactManager.setNodeTemplateOperation(nodeTemplateOperation);
311 bl = new ResourceBusinessLogic(mockElementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
312 interfaceOperation, interfaceLifecycleTypeOperation, artifactManager, componentInstanceBusinessLogic,
313 resourceImportManager, inputsBusinessLogic, outputsBusinessLogic, compositionBusinessLogic, resourceDataMergeBusinessLogic,
314 csarArtifactsAndGroupsBusinessLogic, mergeInstanceUtils, uiComponentDataConverter, csarBusinessLogic,
315 artifactToscaOperation, propertyBusinessLogic, componentContactIdValidator, componentNameValidator,
316 componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator,
317 componentDescriptionValidator, policyBusinessLogic, modelBusinessLogic);
318 bl.setElementDao(mockElementDao);
319 bl.setUserAdmin(mockUserAdmin);
320 bl.setCapabilityTypeOperation(capabilityTypeOperation);
321 bl.setComponentsUtils(componentsUtils);
322 bl.setLifecycleManager(lifecycleBl);
323 bl.setArtifactsManager(artifactManager);
324 bl.setGraphLockOperation(graphLockOperation);
325 bl.setPropertyOperation(propertyOperation);
326 bl.setJanusGraphDao(mockJanusGraphDao);
327 bl.setApplicationDataTypeCache(applicationDataTypeCache);
328 bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
329 bl.setCatalogOperations(catalogOperation);
330 toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
331 csarBusinessLogic.setComponentsUtils(componentsUtils);
332 toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
333 bl.setToscaOperationFacade(toscaOperationFacade);
334 bl.setUserValidations(userValidations);
335 bl.setInterfaceTypeOperation(interfaceTypeOperation);
337 csarBusinessLogic.setCsarOperation(csarOperation);
338 Resource resourceCsar = createResourceObjectCsar(true);
339 setCanWorkOnResource(resourceCsar);
340 Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
341 when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
342 responseManager = ResponseFormatManager.getInstance();
343 bl.setComponentIconValidator(componentIconValidator);
344 bl.setComponentNameValidator(componentNameValidator);
345 bl.setComponentDescriptionValidator(componentDescriptionValidator);
346 bl.setComponentTagsValidator(componentTagsValidator);
347 bl.setComponentContactIdValidator(componentContactIdValidator);
348 bl.setComponentProjectCodeValidator(componentProjectCodeValidator);
349 bl.setComponentValidator(componentValidator);
350 reslist = new ArrayList<>();
351 reslist.add(resourceResponse);
352 reslist.add(genericVF);
353 reslist.add(genericCR);
354 reslist.add(genericVFC);
355 reslist.add(genericPNF);
356 Either<List<Resource>, StorageOperationStatus> returneval= Either.left(reslist);
357 when(toscaOperationFacade.getAllCertifiedResources(true, true)).thenReturn(returneval);
358 when(toscaOperationFacade.validateComponentNameUniqueness("Resource", ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(true));
359 Either<List<Resource>, StorageOperationStatus> returnevalexception= Either.right(StorageOperationStatus.BAD_REQUEST);
360 when(toscaOperationFacade.getAllCertifiedResources(false, false)).thenReturn(returnevalexception);
363 @Test(expected = ComponentException.class)
364 public void createResourcesFromYamlNodeTypesList() throws IOException {
365 Map<String, Object> mappedToscaTemplate = new HashMap<>();
366 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
367 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
368 Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
369 bl.createResourcesFromYamlNodeTypesList(
374 nodeTypesArtifactsToHandle,
375 nodeTypesNewCreatedArtifacts,
377 new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"),true), "");
381 public void handleNodeTypeArtifactsTest() {
382 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = new HashMap<>();
383 List<ArtifactDefinition> defs = new ArrayList<>();
384 defs.add(new ArtifactDefinition());
385 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, defs);
386 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, defs);
387 assertTrue(bl.handleNodeTypeArtifacts(resourceResponse, nodeTypeArtifactsToHandle, new ArrayList<>(), user, true, true).isRight());
391 public void getUiComponentDataTransferByComponentIdTest() {
392 when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(genericCR));
393 assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isLeft());
394 when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.right(StorageOperationStatus.OK));
395 assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isRight());
399 public void shouldUpgradeToLatestDerivedTest() {
402 when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericCR)).thenReturn(Either.left(genericCR));
403 when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericVFC)).thenReturn(Either.right(StorageOperationStatus.OK));
404 assertTrue(bl.shouldUpgradeToLatestDerived(genericVF).isLeft());
405 assertTrue(bl.shouldUpgradeToLatestDerived(genericCR).isLeft());
408 private Resource createResourceObject(boolean afterCreate) {
409 Resource resource = new Resource();
410 resource.setName(RESOURCE_NAME);
411 resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
412 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
413 resource.setDescription("My short description");
414 List<String> tgs = new ArrayList<>();
416 tgs.add(resource.getName());
417 resource.setTags(tgs);
418 List<String> template = new ArrayList<>();
419 template.add("tosca.nodes.Root");
420 resource.setDerivedFrom(template);
421 resource.setVendorName("Motorola");
422 resource.setVendorRelease("1.0.0");
423 resource.setContactId("ya5467");
424 resource.setIcon("defaulticon");
427 resource.setName(resource.getName());
428 resource.setVersion("0.1");
429 resource.setUniqueId(resource.getName()
430 .toLowerCase() + ":" + resource.getVersion());
431 resource.setCreatorUserId(user.getUserId());
432 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
433 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
438 private Resource createResourceObjectWithModel(boolean afterCreate) {
439 Resource resource = new Resource();
440 resource.setName(RESOURCE_NAME);
441 resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
442 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
443 resource.setDescription("My short description");
444 List<String> tgs = new ArrayList<>();
446 tgs.add(resource.getName());
447 resource.setTags(tgs);
448 List<String> template = new ArrayList<>();
449 template.add("tosca.nodes.Root");
450 resource.setDerivedFrom(template);
451 resource.setVendorName("Motorola");
452 resource.setVendorRelease("1.0.0");
453 resource.setContactId("ya5467");
454 resource.setIcon("defaulticon");
455 resource.setModel("Test Model");
458 resource.setName(resource.getName());
459 resource.setVersion("0.1");
460 resource.setUniqueId(resource.getName()
461 .toLowerCase() + ":" + resource.getVersion());
462 resource.setCreatorUserId(user.getUserId());
463 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
464 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
469 private Resource createResourceObjectCsar(boolean afterCreate) {
470 Resource resource = new Resource();
471 resource.setName(RESOURCE_NAME);
472 resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
473 resource.setDescription("My short description");
474 List<String> tgs = new ArrayList<>();
476 tgs.add(resource.getName());
477 resource.setTags(tgs);
478 List<String> template = new ArrayList<>();
479 template.add("tosca.nodes.Root");
480 resource.setDerivedFrom(template);
481 resource.setVendorName("Motorola");
482 resource.setVendorRelease("1.0.0");
483 resource.setResourceVendorModelNumber("");
484 resource.setContactId("ya5467");
485 resource.setIcon("MyIcon");
486 resource.setCsarUUID("valid_vf.csar");
487 resource.setCsarVersion("1");
490 resource.setName(resource.getName());
491 resource.setVersion("0.1");
493 resource.setUniqueId(resource.getName()
494 .toLowerCase() + ":" + resource.getVersion());
495 resource.setCreatorUserId(user.getUserId());
496 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
497 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
502 private Resource setCanWorkOnResource(Resource resource) {
503 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
504 resource.setLastUpdaterUserId(user.getUserId());
509 public void testHappyScenario() {
510 validateUserRoles(Role.ADMIN, Role.DESIGNER);
511 Resource resource = createResourceObject(false);
512 Resource createdResource = null;
514 when(toscaOperationFacade
515 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
516 .thenReturn(Either.left(false));
517 createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
518 assertThat(createResourceObject(true)).isEqualTo(createdResource);
519 } catch (ComponentException e) {
520 assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
526 public void testUpdateHappyScenario() {
527 Resource resource = createResourceObjectCsar(true);
528 setCanWorkOnResource(resource);
529 validateUserRoles(Role.ADMIN, Role.DESIGNER);
530 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource);
531 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes);
532 Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
533 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
534 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
535 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
536 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
537 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
539 assertThat(resource.getUniqueId()).isEqualTo(bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()).getUniqueId());
540 } catch (ComponentException e) {
541 assertThat(e.getResponseFormat().getStatus()).isEqualTo(200);
546 public void testUpdateUnhappyScenario() {
547 Resource resource = createResourceObjectCsar(true);
548 setCanWorkOnResource(resource);
549 validateUserRoles(Role.ADMIN, Role.DESIGNER);
551 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(Either.left(resource));
552 when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(Either.left(true));
553 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(Either.left(setCanWorkOnResource(resource)));
554 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(Either.left(resource));
556 when(csarOperation.getCsar("valid_vf.csar", user)).thenReturn(Either.left(new HashMap<>()));
560 Resource createdResource = bl.validateAndUpdateResourceFromCsar(resource, user, null, "", resource.getUniqueId());
561 assertThat(resource.getUniqueId()).isEqualTo(createdResource.getUniqueId());
562 } catch (ComponentException e) {
563 assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
566 resource.setCsarVersion("2");
567 when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(Either.left(resource));
568 bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId());
569 } catch (ComponentException e) {
570 assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
573 /* CREATE validations - start ***********************/
574 // Resource name - start
577 public void testFailedResourceValidations() {
578 testResourceNameExist();
579 testResourceNameEmpty();
580 // testResourceNameExceedsLimit();
581 testResourceNameWrongFormat();
582 testResourceDescExceedsLimitCreate();
583 testResourceDescNotEnglish();
584 testResourceDescriptionEmpty();
585 testResourceDescriptionMissing();
586 testResourceIconMissing();
587 testResourceIconInvalid();
588 testResourceIconExceedsLimit();
589 testResourceTagNotExist();
590 testResourceTagEmpty();
591 testTagsExceedsLimitCreate();
592 testTagsNoServiceName();
595 testContactIdTooLong();
596 testContactIdWrongFormatCreate();
597 testResourceContactIdEmpty();
598 testResourceContactIdMissing();
599 testVendorNameExceedsLimit();
600 testVendorNameWrongFormatCreate();
601 testVendorReleaseWrongFormat();
602 testVendorReleaseExceedsLimitCreate();
603 testResourceVendorModelNumberExceedsLimit();
604 testResourceVendorNameMissing();
605 testResourceVendorReleaseMissing();
606 testResourceCategoryExist();
607 testResourceBadCategoryCreate();
608 testHappyScenarioCostLicenseType();
609 testCostWrongFormatCreate();
610 testLicenseTypeWrongFormatCreate();
611 testResourceTemplateNotExist();
612 testResourceTemplateEmpty();
613 testResourceTemplateInvalid();
616 private void testResourceNameExist() {
617 String resourceName = "alreadyExists";
618 Resource resourceExist = createResourceObject(false);
619 resourceExist.setName(resourceName);
620 resourceExist.getTags()
622 validateUserRoles(Role.ADMIN, Role.DESIGNER);
623 when(toscaOperationFacade
624 .validateComponentNameAndModelExists(resourceName, null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
625 .thenReturn(Either.left(true));
627 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
628 } catch (ComponentException e) {
629 assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
630 ComponentTypeEnum.RESOURCE.getValue(), resourceName);
634 private void testResourceNameEmpty() {
635 Resource resourceExist = createResourceObject(false);
636 resourceExist.setName(null);
639 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
640 } catch (ComponentException e) {
641 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
645 private void testResourceNameExceedsLimit() {
646 Resource resourceExccedsNameLimit = createResourceObject(false);
647 // 51 chars, the limit is 50
648 String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
649 resourceExccedsNameLimit.setName(tooLongResourceName);
652 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
653 } catch (ComponentException e) {
654 assertComponentException(e, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT,
655 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
659 private void testResourceNameWrongFormat() {
660 Resource resource = createResourceObject(false);
662 String nameWrongFormat = "ljg?fd";
663 resource.setName(nameWrongFormat);
666 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
667 } catch (ComponentException e) {
668 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
672 // Resource name - end
673 // Resource description - start
674 private void testResourceDescExceedsLimitCreate() {
675 Resource resourceExccedsDescLimit = createResourceObject(false);
676 // 1025 chars, the limit is 1024
677 String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
678 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
679 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
680 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
681 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
682 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
683 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
684 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
686 resourceExccedsDescLimit.setDescription(tooLongResourceDesc);
688 bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
689 } catch (ComponentException e) {
690 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
691 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
695 private void testResourceDescNotEnglish() {
696 Resource notEnglish = createResourceObject(false);
698 String notEnglishDesc = "\uC2B5";
699 notEnglish.setDescription(notEnglishDesc);
702 bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
703 } catch (ComponentException e) {
704 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION,
705 ComponentTypeEnum.RESOURCE.getValue());
709 private void testResourceDescriptionEmpty() {
710 Resource resourceExist = createResourceObject(false);
711 resourceExist.setDescription("");
714 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
715 } catch (ComponentException e) {
716 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
717 ComponentTypeEnum.RESOURCE.getValue());
721 private void testResourceDescriptionMissing() {
722 Resource resourceExist = createResourceObject(false);
723 resourceExist.setDescription(null);
726 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
727 } catch (ComponentException e) {
728 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
729 ComponentTypeEnum.RESOURCE.getValue());
732 // Resource description - end
733 // Resource icon start
735 private void testResourceIconMissing() {
736 Resource resourceExist = createResourceObject(false);
737 resourceExist.setIcon(null);
738 when(toscaOperationFacade
739 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
740 .thenReturn(Either.left(false));
742 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
743 } catch (ComponentException e) {
744 assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
748 private void testResourceIconInvalid() {
749 Resource resourceExist = createResourceObject(false);
750 resourceExist.setIcon("kjk3453^&");
753 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
754 } catch (ComponentException e) {
755 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
759 private void testResourceIconExceedsLimit() {
760 Resource resourceExist = createResourceObject(false);
761 resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
763 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
764 } catch (ComponentException e) {
765 assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT,
766 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
771 // Resource tags - start
772 private void testResourceTagNotExist() {
773 Resource resourceExist = createResourceObject(false);
774 resourceExist.setTags(null);
776 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
777 } catch (ComponentException e) {
778 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
782 private void testResourceTagEmpty() {
783 Resource resourceExist = createResourceObject(false);
784 resourceExist.setTags(new ArrayList<>());
786 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
787 } catch (ComponentException e) {
788 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
792 private void testTagsExceedsLimitCreate() {
793 Resource resourceExccedsNameLimit = createResourceObject(false);
794 String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
795 String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
796 String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
797 String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
798 String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
799 String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
800 String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
801 String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
802 String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
803 String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
804 String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
805 String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
806 String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
807 String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
808 String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
809 String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
810 String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
811 String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
812 String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
813 String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
814 String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
816 List<String> tagsList = new ArrayList<>();
838 tagsList.add(resourceExccedsNameLimit.getName());
840 resourceExccedsNameLimit.setTags(tagsList);
842 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
843 } catch (ComponentException e) {
844 assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
845 "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
849 private void testTagsSingleExceedsLimit() {
850 Resource resourceExccedsNameLimit = createResourceObject(false);
851 String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI";
852 String tag2 = resourceExccedsNameLimit.getName();
853 List<String> tagsList = new ArrayList<>();
857 resourceExccedsNameLimit.setTags(tagsList);
859 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
860 } catch (ComponentException e) {
861 assertComponentException(e, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT,
862 "" + ValidationUtils.TAG_MAX_LENGTH);
866 private void testTagsNoServiceName() {
867 Resource serviceExccedsNameLimit = createResourceObject(false);
868 String tag1 = "afzs2qLBb";
869 List<String> tagsList = new ArrayList<>();
871 serviceExccedsNameLimit.setTags(tagsList);
873 bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
874 } catch (ComponentException e) {
875 assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
879 private void testInvalidTag() {
880 Resource serviceExccedsNameLimit = createResourceObject(false);
881 String tag1 = "afzs2qLBb%#%";
882 List<String> tagsList = new ArrayList<>();
884 serviceExccedsNameLimit.setTags(tagsList);
886 bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
887 } catch (ComponentException e) {
888 assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Resource", "tag" });
892 // Resource tags - stop
893 // Resource contact start
895 private void testContactIdTooLong() {
896 Resource resourceContactId = createResourceObject(false);
897 // 59 chars instead of 50
898 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
899 resourceContactId.setContactId(contactIdTooLong);
902 bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
903 } catch (ComponentException e) {
904 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
908 private void testContactIdWrongFormatCreate() {
909 Resource resourceContactId = createResourceObject(false);
910 // 3 letters and 3 digits and special characters
911 String contactIdFormatWrong = "yrt134!!!";
912 resourceContactId.setContactId(contactIdFormatWrong);
914 bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
915 } catch (ComponentException e) {
916 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
920 private void testResourceContactIdEmpty() {
921 Resource resourceExist = createResourceObject(false);
922 resourceExist.setContactId("");
924 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
925 } catch (ComponentException e) {
926 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
930 private void testResourceContactIdMissing() {
931 Resource resourceExist = createResourceObject(false);
932 resourceExist.setContactId(null);
934 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
935 } catch (ComponentException e) {
936 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
940 private void testVendorNameExceedsLimit() {
941 Resource resourceExccedsVendorNameLimit = createResourceObject(false);
942 String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
943 resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
945 bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
946 } catch (ComponentException e) {
947 assertComponentException(e, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
948 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
952 private void testResourceVendorModelNumberExceedsLimit() {
953 Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
954 String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
955 resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
957 bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null,
959 } catch (ComponentException e) {
960 assertComponentException(e, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
961 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
965 private void testVendorNameWrongFormatCreate() {
966 Resource resource = createResourceObject(false);
968 String nameWrongFormat = "ljg*fd";
969 resource.setVendorName(nameWrongFormat);
971 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
972 } catch (ComponentException e) {
973 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
977 private void testVendorReleaseWrongFormat() {
978 Resource resource = createResourceObject(false);
980 String vendorReleaseWrongFormat = "1>2";
981 resource.setVendorRelease(vendorReleaseWrongFormat);
983 bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
984 } catch (ComponentException e) {
985 assertComponentException(e, ActionStatus.INVALID_VENDOR_RELEASE, vendorReleaseWrongFormat);
989 private void testVendorReleaseExceedsLimitCreate() {
990 Resource resourceExccedsNameLimit = createResourceObject(false);
991 String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
992 resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
994 bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
995 } catch (ComponentException e) {
996 assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
997 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
1001 private void testResourceVendorNameMissing() {
1002 Resource resourceExist = createResourceObject(false);
1003 resourceExist.setVendorName(null);
1005 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1006 } catch (ComponentException e) {
1007 assertComponentException(e, ActionStatus.MISSING_VENDOR_NAME);
1011 private void testResourceVendorReleaseMissing() {
1012 Resource resourceExist = createResourceObject(false);
1013 resourceExist.setVendorRelease(null);
1015 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1016 } catch (ComponentException e) {
1017 assertComponentException(e, ActionStatus.MISSING_VENDOR_RELEASE);
1021 // Resource vendor name/release stop
1023 private void testResourceCategoryExist() {
1024 Resource resourceExist = createResourceObject(false);
1025 resourceExist.setCategories(null);
1027 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1028 } catch (ComponentException e) {
1029 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1033 private void testResourceBadCategoryCreate() {
1035 Resource resourceExist = createResourceObject(false);
1036 resourceExist.setCategories(null);
1037 resourceExist.addCategory("koko", "koko");
1039 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1040 } catch (ComponentException e) {
1041 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1047 private void testHappyScenarioCostLicenseType() {
1048 Resource createResourceObject = createResourceObject(false);
1049 Resource createResourceObjectAfterCreate = createResourceObject(true);
1050 // Adding cost and licenseType to basic mock
1051 Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate);
1052 when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
1054 String cost = "123.456";
1055 String licenseType = "User";
1056 createResourceObject.setCost(cost);
1057 createResourceObject.setLicenseType(licenseType);
1058 Resource createdResource;
1060 createdResource = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null,
1062 createResourceObjectAfterCreate.setCost(cost);
1063 createResourceObjectAfterCreate.setLicenseType(licenseType);
1064 assertThat(createResourceObjectAfterCreate).isEqualTo(createdResource);
1065 } catch (ComponentException e) {
1066 assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
1071 private void testCostWrongFormatCreate() {
1072 Resource resourceCost = createResourceObject(false);
1073 // Comma instead of fullstop
1074 String cost = "12356,464";
1075 resourceCost.setCost(cost);
1077 bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1078 } catch (ComponentException e) {
1079 assertComponentException(e, ActionStatus.INVALID_CONTENT);
1084 // License type start
1085 private void testLicenseTypeWrongFormatCreate() {
1086 Resource resourceLicenseType = createResourceObject(false);
1088 String licenseType = "cpu";
1089 resourceLicenseType.setLicenseType(licenseType);
1091 bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1092 } catch (ComponentException e) {
1093 assertComponentException(e, ActionStatus.INVALID_CONTENT);
1097 // License type stop
1098 // Derived from start
1099 private void testResourceTemplateNotExist() {
1100 Resource resourceExist = createResourceObject(false);
1101 List<String> list = null;
1102 resourceExist.setDerivedFrom(list);
1104 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1105 } catch (ComponentException e) {
1106 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1110 private void testResourceTemplateEmpty() {
1111 Resource resourceExist = createResourceObject(false);
1112 resourceExist.setDerivedFrom(new ArrayList<>());
1114 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1115 } catch (ComponentException e) {
1116 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1120 private void testResourceTemplateInvalid() {
1121 Resource resourceExist = createResourceObject(false);
1122 ArrayList<String> derivedFrom = new ArrayList<>();
1123 derivedFrom.add("kuku");
1124 resourceExist.setDerivedFrom(derivedFrom);
1126 bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
1127 } catch (ComponentException e) {
1128 assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
1132 // Derived from stop
1133 private void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) {
1134 ResponseFormat actualResponse = e.getResponseFormat() != null ? e.getResponseFormat()
1135 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1136 assertResponse(actualResponse, expectedStatus, variables);
1139 private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
1140 ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
1141 assertThat(expectedResponse.getStatus()).isEqualTo(actualResponse.getStatus());
1142 assertThat(expectedResponse.getFormattedMessage()).isEqualTo(actualResponse.getFormattedMessage());
1145 private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus,
1146 String... variables) {
1147 assertResponse(createResponse.right()
1148 .value(), expectedStatus, variables);
1151 // UPDATE tests - start
1154 public void testResourceNameWrongFormat_UPDATE() {
1155 Resource resource = createResourceObject(true);
1156 Resource updatedResource = createResourceObject(true);
1158 // this is in order to prevent failing with 403 earlier
1159 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1160 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1162 String nameWrongFormat = "ljg*fd";
1163 updatedResource.setName(nameWrongFormat);
1165 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1166 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1168 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1169 } catch (ComponentException e) {
1170 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
1175 public void testResourceNameAfterCertify_UPDATE() {
1176 Resource resource = createResourceObject(true);
1177 Resource updatedResource = createResourceObject(true);
1179 // this is in order to prevent failing with 403 earlier
1180 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1181 // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
1182 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1184 String name = "ljg";
1185 updatedResource.setName(name);
1186 resource.setVersion("1.0");
1188 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1189 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1191 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1192 } catch (ComponentException e) {
1193 assertComponentException(e, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1198 public void testResourceNameAlreadyExist_UPDATE() {
1199 Resource resource = createResourceObject(true);
1200 Resource updatedResource = createResourceObject(true);
1202 // this is in order to prevent failing with 403 earlier
1203 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1204 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1206 String resourceName = "alreadyExists";
1207 updatedResource.setName(resourceName);
1208 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
1209 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1211 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1212 } catch (ComponentException e) {
1213 assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
1214 ComponentTypeEnum.RESOURCE.getValue(), resourceName);
1221 public void testResourceDescExceedsLimit_UPDATE() {
1222 Resource resource = createResourceObject(true);
1223 Resource updatedResource = createResourceObject(true);
1225 // this is in order to prevent failing with 403 earlier
1226 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1227 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1229 // 1025 chars, the limit is 1024
1230 String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
1231 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
1232 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
1233 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
1234 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
1235 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
1236 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
1237 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
1238 updatedResource.setDescription(tooLongResourceDesc);
1239 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1240 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1242 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1243 } catch (ComponentException e) {
1244 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
1245 ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
1250 public void testIconWrongFormat_UPDATE() {
1251 Resource resource = createResourceObject(true);
1252 Resource updatedResource = createResourceObject(true);
1254 // this is in order to prevent failing with 403 earlier
1255 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1256 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1259 String icon = "icon.jpg";
1260 updatedResource.setIcon(icon);
1261 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1262 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1264 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1265 } catch (ComponentException e) {
1266 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
1271 public void testIconAfterCertify_UPDATE() {
1272 Resource resource = createResourceObject(true);
1273 Resource updatedResource = createResourceObject(true);
1275 // this is in order to prevent failing with 403 earlier
1276 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1277 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1280 String icon = "icon";
1281 updatedResource.setIcon(icon);
1283 resource.setVersion("1.0");
1285 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1286 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1288 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1289 } catch (ComponentException e) {
1290 assertComponentException(e, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
1295 public void testTagsExceedsLimit_UPDATE() {
1296 Resource resource = createResourceObject(true);
1297 Resource updatedResource = createResourceObject(true);
1299 // this is in order to prevent failing with 403 earlier
1300 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1301 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1303 String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
1304 String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
1305 String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
1306 String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
1307 String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
1308 String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
1309 String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
1310 String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
1311 String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
1312 String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
1313 String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
1314 String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
1315 String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
1316 String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
1317 String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
1318 String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
1319 String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
1320 String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
1321 String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
1322 String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
1323 String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
1325 List<String> tagsList = new ArrayList<>();
1335 tagsList.add(tag10);
1336 tagsList.add(tag11);
1337 tagsList.add(tag12);
1338 tagsList.add(tag13);
1339 tagsList.add(tag14);
1340 tagsList.add(tag15);
1341 tagsList.add(tag16);
1342 tagsList.add(tag17);
1343 tagsList.add(tag18);
1344 tagsList.add(tag19);
1345 tagsList.add(tag20);
1346 tagsList.add(tag21);
1347 tagsList.add(resource.getName());
1349 updatedResource.setTags(tagsList);
1350 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1351 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1353 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1354 } catch (ComponentException e) {
1355 assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
1356 "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
1361 public void testVendorNameWrongFormat_UPDATE() {
1362 Resource resource = createResourceObject(true);
1363 Resource updatedResource = createResourceObject(true);
1365 // this is in order to prevent failing with 403 earlier
1366 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1367 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1370 String nameWrongFormat = "ljg*fd";
1371 updatedResource.setVendorName(nameWrongFormat);
1372 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1373 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1375 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1376 } catch (ComponentException e) {
1377 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
1382 public void testVendorNameWrongFormat() {
1383 Resource resource = createResourceObject(true);
1384 Resource updatedResource = createResourceObject(true);
1386 // this is in order to prevent failing with 403 earlier
1387 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1388 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1391 String nameWrongFormat = "ljg*fd";
1392 updatedResource.setVendorName(nameWrongFormat);
1393 resource.setVersion("1.0");
1395 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1396 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1398 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1399 } catch (ComponentException e) {
1400 assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
1405 public void testVendorReleaseExceedsLimit_UPDATE() {
1406 Resource resource = createResourceObject(true);
1407 Resource updatedResource = createResourceObject(true);
1409 // this is in order to prevent failing with 403 earlier
1410 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1411 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1412 // 129 chars, the limit is 128
1413 String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy";
1414 updatedResource.setVendorRelease(tooLongVendorRelease);
1415 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1416 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1418 bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
1419 } catch (ComponentException e) {
1420 assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
1421 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
1426 public void testResourceBadCategory_UPDATE() {
1427 Resource resource = createResourceObject(true);
1428 Resource updatedResource = createResourceObject(true);
1430 // this is in order to prevent failing with 403 earlier
1431 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1432 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1434 String resourceId = resource.getUniqueId();
1435 String badCategory = "ddfds";
1436 updatedResource.setCategories(null);
1437 updatedResource.addCategory(badCategory, "fikt");
1438 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1439 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1441 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1442 } catch (ComponentException e) {
1443 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
1447 @Test(expected = ComponentException.class)
1448 public void createResourceFromCsarTest() {
1449 bl.createResourceFromCsar(resourceResponse, user, new HashMap<>(), "");
1453 public void testCreateResourceFromCsarWithModel() throws URISyntaxException, ZipException {
1455 final File csarFile = new File(
1456 ResourceBusinessLogicTest.class.getClassLoader().getResource("csars/nonOnapCsar.csar").toURI());
1457 final Map<String, byte[]> csar = ZipUtils.readZip(csarFile, false);
1459 String resourceYml = new String(csar.get("Definitions/my_vnf.yaml"));
1461 YamlTemplateParsingHandler yamlTemplateParser = new YamlTemplateParsingHandler(mockJanusGraphDao, null, Mockito.mock(AnnotationBusinessLogic.class), null);
1462 final ParsedToscaYamlInfo parsedToscaYamlInfo = yamlTemplateParser.parseResourceInfoFromYAML("Definitions/my_vnf.yml", resourceYml, Collections.EMPTY_MAP, Collections.EMPTY_MAP, "myVnf", resourceResponse);
1464 when(propertyOperation.getDataTypeByName("tosca.datatypes.testDataType.FromMainTemplate", "testModel")).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1466 when(toscaOperationFacade.getLatestByToscaResourceName(anyString(), any())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1467 Resource vduCp = new Resource();
1468 vduCp.setToscaResourceName("tosca.nodes.nfv.VduCp");
1469 vduCp.setState(LifecycleStateEnum.CERTIFIED);
1470 vduCp.setUniqueId("tosca.nodes.nfv.VduCp");
1471 vduCp.setProperties(new ArrayList<>());
1472 Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
1473 RequirementDefinition req = new RequirementDefinition();
1474 req.setName("virtual_link");
1475 List<RequirementDefinition> listReqs = new ArrayList<>();
1477 requirements.put("tosca.nodes.nfv.VduCp", listReqs);
1478 vduCp.setRequirements(requirements);
1479 PropertyDefinition bitrateProp = new PropertyDefinition();
1480 bitrateProp.setName("bitrate_requirement");
1481 bitrateProp.setType("integer");
1482 vduCp.getProperties().add(bitrateProp);
1483 PropertyDefinition virtNiProp = new PropertyDefinition();
1484 virtNiProp.setName("virtual_network_interface_requirements");
1485 virtNiProp.setType("list");
1486 vduCp.getProperties().add(virtNiProp);
1487 PropertyDefinition descriptionProp = new PropertyDefinition();
1488 descriptionProp.setName("description");
1489 descriptionProp.setType("string");
1490 vduCp.getProperties().add(descriptionProp);
1491 PropertyDefinition roleProp = new PropertyDefinition();
1492 roleProp.setName("role");
1493 roleProp.setType("string");
1494 vduCp.getProperties().add(roleProp);
1495 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel("tosca.nodes.nfv.VduCp", "testModel_myVnf1.0")).thenReturn(Either.left(vduCp));
1498 when(yamlTemplateParsingHandler.parseResourceInfoFromYAML(any(), any(), any(), any(), any(), any())).thenReturn(parsedToscaYamlInfo);
1500 UploadComponentInstanceInfo uploadComponentInstanceInfo = new UploadComponentInstanceInfo();
1501 uploadComponentInstanceInfo.setType("myType");
1502 resourceResponse.setUniqueId("myVnf");
1503 resourceResponse.setName("myVnf");
1504 resourceResponse.setSystemName("myVnf");
1505 resourceResponse.setModel("testModel");
1506 resourceResponse.setResourceType(ResourceTypeEnum.VF);
1507 resourceResponse.setProperties(new ArrayList<>());
1508 resourceResponse.setCsarVersion("1.0");
1510 Resource derivedFrom = new Resource();
1511 List<PropertyDefinition> properties = new ArrayList<>();
1512 PropertyDefinition baseTypeProp = new PropertyDefinition();
1513 baseTypeProp.setName("propInBase");
1514 baseTypeProp.setType("string");
1515 properties.add(baseTypeProp);
1516 derivedFrom.setProperties(properties );
1517 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(any(), eq("tosca.nodes.nfv.VNF"))).thenReturn(Either.left(derivedFrom));
1519 when(toscaOperationFacade
1520 .validateComponentNameAndModelExists("myVnf", "testModel_myVnf1.0", ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(false));
1522 when(toscaOperationFacade.addPropertyToComponent(any(), any(), any())).thenReturn(Either.left(new PropertyDefinition()));
1523 when(toscaOperationFacade.associateComponentInstancePropertiesToComponent(any(), any())).thenReturn(Either.left(Collections.emptyMap()));
1524 when(toscaOperationFacade.associateArtifactsToInstances(any(), any())).thenReturn(StorageOperationStatus.OK);
1525 when(toscaOperationFacade.associateDeploymentArtifactsToInstances(any(), any(), any())).thenReturn(StorageOperationStatus.OK);
1526 when(toscaOperationFacade.associateInstAttributeToComponentToInstances(any(), any())).thenReturn(StorageOperationStatus.OK);
1527 when(toscaOperationFacade.associateResourceInstances(any(Component.class), anyString(), anyList())).thenReturn(Either.left(Collections.EMPTY_LIST));
1528 when(applicationDataTypeCache.getAll("testModel_myVnf1.0")).thenReturn(Either.left(emptyDataTypes));
1530 doAnswer(invocation -> {
1531 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReqs = invocation.getArgument(1);
1532 for (final Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> m: instReqs.entrySet()) {
1533 m.getKey().setRequirements(m.getValue());
1535 return StorageOperationStatus.OK;
1537 when(toscaOperationFacade).associateOrAddCalculatedCapReq(any(), any(), any());
1539 when(toscaOperationFacade.updateCalculatedCapabilitiesRequirements(any(), any(), any())).thenReturn(StorageOperationStatus.OK);
1540 when(groupBusinessLogic.validateUpdateVfGroupNames(any(), any())).thenReturn(Either.left(Collections.EMPTY_MAP));
1542 ComponentInstance ci = new ComponentInstance();
1543 List<ComponentInstance> cis = new ArrayList<>();
1545 doAnswer(invocation -> {
1546 List<ComponentInstance> componentInstances = new ArrayList<ComponentInstance>(((Map<ComponentInstance, Resource>)invocation.getArgument(1)).keySet());
1547 ((Resource)invocation.getArgument(0)).setComponentInstances(componentInstances);
1549 }).when(toscaOperationFacade).associateComponentInstancesToComponent(any(), any(), eq(false), eq(false));
1551 doAnswer(invocation -> {
1552 return Either.left(invocation.getArgument(0));
1553 }).when(csarArtifactsAndGroupsBusinessLogic).deleteVFModules(any(Resource.class), any(CsarInfo.class), eq(true), eq(false));
1555 doAnswer(invocation -> {
1556 return Either.left(resourceResponse);
1557 }).when(toscaOperationFacade).getToscaFullElement("myVnf");
1559 Resource result = bl.createResourceFromCsar(resourceResponse, user, csar, "1234");
1561 assertEquals("myDomain.myVnf", result.getToscaResourceName());
1562 List<String> propIds = result.getProperties().stream().map(prop -> prop.getUniqueId()).collect(Collectors.toList());
1563 assertTrue(propIds.contains("myVnf.propInBase"));
1564 assertTrue(propIds.contains("myVnf.descriptor_id"));
1565 assertTrue(propIds.contains("myVnf.descriptor_version"));
1566 assertTrue(propIds.contains("myVnf.flavour_description"));
1567 assertTrue(propIds.contains("myVnf.flavour_id"));
1568 assertTrue(propIds.contains("myVnf.product_name"));
1569 assertTrue(propIds.contains("myVnf.provider"));
1570 assertTrue(propIds.contains("myVnf.software_version"));
1571 assertTrue(propIds.contains("myVnf.vnfm_info"));
1573 final List<String> reqsName = new ArrayList<>();
1575 final List<ComponentInstance> cisWithExtReq = result.getComponentInstances().stream().filter(instance -> instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).isExternal()).collect(Collectors.toList());
1576 cisWithExtReq.forEach(instance -> reqsName.add(instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).getExternalName()));
1577 assertEquals(3, cisWithExtReq.size());
1581 public void testResourceCategoryAfterCertify_UPDATE() {
1582 Resource resource = createResourceObject(true);
1583 Resource updatedResource = createResourceObject(true);
1585 // this is in order to prevent failing with 403 earlier
1586 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1587 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1589 String resourceId = resource.getUniqueId();
1590 updatedResource.setCategories(null);
1591 updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY);
1592 resource.setVersion("1.0");
1594 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1595 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1597 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1598 } catch (ComponentException e) {
1599 assertComponentException(e, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
1603 // Derived from start
1605 public void testResourceTemplateNotExist_UPDATE() {
1606 Resource resource = createResourceObject(true);
1607 Resource updatedResource = createResourceObject(true);
1609 // this is in order to prevent failing with 403 earlier
1610 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1611 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1612 String resourceId = resource.getUniqueId();
1614 List<String> list = null;
1615 updatedResource.setDerivedFrom(list);
1616 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1617 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1619 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1620 } catch (ComponentException e) {
1621 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1626 public void testResourceTemplateEmpty_UPDATE() {
1627 Resource resource = createResourceObject(true);
1628 Resource updatedResource = createResourceObject(true);
1629 String resourceId = resource.getUniqueId();
1631 // this is in order to prevent failing with 403 earlier
1632 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1633 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1635 updatedResource.setDerivedFrom(new ArrayList<>());
1636 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1637 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1639 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1640 } catch (ComponentException e) {
1641 assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1646 public void testResourceTemplateInvalid_UPDATE() {
1647 Resource resource = createResourceObject(true);
1648 Resource updatedResource = createResourceObject(true);
1649 String resourceId = resource.getUniqueId();
1651 // this is in order to prevent failing with 403 earlier
1652 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1653 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1655 ArrayList<String> derivedFrom = new ArrayList<>();
1656 derivedFrom.add("kuku");
1657 updatedResource.setDerivedFrom(derivedFrom);
1658 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1659 when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
1661 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1662 } catch (ComponentException e) {
1663 assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
1668 public void testResourceTemplateCertify_UPDATE_HAPPY() {
1669 Resource resource = createResourceObject(true);
1670 Resource updatedResource = createResourceObject(true);
1671 String resourceId = resource.getUniqueId();
1673 // this is in order to prevent failing with 403 earlier
1674 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1675 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1677 Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true);
1678 when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
1679 .thenReturn(isToscaNameExtending);
1681 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
1682 .left(new HashMap<>());
1683 when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
1684 .thenReturn(findPropertiesOfNode);
1686 resource.setVersion("1.0");
1688 ArrayList<String> derivedFrom = new ArrayList<>();
1689 derivedFrom.add("tosca.nodes.Root");
1690 updatedResource.setDerivedFrom(derivedFrom);
1691 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
1692 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1693 Resource createdResource = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1694 assertThat(createdResource).isNotNull();
1698 public void testResourceTemplateCertify_UPDATE_SAD() {
1699 Resource resource = createResourceObject(true);
1700 Resource updatedResource = createResourceObject(true);
1701 String resourceId = resource.getUniqueId();
1703 // this is in order to prevent failing with 403 earlier
1704 Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
1705 when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
1707 Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false);
1708 when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
1709 .thenReturn(isToscaNameExtending);
1711 resource.setVersion("1.0");
1713 ArrayList<String> derivedFrom = new ArrayList<>();
1714 derivedFrom.add("tosca.nodes.Root");
1715 updatedResource.setDerivedFrom(derivedFrom);
1716 Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
1717 when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
1718 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
1719 .left(new HashMap<>());
1720 when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
1721 .thenReturn(findPropertiesOfNode);
1724 bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
1725 } catch (ComponentException e) {
1726 assertComponentException(e, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1729 // Derived from stop
1732 public void createOrUpdateResourceAlreadyCheckout() {
1734 Resource resourceExist = createResourceObject(false);
1735 validateUserRoles(Role.ADMIN, Role.DESIGNER);
1736 when(toscaOperationFacade
1737 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1738 .thenReturn(Either.left(false));
1739 Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
1741 createdResource.setLastUpdaterUserId(user.getUserId());
1742 assertThat(createdResource).isNotNull();
1743 Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
1744 Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
1745 when(toscaOperationFacade.getLatestByToscaResourceName(resourceExist.getToscaResourceName(), null))
1746 .thenReturn(getCompLatestResult);
1747 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
1748 .thenReturn(getCompLatestResult);
1749 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1750 .thenReturn(getLatestResult);
1752 Resource resourceToUpdtae = createResourceObject(false);
1754 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1755 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1756 assertNotNull(createOrUpdateResource);
1758 Mockito.verify(toscaOperationFacade, Mockito.times(1))
1759 .overrideComponent(any(Resource.class), any(Resource.class));
1760 Mockito.verify(lifecycleBl, Mockito.times(0))
1761 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1762 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1767 public void createOrUpdateResourceCertified() {
1769 Resource resourceExist = createResourceObject(false);
1770 when(toscaOperationFacade
1771 .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1772 .thenReturn(Either.left(false));
1773 validateUserRoles(Role.ADMIN, Role.DESIGNER);
1774 Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
1777 assertThat(createdResource).isNotNull();
1778 createdResource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
1779 createdResource.setVersion("1.0");
1781 Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
1782 Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
1783 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
1784 .thenReturn(getCompLatestResult);
1785 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1786 .thenReturn(getLatestResult);
1788 when(lifecycleBl.changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1789 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()))
1790 .thenReturn(Either.left(createdResource));
1792 Resource resourceToUpdtae = createResourceObject(false);
1794 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1795 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1796 assertNotNull(createOrUpdateResource);
1798 Mockito.verify(toscaOperationFacade, Mockito.times(1))
1799 .overrideComponent(any(Resource.class), any(Resource.class));
1800 Mockito.verify(lifecycleBl, Mockito.times(1))
1801 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1802 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1807 public void createOrUpdateResourceNotExist() {
1808 Resource resourceToUpdtae = createResourceObject(false);
1810 Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
1811 when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName(), null)).thenReturn(getLatestResult);
1812 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdtae.getToscaResourceName(), null))
1813 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1814 when(toscaOperationFacade
1815 .validateComponentNameAndModelExists(resourceToUpdtae.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1816 .thenReturn(Either.left(false));
1818 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1819 .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
1820 assertThat(createOrUpdateResource).isNotNull();
1822 Mockito.verify(toscaOperationFacade, times(1))
1823 .createToscaComponent(resourceToUpdtae);
1824 Mockito.verify(toscaOperationFacade, Mockito.times(0))
1825 .overrideComponent(any(Resource.class), any(Resource.class));
1826 Mockito.verify(lifecycleBl, Mockito.times(0))
1827 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1828 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1833 public void testIfNodeTypeNameHasValidPrefix() {
1834 final List<String> definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager()
1835 .getConfiguration().getDefinedResourceNamespace();
1837 definedNodeTypeNamespaceList.parallelStream().forEach(validNodeTypePrefix -> {
1838 final String nodeName = validNodeTypePrefix + "." + "abc";
1839 final Optional<String> result = bl.validateNodeTypeNamePrefix(nodeName, definedNodeTypeNamespaceList);
1840 assertTrue(result.isPresent());
1845 public void updateNestedResource_typeIsNew() throws IOException {
1846 Resource resourceToUpdate = createResourceObject(false);
1847 String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
1848 String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
1849 CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
1851 String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
1852 .name(), csarInfo.getVfResourceName(), nodeName)
1854 when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
1855 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1856 when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
1857 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1858 when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
1859 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1861 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
1862 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1863 when(toscaOperationFacade
1864 .validateComponentNameAndModelExists(resourceToUpdate.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
1865 .thenReturn(Either.left(false));
1867 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1868 .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
1869 assertThat(createOrUpdateResource).isNotNull();
1871 Mockito.verify(toscaOperationFacade, times(1))
1872 .createToscaComponent(resourceToUpdate);
1873 Mockito.verify(toscaOperationFacade, times(0))
1874 .overrideComponent(any(Resource.class), any(Resource.class));
1875 Mockito.verify(lifecycleBl, times(0))
1876 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1877 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1881 public void updateNestedResource_typeExists() throws IOException {
1883 Resource resourceToUpdate = createResourceObject(false);
1884 setCanWorkOnResource(resourceResponse);
1885 String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
1886 String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
1887 CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
1889 String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
1890 .name(), csarInfo.getVfResourceName(), nodeName)
1892 when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
1893 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1894 when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
1895 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1896 when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
1897 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
1898 when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
1899 .thenReturn(Either.left(resourceResponse));
1900 when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
1901 .thenReturn(Either.left(resourceResponse));
1903 ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
1904 .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
1905 assertThat(createOrUpdateResource).isNotNull();
1906 Mockito.verify(toscaOperationFacade, times(1))
1907 .overrideComponent(any(Resource.class), any(Resource.class));
1908 Mockito.verify(lifecycleBl, times(0))
1909 .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
1910 any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
1914 public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() {
1915 Resource basic = createResourceObject(true);
1917 Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1918 assertTrue(validatePropertiesDefaultValues);
1922 public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() {
1923 Resource basic = createResourceObject(true);
1924 PropertyDefinition property = new PropertyDefinition();
1925 property.setName("myProperty");
1926 property.setType(ToscaPropertyType.INTEGER.getType());
1927 property.setDefaultValue("1");
1928 List<PropertyDefinition> properties = new ArrayList<>();
1929 properties.add(property);
1930 basic.setProperties(properties);
1931 when(propertyOperation.isPropertyTypeValid(property, null)).thenReturn(true);
1932 when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true);
1933 Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
1934 assertTrue(validatePropertiesDefaultValues);
1937 @Test(expected = ComponentException.class)
1938 public void testValidatePropertiesDefaultValues_FailedWithProperties() {
1939 Resource basic = createResourceObject(true);
1940 PropertyDefinition property = new PropertyDefinition();
1941 property.setName("myProperty");
1942 property.setType(ToscaPropertyType.INTEGER.getType());
1943 property.setDefaultValue("1.5");
1944 List<PropertyDefinition> properties = new ArrayList<>();
1945 properties.add(property);
1946 basic.setProperties(properties);
1948 when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false);
1949 bl.validatePropertiesDefaultValues(basic);
1953 public void testDeleteMarkedResourcesNoResources() {
1954 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(new ArrayList<>());
1956 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
1958 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
1959 assertTrue(deleteMarkedResources.isLeft());
1960 assertTrue(deleteMarkedResources.left().value().isEmpty());
1964 public void testDeleteMarkedResources() {
1965 List<String> ids = new ArrayList<>();
1966 String resourceInUse = "123";
1967 String resourceFree = "456";
1968 ids.add(resourceInUse);
1969 ids.add(resourceFree);
1970 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
1971 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
1973 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
1974 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
1976 List<ArtifactDefinition> artifacts = new ArrayList<>();
1978 when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
1979 when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
1981 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new
1983 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
1985 List<String> deletedComponents = new ArrayList<>();
1986 deletedComponents.add(resourceFree);
1987 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents));
1989 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
1990 assertTrue(deleteMarkedResources.isLeft());
1991 List<String> resourceIdList = deleteMarkedResources.left().value();
1992 assertFalse(resourceIdList.isEmpty());
1993 assertTrue(resourceIdList.contains(resourceFree));
1994 assertFalse(resourceIdList.contains(resourceInUse));
1997 @SuppressWarnings("unchecked")
1999 public void testFindVfCsarArtifactsToHandle() {
2001 Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
2002 String methodName = "findVfCsarArtifactsToHandle";
2003 Resource resource = new Resource();
2004 String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml";
2005 String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml";
2006 String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml";
2008 String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml";
2009 String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml";
2010 String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml";
2011 String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml";
2013 byte[] oldPayloadData = "oldPayloadData".getBytes();
2014 byte[] newPayloadData = "newPayloadData".getBytes();
2015 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
2017 ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition();
2018 deploymentArtifactToUpdate.setMandatory(false);
2019 deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName);
2020 deploymentArtifactToUpdate.setArtifactType("SNMP_POLL");
2021 deploymentArtifactToUpdate.setPayload(oldPayloadData);
2022 deploymentArtifactToUpdate
2023 .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2025 ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition();
2026 deploymentArtifactToDelete.setMandatory(false);
2027 deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName);
2028 deploymentArtifactToDelete.setArtifactType("SNMP_TRAP");
2029 deploymentArtifactToDelete.setPayload(oldPayloadData);
2030 deploymentArtifactToDelete
2031 .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2033 ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition();
2035 deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()),
2036 deploymentArtifactToUpdate);
2037 deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()),
2038 deploymentArtifactToDelete);
2039 deploymentArtifacts.put("ignore", deploymentArtifactToIgnore);
2041 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
2043 ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
2044 artifactToUpdate.setMandatory(false);
2045 artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName);
2046 artifactToUpdate.setArtifactType("SNMP_POLL");
2047 artifactToUpdate.setPayload(oldPayloadData);
2048 artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2050 ArtifactDefinition artifactToDelete = new ArtifactDefinition();
2051 artifactToDelete.setMandatory(false);
2052 artifactToDelete.setArtifactName(artifactInfoToDeleteFileName);
2053 artifactToDelete.setArtifactType("SNMP_TRAP");
2054 artifactToDelete.setPayload(oldPayloadData);
2055 artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2056 artifactToDelete.setIsFromCsar(true);
2058 ArtifactDefinition artifactToNotDelete = new ArtifactDefinition();
2059 artifactToNotDelete.setMandatory(false);
2060 artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName);
2061 artifactToNotDelete.setArtifactType("SNMP_TRAP");
2062 artifactToNotDelete.setPayload(oldPayloadData);
2063 artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
2064 artifactToNotDelete.setIsFromCsar(false);
2066 ArtifactDefinition artifactToIgnore = new ArtifactDefinition();
2068 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate);
2069 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete);
2070 artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()),
2071 artifactToNotDelete);
2072 artifacts.put("ignore", artifactToIgnore);
2074 resource.setDeploymentArtifacts(deploymentArtifacts);
2075 resource.setArtifacts(artifacts);
2077 List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>();
2078 NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(
2079 deploymentArtifactToUpdate.getArtifactName(), null,
2080 deploymentArtifactToUpdate.getArtifactType(),
2081 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false);
2083 NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(
2084 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2085 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), false);
2087 NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
2088 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2089 ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData, artifactToUpdate.getArtifactName(), true);
2091 NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
2092 artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
2093 ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), true);
2095 NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName,
2096 null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData,
2097 deploymentArtifactToCreateFileName, false);
2099 NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName,
2100 null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData,
2101 artifactInfoToCreateFileName, false);
2103 artifactPathAndNameList.add(deploymentArtifactInfoToUpdate);
2104 artifactPathAndNameList.add(informationalArtifactInfoToUpdate);
2105 artifactPathAndNameList.add(deploymentArtifactInfoToCreate);
2106 artifactPathAndNameList.add(informationalArtifactInfoToCreate);
2107 artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar);
2108 artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar);
2110 Object[] argObjects = { resource, artifactPathAndNameList, user };
2111 Class[] argClasses = { Resource.class, List.class, User.class };
2113 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
2114 method.setAccessible(true);
2115 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method
2116 .invoke(bl, argObjects);
2117 assertTrue(findVfCsarArtifactsToHandleRes.isLeft());
2118 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes
2121 assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.CREATE)
2123 assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.UPDATE)
2125 assertEquals(1, foundVfArtifacts.get(ArtifactOperationEnum.DELETE)
2128 } catch (Exception e) {
2129 e.printStackTrace();
2134 public void testVFGeneratedInputs() {
2135 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2136 Resource resource = createVF();
2137 List<InputDefinition> inputs = resource.getInputs();
2138 assertEquals(6, inputs.size());
2139 for (InputDefinition input : inputs) {
2140 assertThat(input.getOwnerId()).isNotNull();
2142 assertEquals(resource.getDerivedFromGenericType(), genericVF.getToscaResourceName());
2143 assertEquals(resource.getDerivedFromGenericVersion(), genericVF.getVersion());
2147 public void testCRGeneratedInputs() {
2148 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2149 Resource resource = createCR();
2150 List<InputDefinition> inputs = resource.getInputs();
2151 assertEquals(3, inputs.size());
2152 for (InputDefinition input : inputs) {
2153 assertThat(input.getOwnerId()).isNotNull();
2155 assertEquals(resource.getDerivedFromGenericType(), genericCR.getToscaResourceName());
2156 assertEquals(resource.getDerivedFromGenericVersion(), genericCR.getVersion());
2160 public void testVFUpdateGenericInputsToLatestOnCheckout() {
2161 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2162 // create a VF that is derived from generic version 1.0
2163 Resource resource = createVF();
2164 // create a new generic version without properties
2165 genericVF.setVersion("2.0");
2166 genericVF.setProperties(null);
2167 String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
2168 List<InputDefinition> currentInputs = resource.getInputs();
2169 // verify previous inputs ownerId fields exist - user may not delete
2171 assertEquals(6, currentInputs.stream()
2172 .filter(p -> null != p.getOwnerId())
2173 .collect(Collectors.toList())
2175 Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
2177 assertTrue(upgradeToLatestGeneric.isLeft());
2178 // verify update required and valid
2179 assertTrue(upgradeToLatestGeneric.left()
2181 // verify version was upgraded
2182 assertNotEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
2183 // verify inputs were not deleted
2184 assertEquals(6, resource.getInputs()
2186 // verify inputs ownerId fields were removed - user may delete/edit
2188 assertEquals(6, resource.getInputs()
2190 .filter(p -> null == p.getOwnerId())
2191 .collect(Collectors.toList())
2196 public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
2198 // create a VF that is derived from generic version 1.0
2199 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2200 Resource resource = createVF();
2202 // add an input to the VF
2203 PropertyDefinition newProp = new PropertyDefinition();
2204 newProp.setType("integer");
2205 newProp.setName("newProp");
2206 resource.getInputs()
2207 .add(new InputDefinition(newProp));
2209 // create a new generic version with a new property which has the same
2210 // name as a user defined input on the VF with a different type
2211 genericVF.setVersion("2.0");
2212 newProp.setType("string");
2213 genericVF.setProperties(new ArrayList<>());
2214 genericVF.getProperties()
2216 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
2217 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
2218 genericVF.getUniqueId())).thenCallRealMethod();
2219 String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
2220 assertEquals(6, resource.getInputs()
2222 .filter(p -> null != p.getOwnerId())
2223 .collect(Collectors.toList())
2225 Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
2227 assertTrue(upgradeToLatestGeneric.isLeft());
2228 // verify update is invalid an void
2229 assertFalse(upgradeToLatestGeneric.left()
2231 // verify version was not upgraded
2232 assertEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
2233 // verify inputs were not removed
2234 assertEquals(7, resource.getInputs()
2236 // verify user defined input exists
2237 assertEquals(1, resource.getInputs()
2239 .filter(p -> null == p.getOwnerId())
2240 .collect(Collectors.toList())
2242 assertEquals("integer", resource.getInputs()
2244 .filter(p -> null == p.getOwnerId())
2251 public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
2252 validateUserRoles(Role.ADMIN, Role.DESIGNER);
2253 Resource resource = createPNF();
2254 List<InputDefinition> inputs = resource.getInputs();
2255 assertEquals(3, inputs.size());
2256 for (InputDefinition input : inputs) {
2257 assertThat(input.getOwnerId()).isNotNull();
2259 assertEquals(resource.getDerivedFromGenericType(), genericPNF.getToscaResourceName());
2260 assertEquals(resource.getDerivedFromGenericVersion(), genericPNF.getVersion());
2261 assertEquals(0, resource.getArtifacts()
2265 private Resource createVF() {
2267 genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
2268 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME))
2269 .thenReturn(Either.left(genericVF));
2270 Resource resource = createResourceObject(true);
2271 resource.setDerivedFrom(null);
2272 resource.setResourceType(ResourceTypeEnum.VF);
2273 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2274 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericVF));
2275 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod();
2276 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
2277 resource.getUniqueId())).thenCallRealMethod();
2278 when(toscaOperationFacade
2279 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE))
2280 .thenReturn(Either.left(false));
2281 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2282 assertThat(createdResource).isNotNull();
2283 return createdResource;
2286 private Resource createRoot() {
2287 rootType = setupGenericTypeMock(GENERIC_ROOT_NAME);
2288 when(toscaOperationFacade.getLatestByToscaResourceName(GENERIC_ROOT_NAME, null))
2289 .thenReturn(Either.left(rootType));
2293 private Resource createCR() {
2295 genericCR = setupGenericTypeMock(GENERIC_CR_NAME);
2296 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME))
2297 .thenReturn(Either.left(genericCR));
2298 Resource resource = createResourceObject(true);
2299 resource.setDerivedFrom(null);
2300 resource.setResourceType(ResourceTypeEnum.CR);
2301 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2302 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericCR));
2303 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod();
2304 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(),
2305 resource.getUniqueId())).thenCallRealMethod();
2306 when(toscaOperationFacade
2307 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE))
2308 .thenReturn(Either.left(false));
2309 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2310 assertThat(createdResource).isNotNull();
2311 return createdResource;
2314 private Resource createPNF() {
2316 genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
2317 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME))
2318 .thenReturn(Either.left(genericPNF));
2319 Resource resource = createResourceObject(true);
2320 resource.setDerivedFrom(null);
2321 resource.setResourceType(ResourceTypeEnum.PNF);
2322 when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
2323 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericPNF));
2324 when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod();
2325 when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(),
2326 resource.getUniqueId())).thenCallRealMethod();
2327 when(toscaOperationFacade
2328 .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE))
2329 .thenReturn(Either.left(false));
2330 Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
2331 assertThat(createdResource).isNotNull();
2332 return createdResource;
2335 private Map<String, String> getGenericPropertiesByToscaName(String toscaName) {
2336 HashMap<String, String> PNFProps = new HashMap<String, String>() {
2338 put("nf_function", "string");
2339 put("nf_role", "string");
2340 put("nf_type", "string");
2344 HashMap<String, String> CRProps = new HashMap<String, String>() {
2346 put("cr_function", "string");
2347 put("cr_role", "string");
2348 put("cr_type", "string");
2352 HashMap<String, String> VFProps = new HashMap<String, String>() {
2355 put("availability_zone_max_count", "integer");
2356 put("min_instances", "integer");
2357 put("max_instances", "integer");
2361 if (toscaName.contains("PNF"))
2363 if (toscaName.contains("CR"))
2365 if (toscaName.contains("VF"))
2368 return new HashMap<>();
2371 private Resource setupGenericTypeMock(String toscaName) {
2373 Resource genericType = createResourceObject(true);
2374 genericType.setVersion("1.0");
2375 genericType.setToscaResourceName(toscaName);
2376 genericType.setAbstract(true);
2377 List<PropertyDefinition> genericProps = new ArrayList<>();
2378 Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName);
2379 genericPropsMap.forEach((name, type) -> {
2380 PropertyDefinition prop = new PropertyDefinition();
2383 genericProps.add(prop);
2386 genericType.setProperties(genericProps);
2390 private void validateUserRoles(Role... roles) {
2391 List<Role> listOfRoles = Stream.of(roles)
2392 .collect(Collectors.toList());
2396 public void testUpdateVolumeGroup() {
2397 Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
2398 bl.updateVolumeGroup(resource);
2399 assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(true));
2403 public void testUpdateVolumeGroupNull() {
2404 Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
2405 resource.setGroups(null);
2406 bl.updateVolumeGroup(resource);
2407 assertThat(resource.getGroups()).isNull();
2411 public void testUpdateVolumeGroupFail() {
2412 Resource resource = getResourceWithType("NON_EXIST_HEAT", "org.openecomp.groups.VfModule");
2413 bl.updateVolumeGroup(resource);
2414 assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(false));
2417 private Resource getResourceWithType(String artifactType, String groupDefinitionType) {
2418 ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
2419 List<GroupDefinition> groups = new ArrayList<>();
2420 GroupDefinition gd = new GroupDefinition();
2421 List<PropertyDataDefinition> properties = new ArrayList<>();
2422 PropertyDataDefinition pdd = new PropertyDataDefinition();
2423 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
2424 List<String> artifactsList = new ArrayList<>();
2426 artifactToUpdate.setArtifactType(artifactType);
2427 artifactToUpdate.setArtifactName(artifactType);
2428 artifactToUpdate.setUniqueId(artifactType);
2429 Resource resource = createResourceObjectCsar(true);
2430 artifactsList.add(artifactToUpdate.getArtifactName());
2433 pdd.setName("volume_group");
2434 pdd.setValue("true");
2435 pdd.setType(ToscaPropertyType.BOOLEAN.getType());
2437 artifacts.put(artifactToUpdate.getArtifactName(), artifactToUpdate);
2439 properties.add(pdd);
2440 gd.setType(groupDefinitionType);
2441 gd.setProperties(properties);
2442 gd.setArtifacts(artifactsList);
2445 resource.setGroups(groups);
2446 resource.setDeploymentArtifacts(artifacts);
2452 public void testgetAllCertifiedResources() throws Exception {
2453 List<Resource> list = bl.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, "USER");
2454 Assert.assertEquals(reslist,list);
2457 @Test(expected = StorageException.class)
2458 public void testgetAllCertifiedResources_exception() throws Exception {
2459 List<Resource> list = bl.getAllCertifiedResources(false, HighestFilterEnum.NON_HIGHEST_ONLY, "USER");
2460 Assert.assertEquals(reslist,list);
2464 public void testvalidateResourceNameExists() throws Exception {
2465 Either<Map<String, Boolean>, ResponseFormat> res = bl.validateResourceNameExists("Resource", ResourceTypeEnum.CR, "jh0003");
2466 Assert.assertEquals(true,res.isLeft());
2470 public void rollbackWithEitherAlwaysReturnARuntimeException() {
2471 JanusGraphDao janusGraphDao = mockJanusGraphDao;
2472 ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
2473 String params = "testName";
2475 Either<Object, RuntimeException> result =
2476 ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
2478 assertTrue(result.isRight());
2479 assertTrue(result.right().value() instanceof ByActionStatusComponentException);
2483 public void rollbackWithEitherWorksWithNullJanusGraphDao() {
2484 JanusGraphDao janusGraphDao = null;
2485 ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
2486 String params = "testName";
2488 Either<Object, RuntimeException> result =
2489 ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
2491 assertTrue(result.isRight());
2492 assertTrue(result.right().value() instanceof ByActionStatusComponentException);