Catalog alignment
[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  */
20
21 package org.openecomp.sdc.be.components.impl;
22
23 import com.google.common.collect.Lists;
24 import com.google.common.collect.Maps;
25 import fj.data.Either;
26 import org.apache.commons.lang3.tuple.ImmutablePair;
27 import org.junit.Assert;
28 import org.junit.Test;
29 import org.mockito.Mockito;
30 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
31 import org.openecomp.sdc.be.dao.api.ActionStatus;
32 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
33 import org.openecomp.sdc.be.datatypes.elements.InterfaceInstanceDataDefinition;
34 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
35 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
36 import org.openecomp.sdc.be.model.ArtifactDefinition;
37 import org.openecomp.sdc.be.model.Component;
38 import org.openecomp.sdc.be.model.ComponentInstance;
39 import org.openecomp.sdc.be.model.ComponentInstanceInterface;
40 import org.openecomp.sdc.be.model.GroupInstance;
41 import org.openecomp.sdc.be.model.Operation;
42 import org.openecomp.sdc.be.model.Resource;
43 import org.openecomp.sdc.be.model.Service;
44 import org.openecomp.sdc.be.model.category.CategoryDefinition;
45 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
46 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
47 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
48 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
49 import org.openecomp.sdc.be.types.ServiceConsumptionData;
50 import org.openecomp.sdc.be.user.Role;
51 import org.openecomp.sdc.common.util.ValidationUtils;
52 import org.openecomp.sdc.exception.ResponseFormat;
53 import org.springframework.http.HttpStatus;
54
55 import java.lang.reflect.Method;
56 import java.util.ArrayList;
57 import java.util.Arrays;
58 import java.util.HashMap;
59 import java.util.List;
60 import java.util.Map;
61 import java.util.UUID;
62 import java.util.stream.Collectors;
63 import java.util.stream.Stream;
64
65 import static org.assertj.core.api.Assertions.assertThat;
66 import static org.junit.Assert.assertEquals;
67 import static org.junit.Assert.assertFalse;
68 import static org.junit.Assert.assertNotNull;
69 import static org.junit.Assert.assertTrue;
70 import static org.junit.Assert.fail;
71 import static org.mockito.Mockito.when;
72
73 public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup {
74
75     private final static String DEFAULT_ICON = "defaulticon";
76     private static final String ALREADY_EXIST = "alreadyExist";
77     private static final String DOES_NOT_EXIST = "doesNotExist";
78
79     @Test
80     public void testGetComponentAuditRecordsCertifiedVersion() {
81         Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
82         assertTrue(componentAuditRecords.isLeft());
83         assertEquals(3, componentAuditRecords.left().value().size());
84     }
85
86     @Test
87     public void testGetComponentAuditRecordsUnCertifiedVersion() {
88         Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
89         assertTrue(componentAuditRecords.isLeft());
90         assertEquals(4, componentAuditRecords.left().value().size());
91     }
92
93     @Test
94     public void testHappyScenario() {
95         Service service = createServiceObject(false);
96         validateUserRoles(Role.ADMIN, Role.DESIGNER);
97         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
98         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
99
100         if (createResponse.isRight()) {
101             assertEquals(new Integer(200), createResponse.right().value().getStatus());
102         }
103         assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
104     }
105     @Test
106     public void testHappyScenarioCRNullProjectCode() {
107         Service service = createServiceObject(false);
108         service.setProjectCode(null);
109         validateUserRoles(Role.ADMIN, Role.DESIGNER);
110         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
111         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
112
113         if (createResponse.isRight()) {
114             assertEquals(new Integer(200), createResponse.right().value().getStatus());
115         }
116         assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
117     }
118     @Test
119     public void testHappyScenarioCREmptyStringProjectCode() {
120         createServiceValidator();
121         Service service = createServiceObject(false);
122         service.setProjectCode("");
123         validateUserRoles(Role.ADMIN, Role.DESIGNER);
124         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
125         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
126
127         if (createResponse.isRight()) {
128             assertEquals(new Integer(200), createResponse.right().value().getStatus());
129         }
130         assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
131     }
132
133     private void validateUserRoles(Role ... roles) {
134         List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
135     }
136
137     private void assertEqualsServiceObject(Service origService, Service newService) {
138         assertEquals(origService.getContactId(), newService.getContactId());
139         assertEquals(origService.getCategories(), newService.getCategories());
140         assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
141         assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
142         assertEquals(origService.getDescription(), newService.getDescription());
143         assertEquals(origService.getIcon(), newService.getIcon());
144         assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
145         assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
146         assertEquals(origService.getName(), newService.getName());
147         assertEquals(origService.getName(), newService.getName());
148         assertEquals(origService.getUniqueId(), newService.getUniqueId());
149         assertEquals(origService.getVersion(), newService.getVersion());
150         assertEquals(origService.getArtifacts(), newService.getArtifacts());
151         assertEquals(origService.getCreationDate(), newService.getCreationDate());
152         assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
153         assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
154         assertEquals(origService.getTags(), newService.getTags());
155     }
156
157
158     /* CREATE validations - start ***********************/
159     // Service name - start
160
161
162     @Test
163     public void testFailedServiceValidations() {
164
165         testServiceNameAlreadyExists();
166         testServiceNameEmpty();
167         testServiceNameWrongFormat();
168         testServiceDescriptionEmpty();
169         testServiceDescriptionMissing();
170         testServiceDescExceedsLimitCreate();
171         testServiceDescNotEnglish();
172         testServiceIconEmpty();
173         testServiceIconMissing();
174         testResourceIconInvalid();
175         testTagsNoServiceName();
176         testInvalidTag();
177         testServiceTagNotExist();
178         testServiceTagEmpty();
179
180         testContactIdTooLong();
181         testContactIdWrongFormatCreate();
182         testInvalidProjectCode();
183         testProjectCodeTooLong();
184         testProjectCodeTooShort();
185
186         testResourceContactIdMissing();
187         testServiceCategoryExist();
188         testServiceBadCategoryCreate();
189     }
190
191     private void testServiceNameAlreadyExists() {
192         String serviceName = ALREADY_EXIST;
193         Service serviceExccedsNameLimit = createServiceObject(false);
194         // 51 chars, the limit is 50
195         serviceExccedsNameLimit.setName(serviceName);
196         List<String> tgs = new ArrayList<>();
197         tgs.add(serviceName);
198         serviceExccedsNameLimit.setTags(tgs);
199         validateUserRoles(Role.ADMIN, Role.DESIGNER);
200         try {
201             bl.createService(serviceExccedsNameLimit, user);
202         } catch (ComponentException exp) {
203             assertResponse(exp.getResponseFormat(), ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
204             return;
205         }
206         fail();
207     }
208
209     private void testServiceNameEmpty() {
210         Service serviceExccedsNameLimit = createServiceObject(false);
211         serviceExccedsNameLimit.setName(null);
212         try{
213             bl.createService(serviceExccedsNameLimit, user);
214         } catch(ComponentException e){
215             assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
216             return;
217         }
218         fail();
219     }
220
221     private void testServiceNameWrongFormat() {
222         Service service = createServiceObject(false);
223         // contains :
224         String nameWrongFormat = "ljg\\fd";
225         service.setName(nameWrongFormat);
226         try{
227             bl.createService(service, user);
228         } catch(ComponentException e){
229             assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
230             return;
231         }
232         fail();
233     }
234
235     // Service name - end
236     // Service description - start
237     private void testServiceDescriptionEmpty() {
238         Service serviceExist = createServiceObject(false);
239         serviceExist.setDescription("");
240         try{
241             bl.createService(serviceExist, user);
242         } catch(ComponentException e){
243             assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
244             return;
245         }
246         fail();
247     }
248
249     private void testServiceDescriptionMissing() {
250         Service serviceExist = createServiceObject(false);
251         serviceExist.setDescription(null);
252         try{
253             bl.createService(serviceExist, user);
254         } catch(ComponentException e){
255             assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
256             return;
257         }
258         fail();
259     }
260
261     private void testServiceDescExceedsLimitCreate() {
262         Service serviceExccedsDescLimit = createServiceObject(false);
263         // 1025 chars, the limit is 1024
264         String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
265                 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
266                 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
267                 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
268                 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
269                 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
270                 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
271                 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
272
273         serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
274         try{
275             bl.createService(serviceExccedsDescLimit, user);
276         } catch(ComponentException e){
277             assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
278             return;
279         }
280         fail();
281     }
282
283     private void testServiceDescNotEnglish() {
284         Service notEnglish = createServiceObject(false);
285         // Not english
286         String tooLongServiceDesc = "\uC2B5";
287         notEnglish.setDescription(tooLongServiceDesc);
288         try{
289             bl.createService(notEnglish, user);
290         } catch(ComponentException e){
291             assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
292             return;
293         }
294         fail();
295     }
296
297     // Service description - stop
298     // Service icon - start
299     private void testServiceIconEmpty() {
300         Service serviceExist = createServiceObject(false);
301         serviceExist.setIcon("");
302         Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist,user,AuditingActionEnum.CREATE_SERVICE);
303         assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
304
305     }
306
307     private void testServiceIconMissing() {
308         Service serviceExist = createServiceObject(false);
309         serviceExist.setIcon(null);
310         Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist,user,AuditingActionEnum.CREATE_SERVICE);
311         assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
312     }
313
314     private void testResourceIconInvalid() {
315         Service resourceExist = createServiceObject(false);
316         resourceExist.setIcon("kjk3453^&");
317
318         Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(resourceExist, user, AuditingActionEnum.CREATE_RESOURCE);
319         assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
320
321     }
322
323     private void testTagsNoServiceName() {
324         Service serviceExccedsNameLimit = createServiceObject(false);
325         String tag1 = "afzs2qLBb";
326         List<String> tagsList = new ArrayList<>();
327         tagsList.add(tag1);
328         serviceExccedsNameLimit.setTags(tagsList);
329         try{
330             bl.createService(serviceExccedsNameLimit, user);
331         } catch(ComponentException e) {
332             assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
333             return;
334         }
335         fail();
336     }
337
338     private void testInvalidTag() {
339         Service serviceExccedsNameLimit = createServiceObject(false);
340         String tag1 = "afzs2qLBb%#%";
341         List<String> tagsList = new ArrayList<>();
342         tagsList.add(tag1);
343         serviceExccedsNameLimit.setTags(tagsList);
344         try{
345             bl.createService(serviceExccedsNameLimit, user);
346         } catch(ComponentException e) {
347             assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
348             return;
349         }
350         fail();
351     }
352
353     private void testServiceTagNotExist() {
354         Service serviceExist = createServiceObject(false);
355         serviceExist.setTags(null);
356
357         Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
358         assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
359     }
360
361     private void testServiceTagEmpty() {
362         Service serviceExist = createServiceObject(false);
363         serviceExist.setTags(new ArrayList<>());
364
365         Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
366         assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
367     }
368
369     // Service tags - stop
370     // Service contactId - start
371     private void testContactIdTooLong() {
372         Service serviceContactId = createServiceObject(false);
373         // 59 chars instead of 50
374         String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
375         serviceContactId.setContactId(contactIdTooLong);
376         try{
377             bl.createService(serviceContactId, user);
378         } catch(ComponentException e) {
379             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
380             return;
381         }
382         fail();
383     }
384
385     private void testContactIdWrongFormatCreate() {
386         Service serviceContactId = createServiceObject(false);
387         // 3 letters and 3 digits and special characters
388         String contactIdTooLong = "yrt134!!!";
389         serviceContactId.setContactId(contactIdTooLong);
390         try{
391             bl.createService(serviceContactId, user);
392         } catch(ComponentException e) {
393             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
394             return;
395         }
396         fail();
397     }
398
399     private void testResourceContactIdMissing() {
400         Service resourceExist = createServiceObject(false);
401         resourceExist.setContactId(null);
402         try{
403             bl.createService(resourceExist, user);
404         } catch(ComponentException e) {
405             assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
406             return;
407         }
408         fail();
409     }
410
411     // Service contactId - stop
412     // Service category - start
413     private void testServiceCategoryExist() {
414         Service serviceExist = createServiceObject(false);
415         serviceExist.setCategories(null);
416         try{
417             bl.createService(serviceExist, user);
418         } catch(ComponentException e) {
419             assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
420             return;
421         }
422         fail();
423     }
424
425     @Test
426     public void markDistributionAsDeployedTestAlreadyDeployed() {
427         String notifyAction = "DNotify";
428         String requestAction = "DRequest";
429         String resultAction = "DResult";
430         String did = "123456";
431
432         setupBeforeDeploy(notifyAction, requestAction, did);
433         List<DistributionDeployEvent> resultList = new ArrayList<>();
434         Map<String, Object> params = new HashMap<>();
435         DistributionDeployEvent event = new DistributionDeployEvent();
436
437         event.setAction(resultAction);
438         event.setDid(did);
439         event.setStatus("200");
440         // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
441         // deployEvent.setFields(params);
442         resultList.add(event);
443         Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
444
445         Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
446
447         Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
448         assertTrue(markDeployed.isLeft());
449
450         Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
451
452     }
453
454     @Test
455     public void markDistributionAsDeployedTestSuccess() {
456         String notifyAction = "DNotify";
457         String requestAction = "DRequest";
458         String did = "123456";
459
460         setupBeforeDeploy(notifyAction, requestAction, did);
461         List<Role> roles = new ArrayList<>();
462         roles.add(Role.ADMIN);
463         roles.add(Role.DESIGNER);
464         Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
465         assertTrue(markDeployed.isLeft());
466     }
467
468     @Test
469     public void markDistributionAsDeployedTestNotDistributed() {
470         String notifyAction = "DNotify";
471         String requestAction = "DRequest";
472         String did = "123456";
473
474         setupBeforeDeploy(notifyAction, requestAction, did);
475         List<ResourceAdminEvent> emptyList = new ArrayList<>();
476         Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
477         Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
478
479         Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
480         Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
481
482         Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
483         assertTrue(markDeployed.isRight());
484         assertEquals(404, markDeployed.right().value().getStatus().intValue());
485
486     }
487
488     private void testServiceBadCategoryCreate() {
489
490         Service serviceExist = createServiceObject(false);
491         CategoryDefinition category = new CategoryDefinition();
492         category.setName("koko");
493         category.setIcons(Arrays.asList(DEFAULT_ICON));
494         List<CategoryDefinition> categories = new ArrayList<>();
495         categories.add(category);
496         serviceExist.setCategories(categories);
497         try{
498             bl.createService(serviceExist, user);
499         } catch(ComponentException e) {
500             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
501             return;
502         }
503         fail();
504     }
505
506     // Service category - stop
507     // Service projectCode - start
508     private void testInvalidProjectCode() {
509
510         Service serviceExist = createServiceObject(false);
511         serviceExist.setProjectCode("koko!!");
512
513         try {
514             bl.createService(serviceExist, user);
515         } catch(ComponentException exp) {
516            assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
517             return;
518         }
519         fail();
520     }
521
522
523     private void testProjectCodeTooLong() {
524
525         Service serviceExist = createServiceObject(false);
526         String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
527         serviceExist.setProjectCode(tooLongProjectCode);
528
529         try {
530             bl.createService(serviceExist, user);
531         } catch(ComponentException exp) {
532             assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
533             return;
534         }
535         fail();
536     }
537
538
539     private void testProjectCodeTooShort() {
540
541         Service serviceExist = createServiceObject(false);
542         serviceExist.setProjectCode("333");
543
544         try {
545             bl.createService(serviceExist, user);
546         } catch(ComponentException exp) {
547             assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
548             return;
549         }
550         fail();
551     }
552
553     @Test
554     public void testDeleteMarkedServices() {
555         List<String> ids = new ArrayList<>();
556         List<String> responseIds = new ArrayList<>();
557         String resourceInUse = "123";
558         ids.add(resourceInUse);
559         String resourceFree = "456";
560         ids.add(resourceFree);
561         responseIds.add(resourceFree);
562         Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
563         when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
564
565         Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
566         Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
567
568         List<ArtifactDefinition> artifacts = new ArrayList<>();
569         Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
570
571         Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
572         when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
573         when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
574         Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
575         assertTrue(deleteMarkedResources.isLeft());
576         List<String> resourceIdList = deleteMarkedResources.left().value();
577         assertFalse(resourceIdList.isEmpty());
578         assertTrue(resourceIdList.contains(resourceFree));
579         assertFalse(resourceIdList.contains(resourceInUse));
580
581     }
582
583
584     @SuppressWarnings({ "unchecked", "rawtypes" })
585     @Test
586     public void testFindGroupInstanceOnRelatedComponentInstance() {
587
588         Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
589         String methodName = "findGroupInstanceOnRelatedComponentInstance";
590         Object invalidId = "invalidId";
591
592         Component service = createNewService();
593         List<ComponentInstance> componentInstances = service.getComponentInstances();
594
595         Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
596         Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
597         Class[] argClasses = {Component.class, String.class,String.class};
598         try {
599             Method method = targetClass.getDeclaredMethod(methodName, argClasses);
600             method.setAccessible(true);
601
602             findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
603             assertNotNull(findGroupInstanceRes);
604             assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
605                                                                                                        .getUniqueId());
606             assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
607                                                                                                          .getGroupInstances()
608                                                                                                          .get(1)
609                                                                                                          .getUniqueId());
610
611             Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
612
613             findGroupInstanceRes =    (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
614             assertNotNull(findGroupInstanceRes);
615             assertTrue(findGroupInstanceRes.isRight());
616             assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
617
618             Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
619
620             findGroupInstanceRes =    (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
621             assertNotNull(findGroupInstanceRes);
622             assertTrue(findGroupInstanceRes.isRight());
623             assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
624         }
625         catch (Exception e) {
626             e.printStackTrace();
627         }
628     }
629
630     private Component createNewComponent() {
631
632         Service service = new Service();
633         int listSize = 3;
634         service.setName("serviceName");
635         service.setUniqueId("serviceUniqueId");
636         List<ComponentInstance> componentInstances = new ArrayList<>();
637         ComponentInstance ci;
638         for(int i= 0; i<listSize; ++i){
639             ci = new ComponentInstance();
640             ci.setName("ciName" + i);
641             ci.setUniqueId("ciId" + i);
642             List<GroupInstance>  groupInstances= new ArrayList<>();
643             GroupInstance gi;
644             for(int j = 0; j<listSize; ++j){
645                 gi = new GroupInstance();
646                 gi.setName(ci.getName( )+ "giName" + j);
647                 gi.setUniqueId(ci.getName() + "giId" + j);
648                 groupInstances.add(gi);
649             }
650             ci.setGroupInstances(groupInstances);
651             componentInstances.add(ci);
652         }
653         service.setComponentInstances(componentInstances);
654         return service;
655     }
656
657     protected Service createNewService() {
658         return (Service)createNewComponent();
659     }
660
661
662     @Test
663     public void testDerivedFromGeneric() {
664         Service service = createServiceObject(true);
665         validateUserRoles(Role.ADMIN, Role.DESIGNER);
666         when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
667         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
668         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
669         assertTrue(createResponse.isLeft());
670         service = createResponse.left().value();
671         assertEquals(service.getDerivedFromGenericType(), genericService.getToscaResourceName());
672         assertEquals(service.getDerivedFromGenericVersion(), genericService.getVersion());
673     }
674
675     @Test
676     public void testUpdateMetadataNamingPolicy() {
677         Service currentService = createServiceObject(true);
678         Service newService = createServiceObject(false);
679         currentService.setEcompGeneratedNaming(false);
680         newService.setEcompGeneratedNaming(true);
681         newService.setNamingPolicy("policy");
682         Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
683         assertThat(resultOfUpdate.isLeft()).isTrue();
684         Service updatedService = resultOfUpdate.left().value();
685         assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
686         assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
687     }
688
689     @Test
690     public void testUpdateMetadataToEmptyProjectCode() {
691         Service currentService = createServiceObject(true);
692         Service newService = createServiceObject(false);
693         currentService.setProjectCode("12345");
694         newService.setProjectCode("");
695         Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
696         assertThat(resultOfUpdate.isLeft()).isTrue();
697         Service updatedService = resultOfUpdate.left().value();
698         assertThat(updatedService.getProjectCode()).isEmpty();
699     }
700
701     @Test
702     public void testUpdateMetadataFromEmptyProjectCode() {
703         Service currentService = createServiceObject(true);
704         Service newService = createServiceObject(false);
705         currentService.setProjectCode("");
706         newService.setProjectCode("12345");
707         Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
708         assertThat(resultOfUpdate.isLeft()).isTrue();
709         Service updatedService = resultOfUpdate.left().value();
710         assertThat(updatedService.getProjectCode()).isEqualTo("12345");
711     }
712
713     @Test
714     public void testUpdateMetadataProjectCode() {
715         Service currentService = createServiceObject(true);
716         Service newService = createServiceObject(false);
717         currentService.setProjectCode("33333");
718         newService.setProjectCode("12345");
719         Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
720         assertThat(resultOfUpdate.isLeft()).isTrue();
721         Service updatedService = resultOfUpdate.left().value();
722         assertThat(updatedService.getProjectCode()).isEqualTo("12345");
723     }
724
725     @Test
726     public void testUpdateMetadataServiceType() {
727         Service currentService = createServiceObject(true);
728         Service newService = createServiceObject(false);
729         currentService.setServiceType("alice");
730         //valid English word
731         newService.setServiceType("bob");
732         Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
733         assertThat(resultOfUpdate.isLeft()).isTrue();
734         Service updatedService = resultOfUpdate.left().value();
735         assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
736         //empty string is invalid
737         newService.setServiceType("");
738         resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
739         assertThat(resultOfUpdate.isLeft()).isTrue();
740         //null is invalid
741         newService.setServiceType(null);
742         resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
743         assertThat(resultOfUpdate.isRight()).isTrue();
744     }
745
746     @Test
747     public void testCreateDefaultMetadataServiceFunction() {
748         Service currentService = createServiceObject(true);
749         assertThat(currentService.getServiceFunction()).isEqualTo("");
750     }
751
752     @Test
753     public void testCreateCustomMetadataServiceFunction() {
754         String customServiceFunctionName = "customName";
755         Service currentService = createServiceObject(true);
756         currentService.setServiceFunction(customServiceFunctionName);
757         assertThat(currentService.getServiceFunction()).isEqualTo(customServiceFunctionName);
758     }
759
760     @Test
761     public void testUpdateMetadataServiceFunction() {
762         Service currentService = createServiceObject(true);
763         Service newService = createServiceObject(false);
764         currentService.setServiceFunction("alice");
765         //valid English word
766         newService.setServiceFunction("bob");
767         Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
768         assertThat(resultOfUpdate.isLeft()).isTrue();
769         Service updatedService = resultOfUpdate.left().value();
770         assertThat(updatedService.getServiceFunction()).isEqualToIgnoringCase("bob");
771         //empty string is valid
772         newService.setServiceFunction("");
773         resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
774         assertThat(resultOfUpdate.isLeft()).isTrue();
775         //null is valid and assigner to ""
776         newService.setServiceFunction(null);
777         resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
778         assertThat(resultOfUpdate.isLeft()).isTrue();
779         assertThat(updatedService.getServiceFunction()).isEqualTo("");
780     }
781
782
783
784     @Test
785     public void testServiceFunctionExceedLength() {
786         String serviceName = "Service";
787         String serviceFunction = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
788         Service serviceFunctionExceedLength = createServiceObject(false);
789         serviceFunctionExceedLength.setName(serviceName);
790         serviceFunctionExceedLength.setServiceFunction(serviceFunction);
791         List<String> tgs = new ArrayList<>();
792         tgs.add(serviceName);
793         serviceFunctionExceedLength.setTags(tgs);
794         try {
795             serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
796         } catch (ComponentException exp) {
797             assertResponse(exp.getResponseFormat(), ActionStatus.PROPERTY_EXCEEDS_LIMIT, SERVICE_FUNCTION);
798         }
799     }
800
801     @Test
802     public void testServiceFunctionInvalidCharacter(){
803         String serviceName = "Service";
804         String serviceFunction = "a?";
805         Service serviceFunctionExceedLength = createServiceObject(false);
806         serviceFunctionExceedLength.setName(serviceName);
807         serviceFunctionExceedLength.setServiceFunction(serviceFunction);
808         List<String> tgs = new ArrayList<>();
809         tgs.add(serviceName);
810         serviceFunctionExceedLength.setTags(tgs);
811         try {
812             serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
813         } catch (ComponentException exp) {
814             assertResponse(exp.getResponseFormat(), ActionStatus.INVALID_PROPERY, SERVICE_FUNCTION);
815         }
816     }
817
818     @Test
819     public void testAddPropertyServiceConsumptionServiceNotFound() {
820         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
821
822         Either<Operation, ResponseFormat> operationEither =
823                 bl.addPropertyServiceConsumption("1", "2", "3",
824                         user.getUserId(), new ServiceConsumptionData());
825         Assert.assertTrue(operationEither.isRight());
826         Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
827     }
828
829     @Test
830     public void testAddPropertyServiceConsumptionParentServiceIsEmpty() {
831         Either<Component, StorageOperationStatus> eitherService = Either.left(createNewComponent());
832         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
833
834         Either<Operation, ResponseFormat> operationEither =
835                 bl.addPropertyServiceConsumption("1", "2", "3",
836                         user.getUserId(), new ServiceConsumptionData());
837         Assert.assertTrue(operationEither.isRight());
838         Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
839     }
840
841     @Test
842     public void testAddPropertyServiceConsumptionNoMatchingComponent() {
843         Service aService = createNewService();
844         Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
845         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
846
847         String weirdUniqueServiceInstanceId = UUID.randomUUID().toString();
848
849         Either<Operation, ResponseFormat> operationEither =
850                 bl.addPropertyServiceConsumption("1", weirdUniqueServiceInstanceId, "3",
851                         user.getUserId(), new ServiceConsumptionData());
852         Assert.assertTrue(operationEither.isRight());
853         Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
854     }
855
856     @Test
857     public void testAddPropertyServiceConsumptionNotComponentInstancesInterfacesOnParentService() {
858         Service aService = createNewService();
859         aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
860         Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
861         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
862
863         Either<Operation, ResponseFormat> operationEither =
864                 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
865                         user.getUserId(), new ServiceConsumptionData());
866         Assert.assertTrue(operationEither.isRight());
867         Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
868     }
869
870     @Test
871     public void testAddPropertyServiceConsumptionInterfaceCandidateNotPresent() {
872         Service aService = createNewService();
873         aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
874         Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
875         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
876
877         Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap =
878                 Maps.newHashMap();
879         componentInstancesInterfacesMap.put(aService.getUniqueId(),
880                 Lists.newArrayList(new ComponentInstanceInterface("1", new InterfaceInstanceDataDefinition())));
881
882         aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
883
884         Either<Operation, ResponseFormat> operationEither =
885                 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
886                         user.getUserId(), new ServiceConsumptionData());
887         Assert.assertTrue(operationEither.isRight());
888         Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
889     }
890
891     @Test
892     public void testAddPropertyServiceConsumptionNoInputsCandidate() {
893         Service aService = createNewService();
894         aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
895         Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
896         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
897
898         String operationId = "operationId";
899         ComponentInstanceInterface componentInstanceInterface =
900                 new ComponentInstanceInterface("interfaceId", new InterfaceInstanceDataDefinition());
901         Map<String, Operation> operationsMap = Maps.newHashMap();
902         operationsMap.put(operationId, new Operation(new ArtifactDataDefinition(), "1",
903                 new ListDataDefinition<>(), new ListDataDefinition<>()));
904         componentInstanceInterface.setOperationsMap(operationsMap);
905
906         Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap = Maps.newHashMap();
907         componentInstancesInterfacesMap.put(aService.getUniqueId(), Lists.newArrayList(componentInstanceInterface));
908         aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
909
910         Either<Operation, ResponseFormat> operationEither =
911                 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), operationId,
912                         user.getUserId(), new ServiceConsumptionData());
913         Assert.assertTrue(operationEither.isRight());
914         Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
915     }
916
917 }