[SDC-29] catalog 1707 rebase commit.
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / 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;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertFalse;
25 import static org.junit.Assert.assertTrue;
26 import static org.mockito.Mockito.when;
27
28 import java.lang.reflect.Method;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33
34 import javax.servlet.ServletContext;
35
36 import org.apache.commons.lang3.tuple.ImmutablePair;
37 import org.junit.Before;
38 import org.junit.Ignore;
39 import org.junit.Test;
40 import org.mockito.Mockito;
41 import org.mockito.invocation.InvocationOnMock;
42 import org.mockito.stubbing.Answer;
43 import org.openecomp.sdc.ElementOperationMock;
44 import org.openecomp.sdc.be.auditing.api.IAuditingManager;
45 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
46 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
47 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
48 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
49 import org.openecomp.sdc.be.config.ConfigurationManager;
50 import org.openecomp.sdc.be.dao.api.ActionStatus;
51 import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
52 import org.openecomp.sdc.be.dao.impl.AuditingDao;
53 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
54 import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
55 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
56 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
57 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
58 import org.openecomp.sdc.be.impl.ComponentsUtils;
59 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
60 import org.openecomp.sdc.be.model.ArtifactDefinition;
61 import org.openecomp.sdc.be.model.Component;
62 import org.openecomp.sdc.be.model.ComponentInstance;
63 import org.openecomp.sdc.be.model.GroupInstance;
64 import org.openecomp.sdc.be.model.InputDefinition;
65 import org.openecomp.sdc.be.model.PropertyDefinition;
66 import org.openecomp.sdc.be.model.Resource;
67 import org.openecomp.sdc.be.model.Service;
68 import org.openecomp.sdc.be.model.User;
69 import org.openecomp.sdc.be.model.category.CategoryDefinition;
70 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
71 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
72 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
73 import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
74 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
75 import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
76 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
77 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
78 import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
79 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
80 import org.openecomp.sdc.be.user.Role;
81 import org.openecomp.sdc.be.user.UserBusinessLogic;
82 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
83 import org.openecomp.sdc.common.api.ConfigurationSource;
84 import org.openecomp.sdc.common.api.Constants;
85 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
86 import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent;
87 import org.openecomp.sdc.common.impl.ExternalConfiguration;
88 import org.openecomp.sdc.common.impl.FSConfigurationSource;
89 import org.openecomp.sdc.common.util.ValidationUtils;
90 import org.openecomp.sdc.exception.ResponseFormat;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
93 import org.springframework.web.context.WebApplicationContext;
94
95 import com.google.gson.Gson;
96 import com.google.gson.GsonBuilder;
97
98 import fj.data.Either;
99
100 public class ServiceBusinessLogicTest {
101
102         private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class.getName());
103         private static final String SERVICE_CATEGORY = "Mobility";
104         final ServletContext servletContext = Mockito.mock(ServletContext.class);
105         IAuditingManager iAuditingManager = null;
106         UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
107         WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
108         WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
109         ServiceBusinessLogic bl = new ServiceBusinessLogic();
110         ResponseFormatManager responseManager = null;
111         IElementOperation mockElementDao;
112         AuditingManager auditingManager = Mockito.mock(AuditingManager.class);
113         ComponentsUtils componentsUtils = new ComponentsUtils();
114         AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
115         ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
116         GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
117         TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
118         ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
119         CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
120
121         User user = null;
122         Service serviceResponse = null;
123         Resource genericService = null;
124         
125         private static final String CERTIFIED_VERSION = "1.0";
126         private static final String UNCERTIFIED_VERSION = "0.2";
127         private static final String COMPONNET_ID = "myUniqueId";
128         private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
129         private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<AuditingFieldsKeysEnum, Object>();
130         private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<AuditingFieldsKeysEnum, Object>();
131         private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<AuditingFieldsKeysEnum, Object>();
132
133         public ServiceBusinessLogicTest() {
134
135         }
136
137         @Before
138         public void setup() {
139
140                 ExternalConfiguration.setAppName("catalog-be");
141                 // Init Configuration
142                 String appConfigDir = "src/test/resources/config/catalog-be";
143                 ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
144                 ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
145         
146                 // Elements
147                 mockElementDao = new ElementOperationMock();
148
149                 // User data and management
150                 user = new User();
151                 user.setUserId("jh0003");
152                 user.setFirstName("Jimmi");
153                 user.setLastName("Hendrix");
154                 user.setRole(Role.ADMIN.name());
155
156                 Either<User, ActionStatus> eitherGetUser = Either.left(user);
157                 when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
158
159                 // Servlet Context attributes
160                 when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
161                 when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation());
162                 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
163                 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
164                 when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
165                 when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
166                 when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
167
168                 // artifact bussinesslogic
169                 ArtifactDefinition artifactDef = new ArtifactDefinition();
170                 when(artifactBl.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
171
172                 // createService
173                 serviceResponse = createServiceObject(true);
174                 Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
175                 when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate);
176                 Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
177                 when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount);
178                 Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
179                 when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist);
180
181                 genericService = setupGenericServiceMock();
182                 Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService);
183                 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric);
184                 
185                 
186                 bl = new ServiceBusinessLogic();
187                 bl.setElementDao(mockElementDao);
188                 bl.setUserAdmin(mockUserAdmin);
189                 bl.setArtifactBl(artifactBl);
190                 bl.setGraphLockOperation(graphLockOperation);
191                 bl.setTitanGenericDao(mockTitanDao);
192                 bl.setToscaOperationFacade(toscaOperationFacade);
193                 
194                 componentsUtils.Init();
195                 componentsUtils.setAuditingManager(auditingManager);
196                 bl.setComponentsUtils(componentsUtils);
197                 bl.setCassandraAuditingDao(auditingDao);
198                 bl.setCacheManagerOperation(cacheManager);
199
200                 mockAuditingDaoLogic();
201
202                 responseManager = ResponseFormatManager.getInstance();
203
204         }
205
206         @Test
207         public void testGetComponentAuditRecordsCertifiedVersion() {
208                 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
209                 assertTrue(componentAuditRecords.isLeft());
210                 int size = componentAuditRecords.left().value().size();
211                 assertTrue(size == 3);
212         }
213
214         @Test
215         public void testGetComponentAuditRecordsUnCertifiedVersion() {
216                 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
217                 assertTrue(componentAuditRecords.isLeft());
218                 int size = componentAuditRecords.left().value().size();
219                 assertTrue(size == 1);
220         }
221
222         @Test
223         public void testHappyScenario() {
224                 Service service = createServiceObject(false);
225                 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
226
227                 if (createResponse.isRight()) {
228                         assertEquals(new Integer(200), createResponse.right().value().getStatus());
229                 }
230                 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
231         }
232
233         private void assertEqualsServiceObject(Service origService, Service newService) {
234                 assertEquals(origService.getContactId(), newService.getContactId());
235                 assertEquals(origService.getCategories(), newService.getCategories());
236                 assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
237                 assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
238                 assertEquals(origService.getDescription(), newService.getDescription());
239                 assertEquals(origService.getIcon(), newService.getIcon());
240                 assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
241                 assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
242                 assertEquals(origService.getName(), newService.getName());
243                 assertEquals(origService.getName(), newService.getName());
244                 assertEquals(origService.getUniqueId(), newService.getUniqueId());
245                 assertEquals(origService.getVersion(), newService.getVersion());
246                 assertEquals(origService.getArtifacts(), newService.getArtifacts());
247                 assertEquals(origService.getCreationDate(), newService.getCreationDate());
248                 assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
249                 assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
250                 assertEquals(origService.getTags(), newService.getTags());
251         }
252
253         private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
254                 ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
255                 ResponseFormat actualResponse = createResponse.right().value();
256                 assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
257                 assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
258         }
259
260         /* CREATE validations - start ***********************/
261         // Service name - start
262
263         @Test
264         public void testFailedServiceValidations() {
265                 testServiceNameAlreadyExists();
266                 testServiceNameEmpty();
267                 // testServiceNameExceedsLimit();
268                 testServiceNameWrongFormat();
269                 testServiceDescriptionEmpty();
270                 testServiceDescriptionMissing();
271                 testServiceDescExceedsLimitCreate();
272                 testServiceDescNotEnglish();
273                 testServiceIconEmpty();
274                 testServiceIconMissing();
275                 testResourceIconInvalid();
276                 testResourceIconExceedsLimit();
277                 // testTagsExceedsLimitCreate();
278                 // testTagsSingleExcessLimit();
279                 testTagsNoServiceName();
280                 testInvalidTag();
281                 testServiceTagNotExist();
282                 testServiceTagEmpty();
283                 
284                 testContactIdTooLong();
285                 testContactIdWrongFormatCreate();
286                 testInvalidProjectCode();
287                 testProjectCodeTooLong();
288                 testProjectCodeTooShort();
289                 
290                 testResourceContactIdMissing();
291                 testServiceCategoryExist();
292                 testServiceBadCategoryCreate();
293                 testMissingProjectCode();
294         }
295
296         private void testServiceNameAlreadyExists() {
297                 String serviceName = "alreadyExist";
298                 Service serviceExccedsNameLimit = createServiceObject(false);
299                 // 51 chars, the limit is 50
300                 serviceExccedsNameLimit.setName(serviceName);
301                 List<String> tgs = new ArrayList<String>();
302                 tgs.add(serviceName);
303                 serviceExccedsNameLimit.setTags(tgs);
304
305                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
306                 assertTrue(createResponse.isRight());
307                 assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
308         }
309
310         private void testServiceNameEmpty() {
311                 Service serviceExccedsNameLimit = createServiceObject(false);
312                 serviceExccedsNameLimit.setName(null);
313
314                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
315                 assertTrue(createResponse.isRight());
316                 assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
317         }
318
319         private void testServiceNameExceedsLimit() {
320                 Service serviceExccedsNameLimit = createServiceObject(false);
321                 // 51 chars, the limit is 50
322                 String tooLongServiceName = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxdsafefegesse";
323                 serviceExccedsNameLimit.setName(tooLongServiceName);
324
325                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
326                 assertTrue(createResponse.isRight());
327                 assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
328         }
329
330         private void testServiceNameWrongFormat() {
331                 Service service = createServiceObject(false);
332                 // contains :
333                 String nameWrongFormat = "ljg\fd";
334                 service.setName(nameWrongFormat);
335
336                 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
337                 assertTrue(createResponse.isRight());
338                 assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
339         }
340
341         // Service name - end
342         // Service description - start
343         private void testServiceDescriptionEmpty() {
344                 Service serviceExist = createServiceObject(false);
345                 serviceExist.setDescription("");
346
347                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
348                 assertTrue(createResponse.isRight());
349
350                 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
351         }
352
353         private void testServiceDescriptionMissing() {
354                 Service serviceExist = createServiceObject(false);
355                 serviceExist.setDescription(null);
356
357                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
358                 assertTrue(createResponse.isRight());
359
360                 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
361         }
362
363         private void testServiceDescExceedsLimitCreate() {
364                 Service serviceExccedsDescLimit = createServiceObject(false);
365                 // 1025 chars, the limit is 1024
366                 String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
367                                 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
368                                 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
369                                 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
370                                 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
371                                 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
372                                 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
373                                 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
374
375                 serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
376
377                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsDescLimit, user);
378                 assertTrue(createResponse.isRight());
379                 assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
380         }
381
382         private void testServiceDescNotEnglish() {
383                 Service notEnglish = createServiceObject(false);
384                 // Not english
385                 String tooLongServiceDesc = "\uC2B5";
386                 notEnglish.setDescription(tooLongServiceDesc);
387
388                 Either<Service, ResponseFormat> createResponse = bl.createService(notEnglish, user);
389                 assertTrue(createResponse.isRight());
390                 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
391         }
392
393         // Service description - stop
394         // Service icon - start
395         private void testServiceIconEmpty() {
396                 Service serviceExist = createServiceObject(false);
397                 serviceExist.setIcon("");
398
399                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
400                 assertTrue(createResponse.isRight());
401
402                 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
403         }
404
405         private void testServiceIconMissing() {
406                 Service serviceExist = createServiceObject(false);
407                 serviceExist.setIcon(null);
408
409                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
410                 assertTrue(createResponse.isRight());
411
412                 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
413         }
414
415         private void testResourceIconInvalid() {
416                 Service resourceExist = createServiceObject(false);
417                 resourceExist.setIcon("kjk3453^&");
418
419                 Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
420                 assertTrue(createResponse.isRight());
421
422                 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
423         }
424
425         private void testResourceIconExceedsLimit() {
426                 Service resourceExist = createServiceObject(false);
427                 resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
428
429                 Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
430                 assertTrue(createResponse.isRight());
431
432                 assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
433         }
434
435         // Service icon - stop
436         // Service tags - start
437         private void testTagsExceedsLimitCreate() {
438                 Service serviceExccedsNameLimit = createServiceObject(false);
439                 String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
440                 String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
441                 String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
442                 String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
443                 String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
444                 String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
445                 String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
446                 String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
447                 String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
448                 String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
449                 String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
450                 String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
451                 String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
452                 String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
453                 String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
454                 String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
455                 String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
456                 String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
457                 String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
458                 String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
459                 String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
460
461                 List<String> tagsList = new ArrayList<String>();
462                 tagsList.add(tag1);
463                 tagsList.add(tag2);
464                 tagsList.add(tag3);
465                 tagsList.add(tag4);
466                 tagsList.add(tag5);
467                 tagsList.add(tag6);
468                 tagsList.add(tag7);
469                 tagsList.add(tag8);
470                 tagsList.add(tag9);
471                 tagsList.add(tag10);
472                 tagsList.add(tag11);
473                 tagsList.add(tag12);
474                 tagsList.add(tag13);
475                 tagsList.add(tag14);
476                 tagsList.add(tag15);
477                 tagsList.add(tag16);
478                 tagsList.add(tag17);
479                 tagsList.add(tag18);
480                 tagsList.add(tag19);
481                 tagsList.add(tag20);
482                 tagsList.add(tag21);
483                 tagsList.add(serviceExccedsNameLimit.getName());
484
485                 serviceExccedsNameLimit.setTags(tagsList);
486
487                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
488                 assertTrue(createResponse.isRight());
489                 assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
490
491         }
492
493         private void testTagsSingleExcessLimit() {
494                 Service serviceExccedsNameLimit = createServiceObject(false);
495                 String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9a";
496                 String tag2 = serviceExccedsNameLimit.getName();
497                 List<String> tagsList = new ArrayList<String>();
498                 tagsList.add(tag1);
499                 tagsList.add(tag2);
500                 serviceExccedsNameLimit.setTags(tagsList);
501
502                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
503                 assertTrue(createResponse.isRight());
504                 assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH);
505
506         }
507
508         private void testTagsNoServiceName() {
509                 Service serviceExccedsNameLimit = createServiceObject(false);
510                 String tag1 = "afzs2qLBb";
511                 List<String> tagsList = new ArrayList<String>();
512                 tagsList.add(tag1);
513                 serviceExccedsNameLimit.setTags(tagsList);
514
515                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
516                 assertTrue(createResponse.isRight());
517                 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
518
519         }
520
521         private void testInvalidTag() {
522                 Service serviceExccedsNameLimit = createServiceObject(false);
523                 String tag1 = "afzs2qLBb%#%";
524                 List<String> tagsList = new ArrayList<String>();
525                 tagsList.add(tag1);
526                 serviceExccedsNameLimit.setTags(tagsList);
527
528                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
529                 assertTrue(createResponse.isRight());
530                 assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" });
531
532         }
533
534         private void testServiceTagNotExist() {
535                 Service serviceExist = createServiceObject(false);
536                 serviceExist.setTags(null);
537
538                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
539                 assertTrue(createResponse.isRight());
540
541                 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
542         }
543
544         private void testServiceTagEmpty() {
545                 Service serviceExist = createServiceObject(false);
546                 serviceExist.setTags(new ArrayList<String>());
547
548                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
549                 assertTrue(createResponse.isRight());
550
551                 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
552         }
553
554         // Service tags - stop
555         // Service contactId - start
556         private void testContactIdTooLong() {
557                 Service serviceContactId = createServiceObject(false);
558                 // 59 chars instead of 50
559                 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
560                 serviceContactId.setContactId(contactIdTooLong);
561
562                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
563                 assertTrue(createResponse.isRight());
564                 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
565         }
566
567         private void testContactIdWrongFormatCreate() {
568                 Service serviceContactId = createServiceObject(false);
569                 // 3 letters and 3 digits and special characters
570                 String contactIdTooLong = "yrt134!!!";
571                 serviceContactId.setContactId(contactIdTooLong);
572
573                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
574                 assertTrue(createResponse.isRight());
575                 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
576         }
577
578         private void testResourceContactIdMissing() {
579                 Service resourceExist = createServiceObject(false);
580                 resourceExist.setContactId(null);
581
582                 Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
583                 assertTrue(createResponse.isRight());
584                 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
585         }
586
587         // Service contactId - stop
588         // Service category - start
589         private void testServiceCategoryExist() {
590                 Service serviceExist = createServiceObject(false);
591                 serviceExist.setCategories(null);
592
593                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
594                 assertTrue(createResponse.isRight());
595
596                 assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
597         }
598
599         public void markDistributionAsDeployedTestAlreadyDeployed() {
600                 String notifyAction = "DNotify";
601                 String requestAction = "DRequest";
602                 String resultAction = "DResult";
603                 String did = "123456";
604
605                 setupBeforeDeploy(notifyAction, requestAction, did);
606                 List<DistributionDeployEvent> resultList = new ArrayList<DistributionDeployEvent>();
607                 Map<String, Object> params = new HashMap<String, Object>();
608                 DistributionDeployEvent event = new DistributionDeployEvent();
609
610                 event.setAction(resultAction);
611                 event.setDid(did);
612                 event.setStatus("200");
613                 // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
614                 // deployEvent.setFields(params);
615                 resultList.add(event);
616                 Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
617
618                 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
619
620                 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
621                 assertTrue(markDeployed.isLeft());
622
623                 Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
624
625         }
626
627         @Test
628         public void markDistributionAsDeployedTestSuccess() {
629                 String notifyAction = "DNotify";
630                 String requestAction = "DRequest";
631                 String did = "123456";
632
633                 setupBeforeDeploy(notifyAction, requestAction, did);
634
635                 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
636                 assertTrue(markDeployed.isLeft());
637
638         }
639
640         @Test
641         public void markDistributionAsDeployedTestNotDistributed() {
642                 String notifyAction = "DNotify";
643                 String requestAction = "DRequest";
644                 String did = "123456";
645
646                 setupBeforeDeploy(notifyAction, requestAction, did);
647                 List<ResourceAdminEvent> emptyList = new ArrayList<ResourceAdminEvent>();
648                 Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
649                 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
650
651                 Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
652                 Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
653
654                 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
655                 assertTrue(markDeployed.isRight());
656                 assertEquals(404, markDeployed.right().value().getStatus().intValue());
657
658         }
659
660         private void testServiceBadCategoryCreate() {
661
662                 Service serviceExist = createServiceObject(false);
663                 CategoryDefinition category = new CategoryDefinition();
664                 category.setName("koko");
665                 List<CategoryDefinition> categories = new ArrayList<>();
666                 categories.add(category);
667                 serviceExist.setCategories(categories);
668
669                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
670                 assertTrue(createResponse.isRight());
671
672                 assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
673         }
674
675         // Service category - stop
676         // Service projectCode - start
677         private void testInvalidProjectCode() {
678
679                 Service serviceExist = createServiceObject(false);
680                 serviceExist.setProjectCode("koko!!");
681
682                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
683                 assertTrue(createResponse.isRight());
684
685                 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
686         }
687
688         private void testProjectCodeTooLong() {
689
690                 Service serviceExist = createServiceObject(false);
691                 String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode"; 
692                 serviceExist.setProjectCode(tooLongProjectCode);
693
694                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
695                 assertTrue(createResponse.isRight());
696
697                 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
698         }
699
700         private void testProjectCodeTooShort() {
701
702                 Service serviceExist = createServiceObject(false);
703                 serviceExist.setProjectCode("333");
704
705                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
706                 assertTrue(createResponse.isRight());
707
708                 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
709         }
710
711         private void testMissingProjectCode() {
712
713                 Service serviceExist = createServiceObject(false);
714                 serviceExist.setProjectCode(null);
715
716                 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
717                 assertTrue(createResponse.isRight());
718
719                 assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE);
720         }
721
722 //      @Test
723 //      public void testDeleteMarkedServicesNoServices() {
724 //              List<String> ids = new ArrayList<String>();
725 //              Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
726 //              when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources);
727 //
728 //              Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
729 //              assertTrue(deleteMarkedResources.isLeft());
730 //              assertTrue(deleteMarkedResources.left().value().isEmpty());
731 //
732 //              Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList());
733 //
734 //      }
735
736         @Test
737         @Ignore
738         public void testDeleteMarkedServices() {
739                 List<String> ids = new ArrayList<String>();
740                 String resourceInUse = "123";
741                 ids.add(resourceInUse);
742                 String resourceFree = "456";
743                 ids.add(resourceFree);
744                 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
745                 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
746
747                 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
748                 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
749
750                 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
751                 Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
752 //              when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse);
753
754                 when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
755                 when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
756
757                 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
758                 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
759
760                 when(artifactBl.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK);
761
762                 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
763                 assertTrue(deleteMarkedResources.isLeft());
764                 List<String> resourceIdList = deleteMarkedResources.left().value();
765                 assertFalse(resourceIdList.isEmpty());
766                 assertTrue(resourceIdList.contains(resourceFree));
767                 assertFalse(resourceIdList.contains(resourceInUse));
768
769                 Mockito.verify(artifactBl, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts);
770         }
771
772         private Service createServiceObject(boolean afterCreate) {
773                 Service service = new Service();
774                 service.setName("Service");
775                 CategoryDefinition category = new CategoryDefinition();
776                 category.setName(SERVICE_CATEGORY);
777                 List<CategoryDefinition> categories = new ArrayList<>();
778                 categories.add(category);
779                 service.setCategories(categories);
780
781                 service.setDescription("description");
782                 List<String> tgs = new ArrayList<String>();
783                 tgs.add(service.getName());
784                 service.setTags(tgs);
785                 // service.setVendorName("Motorola");
786                 // service.setVendorRelease("1.0.0");
787                 service.setIcon("MyIcon");
788                 // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
789                 service.setContactId("aa1234");
790                 service.setProjectCode("12345");
791
792                 if (afterCreate) {
793                         service.setVersion("0.1");
794                         service.setUniqueId(service.getName() + ":" + service.getVersion());
795                         service.setCreatorUserId(user.getUserId());
796                         service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
797                 }
798                 return service;
799         }
800
801         private void mockAuditingDaoLogic() {
802                 FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
803                 FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
804                 FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
805
806                 FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION);
807                 FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION);
808
809                 final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
810                 createResourceAudit.setModifier("Carlos Santana(cs0008)");
811                 createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
812                 createResourceAudit.setCurrVersion("0.1");
813                 createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
814                 createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f");
815                 createResourceAudit.setDesc("OK");
816                 createResourceAudit.setResourceType("Resource");
817                 createResourceAudit.setStatus("201");
818                 createResourceAudit.setPrevVersion("");
819                 createResourceAudit.setAction("Create");
820                 // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977");
821                 createResourceAudit.setPrevState("");
822                 createResourceAudit.setResourceName("MyTestResource");
823                 // createResourceAudit.setFields(fields);
824
825                 final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent();
826                 checkInResourceAudit.setModifier("Carlos Santana(cs0008)");
827                 checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN");
828                 checkInResourceAudit.setCurrVersion("0.1");
829                 checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
830                 checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091");
831                 checkInResourceAudit.setDesc("OK");
832                 checkInResourceAudit.setComment("Stam");
833                 checkInResourceAudit.setResourceType("Resource");
834                 checkInResourceAudit.setStatus("200");
835                 checkInResourceAudit.setPrevVersion("0.1");
836                 checkInResourceAudit.setAction("Checkin");
837                 // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797");
838                 checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT");
839                 checkInResourceAudit.setResourceName("MyTestResource");
840
841                 final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent();
842                 checkOutResourceAudit.setModifier("Carlos Santana(cs0008)");
843                 checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
844                 checkOutResourceAudit.setCurrVersion("0.2");
845                 checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
846                 checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8");
847                 checkOutResourceAudit.setDesc("OK");
848                 checkOutResourceAudit.setComment("");
849                 checkOutResourceAudit.setResourceType("Resource");
850                 checkOutResourceAudit.setStatus("200");
851                 checkOutResourceAudit.setPrevVersion("0.1");
852                 checkOutResourceAudit.setAction("Checkout");
853                 // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024");
854                 checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN");
855                 checkOutResourceAudit.setResourceName("MyTestResource");
856                 // checkOutResourceAudit.setFields(fields);
857
858                 // Mockito.doAnswer(new Answer<Either<List<ESTimeBasedEvent>,
859                 // ActionStatus> >() {
860                 // public Either<List<ESTimeBasedEvent>, ActionStatus>
861                 // answer(InvocationOnMock invocation) {
862                 // final Either<List<ESTimeBasedEvent>, ActionStatus> either;
863                 // final List<ESTimeBasedEvent> list;
864                 // Object[] args = invocation.getArguments();
865                 // Map<AuditingFieldsKeysEnum, Object> filterMap =
866                 // (Map<AuditingFieldsKeysEnum, Object>) args[0];
867                 // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){
868                 // list = new
869                 // ArrayList<ESTimeBasedEvent>(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}};
870                 // either = Either.left(list);
871                 //
872                 // }
873                 // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){
874                 // list = new ArrayList<ESTimeBasedEvent>();
875                 // either = Either.left(list);
876                 // }
877                 // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){
878                 // list = new
879                 // ArrayList<ESTimeBasedEvent>(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}};
880                 // either = Either.left(list);
881                 // }
882                 // else{
883                 // either = null;
884                 // }
885                 // return either;
886                 // }
887                 // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap());
888                 //
889                 //
890                 List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() {
891                         {
892                                 add(createResourceAudit);
893                                 add(checkInResourceAudit);
894                                 add(checkOutResourceAudit);
895                         }
896                 };
897                 Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
898                 Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
899
900                 List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>();
901                 Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
902                 Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
903
904                 List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() {
905                         {
906                                 add(checkOutResourceAudit);
907                         }
908                 };
909                 Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr);
910                 Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr);
911
912         }
913
914         private void setupBeforeDeploy(String notifyAction, String requestAction, String did) {
915
916                 DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent();
917                 notifyEvent.setAction(notifyAction);
918                 notifyEvent.setDid(did);
919                 notifyEvent.setStatus("200");
920
921                 ResourceAdminEvent requestEvent = new ResourceAdminEvent();
922                 requestEvent.setAction(requestAction);
923                 requestEvent.setDid(did);
924                 requestEvent.setStatus("200");
925
926                 ArrayList<DistributionNotificationEvent> arrayList = new ArrayList<DistributionNotificationEvent>();
927                 List<DistributionNotificationEvent> notifyResults = arrayList;
928                 notifyResults.add(notifyEvent);
929                 Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults);
930
931                 Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify);
932
933                 List<ResourceAdminEvent> requestResults = new ArrayList<ResourceAdminEvent>();
934                 requestResults.add(requestEvent);
935                 Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults);
936                 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest);
937
938                 Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true));
939                 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
940
941                 List<DistributionDeployEvent> emptyList = new ArrayList<DistributionDeployEvent>();
942                 Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
943                 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList);
944         }
945         
946         @SuppressWarnings({ "unchecked", "rawtypes" })
947         @Test
948         public void testFindGroupInstanceOnRelatedComponentInstance() {
949                 
950                 Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
951                 String methodName = "findGroupInstanceOnRelatedComponentInstance";
952                 Object invalidId = "invalidId";
953                 
954                 Component service = createNewService();
955                 List<ComponentInstance> componentInstances = service.getComponentInstances();
956                 
957                 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
958                 Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
959                 Class[] argClasses = {Component.class, String.class,String.class};
960             try {
961                 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
962                 method.setAccessible(true);
963                 
964                 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
965                 assertTrue(findGroupInstanceRes != null);
966                 assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId()));
967                 assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId()));
968                 
969                         Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
970                         
971                         findGroupInstanceRes =  (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
972                 assertTrue(findGroupInstanceRes != null);
973                 assertTrue(findGroupInstanceRes.isRight());
974                 assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593"));
975                 
976                         Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
977                         
978                         findGroupInstanceRes =  (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
979                 assertTrue(findGroupInstanceRes != null);
980                 assertTrue(findGroupInstanceRes.isRight());
981                 assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653"));
982             }
983             catch (Exception e) {
984                 e.printStackTrace();
985             }
986         }
987
988         private Component createNewService() {
989                 
990                 Service service = new Service();
991                 int listSize = 3;
992                 service.setName("serviceName");
993                 service.setUniqueId("serviceUniqueId");
994                 List<ComponentInstance> componentInstances = new ArrayList<>();
995                 ComponentInstance ci;
996                 for(int i= 0; i<listSize; ++i){
997                         ci = new ComponentInstance();
998                         ci.setName("ciName" + i);
999                         ci.setUniqueId("ciId" + i);
1000                         List<GroupInstance>  groupInstances= new ArrayList<>();
1001                         GroupInstance gi;
1002                         for(int j = 0; j<listSize; ++j){
1003                                 gi = new GroupInstance();
1004                                 gi.setName(ci.getName( )+ "giName" + j);
1005                                 gi.setUniqueId(ci.getName() + "giId" + j);
1006                                 groupInstances.add(gi);
1007                         }
1008                         ci.setGroupInstances(groupInstances);
1009                         componentInstances.add(ci);
1010                 }
1011                 service.setComponentInstances(componentInstances);
1012                 return service;
1013         }
1014         
1015
1016         @Test
1017         public void testDerivedFromGeneric() {
1018                 Service service = createServiceObject(true);
1019                 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
1020                 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
1021                 assertTrue(createResponse.isLeft());
1022                 service = createResponse.left().value();
1023                 assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName()));
1024                 assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion()));
1025         }
1026
1027         
1028         private Resource setupGenericServiceMock(){
1029                 Resource genericService = new Resource();
1030                 genericService.setVersion("1.0");
1031                 genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
1032                 return genericService;
1033         }
1034 }