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