05ca32cbbc4ba60524210655e31cf951f043292c
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / impl / ServiceBusinessLogicTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  * Modifications copyright (c) 2019 Nokia
20  * ================================================================================
21  */
22
23 package org.openecomp.sdc.be.components.impl;
24
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.GraphLockOperation;
51 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
52 import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
53 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
54 import org.openecomp.sdc.be.user.Role;
55 import org.openecomp.sdc.be.user.UserBusinessLogic;
56 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
57 import org.openecomp.sdc.common.api.ConfigurationSource;
58 import org.openecomp.sdc.common.api.Constants;
59 import org.openecomp.sdc.common.impl.ExternalConfiguration;
60 import org.openecomp.sdc.common.impl.FSConfigurationSource;
61 import org.openecomp.sdc.common.util.ValidationUtils;
62 import org.openecomp.sdc.exception.ResponseFormat;
63 import org.springframework.web.context.WebApplicationContext;
64
65 import javax.servlet.ServletContext;
66 import java.lang.reflect.Method;
67 import java.util.*;
68 import java.util.stream.Collectors;
69 import java.util.stream.Stream;
70
71 import static org.assertj.core.api.Assertions.assertThat;
72 import static org.junit.Assert.*;
73 import static org.junit.Assert.assertNotNull;
74 import static org.mockito.ArgumentMatchers.anyString;
75 import static org.mockito.ArgumentMatchers.eq;
76 import static org.mockito.Mockito.when;
77 import static org.mockito.ArgumentMatchers.eq;
78
79 public class ServiceBusinessLogicTest {
80
81     private static final String SERVICE_CATEGORY = "Mobility";
82     private static final String INSTANTIATION_TYPE = "A-la-carte";
83     private final ServletContext servletContext = Mockito.mock(ServletContext.class);
84     private UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
85     private WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
86     private WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
87     private ServiceBusinessLogic bl = new ServiceBusinessLogic();
88     private ResponseFormatManager responseManager = null;
89     private ComponentsUtils componentsUtils;
90     private AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
91     private ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
92     private GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
93     private JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class);
94     private ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
95     private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
96     private UserValidations userValidations = Mockito.mock(UserValidations.class);
97     private ResourceAdminEvent auditArchive1 = Mockito.mock(ResourceAdminEvent.class);
98     private ResourceAdminEvent auditArchive2 = Mockito.mock(ResourceAdminEvent.class);
99     private ResourceAdminEvent auditRestore = Mockito.mock(ResourceAdminEvent.class);
100
101     private User user = null;
102     private Resource genericService = null;
103
104     private static final String CERTIFIED_VERSION = "1.0";
105     private static final String UNCERTIFIED_VERSION = "0.2";
106     private static final String COMPONNET_ID = "myUniqueId";
107     private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
108
109     public ServiceBusinessLogicTest() {
110
111     }
112
113     @Before
114     public void setup() {
115
116         ExternalConfiguration.setAppName("catalog-be");
117         // init Configuration
118         String appConfigDir = "src/test/resources/config/catalog-be";
119         ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
120         ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
121         componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
122
123         // Elements
124         IElementOperation mockElementDao = new ElementOperationMock();
125
126         // User data and management
127         user = new User();
128         user.setUserId("jh0003");
129         user.setFirstName("Jimmi");
130         user.setLastName("Hendrix");
131         user.setRole(Role.ADMIN.name());
132
133         Either<User, ActionStatus> eitherGetUser = Either.left(user);
134         when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
135         when(userValidations.validateUserExists(eq("jh0003"), anyString(), eq(false))).thenReturn(user);
136         when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
137         when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
138         when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
139         when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
140         when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
141         when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
142         when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
143
144         // artifact bussinesslogic
145         ArtifactDefinition artifactDef = new ArtifactDefinition();
146         when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
147
148         // createService
149         Service serviceResponse = createServiceObject(true);
150         Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
151         when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate);
152         Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
153         when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount);
154         Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
155         when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist);
156
157         genericService = setupGenericServiceMock();
158         Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService);
159         when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric);
160
161
162         bl = new ServiceBusinessLogic();
163         bl.setElementDao(mockElementDao);
164         bl.setUserAdmin(mockUserAdmin);
165         bl.setArtifactBl(artifactBl);
166         bl.setGraphLockOperation(graphLockOperation);
167         bl.setJanusGraphGenericDao(mockJanusGraphDao);
168         bl.setToscaOperationFacade(toscaOperationFacade);
169         bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
170         bl.setComponentsUtils(componentsUtils);
171         bl.setCassandraAuditingDao(auditingDao);
172         bl.setUserValidations(userValidations);
173
174         mockAuditingDaoLogic();
175
176         responseManager = ResponseFormatManager.getInstance();
177
178     }
179
180     @Test
181     public void testGetComponentAuditRecordsCertifiedVersion() {
182         Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
183         assertTrue(componentAuditRecords.isLeft());
184         assertEquals(3, componentAuditRecords.left().value().size());
185     }
186
187     @Test
188     public void testGetComponentAuditRecordsUnCertifiedVersion() {
189         Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
190         assertTrue(componentAuditRecords.isLeft());
191         assertEquals(4, componentAuditRecords.left().value().size());
192     }
193
194     @Test
195     public void testHappyScenario() {
196         Service service = createServiceObject(false);
197         validateUserRoles(Role.ADMIN, Role.DESIGNER);
198         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
199         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
200
201         if (createResponse.isRight()) {
202             assertEquals(new Integer(200), createResponse.right().value().getStatus());
203         }
204         assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
205     }
206
207     private void validateUserRoles(Role ... roles) {
208         List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
209     }
210
211     private void assertEqualsServiceObject(Service origService, Service newService) {
212         assertEquals(origService.getContactId(), newService.getContactId());
213         assertEquals(origService.getCategories(), newService.getCategories());
214         assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
215         assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
216         assertEquals(origService.getDescription(), newService.getDescription());
217         assertEquals(origService.getIcon(), newService.getIcon());
218         assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
219         assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
220         assertEquals(origService.getName(), newService.getName());
221         assertEquals(origService.getName(), newService.getName());
222         assertEquals(origService.getUniqueId(), newService.getUniqueId());
223         assertEquals(origService.getVersion(), newService.getVersion());
224         assertEquals(origService.getArtifacts(), newService.getArtifacts());
225         assertEquals(origService.getCreationDate(), newService.getCreationDate());
226         assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
227         assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
228         assertEquals(origService.getTags(), newService.getTags());
229     }
230
231     private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
232         assertResponse(createResponse.right().value(), expectedStatus, variables);
233     }
234
235     private void assertComponentException(ByActionStatusComponentException e, ActionStatus expectedStatus, String... variables) {
236         ResponseFormat actualResponse = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
237         assertResponse(actualResponse, expectedStatus, variables);
238     }
239
240     private void assertComponentException(ByResponseFormatComponentException e, ActionStatus expectedStatus, String... variables) {
241         ResponseFormat actualResponse = e.getResponseFormat();
242         assertResponse(actualResponse, expectedStatus, variables);
243     }
244
245     private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
246         ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
247         assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
248         assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
249     }
250
251
252     @Test
253     public void testFailedServiceValidations() {
254         testServiceNameAlreadyExists();
255         testServiceNameEmpty();
256         testServiceNameWrongFormat();
257         testServiceDescriptionEmpty();
258         testServiceDescriptionMissing();
259         testServiceDescExceedsLimitCreate();
260         testServiceDescNotEnglish();
261         testServiceIconEmpty();
262         testServiceIconMissing();
263         testResourceIconInvalid();
264         testResourceIconExceedsLimit();
265         testTagsNoServiceName();
266         testInvalidTag();
267         testServiceTagNotExist();
268         testServiceTagEmpty();
269
270         testContactIdTooLong();
271         testContactIdWrongFormatCreate();
272         testInvalidProjectCode();
273         testProjectCodeTooLong();
274         testProjectCodeTooShort();
275
276         testResourceContactIdMissing();
277         testServiceCategoryExist();
278         testServiceBadCategoryCreate();
279         testMissingProjectCode();
280     }
281
282     private void testServiceNameAlreadyExists() {
283         String serviceName = "alreadyExist";
284         Service serviceExccedsNameLimit = createServiceObject(false);
285         // 51 chars, the limit is 50
286         serviceExccedsNameLimit.setName(serviceName);
287         List<String> tgs = new ArrayList<>();
288         tgs.add(serviceName);
289         serviceExccedsNameLimit.setTags(tgs);
290         validateUserRoles(Role.ADMIN, Role.DESIGNER);
291         Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
292         assertTrue(createResponse.isRight());
293         assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
294     }
295
296     private void testServiceNameEmpty() {
297         Service serviceExccedsNameLimit = createServiceObject(false);
298         serviceExccedsNameLimit.setName(null);
299         try{
300             bl.createService(serviceExccedsNameLimit, user);
301         } catch(ByActionStatusComponentException e){
302             assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
303         }
304     }
305
306     private void testServiceNameWrongFormat() {
307         Service service = createServiceObject(false);
308         // contains :
309         String nameWrongFormat = "ljg\fd";
310         service.setName(nameWrongFormat);
311         try{
312             bl.createService(service, user);
313         } catch(ByActionStatusComponentException e){
314             assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
315         }
316     }
317
318     private void testServiceDescriptionEmpty() {
319         Service serviceExist = createServiceObject(false);
320         serviceExist.setDescription("");
321         try{
322             bl.createService(serviceExist, user);
323         } catch(ByActionStatusComponentException e){
324             assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
325         }
326     }
327
328     private void testServiceDescriptionMissing() {
329         Service serviceExist = createServiceObject(false);
330         serviceExist.setDescription(null);
331         try{
332             bl.createService(serviceExist, user);
333         } catch(ByActionStatusComponentException e){
334             assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
335         }
336     }
337
338     private void testServiceDescExceedsLimitCreate() {
339         Service serviceExccedsDescLimit = createServiceObject(false);
340         // 1025 chars, the limit is 1024
341         String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
342                 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
343                 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
344                 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
345                 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
346                 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
347                 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
348                 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
349
350         serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
351         try{
352             bl.createService(serviceExccedsDescLimit, user);
353         } catch(ByActionStatusComponentException e){
354             assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
355         }
356     }
357
358     private void testServiceDescNotEnglish() {
359         Service notEnglish = createServiceObject(false);
360         // Not english
361         String tooLongServiceDesc = "\uC2B5";
362         notEnglish.setDescription(tooLongServiceDesc);
363         try{
364             bl.createService(notEnglish, user);
365         } catch(ByActionStatusComponentException e){
366             assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
367         }
368     }
369
370     // Service description - stop
371     // Service icon - start
372     private void testServiceIconEmpty() {
373         Service serviceExist = createServiceObject(false);
374         serviceExist.setIcon("");
375         try{
376             bl.createService(serviceExist, user);
377         } catch(ByActionStatusComponentException e) {
378             assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
379         }
380     }
381
382     private void testServiceIconMissing() {
383         Service serviceExist = createServiceObject(false);
384         serviceExist.setIcon(null);
385         try{
386             bl.createService(serviceExist, user);
387         } catch(ByActionStatusComponentException e) {
388             assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
389         }
390     }
391
392     private void testResourceIconInvalid() {
393         Service resourceExist = createServiceObject(false);
394         resourceExist.setIcon("kjk3453^&");
395         try{
396             bl.createService(resourceExist, user);
397         } catch(ByActionStatusComponentException e) {
398             assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
399         }
400     }
401
402     private void testResourceIconExceedsLimit() {
403         Service resourceExist = createServiceObject(false);
404         resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
405         try{
406             bl.createService(resourceExist, user);
407         } catch(ByActionStatusComponentException e) {
408             assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, "Service", "25");
409         }
410     }
411
412     private void testTagsNoServiceName() {
413         Service serviceExccedsNameLimit = createServiceObject(false);
414         String tag1 = "afzs2qLBb";
415         List<String> tagsList = new ArrayList<>();
416         tagsList.add(tag1);
417         serviceExccedsNameLimit.setTags(tagsList);
418         try{
419             bl.createService(serviceExccedsNameLimit, user);
420         } catch(ByActionStatusComponentException e) {
421             assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
422         }
423     }
424
425     private void testInvalidTag() {
426         Service serviceExccedsNameLimit = createServiceObject(false);
427         String tag1 = "afzs2qLBb%#%";
428         List<String> tagsList = new ArrayList<>();
429         tagsList.add(tag1);
430         serviceExccedsNameLimit.setTags(tagsList);
431         try{
432             bl.createService(serviceExccedsNameLimit, user);
433         } catch(ByActionStatusComponentException e) {
434             assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
435         }
436     }
437
438     private void testServiceTagNotExist() {
439         Service serviceExist = createServiceObject(false);
440         serviceExist.setTags(null);
441         try{
442             bl.createService(serviceExist, user);
443         } catch(ByActionStatusComponentException e) {
444             assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
445         }
446     }
447
448     private void testServiceTagEmpty() {
449         Service serviceExist = createServiceObject(false);
450         serviceExist.setTags(new ArrayList<>());
451         try{
452             bl.createService(serviceExist, user);
453         } catch(ByActionStatusComponentException e) {
454             assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
455         }
456     }
457
458     // Service tags - stop
459     // Service contactId - start
460     private void testContactIdTooLong() {
461         Service serviceContactId = createServiceObject(false);
462         // 59 chars instead of 50
463         String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
464         serviceContactId.setContactId(contactIdTooLong);
465         try{
466             bl.createService(serviceContactId, user);
467         } catch(ByActionStatusComponentException e) {
468             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
469         }
470     }
471
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);
477         try{
478             bl.createService(serviceContactId, user);
479         } catch(ByActionStatusComponentException e) {
480             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
481         }
482     }
483
484     private void testResourceContactIdMissing() {
485         Service resourceExist = createServiceObject(false);
486         resourceExist.setContactId(null);
487         try{
488             bl.createService(resourceExist, user);
489         } catch(ByActionStatusComponentException e) {
490             assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
491         }
492     }
493
494     // Service contactId - stop
495     // Service category - start
496     private void testServiceCategoryExist() {
497         Service serviceExist = createServiceObject(false);
498         serviceExist.setCategories(null);
499         try{
500             bl.createService(serviceExist, user);
501         } catch(ByActionStatusComponentException e) {
502             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
503         }
504     }
505
506     @Test
507     public void markDistributionAsDeployedTestAlreadyDeployed() {
508         String notifyAction = "DNotify";
509         String requestAction = "DRequest";
510         String resultAction = "DResult";
511         String did = "123456";
512
513         setupBeforeDeploy(notifyAction, requestAction, did);
514         List<DistributionDeployEvent> resultList = new ArrayList<>();
515         Map<String, Object> params = new HashMap<>();
516         DistributionDeployEvent event = new DistributionDeployEvent();
517
518         event.setAction(resultAction);
519         event.setDid(did);
520         event.setStatus("200");
521         // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
522         // deployEvent.setFields(params);
523         resultList.add(event);
524         Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
525
526         Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
527
528         Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
529         assertTrue(markDeployed.isLeft());
530
531         Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
532
533     }
534
535     @Test
536     public void markDistributionAsDeployedTestSuccess() {
537         String notifyAction = "DNotify";
538         String requestAction = "DRequest";
539         String did = "123456";
540
541         setupBeforeDeploy(notifyAction, requestAction, did);
542         List<Role> roles = new ArrayList<>();
543         roles.add(Role.ADMIN);
544         roles.add(Role.OPS);
545         Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
546         assertTrue(markDeployed.isLeft());
547     }
548
549     @Test
550     public void markDistributionAsDeployedTestNotDistributed() {
551         String notifyAction = "DNotify";
552         String requestAction = "DRequest";
553         String did = "123456";
554
555         setupBeforeDeploy(notifyAction, requestAction, did);
556         List<ResourceAdminEvent> emptyList = new ArrayList<>();
557         Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
558         Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
559
560         Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
561         Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
562
563         Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
564         assertTrue(markDeployed.isRight());
565         assertEquals(404, markDeployed.right().value().getStatus().intValue());
566
567     }
568
569     private void testServiceBadCategoryCreate() {
570
571         Service serviceExist = createServiceObject(false);
572         CategoryDefinition category = new CategoryDefinition();
573         category.setName("koko");
574         List<CategoryDefinition> categories = new ArrayList<>();
575         categories.add(category);
576         serviceExist.setCategories(categories);
577         try{
578             bl.createService(serviceExist, user);
579         } catch(ByActionStatusComponentException e) {
580             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
581         }
582     }
583
584     // Service category - stop
585     // Service projectCode - start
586     private void testInvalidProjectCode() {
587
588         Service serviceExist = createServiceObject(false);
589         serviceExist.setProjectCode("koko!!");
590
591         Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
592         assertTrue(createResponse.isRight());
593
594         assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
595     }
596
597     private void testProjectCodeTooLong() {
598
599         Service serviceExist = createServiceObject(false);
600         String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
601         serviceExist.setProjectCode(tooLongProjectCode);
602
603         Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
604         assertTrue(createResponse.isRight());
605
606         assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
607     }
608
609     private void testProjectCodeTooShort() {
610
611         Service serviceExist = createServiceObject(false);
612         serviceExist.setProjectCode("333");
613
614         Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
615         assertTrue(createResponse.isRight());
616
617         assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
618     }
619
620     private void testMissingProjectCode() {
621
622         Service serviceExist = createServiceObject(false);
623         serviceExist.setProjectCode(null);
624         try{
625             bl.createService(serviceExist, user);
626         } catch(ByActionStatusComponentException e) {
627             assertComponentException(e, ActionStatus.MISSING_PROJECT_CODE);
628         }
629     }
630
631     @Test
632     public void testDeleteMarkedServices() {
633         List<String> ids = new ArrayList<>();
634         List<String> responseIds = new ArrayList<>();
635         String resourceInUse = "123";
636         ids.add(resourceInUse);
637         String resourceFree = "456";
638         ids.add(resourceFree);
639         responseIds.add(resourceFree);
640         Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
641         when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
642
643         Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
644         Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
645
646         List<ArtifactDefinition> artifacts = new ArrayList<>();
647         Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
648
649         Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
650         when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
651         when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
652         Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
653         assertTrue(deleteMarkedResources.isLeft());
654         List<String> resourceIdList = deleteMarkedResources.left().value();
655         assertFalse(resourceIdList.isEmpty());
656         assertTrue(resourceIdList.contains(resourceFree));
657         assertFalse(resourceIdList.contains(resourceInUse));
658
659     }
660
661     private Service createServiceObject(boolean afterCreate) {
662         Service service = new Service();
663         service.setUniqueId("sid");
664         service.setName("Service");
665         CategoryDefinition category = new CategoryDefinition();
666         category.setName(SERVICE_CATEGORY);
667         List<CategoryDefinition> categories = new ArrayList<>();
668         categories.add(category);
669         service.setCategories(categories);
670         service.setInstantiationType(INSTANTIATION_TYPE);
671
672         service.setDescription("description");
673         List<String> tgs = new ArrayList<>();
674         tgs.add(service.getName());
675         service.setTags(tgs);
676         service.setIcon("MyIcon");
677         service.setContactId("aa1234");
678         service.setProjectCode("12345");
679
680         if (afterCreate) {
681             service.setVersion("0.1");
682             service.setUniqueId(service.getName() + ":" + service.getVersion());
683             service.setCreatorUserId(user.getUserId());
684             service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
685         }
686         return service;
687     }
688
689     private void mockAuditingDaoLogic() {
690         final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
691         createResourceAudit.setModifier("Carlos Santana(cs0008)");
692         createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
693         createResourceAudit.setCurrVersion("0.1");
694         createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
695         createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f");
696         createResourceAudit.setDesc("OK");
697         createResourceAudit.setResourceType("Resource");
698         createResourceAudit.setStatus("201");
699         createResourceAudit.setPrevVersion("");
700         createResourceAudit.setAction("Create");
701         // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977");
702         createResourceAudit.setPrevState("");
703         createResourceAudit.setResourceName("MyTestResource");
704         // createResourceAudit.setFields(fields);
705
706         final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent();
707         checkInResourceAudit.setModifier("Carlos Santana(cs0008)");
708         checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN");
709         checkInResourceAudit.setCurrVersion("0.1");
710         checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
711         checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091");
712         checkInResourceAudit.setDesc("OK");
713         checkInResourceAudit.setComment("Stam");
714         checkInResourceAudit.setResourceType("Resource");
715         checkInResourceAudit.setStatus("200");
716         checkInResourceAudit.setPrevVersion("0.1");
717         checkInResourceAudit.setAction("Checkin");
718         // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797");
719         checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT");
720         checkInResourceAudit.setResourceName("MyTestResource");
721
722         final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent();
723         checkOutResourceAudit.setModifier("Carlos Santana(cs0008)");
724         checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
725         checkOutResourceAudit.setCurrVersion("0.2");
726         checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
727         checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8");
728         checkOutResourceAudit.setDesc("OK");
729         checkOutResourceAudit.setComment("");
730         checkOutResourceAudit.setResourceType("Resource");
731         checkOutResourceAudit.setStatus("200");
732         checkOutResourceAudit.setPrevVersion("0.1");
733         checkOutResourceAudit.setAction("Checkout");
734         // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024");
735         checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN");
736         checkOutResourceAudit.setResourceName("MyTestResource");
737         List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() {
738             {
739                 add(createResourceAudit);
740                 add(checkInResourceAudit);
741                 add(checkOutResourceAudit);
742             }
743         };
744         Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
745         Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
746
747         List<ResourceAdminEvent> listPrev = new ArrayList<>();
748         Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
749         Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
750
751         List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() {
752             {
753                 add(checkOutResourceAudit);
754             }
755         };
756         Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr);
757         Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr);
758
759         Either<List<ResourceAdminEvent>, ActionStatus> archiveAuditList = Either.left(Arrays.asList(auditArchive1, auditArchive2));
760         when(auditingDao.getArchiveAuditByServiceInstanceId(anyString())).thenReturn(archiveAuditList);
761
762         Either<List<ResourceAdminEvent>, ActionStatus> restoreAuditList = Either.left(Arrays.asList(auditRestore));
763         when(auditingDao.getRestoreAuditByServiceInstanceId(anyString())).thenReturn(restoreAuditList);
764
765     }
766
767     private void setupBeforeDeploy(String notifyAction, String requestAction, String did) {
768
769         DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent();
770         notifyEvent.setAction(notifyAction);
771         notifyEvent.setDid(did);
772         notifyEvent.setStatus("200");
773
774         ResourceAdminEvent requestEvent = new ResourceAdminEvent();
775         requestEvent.setAction(requestAction);
776         requestEvent.setDid(did);
777         requestEvent.setStatus("200");
778
779         List<DistributionNotificationEvent> notifyResults = Collections.singletonList(notifyEvent);
780         Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults);
781
782         Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify);
783
784         List<ResourceAdminEvent> requestResults = Collections.singletonList(requestEvent);
785         Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults);
786         Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest);
787
788         Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true));
789         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
790
791         Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(Collections.emptyList());
792         Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList);
793     }
794
795     @SuppressWarnings({ "unchecked", "rawtypes" })
796     @Test
797     public void testFindGroupInstanceOnRelatedComponentInstance() {
798
799         Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
800         String methodName = "findGroupInstanceOnRelatedComponentInstance";
801         Object invalidId = "invalidId";
802
803         Component service = createNewService();
804         List<ComponentInstance> componentInstances = service.getComponentInstances();
805
806         Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
807         Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
808         Class[] argClasses = {Component.class, String.class,String.class};
809         try {
810             Method method = targetClass.getDeclaredMethod(methodName, argClasses);
811             method.setAccessible(true);
812
813             findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
814             assertNotNull(findGroupInstanceRes);
815             assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
816                                                                                                        .getUniqueId());
817             assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
818                                                                                                          .getGroupInstances()
819                                                                                                          .get(1)
820                                                                                                          .getUniqueId());
821
822             Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
823
824             findGroupInstanceRes =    (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
825             assertNotNull(findGroupInstanceRes);
826             assertTrue(findGroupInstanceRes.isRight());
827             assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
828
829             Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
830
831             findGroupInstanceRes =    (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
832             assertNotNull(findGroupInstanceRes);
833             assertTrue(findGroupInstanceRes.isRight());
834             assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
835         }
836         catch (Exception e) {
837             e.printStackTrace();
838         }
839     }
840
841     private Component createNewService() {
842
843         Service service = new Service();
844         int listSize = 3;
845         service.setName("serviceName");
846         service.setUniqueId("serviceUniqueId");
847         List<ComponentInstance> componentInstances = new ArrayList<>();
848         ComponentInstance ci;
849         for(int i= 0; i<listSize; ++i){
850             ci = new ComponentInstance();
851             ci.setName("ciName" + i);
852             ci.setUniqueId("ciId" + i);
853             List<GroupInstance>  groupInstances= new ArrayList<>();
854             GroupInstance gi;
855             for(int j = 0; j<listSize; ++j){
856                 gi = new GroupInstance();
857                 gi.setName(ci.getName( )+ "giName" + j);
858                 gi.setUniqueId(ci.getName() + "giId" + j);
859                 groupInstances.add(gi);
860             }
861             ci.setGroupInstances(groupInstances);
862             componentInstances.add(ci);
863         }
864         service.setComponentInstances(componentInstances);
865         return service;
866     }
867
868
869     @Test
870     public void testDerivedFromGeneric() {
871         Service service = createServiceObject(true);
872         validateUserRoles(Role.ADMIN, Role.DESIGNER);
873         when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
874         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
875         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
876         assertTrue(createResponse.isLeft());
877         service = createResponse.left().value();
878         assertEquals(service.getDerivedFromGenericType(), genericService.getToscaResourceName());
879         assertEquals(service.getDerivedFromGenericVersion(), genericService.getVersion());
880     }
881
882     @Test
883     public void testUpdateMetadataNamingPolicy() {
884         Service currentService = createServiceObject(true);
885         Service newService = createServiceObject(false);
886         currentService.setEcompGeneratedNaming(false);
887         newService.setEcompGeneratedNaming(true);
888         newService.setNamingPolicy("policy");
889         Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
890         assertThat(resultOfUpdate.isLeft()).isTrue();
891         Service updatedService = resultOfUpdate.left().value();
892         assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
893         assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
894     }
895
896     @Test
897     public void testUpdateMetadataServiceType() {
898         Service currentService = createServiceObject(true);
899         Service newService = createServiceObject(false);
900         currentService.setServiceType("alice");
901         //valid English word
902         newService.setServiceType("bob");
903         Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
904         assertThat(resultOfUpdate.isLeft()).isTrue();
905         Service updatedService = resultOfUpdate.left().value();
906         assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
907         //empty string is invalid
908         newService.setServiceType("");
909         resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
910         assertThat(resultOfUpdate.isLeft()).isTrue();
911         //null is invalid
912         newService.setServiceType(null);
913         resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
914         assertThat(resultOfUpdate.isRight()).isTrue();
915     }
916
917     private Resource setupGenericServiceMock(){
918         Resource genericService = new Resource();
919         genericService.setVersion("1.0");
920         genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
921         return genericService;
922     }
923 }