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