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;
23 import fj.data.Either;
24 import org.apache.commons.lang3.tuple.ImmutablePair;
25 import org.junit.Before;
26 import org.junit.Ignore;
27 import org.junit.Test;
28 import org.mockito.Mockito;
29 import org.openecomp.sdc.ElementOperationMock;
30 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
31 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
32 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
33 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
34 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
35 import org.openecomp.sdc.be.components.validation.UserValidations;
36 import org.openecomp.sdc.be.config.ConfigurationManager;
37 import org.openecomp.sdc.be.dao.api.ActionStatus;
38 import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
39 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
40 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
41 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
42 import org.openecomp.sdc.be.impl.ComponentsUtils;
43 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
44 import org.openecomp.sdc.be.model.ArtifactDefinition;
45 import org.openecomp.sdc.be.model.Component;
46 import org.openecomp.sdc.be.model.ComponentInstance;
47 import org.openecomp.sdc.be.model.GroupInstance;
48 import org.openecomp.sdc.be.model.Resource;
49 import org.openecomp.sdc.be.model.Service;
50 import org.openecomp.sdc.be.model.User;
51 import org.openecomp.sdc.be.model.category.CategoryDefinition;
52 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
53 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
54 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
55 import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
56 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
57 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
58 import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
59 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
60 import org.openecomp.sdc.be.user.Role;
61 import org.openecomp.sdc.be.user.UserBusinessLogic;
62 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
63 import org.openecomp.sdc.common.api.ConfigurationSource;
64 import org.openecomp.sdc.common.api.Constants;
65 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
66 import org.openecomp.sdc.common.impl.ExternalConfiguration;
67 import org.openecomp.sdc.common.impl.FSConfigurationSource;
68 import org.openecomp.sdc.common.util.ValidationUtils;
69 import org.openecomp.sdc.exception.ResponseFormat;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import org.springframework.web.context.WebApplicationContext;
74 import javax.servlet.ServletContext;
75 import java.lang.reflect.Method;
76 import java.util.ArrayList;
77 import java.util.HashMap;
78 import java.util.List;
80 import java.util.stream.Collectors;
81 import java.util.stream.Stream;
83 import static org.junit.Assert.assertEquals;
84 import static org.junit.Assert.assertFalse;
85 import static org.junit.Assert.assertTrue;
86 import static org.mockito.ArgumentMatchers.anyString;
87 import static org.mockito.ArgumentMatchers.eq;
88 import static org.mockito.Mockito.when;
90 public class ServiceBusinessLogicTest {
92 private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class);
93 private static final String SERVICE_CATEGORY = "Mobility";
94 final ServletContext servletContext = Mockito.mock(ServletContext.class);
95 UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
96 WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
97 WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
98 ServiceBusinessLogic bl = new ServiceBusinessLogic();
99 ResponseFormatManager responseManager = null;
100 IElementOperation mockElementDao;
101 ComponentsUtils componentsUtils;
102 AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
103 ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
104 GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
105 TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
106 ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
107 CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
108 GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
109 UserValidations userValidations = Mockito.mock(UserValidations.class);
112 Service serviceResponse = null;
113 Resource genericService = null;
115 private static final String CERTIFIED_VERSION = "1.0";
116 private static final String UNCERTIFIED_VERSION = "0.2";
117 private static final String COMPONNET_ID = "myUniqueId";
118 private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
119 private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<AuditingFieldsKeysEnum, Object>();
120 private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<AuditingFieldsKeysEnum, Object>();
121 private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<AuditingFieldsKeysEnum, Object>();
123 public ServiceBusinessLogicTest() {
128 public void setup() {
130 ExternalConfiguration.setAppName("catalog-be");
131 // init Configuration
132 String appConfigDir = "src/test/resources/config/catalog-be";
133 ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
134 ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
135 componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
138 mockElementDao = new ElementOperationMock();
140 // User data and management
142 user.setUserId("jh0003");
143 user.setFirstName("Jimmi");
144 user.setLastName("Hendrix");
145 user.setRole(Role.ADMIN.name());
147 Either<User, ActionStatus> eitherGetUser = Either.left(user);
148 when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
149 when(userValidations.validateUserExists(eq("jh0003"), anyString(), eq(false))).thenReturn(Either.left(user));
150 when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user));
151 when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
152 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
153 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
154 when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
155 when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
156 when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
158 // artifact bussinesslogic
159 ArtifactDefinition artifactDef = new ArtifactDefinition();
160 when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
163 serviceResponse = createServiceObject(true);
164 Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
165 when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate);
166 Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
167 when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount);
168 Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
169 when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist);
171 genericService = setupGenericServiceMock();
172 Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService);
173 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric);
176 bl = new ServiceBusinessLogic();
177 bl.setElementDao(mockElementDao);
178 bl.setUserAdmin(mockUserAdmin);
179 bl.setArtifactBl(artifactBl);
180 bl.setGraphLockOperation(graphLockOperation);
181 bl.setTitanGenericDao(mockTitanDao);
182 bl.setToscaOperationFacade(toscaOperationFacade);
183 bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
184 bl.setComponentsUtils(componentsUtils);
185 bl.setCassandraAuditingDao(auditingDao);
186 bl.setCacheManagerOperation(cacheManager);
187 bl.setUserValidations(userValidations);
189 mockAuditingDaoLogic();
191 responseManager = ResponseFormatManager.getInstance();
196 public void testGetComponentAuditRecordsCertifiedVersion() {
197 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
198 assertTrue(componentAuditRecords.isLeft());
199 int size = componentAuditRecords.left().value().size();
200 assertTrue(size == 3);
204 public void testGetComponentAuditRecordsUnCertifiedVersion() {
205 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
206 assertTrue(componentAuditRecords.isLeft());
207 int size = componentAuditRecords.left().value().size();
208 assertTrue(size == 1);
212 public void testHappyScenario() {
213 Service service = createServiceObject(false);
214 validateUserRoles(Role.ADMIN, Role.DESIGNER);
215 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
216 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
218 if (createResponse.isRight()) {
219 assertEquals(new Integer(200), createResponse.right().value().getStatus());
221 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
224 private void validateUserRoles(Role ... roles) {
225 List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
226 when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true));
229 private void assertEqualsServiceObject(Service origService, Service newService) {
230 assertEquals(origService.getContactId(), newService.getContactId());
231 assertEquals(origService.getCategories(), newService.getCategories());
232 assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
233 assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
234 assertEquals(origService.getDescription(), newService.getDescription());
235 assertEquals(origService.getIcon(), newService.getIcon());
236 assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
237 assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
238 assertEquals(origService.getName(), newService.getName());
239 assertEquals(origService.getName(), newService.getName());
240 assertEquals(origService.getUniqueId(), newService.getUniqueId());
241 assertEquals(origService.getVersion(), newService.getVersion());
242 assertEquals(origService.getArtifacts(), newService.getArtifacts());
243 assertEquals(origService.getCreationDate(), newService.getCreationDate());
244 assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
245 assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
246 assertEquals(origService.getTags(), newService.getTags());
249 private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
250 ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
251 ResponseFormat actualResponse = createResponse.right().value();
252 assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
253 assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
258 public void testFailedServiceValidations() {
259 testServiceNameAlreadyExists();
260 testServiceNameEmpty();
261 testServiceNameWrongFormat();
262 testServiceDescriptionEmpty();
263 testServiceDescriptionMissing();
264 testServiceDescExceedsLimitCreate();
265 testServiceDescNotEnglish();
266 testServiceIconEmpty();
267 testServiceIconMissing();
268 testResourceIconInvalid();
269 testResourceIconExceedsLimit();
270 testTagsNoServiceName();
272 testServiceTagNotExist();
273 testServiceTagEmpty();
275 testContactIdTooLong();
276 testContactIdWrongFormatCreate();
277 testInvalidProjectCode();
278 testProjectCodeTooLong();
279 testProjectCodeTooShort();
281 testResourceContactIdMissing();
282 testServiceCategoryExist();
283 testServiceBadCategoryCreate();
284 testMissingProjectCode();
287 private void testServiceNameAlreadyExists() {
288 String serviceName = "alreadyExist";
289 Service serviceExccedsNameLimit = createServiceObject(false);
290 // 51 chars, the limit is 50
291 serviceExccedsNameLimit.setName(serviceName);
292 List<String> tgs = new ArrayList<String>();
293 tgs.add(serviceName);
294 serviceExccedsNameLimit.setTags(tgs);
295 validateUserRoles(Role.ADMIN, Role.DESIGNER);
296 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
297 assertTrue(createResponse.isRight());
298 assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
301 private void testServiceNameEmpty() {
302 Service serviceExccedsNameLimit = createServiceObject(false);
303 serviceExccedsNameLimit.setName(null);
305 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
306 assertTrue(createResponse.isRight());
307 assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
310 private void testServiceNameWrongFormat() {
311 Service service = createServiceObject(false);
313 String nameWrongFormat = "ljg\fd";
314 service.setName(nameWrongFormat);
316 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
317 assertTrue(createResponse.isRight());
318 assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
321 private void testServiceDescriptionEmpty() {
322 Service serviceExist = createServiceObject(false);
323 serviceExist.setDescription("");
325 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
326 assertTrue(createResponse.isRight());
328 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
331 private void testServiceDescriptionMissing() {
332 Service serviceExist = createServiceObject(false);
333 serviceExist.setDescription(null);
335 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
336 assertTrue(createResponse.isRight());
338 assertResponse(createResponse, 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 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsDescLimit, user);
356 assertTrue(createResponse.isRight());
357 assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
360 private void testServiceDescNotEnglish() {
361 Service notEnglish = createServiceObject(false);
363 String tooLongServiceDesc = "\uC2B5";
364 notEnglish.setDescription(tooLongServiceDesc);
366 Either<Service, ResponseFormat> createResponse = bl.createService(notEnglish, user);
367 assertTrue(createResponse.isRight());
368 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
371 // Service description - stop
372 // Service icon - start
373 private void testServiceIconEmpty() {
374 Service serviceExist = createServiceObject(false);
375 serviceExist.setIcon("");
377 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
378 assertTrue(createResponse.isRight());
380 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
383 private void testServiceIconMissing() {
384 Service serviceExist = createServiceObject(false);
385 serviceExist.setIcon(null);
387 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
388 assertTrue(createResponse.isRight());
390 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
393 private void testResourceIconInvalid() {
394 Service resourceExist = createServiceObject(false);
395 resourceExist.setIcon("kjk3453^&");
397 Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
398 assertTrue(createResponse.isRight());
400 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
403 private void testResourceIconExceedsLimit() {
404 Service resourceExist = createServiceObject(false);
405 resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
407 Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
408 assertTrue(createResponse.isRight());
410 assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
413 private void testTagsNoServiceName() {
414 Service serviceExccedsNameLimit = createServiceObject(false);
415 String tag1 = "afzs2qLBb";
416 List<String> tagsList = new ArrayList<String>();
418 serviceExccedsNameLimit.setTags(tagsList);
420 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
421 assertTrue(createResponse.isRight());
422 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
426 private void testInvalidTag() {
427 Service serviceExccedsNameLimit = createServiceObject(false);
428 String tag1 = "afzs2qLBb%#%";
429 List<String> tagsList = new ArrayList<String>();
431 serviceExccedsNameLimit.setTags(tagsList);
433 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
434 assertTrue(createResponse.isRight());
435 assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" });
439 private void testServiceTagNotExist() {
440 Service serviceExist = createServiceObject(false);
441 serviceExist.setTags(null);
443 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
444 assertTrue(createResponse.isRight());
446 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
449 private void testServiceTagEmpty() {
450 Service serviceExist = createServiceObject(false);
451 serviceExist.setTags(new ArrayList<String>());
453 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
454 assertTrue(createResponse.isRight());
456 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
459 // Service tags - stop
460 // Service contactId - start
461 private void testContactIdTooLong() {
462 Service serviceContactId = createServiceObject(false);
463 // 59 chars instead of 50
464 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
465 serviceContactId.setContactId(contactIdTooLong);
467 Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
468 assertTrue(createResponse.isRight());
469 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
472 private void testContactIdWrongFormatCreate() {
473 Service serviceContactId = createServiceObject(false);
474 // 3 letters and 3 digits and special characters
475 String contactIdTooLong = "yrt134!!!";
476 serviceContactId.setContactId(contactIdTooLong);
478 Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
479 assertTrue(createResponse.isRight());
480 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
483 private void testResourceContactIdMissing() {
484 Service resourceExist = createServiceObject(false);
485 resourceExist.setContactId(null);
487 Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
488 assertTrue(createResponse.isRight());
489 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
492 // Service contactId - stop
493 // Service category - start
494 private void testServiceCategoryExist() {
495 Service serviceExist = createServiceObject(false);
496 serviceExist.setCategories(null);
498 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
499 assertTrue(createResponse.isRight());
501 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
505 public void markDistributionAsDeployedTestSuccess() {
506 String notifyAction = "DNotify";
507 String requestAction = "DRequest";
508 String did = "123456";
510 setupBeforeDeploy(notifyAction, requestAction, did);
511 List<Role> roles = new ArrayList<>();
512 roles.add(Role.ADMIN);
514 when(userValidations.validateUserRole(user, roles)).thenReturn(Either.left(true));
515 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
516 assertTrue(markDeployed.isLeft());
520 private void testServiceBadCategoryCreate() {
522 Service serviceExist = createServiceObject(false);
523 CategoryDefinition category = new CategoryDefinition();
524 category.setName("koko");
525 List<CategoryDefinition> categories = new ArrayList<>();
526 categories.add(category);
527 serviceExist.setCategories(categories);
529 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
530 assertTrue(createResponse.isRight());
532 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
535 // Service category - stop
536 // Service projectCode - start
537 private void testInvalidProjectCode() {
539 Service serviceExist = createServiceObject(false);
540 serviceExist.setProjectCode("koko!!");
542 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
543 assertTrue(createResponse.isRight());
545 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
548 private void testProjectCodeTooLong() {
550 Service serviceExist = createServiceObject(false);
551 String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
552 serviceExist.setProjectCode(tooLongProjectCode);
554 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
555 assertTrue(createResponse.isRight());
557 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
560 private void testProjectCodeTooShort() {
562 Service serviceExist = createServiceObject(false);
563 serviceExist.setProjectCode("333");
565 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
566 assertTrue(createResponse.isRight());
568 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
571 private void testMissingProjectCode() {
573 Service serviceExist = createServiceObject(false);
574 serviceExist.setProjectCode(null);
576 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
577 assertTrue(createResponse.isRight());
579 assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE);
584 public void testDeleteMarkedServices() {
585 List<String> ids = new ArrayList<String>();
586 String resourceInUse = "123";
587 ids.add(resourceInUse);
588 String resourceFree = "456";
589 ids.add(resourceFree);
590 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
591 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
593 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
594 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
596 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
597 Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
599 when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
600 when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
602 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
603 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
605 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
606 assertTrue(deleteMarkedResources.isLeft());
607 List<String> resourceIdList = deleteMarkedResources.left().value();
608 assertFalse(resourceIdList.isEmpty());
609 assertTrue(resourceIdList.contains(resourceFree));
610 assertFalse(resourceIdList.contains(resourceInUse));
614 private Service createServiceObject(boolean afterCreate) {
615 Service service = new Service();
616 service.setUniqueId("sid");
617 service.setName("Service");
618 CategoryDefinition category = new CategoryDefinition();
619 category.setName(SERVICE_CATEGORY);
620 List<CategoryDefinition> categories = new ArrayList<>();
621 categories.add(category);
622 service.setCategories(categories);
624 service.setDescription("description");
625 List<String> tgs = new ArrayList<String>();
626 tgs.add(service.getName());
627 service.setTags(tgs);
628 service.setIcon("MyIcon");
629 service.setContactId("aa1234");
630 service.setProjectCode("12345");
633 service.setVersion("0.1");
634 service.setUniqueId(service.getName() + ":" + service.getVersion());
635 service.setCreatorUserId(user.getUserId());
636 service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
641 private void mockAuditingDaoLogic() {
642 FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
643 FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
644 FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
646 FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION);
647 FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION);
649 final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
650 createResourceAudit.setModifier("Carlos Santana(cs0008)");
651 createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
652 createResourceAudit.setCurrVersion("0.1");
653 createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
654 createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f");
655 createResourceAudit.setDesc("OK");
656 createResourceAudit.setResourceType("Resource");
657 createResourceAudit.setStatus("201");
658 createResourceAudit.setPrevVersion("");
659 createResourceAudit.setAction("Create");
660 // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977");
661 createResourceAudit.setPrevState("");
662 createResourceAudit.setResourceName("MyTestResource");
663 // createResourceAudit.setFields(fields);
665 final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent();
666 checkInResourceAudit.setModifier("Carlos Santana(cs0008)");
667 checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN");
668 checkInResourceAudit.setCurrVersion("0.1");
669 checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
670 checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091");
671 checkInResourceAudit.setDesc("OK");
672 checkInResourceAudit.setComment("Stam");
673 checkInResourceAudit.setResourceType("Resource");
674 checkInResourceAudit.setStatus("200");
675 checkInResourceAudit.setPrevVersion("0.1");
676 checkInResourceAudit.setAction("Checkin");
677 // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797");
678 checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT");
679 checkInResourceAudit.setResourceName("MyTestResource");
681 final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent();
682 checkOutResourceAudit.setModifier("Carlos Santana(cs0008)");
683 checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
684 checkOutResourceAudit.setCurrVersion("0.2");
685 checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
686 checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8");
687 checkOutResourceAudit.setDesc("OK");
688 checkOutResourceAudit.setComment("");
689 checkOutResourceAudit.setResourceType("Resource");
690 checkOutResourceAudit.setStatus("200");
691 checkOutResourceAudit.setPrevVersion("0.1");
692 checkOutResourceAudit.setAction("Checkout");
693 // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024");
694 checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN");
695 checkOutResourceAudit.setResourceName("MyTestResource");
696 List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() {
698 add(createResourceAudit);
699 add(checkInResourceAudit);
700 add(checkOutResourceAudit);
703 Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
704 Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
706 List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>();
707 Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
708 Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
710 List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() {
712 add(checkOutResourceAudit);
715 Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr);
716 Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr);
720 private void setupBeforeDeploy(String notifyAction, String requestAction, String did) {
722 DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent();
723 notifyEvent.setAction(notifyAction);
724 notifyEvent.setDid(did);
725 notifyEvent.setStatus("200");
727 ResourceAdminEvent requestEvent = new ResourceAdminEvent();
728 requestEvent.setAction(requestAction);
729 requestEvent.setDid(did);
730 requestEvent.setStatus("200");
732 ArrayList<DistributionNotificationEvent> arrayList = new ArrayList<DistributionNotificationEvent>();
733 List<DistributionNotificationEvent> notifyResults = arrayList;
734 notifyResults.add(notifyEvent);
735 Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults);
737 Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify);
739 List<ResourceAdminEvent> requestResults = new ArrayList<ResourceAdminEvent>();
740 requestResults.add(requestEvent);
741 Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults);
742 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest);
744 Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true));
745 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
747 List<DistributionDeployEvent> emptyList = new ArrayList<DistributionDeployEvent>();
748 Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
749 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList);
752 @SuppressWarnings({ "unchecked", "rawtypes" })
754 public void testFindGroupInstanceOnRelatedComponentInstance() {
756 Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
757 String methodName = "findGroupInstanceOnRelatedComponentInstance";
758 Object invalidId = "invalidId";
760 Component service = createNewService();
761 List<ComponentInstance> componentInstances = service.getComponentInstances();
763 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
764 Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
765 Class[] argClasses = {Component.class, String.class,String.class};
767 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
768 method.setAccessible(true);
770 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
771 assertTrue(findGroupInstanceRes != null);
772 assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId()));
773 assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId()));
775 Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
777 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
778 assertTrue(findGroupInstanceRes != null);
779 assertTrue(findGroupInstanceRes.isRight());
780 assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593"));
782 Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
784 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
785 assertTrue(findGroupInstanceRes != null);
786 assertTrue(findGroupInstanceRes.isRight());
787 assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653"));
789 catch (Exception e) {
794 private Component createNewService() {
796 Service service = new Service();
798 service.setName("serviceName");
799 service.setUniqueId("serviceUniqueId");
800 List<ComponentInstance> componentInstances = new ArrayList<>();
801 ComponentInstance ci;
802 for(int i= 0; i<listSize; ++i){
803 ci = new ComponentInstance();
804 ci.setName("ciName" + i);
805 ci.setUniqueId("ciId" + i);
806 List<GroupInstance> groupInstances= new ArrayList<>();
808 for(int j = 0; j<listSize; ++j){
809 gi = new GroupInstance();
810 gi.setName(ci.getName( )+ "giName" + j);
811 gi.setUniqueId(ci.getName() + "giId" + j);
812 groupInstances.add(gi);
814 ci.setGroupInstances(groupInstances);
815 componentInstances.add(ci);
817 service.setComponentInstances(componentInstances);
823 public void testDerivedFromGeneric() {
824 Service service = createServiceObject(true);
825 validateUserRoles(Role.ADMIN, Role.DESIGNER);
826 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
827 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
828 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
829 assertTrue(createResponse.isLeft());
830 service = createResponse.left().value();
831 assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName()));
832 assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion()));
836 private Resource setupGenericServiceMock(){
837 Resource genericService = new Resource();
838 genericService.setVersion("1.0");
839 genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
840 return genericService;