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