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.Matchers.anyString;
87 import static org.mockito.Matchers.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(userValidations.validateUserRole(user))
152 // Servlet Context attributes
153 when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
154 // when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation());
155 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
156 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
157 when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
158 when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
159 when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
161 // artifact bussinesslogic
162 ArtifactDefinition artifactDef = new ArtifactDefinition();
163 when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
166 serviceResponse = createServiceObject(true);
167 Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
168 when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate);
169 Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
170 when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount);
171 Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
172 when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist);
174 genericService = setupGenericServiceMock();
175 Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService);
176 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric);
179 bl = new ServiceBusinessLogic();
180 bl.setElementDao(mockElementDao);
181 bl.setUserAdmin(mockUserAdmin);
182 bl.setArtifactBl(artifactBl);
183 bl.setGraphLockOperation(graphLockOperation);
184 bl.setTitanGenericDao(mockTitanDao);
185 bl.setToscaOperationFacade(toscaOperationFacade);
186 bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
187 bl.setComponentsUtils(componentsUtils);
188 bl.setCassandraAuditingDao(auditingDao);
189 bl.setCacheManagerOperation(cacheManager);
190 bl.setUserValidations(userValidations);
192 mockAuditingDaoLogic();
194 responseManager = ResponseFormatManager.getInstance();
199 public void testGetComponentAuditRecordsCertifiedVersion() {
200 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
201 assertTrue(componentAuditRecords.isLeft());
202 int size = componentAuditRecords.left().value().size();
203 assertTrue(size == 3);
207 public void testGetComponentAuditRecordsUnCertifiedVersion() {
208 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
209 assertTrue(componentAuditRecords.isLeft());
210 int size = componentAuditRecords.left().value().size();
211 assertTrue(size == 1);
215 public void testHappyScenario() {
216 Service service = createServiceObject(false);
217 validateUserRoles(Role.ADMIN, Role.DESIGNER);
218 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
219 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
221 if (createResponse.isRight()) {
222 assertEquals(new Integer(200), createResponse.right().value().getStatus());
224 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
227 private void validateUserRoles(Role ... roles) {
228 List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
229 when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true));
232 private void assertEqualsServiceObject(Service origService, Service newService) {
233 assertEquals(origService.getContactId(), newService.getContactId());
234 assertEquals(origService.getCategories(), newService.getCategories());
235 assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
236 assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
237 assertEquals(origService.getDescription(), newService.getDescription());
238 assertEquals(origService.getIcon(), newService.getIcon());
239 assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
240 assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
241 assertEquals(origService.getName(), newService.getName());
242 assertEquals(origService.getName(), newService.getName());
243 assertEquals(origService.getUniqueId(), newService.getUniqueId());
244 assertEquals(origService.getVersion(), newService.getVersion());
245 assertEquals(origService.getArtifacts(), newService.getArtifacts());
246 assertEquals(origService.getCreationDate(), newService.getCreationDate());
247 assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
248 assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
249 assertEquals(origService.getTags(), newService.getTags());
252 private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
253 ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
254 ResponseFormat actualResponse = createResponse.right().value();
255 assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
256 assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
259 /* CREATE validations - start ***********************/
260 // Service name - start
263 public void testFailedServiceValidations() {
264 testServiceNameAlreadyExists();
265 testServiceNameEmpty();
266 // testServiceNameExceedsLimit();
267 testServiceNameWrongFormat();
268 testServiceDescriptionEmpty();
269 testServiceDescriptionMissing();
270 testServiceDescExceedsLimitCreate();
271 testServiceDescNotEnglish();
272 testServiceIconEmpty();
273 testServiceIconMissing();
274 testResourceIconInvalid();
275 testResourceIconExceedsLimit();
276 // testTagsExceedsLimitCreate();
277 // testTagsSingleExcessLimit();
278 testTagsNoServiceName();
280 testServiceTagNotExist();
281 testServiceTagEmpty();
283 testContactIdTooLong();
284 testContactIdWrongFormatCreate();
285 testInvalidProjectCode();
286 testProjectCodeTooLong();
287 testProjectCodeTooShort();
289 testResourceContactIdMissing();
290 testServiceCategoryExist();
291 testServiceBadCategoryCreate();
292 testMissingProjectCode();
295 private void testServiceNameAlreadyExists() {
296 String serviceName = "alreadyExist";
297 Service serviceExccedsNameLimit = createServiceObject(false);
298 // 51 chars, the limit is 50
299 serviceExccedsNameLimit.setName(serviceName);
300 List<String> tgs = new ArrayList<String>();
301 tgs.add(serviceName);
302 serviceExccedsNameLimit.setTags(tgs);
303 validateUserRoles(Role.ADMIN, Role.DESIGNER);
304 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
305 assertTrue(createResponse.isRight());
306 assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
309 private void testServiceNameEmpty() {
310 Service serviceExccedsNameLimit = createServiceObject(false);
311 serviceExccedsNameLimit.setName(null);
313 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
314 assertTrue(createResponse.isRight());
315 assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
318 private void testServiceNameWrongFormat() {
319 Service service = createServiceObject(false);
321 String nameWrongFormat = "ljg\fd";
322 service.setName(nameWrongFormat);
324 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
325 assertTrue(createResponse.isRight());
326 assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
329 // Service name - end
330 // Service description - start
331 private void testServiceDescriptionEmpty() {
332 Service serviceExist = createServiceObject(false);
333 serviceExist.setDescription("");
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 testServiceDescriptionMissing() {
342 Service serviceExist = createServiceObject(false);
343 serviceExist.setDescription(null);
345 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
346 assertTrue(createResponse.isRight());
348 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
351 private void testServiceDescExceedsLimitCreate() {
352 Service serviceExccedsDescLimit = createServiceObject(false);
353 // 1025 chars, the limit is 1024
354 String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
355 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
356 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
357 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
358 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
359 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
360 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
361 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
363 serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
365 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsDescLimit, user);
366 assertTrue(createResponse.isRight());
367 assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
370 private void testServiceDescNotEnglish() {
371 Service notEnglish = createServiceObject(false);
373 String tooLongServiceDesc = "\uC2B5";
374 notEnglish.setDescription(tooLongServiceDesc);
376 Either<Service, ResponseFormat> createResponse = bl.createService(notEnglish, user);
377 assertTrue(createResponse.isRight());
378 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
381 // Service description - stop
382 // Service icon - start
383 private void testServiceIconEmpty() {
384 Service serviceExist = createServiceObject(false);
385 serviceExist.setIcon("");
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 testServiceIconMissing() {
394 Service serviceExist = createServiceObject(false);
395 serviceExist.setIcon(null);
397 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
398 assertTrue(createResponse.isRight());
400 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
403 private void testResourceIconInvalid() {
404 Service resourceExist = createServiceObject(false);
405 resourceExist.setIcon("kjk3453^&");
407 Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
408 assertTrue(createResponse.isRight());
410 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
413 private void testResourceIconExceedsLimit() {
414 Service resourceExist = createServiceObject(false);
415 resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
417 Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
418 assertTrue(createResponse.isRight());
420 assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
423 private void testTagsNoServiceName() {
424 Service serviceExccedsNameLimit = createServiceObject(false);
425 String tag1 = "afzs2qLBb";
426 List<String> tagsList = new ArrayList<String>();
428 serviceExccedsNameLimit.setTags(tagsList);
430 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
431 assertTrue(createResponse.isRight());
432 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
436 private void testInvalidTag() {
437 Service serviceExccedsNameLimit = createServiceObject(false);
438 String tag1 = "afzs2qLBb%#%";
439 List<String> tagsList = new ArrayList<String>();
441 serviceExccedsNameLimit.setTags(tagsList);
443 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
444 assertTrue(createResponse.isRight());
445 assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" });
449 private void testServiceTagNotExist() {
450 Service serviceExist = createServiceObject(false);
451 serviceExist.setTags(null);
453 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
454 assertTrue(createResponse.isRight());
456 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
459 private void testServiceTagEmpty() {
460 Service serviceExist = createServiceObject(false);
461 serviceExist.setTags(new ArrayList<String>());
463 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
464 assertTrue(createResponse.isRight());
466 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
469 // Service tags - stop
470 // Service contactId - start
471 private void testContactIdTooLong() {
472 Service serviceContactId = createServiceObject(false);
473 // 59 chars instead of 50
474 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
475 serviceContactId.setContactId(contactIdTooLong);
477 Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
478 assertTrue(createResponse.isRight());
479 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
482 private void testContactIdWrongFormatCreate() {
483 Service serviceContactId = createServiceObject(false);
484 // 3 letters and 3 digits and special characters
485 String contactIdTooLong = "yrt134!!!";
486 serviceContactId.setContactId(contactIdTooLong);
488 Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
489 assertTrue(createResponse.isRight());
490 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
493 private void testResourceContactIdMissing() {
494 Service resourceExist = createServiceObject(false);
495 resourceExist.setContactId(null);
497 Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
498 assertTrue(createResponse.isRight());
499 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
502 // Service contactId - stop
503 // Service category - start
504 private void testServiceCategoryExist() {
505 Service serviceExist = createServiceObject(false);
506 serviceExist.setCategories(null);
508 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
509 assertTrue(createResponse.isRight());
511 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
514 public void markDistributionAsDeployedTestAlreadyDeployed() {
515 String notifyAction = "DNotify";
516 String requestAction = "DRequest";
517 String resultAction = "DResult";
518 String did = "123456";
520 setupBeforeDeploy(notifyAction, requestAction, did);
521 List<DistributionDeployEvent> resultList = new ArrayList<DistributionDeployEvent>();
522 Map<String, Object> params = new HashMap<String, Object>();
523 DistributionDeployEvent event = new DistributionDeployEvent();
525 event.setAction(resultAction);
527 event.setStatus("200");
528 // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
529 // deployEvent.setFields(params);
530 resultList.add(event);
531 Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
533 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
535 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
536 assertTrue(markDeployed.isLeft());
538 Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
543 public void markDistributionAsDeployedTestSuccess() {
544 String notifyAction = "DNotify";
545 String requestAction = "DRequest";
546 String did = "123456";
548 setupBeforeDeploy(notifyAction, requestAction, did);
549 List<Role> roles = new ArrayList<>();
550 roles.add(Role.ADMIN);
552 when(userValidations.validateUserRole(user, roles)).thenReturn(Either.left(true));
553 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
554 assertTrue(markDeployed.isLeft());
558 public void markDistributionAsDeployedTestNotDistributed() {
559 String notifyAction = "DNotify";
560 String requestAction = "DRequest";
561 String did = "123456";
563 setupBeforeDeploy(notifyAction, requestAction, did);
564 List<ResourceAdminEvent> emptyList = new ArrayList<ResourceAdminEvent>();
565 Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
566 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
568 Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
569 Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
571 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
572 assertTrue(markDeployed.isRight());
573 assertEquals(404, markDeployed.right().value().getStatus().intValue());
577 private void testServiceBadCategoryCreate() {
579 Service serviceExist = createServiceObject(false);
580 CategoryDefinition category = new CategoryDefinition();
581 category.setName("koko");
582 List<CategoryDefinition> categories = new ArrayList<>();
583 categories.add(category);
584 serviceExist.setCategories(categories);
586 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
587 assertTrue(createResponse.isRight());
589 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
592 // Service category - stop
593 // Service projectCode - start
594 private void testInvalidProjectCode() {
596 Service serviceExist = createServiceObject(false);
597 serviceExist.setProjectCode("koko!!");
599 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
600 assertTrue(createResponse.isRight());
602 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
605 private void testProjectCodeTooLong() {
607 Service serviceExist = createServiceObject(false);
608 String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
609 serviceExist.setProjectCode(tooLongProjectCode);
611 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
612 assertTrue(createResponse.isRight());
614 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
617 private void testProjectCodeTooShort() {
619 Service serviceExist = createServiceObject(false);
620 serviceExist.setProjectCode("333");
622 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
623 assertTrue(createResponse.isRight());
625 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
628 private void testMissingProjectCode() {
630 Service serviceExist = createServiceObject(false);
631 serviceExist.setProjectCode(null);
633 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
634 assertTrue(createResponse.isRight());
636 assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE);
640 // public void testDeleteMarkedServicesNoServices() {
641 // List<String> ids = new ArrayList<String>();
642 // Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
643 // when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources);
645 // Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
646 // assertTrue(deleteMarkedResources.isLeft());
647 // assertTrue(deleteMarkedResources.left().value().isEmpty());
649 // Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList());
655 public void testDeleteMarkedServices() {
656 List<String> ids = new ArrayList<String>();
657 String resourceInUse = "123";
658 ids.add(resourceInUse);
659 String resourceFree = "456";
660 ids.add(resourceFree);
661 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
662 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
664 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
665 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
667 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
668 Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
669 // when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse);
671 when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
672 when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
674 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
675 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
677 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
678 assertTrue(deleteMarkedResources.isLeft());
679 List<String> resourceIdList = deleteMarkedResources.left().value();
680 assertFalse(resourceIdList.isEmpty());
681 assertTrue(resourceIdList.contains(resourceFree));
682 assertFalse(resourceIdList.contains(resourceInUse));
686 private Service createServiceObject(boolean afterCreate) {
687 Service service = new Service();
688 service.setUniqueId("sid");
689 service.setName("Service");
690 CategoryDefinition category = new CategoryDefinition();
691 category.setName(SERVICE_CATEGORY);
692 List<CategoryDefinition> categories = new ArrayList<>();
693 categories.add(category);
694 service.setCategories(categories);
696 service.setDescription("description");
697 List<String> tgs = new ArrayList<String>();
698 tgs.add(service.getName());
699 service.setTags(tgs);
700 // service.setVendorName("Motorola");
701 // service.setVendorRelease("1.0.0");
702 service.setIcon("MyIcon");
703 // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
704 service.setContactId("aa1234");
705 service.setProjectCode("12345");
708 service.setVersion("0.1");
709 service.setUniqueId(service.getName() + ":" + service.getVersion());
710 service.setCreatorUserId(user.getUserId());
711 service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
716 private void mockAuditingDaoLogic() {
717 FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
718 FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
719 FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
721 FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION);
722 FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION);
724 final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
725 createResourceAudit.setModifier("Carlos Santana(cs0008)");
726 createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
727 createResourceAudit.setCurrVersion("0.1");
728 createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
729 createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f");
730 createResourceAudit.setDesc("OK");
731 createResourceAudit.setResourceType("Resource");
732 createResourceAudit.setStatus("201");
733 createResourceAudit.setPrevVersion("");
734 createResourceAudit.setAction("Create");
735 // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977");
736 createResourceAudit.setPrevState("");
737 createResourceAudit.setResourceName("MyTestResource");
738 // createResourceAudit.setFields(fields);
740 final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent();
741 checkInResourceAudit.setModifier("Carlos Santana(cs0008)");
742 checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN");
743 checkInResourceAudit.setCurrVersion("0.1");
744 checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
745 checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091");
746 checkInResourceAudit.setDesc("OK");
747 checkInResourceAudit.setComment("Stam");
748 checkInResourceAudit.setResourceType("Resource");
749 checkInResourceAudit.setStatus("200");
750 checkInResourceAudit.setPrevVersion("0.1");
751 checkInResourceAudit.setAction("Checkin");
752 // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797");
753 checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT");
754 checkInResourceAudit.setResourceName("MyTestResource");
756 final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent();
757 checkOutResourceAudit.setModifier("Carlos Santana(cs0008)");
758 checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
759 checkOutResourceAudit.setCurrVersion("0.2");
760 checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
761 checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8");
762 checkOutResourceAudit.setDesc("OK");
763 checkOutResourceAudit.setComment("");
764 checkOutResourceAudit.setResourceType("Resource");
765 checkOutResourceAudit.setStatus("200");
766 checkOutResourceAudit.setPrevVersion("0.1");
767 checkOutResourceAudit.setAction("Checkout");
768 // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024");
769 checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN");
770 checkOutResourceAudit.setResourceName("MyTestResource");
771 // checkOutResourceAudit.setFields(fields);
773 // Mockito.doAnswer(new Answer<Either<List<ESTimeBasedEvent>,
774 // ActionStatus> >() {
775 // public Either<List<ESTimeBasedEvent>, ActionStatus>
776 // answer(InvocationOnMock invocation) {
777 // final Either<List<ESTimeBasedEvent>, ActionStatus> either;
778 // final List<ESTimeBasedEvent> list;
779 // Object[] args = invocation.getArguments();
780 // Map<AuditingFieldsKeysEnum, Object> filterMap =
781 // (Map<AuditingFieldsKeysEnum, Object>) args[0];
782 // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){
784 // ArrayList<ESTimeBasedEvent>(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}};
785 // either = Either.left(list);
788 // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){
789 // list = new ArrayList<ESTimeBasedEvent>();
790 // either = Either.left(list);
792 // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){
794 // ArrayList<ESTimeBasedEvent>(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}};
795 // either = Either.left(list);
802 // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap());
805 List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() {
807 add(createResourceAudit);
808 add(checkInResourceAudit);
809 add(checkOutResourceAudit);
812 Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
813 Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
815 List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>();
816 Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
817 Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
819 List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() {
821 add(checkOutResourceAudit);
824 Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr);
825 Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr);
829 private void setupBeforeDeploy(String notifyAction, String requestAction, String did) {
831 DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent();
832 notifyEvent.setAction(notifyAction);
833 notifyEvent.setDid(did);
834 notifyEvent.setStatus("200");
836 ResourceAdminEvent requestEvent = new ResourceAdminEvent();
837 requestEvent.setAction(requestAction);
838 requestEvent.setDid(did);
839 requestEvent.setStatus("200");
841 ArrayList<DistributionNotificationEvent> arrayList = new ArrayList<DistributionNotificationEvent>();
842 List<DistributionNotificationEvent> notifyResults = arrayList;
843 notifyResults.add(notifyEvent);
844 Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults);
846 Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify);
848 List<ResourceAdminEvent> requestResults = new ArrayList<ResourceAdminEvent>();
849 requestResults.add(requestEvent);
850 Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults);
851 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest);
853 Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true));
854 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
856 List<DistributionDeployEvent> emptyList = new ArrayList<DistributionDeployEvent>();
857 Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
858 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList);
861 @SuppressWarnings({ "unchecked", "rawtypes" })
863 public void testFindGroupInstanceOnRelatedComponentInstance() {
865 Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
866 String methodName = "findGroupInstanceOnRelatedComponentInstance";
867 Object invalidId = "invalidId";
869 Component service = createNewService();
870 List<ComponentInstance> componentInstances = service.getComponentInstances();
872 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
873 Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
874 Class[] argClasses = {Component.class, String.class,String.class};
876 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
877 method.setAccessible(true);
879 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
880 assertTrue(findGroupInstanceRes != null);
881 assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId()));
882 assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId()));
884 Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
886 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
887 assertTrue(findGroupInstanceRes != null);
888 assertTrue(findGroupInstanceRes.isRight());
889 assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593"));
891 Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
893 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
894 assertTrue(findGroupInstanceRes != null);
895 assertTrue(findGroupInstanceRes.isRight());
896 assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653"));
898 catch (Exception e) {
903 private Component createNewService() {
905 Service service = new Service();
907 service.setName("serviceName");
908 service.setUniqueId("serviceUniqueId");
909 List<ComponentInstance> componentInstances = new ArrayList<>();
910 ComponentInstance ci;
911 for(int i= 0; i<listSize; ++i){
912 ci = new ComponentInstance();
913 ci.setName("ciName" + i);
914 ci.setUniqueId("ciId" + i);
915 List<GroupInstance> groupInstances= new ArrayList<>();
917 for(int j = 0; j<listSize; ++j){
918 gi = new GroupInstance();
919 gi.setName(ci.getName( )+ "giName" + j);
920 gi.setUniqueId(ci.getName() + "giId" + j);
921 groupInstances.add(gi);
923 ci.setGroupInstances(groupInstances);
924 componentInstances.add(ci);
926 service.setComponentInstances(componentInstances);
932 public void testDerivedFromGeneric() {
933 Service service = createServiceObject(true);
934 validateUserRoles(Role.ADMIN, Role.DESIGNER);
935 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
936 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
937 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
938 assertTrue(createResponse.isLeft());
939 service = createResponse.left().value();
940 assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName()));
941 assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion()));
945 private Resource setupGenericServiceMock(){
946 Resource genericService = new Resource();
947 genericService.setVersion("1.0");
948 genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
949 return genericService;