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