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=========================================================
19 * Modifications copyright (c) 2019 Nokia
20 * ================================================================================
23 package org.openecomp.sdc.be.components.impl;
25 import fj.data.Either;
26 import org.apache.commons.lang3.tuple.ImmutablePair;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.mockito.Mockito;
30 import org.openecomp.sdc.ElementOperationMock;
31 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
32 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
33 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
34 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
35 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
36 import org.openecomp.sdc.be.components.validation.UserValidations;
37 import org.openecomp.sdc.be.config.ConfigurationManager;
38 import org.openecomp.sdc.be.dao.api.ActionStatus;
39 import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
40 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
41 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
42 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
43 import org.openecomp.sdc.be.impl.ComponentsUtils;
44 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
45 import org.openecomp.sdc.be.model.*;
46 import org.openecomp.sdc.be.model.category.CategoryDefinition;
47 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
48 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
49 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
50 import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
51 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
52 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
53 import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
54 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
55 import org.openecomp.sdc.be.user.Role;
56 import org.openecomp.sdc.be.user.UserBusinessLogic;
57 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
58 import org.openecomp.sdc.common.api.ConfigurationSource;
59 import org.openecomp.sdc.common.api.Constants;
60 import org.openecomp.sdc.common.impl.ExternalConfiguration;
61 import org.openecomp.sdc.common.impl.FSConfigurationSource;
62 import org.openecomp.sdc.common.util.ValidationUtils;
63 import org.openecomp.sdc.exception.ResponseFormat;
64 import org.springframework.web.context.WebApplicationContext;
66 import javax.servlet.ServletContext;
67 import java.lang.reflect.Method;
69 import java.util.stream.Collectors;
70 import java.util.stream.Stream;
72 import static org.assertj.core.api.Assertions.assertThat;
73 import static org.junit.Assert.*;
74 import static org.junit.Assert.assertNotNull;
75 import static org.mockito.ArgumentMatchers.anyString;
76 import static org.mockito.ArgumentMatchers.eq;
77 import static org.mockito.Mockito.when;
78 import static org.mockito.ArgumentMatchers.eq;
80 public class ServiceBusinessLogicTest {
82 private static final String SERVICE_CATEGORY = "Mobility";
83 private static final String INSTANTIATION_TYPE = "A-la-carte";
84 private final ServletContext servletContext = Mockito.mock(ServletContext.class);
85 private UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
86 private WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
87 private WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
88 private ServiceBusinessLogic bl = new ServiceBusinessLogic();
89 private ResponseFormatManager responseManager = null;
90 private ComponentsUtils componentsUtils;
91 private AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
92 private ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
93 private GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
94 private JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class);
95 private ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
96 private CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
97 private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
98 private UserValidations userValidations = Mockito.mock(UserValidations.class);
99 private ResourceAdminEvent auditArchive1 = Mockito.mock(ResourceAdminEvent.class);
100 private ResourceAdminEvent auditArchive2 = Mockito.mock(ResourceAdminEvent.class);
101 private ResourceAdminEvent auditRestore = Mockito.mock(ResourceAdminEvent.class);
103 private User user = null;
104 private Resource genericService = null;
106 private static final String CERTIFIED_VERSION = "1.0";
107 private static final String UNCERTIFIED_VERSION = "0.2";
108 private static final String COMPONNET_ID = "myUniqueId";
109 private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
111 public ServiceBusinessLogicTest() {
116 public void setup() {
118 ExternalConfiguration.setAppName("catalog-be");
119 // init Configuration
120 String appConfigDir = "src/test/resources/config/catalog-be";
121 ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
122 ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
123 componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
126 IElementOperation mockElementDao = new ElementOperationMock();
128 // User data and management
130 user.setUserId("jh0003");
131 user.setFirstName("Jimmi");
132 user.setLastName("Hendrix");
133 user.setRole(Role.ADMIN.name());
135 Either<User, ActionStatus> eitherGetUser = Either.left(user);
136 when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
137 when(userValidations.validateUserExists(eq("jh0003"), anyString(), eq(false))).thenReturn(user);
138 when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
139 when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
140 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
141 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
142 when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
143 when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
144 when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
146 // artifact bussinesslogic
147 ArtifactDefinition artifactDef = new ArtifactDefinition();
148 when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
151 Service serviceResponse = createServiceObject(true);
152 Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
153 when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate);
154 Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
155 when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount);
156 Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
157 when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist);
159 genericService = setupGenericServiceMock();
160 Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService);
161 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric);
164 bl = new ServiceBusinessLogic();
165 bl.setElementDao(mockElementDao);
166 bl.setUserAdmin(mockUserAdmin);
167 bl.setArtifactBl(artifactBl);
168 bl.setGraphLockOperation(graphLockOperation);
169 bl.setJanusGraphGenericDao(mockJanusGraphDao);
170 bl.setToscaOperationFacade(toscaOperationFacade);
171 bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
172 bl.setComponentsUtils(componentsUtils);
173 bl.setCassandraAuditingDao(auditingDao);
174 bl.setCacheManagerOperation(cacheManager);
175 bl.setUserValidations(userValidations);
177 mockAuditingDaoLogic();
179 responseManager = ResponseFormatManager.getInstance();
184 public void testGetComponentAuditRecordsCertifiedVersion() {
185 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
186 assertTrue(componentAuditRecords.isLeft());
187 assertEquals(3, componentAuditRecords.left().value().size());
191 public void testGetComponentAuditRecordsUnCertifiedVersion() {
192 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
193 assertTrue(componentAuditRecords.isLeft());
194 assertEquals(4, componentAuditRecords.left().value().size());
198 public void testHappyScenario() {
199 Service service = createServiceObject(false);
200 validateUserRoles(Role.ADMIN, Role.DESIGNER);
201 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
202 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
204 if (createResponse.isRight()) {
205 assertEquals(new Integer(200), createResponse.right().value().getStatus());
207 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
210 private void validateUserRoles(Role ... roles) {
211 List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
214 private void assertEqualsServiceObject(Service origService, Service newService) {
215 assertEquals(origService.getContactId(), newService.getContactId());
216 assertEquals(origService.getCategories(), newService.getCategories());
217 assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
218 assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
219 assertEquals(origService.getDescription(), newService.getDescription());
220 assertEquals(origService.getIcon(), newService.getIcon());
221 assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
222 assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
223 assertEquals(origService.getName(), newService.getName());
224 assertEquals(origService.getName(), newService.getName());
225 assertEquals(origService.getUniqueId(), newService.getUniqueId());
226 assertEquals(origService.getVersion(), newService.getVersion());
227 assertEquals(origService.getArtifacts(), newService.getArtifacts());
228 assertEquals(origService.getCreationDate(), newService.getCreationDate());
229 assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
230 assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
231 assertEquals(origService.getTags(), newService.getTags());
234 private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
235 assertResponse(createResponse.right().value(), expectedStatus, variables);
238 private void assertComponentException(ByActionStatusComponentException e, ActionStatus expectedStatus, String... variables) {
239 ResponseFormat actualResponse = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
240 assertResponse(actualResponse, expectedStatus, variables);
243 private void assertComponentException(ByResponseFormatComponentException e, ActionStatus expectedStatus, String... variables) {
244 ResponseFormat actualResponse = e.getResponseFormat();
245 assertResponse(actualResponse, expectedStatus, variables);
248 private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
249 ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
250 assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
251 assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
256 public void testFailedServiceValidations() {
257 testServiceNameAlreadyExists();
258 testServiceNameEmpty();
259 testServiceNameWrongFormat();
260 testServiceDescriptionEmpty();
261 testServiceDescriptionMissing();
262 testServiceDescExceedsLimitCreate();
263 testServiceDescNotEnglish();
264 testServiceIconEmpty();
265 testServiceIconMissing();
266 testResourceIconInvalid();
267 testResourceIconExceedsLimit();
268 testTagsNoServiceName();
270 testServiceTagNotExist();
271 testServiceTagEmpty();
273 testContactIdTooLong();
274 testContactIdWrongFormatCreate();
275 testInvalidProjectCode();
276 testProjectCodeTooLong();
277 testProjectCodeTooShort();
279 testResourceContactIdMissing();
280 testServiceCategoryExist();
281 testServiceBadCategoryCreate();
282 testMissingProjectCode();
285 private void testServiceNameAlreadyExists() {
286 String serviceName = "alreadyExist";
287 Service serviceExccedsNameLimit = createServiceObject(false);
288 // 51 chars, the limit is 50
289 serviceExccedsNameLimit.setName(serviceName);
290 List<String> tgs = new ArrayList<>();
291 tgs.add(serviceName);
292 serviceExccedsNameLimit.setTags(tgs);
293 validateUserRoles(Role.ADMIN, Role.DESIGNER);
294 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
295 assertTrue(createResponse.isRight());
296 assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
299 private void testServiceNameEmpty() {
300 Service serviceExccedsNameLimit = createServiceObject(false);
301 serviceExccedsNameLimit.setName(null);
303 bl.createService(serviceExccedsNameLimit, user);
304 } catch(ByActionStatusComponentException e){
305 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
309 private void testServiceNameWrongFormat() {
310 Service service = createServiceObject(false);
312 String nameWrongFormat = "ljg\fd";
313 service.setName(nameWrongFormat);
315 bl.createService(service, user);
316 } catch(ByActionStatusComponentException e){
317 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
321 private void testServiceDescriptionEmpty() {
322 Service serviceExist = createServiceObject(false);
323 serviceExist.setDescription("");
325 bl.createService(serviceExist, user);
326 } catch(ByActionStatusComponentException e){
327 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
331 private void testServiceDescriptionMissing() {
332 Service serviceExist = createServiceObject(false);
333 serviceExist.setDescription(null);
335 bl.createService(serviceExist, user);
336 } catch(ByActionStatusComponentException e){
337 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
341 private void testServiceDescExceedsLimitCreate() {
342 Service serviceExccedsDescLimit = createServiceObject(false);
343 // 1025 chars, the limit is 1024
344 String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
345 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
346 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
347 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
348 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
349 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
350 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
351 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
353 serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
355 bl.createService(serviceExccedsDescLimit, user);
356 } catch(ByActionStatusComponentException e){
357 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
361 private void testServiceDescNotEnglish() {
362 Service notEnglish = createServiceObject(false);
364 String tooLongServiceDesc = "\uC2B5";
365 notEnglish.setDescription(tooLongServiceDesc);
367 bl.createService(notEnglish, user);
368 } catch(ByActionStatusComponentException e){
369 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
373 // Service description - stop
374 // Service icon - start
375 private void testServiceIconEmpty() {
376 Service serviceExist = createServiceObject(false);
377 serviceExist.setIcon("");
379 bl.createService(serviceExist, user);
380 } catch(ByActionStatusComponentException e) {
381 assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
385 private void testServiceIconMissing() {
386 Service serviceExist = createServiceObject(false);
387 serviceExist.setIcon(null);
389 bl.createService(serviceExist, user);
390 } catch(ByActionStatusComponentException e) {
391 assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
395 private void testResourceIconInvalid() {
396 Service resourceExist = createServiceObject(false);
397 resourceExist.setIcon("kjk3453^&");
399 bl.createService(resourceExist, user);
400 } catch(ByActionStatusComponentException e) {
401 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
405 private void testResourceIconExceedsLimit() {
406 Service resourceExist = createServiceObject(false);
407 resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
409 bl.createService(resourceExist, user);
410 } catch(ByActionStatusComponentException e) {
411 assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, "Service", "25");
415 private void testTagsNoServiceName() {
416 Service serviceExccedsNameLimit = createServiceObject(false);
417 String tag1 = "afzs2qLBb";
418 List<String> tagsList = new ArrayList<>();
420 serviceExccedsNameLimit.setTags(tagsList);
422 bl.createService(serviceExccedsNameLimit, user);
423 } catch(ByActionStatusComponentException e) {
424 assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
428 private void testInvalidTag() {
429 Service serviceExccedsNameLimit = createServiceObject(false);
430 String tag1 = "afzs2qLBb%#%";
431 List<String> tagsList = new ArrayList<>();
433 serviceExccedsNameLimit.setTags(tagsList);
435 bl.createService(serviceExccedsNameLimit, user);
436 } catch(ByActionStatusComponentException e) {
437 assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
441 private void testServiceTagNotExist() {
442 Service serviceExist = createServiceObject(false);
443 serviceExist.setTags(null);
445 bl.createService(serviceExist, user);
446 } catch(ByActionStatusComponentException e) {
447 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
451 private void testServiceTagEmpty() {
452 Service serviceExist = createServiceObject(false);
453 serviceExist.setTags(new ArrayList<>());
455 bl.createService(serviceExist, user);
456 } catch(ByActionStatusComponentException e) {
457 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
461 // Service tags - stop
462 // Service contactId - start
463 private void testContactIdTooLong() {
464 Service serviceContactId = createServiceObject(false);
465 // 59 chars instead of 50
466 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
467 serviceContactId.setContactId(contactIdTooLong);
469 bl.createService(serviceContactId, user);
470 } catch(ByActionStatusComponentException e) {
471 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
475 private void testContactIdWrongFormatCreate() {
476 Service serviceContactId = createServiceObject(false);
477 // 3 letters and 3 digits and special characters
478 String contactIdTooLong = "yrt134!!!";
479 serviceContactId.setContactId(contactIdTooLong);
481 bl.createService(serviceContactId, user);
482 } catch(ByActionStatusComponentException e) {
483 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
487 private void testResourceContactIdMissing() {
488 Service resourceExist = createServiceObject(false);
489 resourceExist.setContactId(null);
491 bl.createService(resourceExist, user);
492 } catch(ByActionStatusComponentException e) {
493 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
497 // Service contactId - stop
498 // Service category - start
499 private void testServiceCategoryExist() {
500 Service serviceExist = createServiceObject(false);
501 serviceExist.setCategories(null);
503 bl.createService(serviceExist, user);
504 } catch(ByActionStatusComponentException e) {
505 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
510 public void markDistributionAsDeployedTestAlreadyDeployed() {
511 String notifyAction = "DNotify";
512 String requestAction = "DRequest";
513 String resultAction = "DResult";
514 String did = "123456";
516 setupBeforeDeploy(notifyAction, requestAction, did);
517 List<DistributionDeployEvent> resultList = new ArrayList<>();
518 Map<String, Object> params = new HashMap<>();
519 DistributionDeployEvent event = new DistributionDeployEvent();
521 event.setAction(resultAction);
523 event.setStatus("200");
524 // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
525 // deployEvent.setFields(params);
526 resultList.add(event);
527 Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
529 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
531 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
532 assertTrue(markDeployed.isLeft());
534 Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
539 public void markDistributionAsDeployedTestSuccess() {
540 String notifyAction = "DNotify";
541 String requestAction = "DRequest";
542 String did = "123456";
544 setupBeforeDeploy(notifyAction, requestAction, did);
545 List<Role> roles = new ArrayList<>();
546 roles.add(Role.ADMIN);
548 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
549 assertTrue(markDeployed.isLeft());
553 public void markDistributionAsDeployedTestNotDistributed() {
554 String notifyAction = "DNotify";
555 String requestAction = "DRequest";
556 String did = "123456";
558 setupBeforeDeploy(notifyAction, requestAction, did);
559 List<ResourceAdminEvent> emptyList = new ArrayList<>();
560 Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
561 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
563 Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
564 Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
566 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
567 assertTrue(markDeployed.isRight());
568 assertEquals(404, markDeployed.right().value().getStatus().intValue());
572 private void testServiceBadCategoryCreate() {
574 Service serviceExist = createServiceObject(false);
575 CategoryDefinition category = new CategoryDefinition();
576 category.setName("koko");
577 List<CategoryDefinition> categories = new ArrayList<>();
578 categories.add(category);
579 serviceExist.setCategories(categories);
581 bl.createService(serviceExist, user);
582 } catch(ByActionStatusComponentException e) {
583 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
587 // Service category - stop
588 // Service projectCode - start
589 private void testInvalidProjectCode() {
591 Service serviceExist = createServiceObject(false);
592 serviceExist.setProjectCode("koko!!");
594 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
595 assertTrue(createResponse.isRight());
597 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
600 private void testProjectCodeTooLong() {
602 Service serviceExist = createServiceObject(false);
603 String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
604 serviceExist.setProjectCode(tooLongProjectCode);
606 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
607 assertTrue(createResponse.isRight());
609 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
612 private void testProjectCodeTooShort() {
614 Service serviceExist = createServiceObject(false);
615 serviceExist.setProjectCode("333");
617 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
618 assertTrue(createResponse.isRight());
620 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
623 private void testMissingProjectCode() {
625 Service serviceExist = createServiceObject(false);
626 serviceExist.setProjectCode(null);
628 bl.createService(serviceExist, user);
629 } catch(ByActionStatusComponentException e) {
630 assertComponentException(e, ActionStatus.MISSING_PROJECT_CODE);
635 public void testDeleteMarkedServices() {
636 List<String> ids = new ArrayList<>();
637 List<String> responseIds = new ArrayList<>();
638 String resourceInUse = "123";
639 ids.add(resourceInUse);
640 String resourceFree = "456";
641 ids.add(resourceFree);
642 responseIds.add(resourceFree);
643 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
644 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
646 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
647 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
649 List<ArtifactDefinition> artifacts = new ArrayList<>();
650 Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
652 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
653 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
654 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
655 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
656 assertTrue(deleteMarkedResources.isLeft());
657 List<String> resourceIdList = deleteMarkedResources.left().value();
658 assertFalse(resourceIdList.isEmpty());
659 assertTrue(resourceIdList.contains(resourceFree));
660 assertFalse(resourceIdList.contains(resourceInUse));
664 private Service createServiceObject(boolean afterCreate) {
665 Service service = new Service();
666 service.setUniqueId("sid");
667 service.setName("Service");
668 CategoryDefinition category = new CategoryDefinition();
669 category.setName(SERVICE_CATEGORY);
670 List<CategoryDefinition> categories = new ArrayList<>();
671 categories.add(category);
672 service.setCategories(categories);
673 service.setInstantiationType(INSTANTIATION_TYPE);
675 service.setDescription("description");
676 List<String> tgs = new ArrayList<>();
677 tgs.add(service.getName());
678 service.setTags(tgs);
679 service.setIcon("MyIcon");
680 service.setContactId("aa1234");
681 service.setProjectCode("12345");
684 service.setVersion("0.1");
685 service.setUniqueId(service.getName() + ":" + service.getVersion());
686 service.setCreatorUserId(user.getUserId());
687 service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
692 private void mockAuditingDaoLogic() {
693 final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
694 createResourceAudit.setModifier("Carlos Santana(cs0008)");
695 createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
696 createResourceAudit.setCurrVersion("0.1");
697 createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
698 createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f");
699 createResourceAudit.setDesc("OK");
700 createResourceAudit.setResourceType("Resource");
701 createResourceAudit.setStatus("201");
702 createResourceAudit.setPrevVersion("");
703 createResourceAudit.setAction("Create");
704 // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977");
705 createResourceAudit.setPrevState("");
706 createResourceAudit.setResourceName("MyTestResource");
707 // createResourceAudit.setFields(fields);
709 final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent();
710 checkInResourceAudit.setModifier("Carlos Santana(cs0008)");
711 checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN");
712 checkInResourceAudit.setCurrVersion("0.1");
713 checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
714 checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091");
715 checkInResourceAudit.setDesc("OK");
716 checkInResourceAudit.setComment("Stam");
717 checkInResourceAudit.setResourceType("Resource");
718 checkInResourceAudit.setStatus("200");
719 checkInResourceAudit.setPrevVersion("0.1");
720 checkInResourceAudit.setAction("Checkin");
721 // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797");
722 checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT");
723 checkInResourceAudit.setResourceName("MyTestResource");
725 final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent();
726 checkOutResourceAudit.setModifier("Carlos Santana(cs0008)");
727 checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
728 checkOutResourceAudit.setCurrVersion("0.2");
729 checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
730 checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8");
731 checkOutResourceAudit.setDesc("OK");
732 checkOutResourceAudit.setComment("");
733 checkOutResourceAudit.setResourceType("Resource");
734 checkOutResourceAudit.setStatus("200");
735 checkOutResourceAudit.setPrevVersion("0.1");
736 checkOutResourceAudit.setAction("Checkout");
737 // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024");
738 checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN");
739 checkOutResourceAudit.setResourceName("MyTestResource");
740 List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() {
742 add(createResourceAudit);
743 add(checkInResourceAudit);
744 add(checkOutResourceAudit);
747 Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
748 Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
750 List<ResourceAdminEvent> listPrev = new ArrayList<>();
751 Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
752 Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
754 List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() {
756 add(checkOutResourceAudit);
759 Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr);
760 Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr);
762 Either<List<ResourceAdminEvent>, ActionStatus> archiveAuditList = Either.left(Arrays.asList(auditArchive1, auditArchive2));
763 when(auditingDao.getArchiveAuditByServiceInstanceId(anyString())).thenReturn(archiveAuditList);
765 Either<List<ResourceAdminEvent>, ActionStatus> restoreAuditList = Either.left(Arrays.asList(auditRestore));
766 when(auditingDao.getRestoreAuditByServiceInstanceId(anyString())).thenReturn(restoreAuditList);
770 private void setupBeforeDeploy(String notifyAction, String requestAction, String did) {
772 DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent();
773 notifyEvent.setAction(notifyAction);
774 notifyEvent.setDid(did);
775 notifyEvent.setStatus("200");
777 ResourceAdminEvent requestEvent = new ResourceAdminEvent();
778 requestEvent.setAction(requestAction);
779 requestEvent.setDid(did);
780 requestEvent.setStatus("200");
782 List<DistributionNotificationEvent> notifyResults = Collections.singletonList(notifyEvent);
783 Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults);
785 Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify);
787 List<ResourceAdminEvent> requestResults = Collections.singletonList(requestEvent);
788 Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults);
789 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest);
791 Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true));
792 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
794 Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(Collections.emptyList());
795 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList);
798 @SuppressWarnings({ "unchecked", "rawtypes" })
800 public void testFindGroupInstanceOnRelatedComponentInstance() {
802 Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
803 String methodName = "findGroupInstanceOnRelatedComponentInstance";
804 Object invalidId = "invalidId";
806 Component service = createNewService();
807 List<ComponentInstance> componentInstances = service.getComponentInstances();
809 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
810 Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
811 Class[] argClasses = {Component.class, String.class,String.class};
813 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
814 method.setAccessible(true);
816 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
817 assertNotNull(findGroupInstanceRes);
818 assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
820 assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
825 Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
827 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
828 assertNotNull(findGroupInstanceRes);
829 assertTrue(findGroupInstanceRes.isRight());
830 assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
832 Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
834 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
835 assertNotNull(findGroupInstanceRes);
836 assertTrue(findGroupInstanceRes.isRight());
837 assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
839 catch (Exception e) {
844 private Component createNewService() {
846 Service service = new Service();
848 service.setName("serviceName");
849 service.setUniqueId("serviceUniqueId");
850 List<ComponentInstance> componentInstances = new ArrayList<>();
851 ComponentInstance ci;
852 for(int i= 0; i<listSize; ++i){
853 ci = new ComponentInstance();
854 ci.setName("ciName" + i);
855 ci.setUniqueId("ciId" + i);
856 List<GroupInstance> groupInstances= new ArrayList<>();
858 for(int j = 0; j<listSize; ++j){
859 gi = new GroupInstance();
860 gi.setName(ci.getName( )+ "giName" + j);
861 gi.setUniqueId(ci.getName() + "giId" + j);
862 groupInstances.add(gi);
864 ci.setGroupInstances(groupInstances);
865 componentInstances.add(ci);
867 service.setComponentInstances(componentInstances);
873 public void testDerivedFromGeneric() {
874 Service service = createServiceObject(true);
875 validateUserRoles(Role.ADMIN, Role.DESIGNER);
876 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
877 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
878 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
879 assertTrue(createResponse.isLeft());
880 service = createResponse.left().value();
881 assertEquals(service.getDerivedFromGenericType(), genericService.getToscaResourceName());
882 assertEquals(service.getDerivedFromGenericVersion(), genericService.getVersion());
886 public void testUpdateMetadataNamingPolicy() {
887 Service currentService = createServiceObject(true);
888 Service newService = createServiceObject(false);
889 currentService.setEcompGeneratedNaming(false);
890 newService.setEcompGeneratedNaming(true);
891 newService.setNamingPolicy("policy");
892 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
893 assertThat(resultOfUpdate.isLeft()).isTrue();
894 Service updatedService = resultOfUpdate.left().value();
895 assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
896 assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
900 public void testUpdateMetadataServiceType() {
901 Service currentService = createServiceObject(true);
902 Service newService = createServiceObject(false);
903 currentService.setServiceType("alice");
905 newService.setServiceType("bob");
906 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
907 assertThat(resultOfUpdate.isLeft()).isTrue();
908 Service updatedService = resultOfUpdate.left().value();
909 assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
910 //empty string is invalid
911 newService.setServiceType("");
912 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
913 assertThat(resultOfUpdate.isLeft()).isTrue();
915 newService.setServiceType(null);
916 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
917 assertThat(resultOfUpdate.isRight()).isTrue();
920 private Resource setupGenericServiceMock(){
921 Resource genericService = new Resource();
922 genericService.setVersion("1.0");
923 genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
924 return genericService;