2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import fj.data.Either;
24 import org.apache.commons.lang3.tuple.ImmutablePair;
25 import org.junit.Before;
26 import org.junit.Test;
27 import org.mockito.Mockito;
28 import org.openecomp.sdc.ElementOperationMock;
29 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
30 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
31 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
32 import org.openecomp.sdc.be.components.validation.UserValidations;
33 import org.openecomp.sdc.be.config.ConfigurationManager;
34 import org.openecomp.sdc.be.dao.api.ActionStatus;
35 import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
36 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
37 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
38 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
39 import org.openecomp.sdc.be.impl.ComponentsUtils;
40 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
41 import org.openecomp.sdc.be.model.*;
42 import org.openecomp.sdc.be.model.category.CategoryDefinition;
43 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
44 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
45 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
46 import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
47 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
48 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
49 import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
50 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
51 import org.openecomp.sdc.be.user.Role;
52 import org.openecomp.sdc.be.user.UserBusinessLogic;
53 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
54 import org.openecomp.sdc.common.api.ConfigurationSource;
55 import org.openecomp.sdc.common.api.Constants;
56 import org.openecomp.sdc.common.impl.ExternalConfiguration;
57 import org.openecomp.sdc.common.impl.FSConfigurationSource;
58 import org.openecomp.sdc.common.util.ValidationUtils;
59 import org.openecomp.sdc.exception.ResponseFormat;
60 import org.springframework.web.context.WebApplicationContext;
62 import javax.servlet.ServletContext;
63 import java.lang.reflect.Method;
65 import java.util.stream.Collectors;
66 import java.util.stream.Stream;
68 import static org.assertj.core.api.Assertions.assertThat;
69 import static org.junit.Assert.*;
70 import static org.junit.Assert.assertNotNull;
71 import static org.mockito.ArgumentMatchers.anyString;
72 import static org.mockito.ArgumentMatchers.eq;
73 import static org.mockito.Mockito.when;
74 import static org.mockito.ArgumentMatchers.anyString;
75 import static org.mockito.ArgumentMatchers.eq;
76 import static org.mockito.Mockito.when;
78 public class ServiceBusinessLogicTest {
80 private static final String SERVICE_CATEGORY = "Mobility";
81 private static final String INSTANTIATION_TYPE = "A-la-carte";
82 private final ServletContext servletContext = Mockito.mock(ServletContext.class);
83 private UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
84 private WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
85 private WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
86 private ServiceBusinessLogic bl = new ServiceBusinessLogic();
87 private ResponseFormatManager responseManager = null;
88 private ComponentsUtils componentsUtils;
89 private AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
90 private ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
91 private GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
92 private TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
93 private ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
94 private CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
95 private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
96 private UserValidations userValidations = Mockito.mock(UserValidations.class);
97 private ResourceAdminEvent auditArchive1 = Mockito.mock(ResourceAdminEvent.class);
98 private ResourceAdminEvent auditArchive2 = Mockito.mock(ResourceAdminEvent.class);
99 private ResourceAdminEvent auditRestore = Mockito.mock(ResourceAdminEvent.class);
101 private User user = null;
102 private Resource genericService = null;
104 private static final String CERTIFIED_VERSION = "1.0";
105 private static final String UNCERTIFIED_VERSION = "0.2";
106 private static final String COMPONNET_ID = "myUniqueId";
107 private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
109 public ServiceBusinessLogicTest() {
114 public void setup() {
116 ExternalConfiguration.setAppName("catalog-be");
117 // init Configuration
118 String appConfigDir = "src/test/resources/config/catalog-be";
119 ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
120 ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
121 componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
124 IElementOperation mockElementDao = new ElementOperationMock();
126 // User data and management
128 user.setUserId("jh0003");
129 user.setFirstName("Jimmi");
130 user.setLastName("Hendrix");
131 user.setRole(Role.ADMIN.name());
133 Either<User, ActionStatus> eitherGetUser = Either.left(user);
134 when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
135 when(userValidations.validateUserExists(eq("jh0003"), anyString(), eq(false))).thenReturn(user);
136 when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
137 when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
138 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
139 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
140 when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
141 when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
142 when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
144 // artifact bussinesslogic
145 ArtifactDefinition artifactDef = new ArtifactDefinition();
146 when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
149 Service serviceResponse = createServiceObject(true);
150 Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
151 when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate);
152 Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
153 when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount);
154 Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
155 when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist);
157 genericService = setupGenericServiceMock();
158 Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService);
159 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric);
162 bl = new ServiceBusinessLogic();
163 bl.setElementDao(mockElementDao);
164 bl.setUserAdmin(mockUserAdmin);
165 bl.setArtifactBl(artifactBl);
166 bl.setGraphLockOperation(graphLockOperation);
167 bl.setTitanGenericDao(mockTitanDao);
168 bl.setToscaOperationFacade(toscaOperationFacade);
169 bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
170 bl.setComponentsUtils(componentsUtils);
171 bl.setCassandraAuditingDao(auditingDao);
172 bl.setCacheManagerOperation(cacheManager);
173 bl.setUserValidations(userValidations);
175 mockAuditingDaoLogic();
177 responseManager = ResponseFormatManager.getInstance();
182 public void testGetComponentAuditRecordsCertifiedVersion() {
183 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
184 assertTrue(componentAuditRecords.isLeft());
185 assertEquals(3, componentAuditRecords.left().value().size());
189 public void testGetComponentAuditRecordsUnCertifiedVersion() {
190 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
191 assertTrue(componentAuditRecords.isLeft());
192 assertEquals(4, componentAuditRecords.left().value().size());
196 public void testHappyScenario() {
197 Service service = createServiceObject(false);
198 validateUserRoles(Role.ADMIN, Role.DESIGNER);
199 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
200 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
202 if (createResponse.isRight()) {
203 assertEquals(new Integer(200), createResponse.right().value().getStatus());
205 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
208 private void validateUserRoles(Role ... roles) {
209 List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
212 private void assertEqualsServiceObject(Service origService, Service newService) {
213 assertEquals(origService.getContactId(), newService.getContactId());
214 assertEquals(origService.getCategories(), newService.getCategories());
215 assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
216 assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
217 assertEquals(origService.getDescription(), newService.getDescription());
218 assertEquals(origService.getIcon(), newService.getIcon());
219 assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
220 assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
221 assertEquals(origService.getName(), newService.getName());
222 assertEquals(origService.getName(), newService.getName());
223 assertEquals(origService.getUniqueId(), newService.getUniqueId());
224 assertEquals(origService.getVersion(), newService.getVersion());
225 assertEquals(origService.getArtifacts(), newService.getArtifacts());
226 assertEquals(origService.getCreationDate(), newService.getCreationDate());
227 assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
228 assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
229 assertEquals(origService.getTags(), newService.getTags());
232 private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
233 assertResponse(createResponse.right().value(), expectedStatus, variables);
236 private void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) {
237 ResponseFormat actualResponse = e.getResponseFormat() != null ?
238 e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
239 assertResponse(actualResponse, expectedStatus, variables);
242 private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
243 ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
244 assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
245 assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
250 public void testFailedServiceValidations() {
251 testServiceNameAlreadyExists();
252 testServiceNameEmpty();
253 testServiceNameWrongFormat();
254 testServiceDescriptionEmpty();
255 testServiceDescriptionMissing();
256 testServiceDescExceedsLimitCreate();
257 testServiceDescNotEnglish();
258 testServiceIconEmpty();
259 testServiceIconMissing();
260 testResourceIconInvalid();
261 testResourceIconExceedsLimit();
262 testTagsNoServiceName();
264 testServiceTagNotExist();
265 testServiceTagEmpty();
267 testContactIdTooLong();
268 testContactIdWrongFormatCreate();
269 testInvalidProjectCode();
270 testProjectCodeTooLong();
271 testProjectCodeTooShort();
273 testResourceContactIdMissing();
274 testServiceCategoryExist();
275 testServiceBadCategoryCreate();
276 testMissingProjectCode();
279 private void testServiceNameAlreadyExists() {
280 String serviceName = "alreadyExist";
281 Service serviceExccedsNameLimit = createServiceObject(false);
282 // 51 chars, the limit is 50
283 serviceExccedsNameLimit.setName(serviceName);
284 List<String> tgs = new ArrayList<>();
285 tgs.add(serviceName);
286 serviceExccedsNameLimit.setTags(tgs);
287 validateUserRoles(Role.ADMIN, Role.DESIGNER);
288 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
289 assertTrue(createResponse.isRight());
290 assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
293 private void testServiceNameEmpty() {
294 Service serviceExccedsNameLimit = createServiceObject(false);
295 serviceExccedsNameLimit.setName(null);
297 bl.createService(serviceExccedsNameLimit, user);
298 } catch(ComponentException e){
299 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
303 private void testServiceNameWrongFormat() {
304 Service service = createServiceObject(false);
306 String nameWrongFormat = "ljg\fd";
307 service.setName(nameWrongFormat);
309 bl.createService(service, user);
310 } catch(ComponentException e){
311 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
315 private void testServiceDescriptionEmpty() {
316 Service serviceExist = createServiceObject(false);
317 serviceExist.setDescription("");
319 bl.createService(serviceExist, user);
320 } catch(ComponentException e){
321 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
325 private void testServiceDescriptionMissing() {
326 Service serviceExist = createServiceObject(false);
327 serviceExist.setDescription(null);
329 bl.createService(serviceExist, user);
330 } catch(ComponentException e){
331 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
335 private void testServiceDescExceedsLimitCreate() {
336 Service serviceExccedsDescLimit = createServiceObject(false);
337 // 1025 chars, the limit is 1024
338 String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
339 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
340 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
341 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
342 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
343 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
344 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
345 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
347 serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
349 bl.createService(serviceExccedsDescLimit, user);
350 } catch(ComponentException e){
351 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
355 private void testServiceDescNotEnglish() {
356 Service notEnglish = createServiceObject(false);
358 String tooLongServiceDesc = "\uC2B5";
359 notEnglish.setDescription(tooLongServiceDesc);
361 bl.createService(notEnglish, user);
362 } catch(ComponentException e){
363 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
367 // Service description - stop
368 // Service icon - start
369 private void testServiceIconEmpty() {
370 Service serviceExist = createServiceObject(false);
371 serviceExist.setIcon("");
373 bl.createService(serviceExist, user);
374 } catch(ComponentException e) {
375 assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
379 private void testServiceIconMissing() {
380 Service serviceExist = createServiceObject(false);
381 serviceExist.setIcon(null);
383 bl.createService(serviceExist, user);
384 } catch(ComponentException e) {
385 assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
389 private void testResourceIconInvalid() {
390 Service resourceExist = createServiceObject(false);
391 resourceExist.setIcon("kjk3453^&");
393 bl.createService(resourceExist, user);
394 } catch(ComponentException e) {
395 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
399 private void testResourceIconExceedsLimit() {
400 Service resourceExist = createServiceObject(false);
401 resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
403 bl.createService(resourceExist, user);
404 } catch(ComponentException e) {
405 assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, "Service", "25");
409 private void testTagsNoServiceName() {
410 Service serviceExccedsNameLimit = createServiceObject(false);
411 String tag1 = "afzs2qLBb";
412 List<String> tagsList = new ArrayList<>();
414 serviceExccedsNameLimit.setTags(tagsList);
416 bl.createService(serviceExccedsNameLimit, user);
417 } catch(ComponentException e) {
418 assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
422 private void testInvalidTag() {
423 Service serviceExccedsNameLimit = createServiceObject(false);
424 String tag1 = "afzs2qLBb%#%";
425 List<String> tagsList = new ArrayList<>();
427 serviceExccedsNameLimit.setTags(tagsList);
429 bl.createService(serviceExccedsNameLimit, user);
430 } catch(ComponentException e) {
431 assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
435 private void testServiceTagNotExist() {
436 Service serviceExist = createServiceObject(false);
437 serviceExist.setTags(null);
439 bl.createService(serviceExist, user);
440 } catch(ComponentException e) {
441 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
445 private void testServiceTagEmpty() {
446 Service serviceExist = createServiceObject(false);
447 serviceExist.setTags(new ArrayList<>());
449 bl.createService(serviceExist, user);
450 } catch(ComponentException e) {
451 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
455 // Service tags - stop
456 // Service contactId - start
457 private void testContactIdTooLong() {
458 Service serviceContactId = createServiceObject(false);
459 // 59 chars instead of 50
460 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
461 serviceContactId.setContactId(contactIdTooLong);
463 bl.createService(serviceContactId, user);
464 } catch(ComponentException e) {
465 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
469 private void testContactIdWrongFormatCreate() {
470 Service serviceContactId = createServiceObject(false);
471 // 3 letters and 3 digits and special characters
472 String contactIdTooLong = "yrt134!!!";
473 serviceContactId.setContactId(contactIdTooLong);
475 bl.createService(serviceContactId, user);
476 } catch(ComponentException e) {
477 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
481 private void testResourceContactIdMissing() {
482 Service resourceExist = createServiceObject(false);
483 resourceExist.setContactId(null);
485 bl.createService(resourceExist, user);
486 } catch(ComponentException e) {
487 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
491 // Service contactId - stop
492 // Service category - start
493 private void testServiceCategoryExist() {
494 Service serviceExist = createServiceObject(false);
495 serviceExist.setCategories(null);
497 bl.createService(serviceExist, user);
498 } catch(ComponentException e) {
499 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
504 public void markDistributionAsDeployedTestAlreadyDeployed() {
505 String notifyAction = "DNotify";
506 String requestAction = "DRequest";
507 String resultAction = "DResult";
508 String did = "123456";
510 setupBeforeDeploy(notifyAction, requestAction, did);
511 List<DistributionDeployEvent> resultList = new ArrayList<>();
512 Map<String, Object> params = new HashMap<>();
513 DistributionDeployEvent event = new DistributionDeployEvent();
515 event.setAction(resultAction);
517 event.setStatus("200");
518 // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
519 // deployEvent.setFields(params);
520 resultList.add(event);
521 Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
523 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
525 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
526 assertTrue(markDeployed.isLeft());
528 Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
533 public void markDistributionAsDeployedTestSuccess() {
534 String notifyAction = "DNotify";
535 String requestAction = "DRequest";
536 String did = "123456";
538 setupBeforeDeploy(notifyAction, requestAction, did);
539 List<Role> roles = new ArrayList<>();
540 roles.add(Role.ADMIN);
542 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
543 assertTrue(markDeployed.isLeft());
547 public void markDistributionAsDeployedTestNotDistributed() {
548 String notifyAction = "DNotify";
549 String requestAction = "DRequest";
550 String did = "123456";
552 setupBeforeDeploy(notifyAction, requestAction, did);
553 List<ResourceAdminEvent> emptyList = new ArrayList<>();
554 Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
555 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
557 Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
558 Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
560 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
561 assertTrue(markDeployed.isRight());
562 assertEquals(404, markDeployed.right().value().getStatus().intValue());
566 private void testServiceBadCategoryCreate() {
568 Service serviceExist = createServiceObject(false);
569 CategoryDefinition category = new CategoryDefinition();
570 category.setName("koko");
571 List<CategoryDefinition> categories = new ArrayList<>();
572 categories.add(category);
573 serviceExist.setCategories(categories);
575 bl.createService(serviceExist, user);
576 } catch(ComponentException e) {
577 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
581 // Service category - stop
582 // Service projectCode - start
583 private void testInvalidProjectCode() {
585 Service serviceExist = createServiceObject(false);
586 serviceExist.setProjectCode("koko!!");
588 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
589 assertTrue(createResponse.isRight());
591 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
594 private void testProjectCodeTooLong() {
596 Service serviceExist = createServiceObject(false);
597 String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
598 serviceExist.setProjectCode(tooLongProjectCode);
600 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
601 assertTrue(createResponse.isRight());
603 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
606 private void testProjectCodeTooShort() {
608 Service serviceExist = createServiceObject(false);
609 serviceExist.setProjectCode("333");
611 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
612 assertTrue(createResponse.isRight());
614 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
617 private void testMissingProjectCode() {
619 Service serviceExist = createServiceObject(false);
620 serviceExist.setProjectCode(null);
622 bl.createService(serviceExist, user);
623 } catch(ComponentException e) {
624 assertComponentException(e, ActionStatus.MISSING_PROJECT_CODE);
629 public void testDeleteMarkedServices() {
630 List<String> ids = new ArrayList<>();
631 List<String> responseIds = new ArrayList<>();
632 String resourceInUse = "123";
633 ids.add(resourceInUse);
634 String resourceFree = "456";
635 ids.add(resourceFree);
636 responseIds.add(resourceFree);
637 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
638 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
640 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
641 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
643 List<ArtifactDefinition> artifacts = new ArrayList<>();
644 Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
646 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
647 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
648 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
649 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
650 assertTrue(deleteMarkedResources.isLeft());
651 List<String> resourceIdList = deleteMarkedResources.left().value();
652 assertFalse(resourceIdList.isEmpty());
653 assertTrue(resourceIdList.contains(resourceFree));
654 assertFalse(resourceIdList.contains(resourceInUse));
658 private Service createServiceObject(boolean afterCreate) {
659 Service service = new Service();
660 service.setUniqueId("sid");
661 service.setName("Service");
662 CategoryDefinition category = new CategoryDefinition();
663 category.setName(SERVICE_CATEGORY);
664 List<CategoryDefinition> categories = new ArrayList<>();
665 categories.add(category);
666 service.setCategories(categories);
667 service.setInstantiationType(INSTANTIATION_TYPE);
669 service.setDescription("description");
670 List<String> tgs = new ArrayList<>();
671 tgs.add(service.getName());
672 service.setTags(tgs);
673 service.setIcon("MyIcon");
674 service.setContactId("aa1234");
675 service.setProjectCode("12345");
678 service.setVersion("0.1");
679 service.setUniqueId(service.getName() + ":" + service.getVersion());
680 service.setCreatorUserId(user.getUserId());
681 service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
686 private void mockAuditingDaoLogic() {
687 final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
688 createResourceAudit.setModifier("Carlos Santana(cs0008)");
689 createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
690 createResourceAudit.setCurrVersion("0.1");
691 createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
692 createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f");
693 createResourceAudit.setDesc("OK");
694 createResourceAudit.setResourceType("Resource");
695 createResourceAudit.setStatus("201");
696 createResourceAudit.setPrevVersion("");
697 createResourceAudit.setAction("Create");
698 // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977");
699 createResourceAudit.setPrevState("");
700 createResourceAudit.setResourceName("MyTestResource");
701 // createResourceAudit.setFields(fields);
703 final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent();
704 checkInResourceAudit.setModifier("Carlos Santana(cs0008)");
705 checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN");
706 checkInResourceAudit.setCurrVersion("0.1");
707 checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
708 checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091");
709 checkInResourceAudit.setDesc("OK");
710 checkInResourceAudit.setComment("Stam");
711 checkInResourceAudit.setResourceType("Resource");
712 checkInResourceAudit.setStatus("200");
713 checkInResourceAudit.setPrevVersion("0.1");
714 checkInResourceAudit.setAction("Checkin");
715 // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797");
716 checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT");
717 checkInResourceAudit.setResourceName("MyTestResource");
719 final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent();
720 checkOutResourceAudit.setModifier("Carlos Santana(cs0008)");
721 checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
722 checkOutResourceAudit.setCurrVersion("0.2");
723 checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
724 checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8");
725 checkOutResourceAudit.setDesc("OK");
726 checkOutResourceAudit.setComment("");
727 checkOutResourceAudit.setResourceType("Resource");
728 checkOutResourceAudit.setStatus("200");
729 checkOutResourceAudit.setPrevVersion("0.1");
730 checkOutResourceAudit.setAction("Checkout");
731 // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024");
732 checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN");
733 checkOutResourceAudit.setResourceName("MyTestResource");
734 List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() {
736 add(createResourceAudit);
737 add(checkInResourceAudit);
738 add(checkOutResourceAudit);
741 Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
742 Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
744 List<ResourceAdminEvent> listPrev = new ArrayList<>();
745 Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
746 Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
748 List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() {
750 add(checkOutResourceAudit);
753 Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr);
754 Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr);
756 Either<List<ResourceAdminEvent>, ActionStatus> archiveAuditList = Either.left(Arrays.asList(auditArchive1, auditArchive2));
757 when(auditingDao.getArchiveAuditByServiceInstanceId(anyString())).thenReturn(archiveAuditList);
759 Either<List<ResourceAdminEvent>, ActionStatus> restoreAuditList = Either.left(Arrays.asList(auditRestore));
760 when(auditingDao.getRestoreAuditByServiceInstanceId(anyString())).thenReturn(restoreAuditList);
764 private void setupBeforeDeploy(String notifyAction, String requestAction, String did) {
766 DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent();
767 notifyEvent.setAction(notifyAction);
768 notifyEvent.setDid(did);
769 notifyEvent.setStatus("200");
771 ResourceAdminEvent requestEvent = new ResourceAdminEvent();
772 requestEvent.setAction(requestAction);
773 requestEvent.setDid(did);
774 requestEvent.setStatus("200");
776 List<DistributionNotificationEvent> notifyResults = Collections.singletonList(notifyEvent);
777 Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults);
779 Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify);
781 List<ResourceAdminEvent> requestResults = Collections.singletonList(requestEvent);
782 Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults);
783 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest);
785 Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true));
786 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
788 Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(Collections.emptyList());
789 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList);
792 @SuppressWarnings({ "unchecked", "rawtypes" })
794 public void testFindGroupInstanceOnRelatedComponentInstance() {
796 Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
797 String methodName = "findGroupInstanceOnRelatedComponentInstance";
798 Object invalidId = "invalidId";
800 Component service = createNewService();
801 List<ComponentInstance> componentInstances = service.getComponentInstances();
803 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
804 Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
805 Class[] argClasses = {Component.class, String.class,String.class};
807 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
808 method.setAccessible(true);
810 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
811 assertNotNull(findGroupInstanceRes);
812 assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
814 assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
819 Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
821 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
822 assertNotNull(findGroupInstanceRes);
823 assertTrue(findGroupInstanceRes.isRight());
824 assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
826 Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
828 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
829 assertNotNull(findGroupInstanceRes);
830 assertTrue(findGroupInstanceRes.isRight());
831 assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
833 catch (Exception e) {
838 private Component createNewService() {
840 Service service = new Service();
842 service.setName("serviceName");
843 service.setUniqueId("serviceUniqueId");
844 List<ComponentInstance> componentInstances = new ArrayList<>();
845 ComponentInstance ci;
846 for(int i= 0; i<listSize; ++i){
847 ci = new ComponentInstance();
848 ci.setName("ciName" + i);
849 ci.setUniqueId("ciId" + i);
850 List<GroupInstance> groupInstances= new ArrayList<>();
852 for(int j = 0; j<listSize; ++j){
853 gi = new GroupInstance();
854 gi.setName(ci.getName( )+ "giName" + j);
855 gi.setUniqueId(ci.getName() + "giId" + j);
856 groupInstances.add(gi);
858 ci.setGroupInstances(groupInstances);
859 componentInstances.add(ci);
861 service.setComponentInstances(componentInstances);
867 public void testDerivedFromGeneric() {
868 Service service = createServiceObject(true);
869 validateUserRoles(Role.ADMIN, Role.DESIGNER);
870 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
871 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
872 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
873 assertTrue(createResponse.isLeft());
874 service = createResponse.left().value();
875 assertEquals(service.getDerivedFromGenericType(), genericService.getToscaResourceName());
876 assertEquals(service.getDerivedFromGenericVersion(), genericService.getVersion());
880 public void testUpdateMetadataNamingPolicy() {
881 Service currentService = createServiceObject(true);
882 Service newService = createServiceObject(false);
883 currentService.setEcompGeneratedNaming(false);
884 newService.setEcompGeneratedNaming(true);
885 newService.setNamingPolicy("policy");
886 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
887 assertThat(resultOfUpdate.isLeft()).isTrue();
888 Service updatedService = resultOfUpdate.left().value();
889 assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
890 assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
894 public void testUpdateMetadataServiceType() {
895 Service currentService = createServiceObject(true);
896 Service newService = createServiceObject(false);
897 currentService.setServiceType("alice");
899 newService.setServiceType("bob");
900 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
901 assertThat(resultOfUpdate.isLeft()).isTrue();
902 Service updatedService = resultOfUpdate.left().value();
903 assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
904 //empty string is invalid
905 newService.setServiceType("");
906 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
907 assertThat(resultOfUpdate.isLeft()).isTrue();
909 newService.setServiceType(null);
910 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
911 assertThat(resultOfUpdate.isRight()).isTrue();
914 private Resource setupGenericServiceMock(){
915 Resource genericService = new Resource();
916 genericService.setVersion("1.0");
917 genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
918 return genericService;