9c7327531667739b6e326c8b731416e520e73b51
[sdc.git] /
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.onap.sdc.backend.ci.tests.utils.general;
22
23 import com.aventstack.extentreports.Status;
24 import com.google.gson.Gson;
25 import fj.data.Either;
26 import org.apache.commons.codec.binary.Base64;
27 import org.apache.commons.lang3.tuple.Pair;
28 import org.json.JSONException;
29 import org.onap.sdc.backend.ci.tests.datatypes.*;
30 import org.onap.sdc.backend.ci.tests.datatypes.enums.*;
31 import org.onap.sdc.backend.ci.tests.datatypes.http.HttpHeaderEnum;
32 import org.onap.sdc.backend.ci.tests.datatypes.http.HttpRequest;
33 import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse;
34 import org.onap.sdc.backend.ci.tests.execute.lifecycle.LCSbaseTest;
35 import org.onap.sdc.backend.ci.tests.utils.rest.*;
36 import org.onap.sdc.backend.ci.tests.datatypes.enums.*;
37 import org.onap.sdc.backend.ci.tests.utils.rest.*;
38 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
39 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
40 import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
41 import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
42 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
43 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
44 import org.openecomp.sdc.be.model.*;
45 import org.onap.sdc.backend.ci.tests.api.ComponentBaseTest;
46 import org.onap.sdc.backend.ci.tests.api.ExtentTestActions;
47 import org.onap.sdc.backend.ci.tests.api.Urls;
48 import org.onap.sdc.backend.ci.tests.config.Config;
49 import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaDefinition;
50 import org.onap.sdc.backend.ci.tests.utils.CsarToscaTester;
51 import org.onap.sdc.backend.ci.tests.utils.DistributionUtils;
52 import org.onap.sdc.backend.ci.tests.utils.ToscaParserUtils;
53 import org.onap.sdc.backend.ci.tests.utils.Utils;
54 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
55 import org.openecomp.sdc.common.util.GeneralUtility;
56 import org.testng.SkipException;
57
58 import java.io.File;
59 import java.io.IOException;
60 import java.nio.file.Files;
61 import java.nio.file.Path;
62 import java.nio.file.Paths;
63 import java.util.ArrayList;
64 import java.util.HashMap;
65 import java.util.List;
66 import java.util.Map;
67 import java.util.Map.Entry;
68 import java.util.concurrent.TimeUnit;
69 import java.util.stream.Collectors;
70
71 import static org.junit.Assert.assertFalse;
72 import static org.testng.AssertJUnit.assertEquals;
73 import static org.testng.AssertJUnit.assertTrue;
74
75 public final class AtomicOperationUtils {
76
77         static final String basicAuthentication = "Basic Y2k6MTIzNDU2";
78
79         private AtomicOperationUtils() {
80                 throw new UnsupportedOperationException();
81         }
82
83         // *********** RESOURCE ****************
84         /**
85          * Import a vfc From tosca file
86          *
87          * @param filePath
88          * @param fileName
89          * @return
90          * @throws IOException
91          * @throws JSONException
92          */
93         public static Either<Resource, RestResponse> importResource(String filePath, String fileName) {
94                 try {
95                         User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
96                         ImportReqDetails importReqDetails = ElementFactory.getDefaultImportResource(ElementFactory.getResourcePrefix());
97                         importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, filePath, fileName);
98                         RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, designer, null);
99                         return buildResourceFromResponse(importResourceResponse);
100                 } catch (Exception e) {
101                         throw new AtomicOperationException(e);
102                 }
103         }
104
105         public static Either<Resource, RestResponse> importResource(ImportReqDetails importReqDetails, String filePath, String fileName, User userRole, Boolean validateState) {
106                 try {
107                         importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, filePath, fileName);
108                         RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, userRole, null);
109
110                         if (validateState) {
111                                 assertTrue("Import resource failed with error: " + importResourceResponse.getResponse(),importResourceResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
112                         }
113
114                         if (importResourceResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
115                                 Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
116                                 return Either.left(resourceResponseObject);
117                         }
118                         return Either.right(importResourceResponse);
119                 } catch (Exception e) {
120                         throw new AtomicOperationException(e);
121                 }
122         }
123
124
125         public static Either<Resource, RestResponse> createResourceByType(ResourceTypeEnum resourceType, UserRoleEnum userRole, Boolean validateState) {
126                 try {
127                         User defaultUser = ElementFactory.getDefaultUser(userRole);
128                         ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByType(resourceType, defaultUser);
129                         RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
130
131                         if (validateState) {
132                                 assertTrue("Create resource failed with error: " + resourceResp.getResponse(),resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
133                         }
134
135                         if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
136                                 Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
137                                 return Either.left(resourceResponseObject);
138                         }
139                         return Either.right(resourceResp);
140                 } catch (Exception e) {
141                         throw new AtomicOperationException(e);
142                 }
143         }
144
145         public static Either<Resource, RestResponse> createResourceByResourceDetails(ResourceReqDetails resourceDetails, UserRoleEnum userRole, Boolean validateState) {
146                 try {
147                         User defaultUser = ElementFactory.getDefaultUser(userRole);
148                         RestResponse resourceResp = ResourceRestUtils.createResource(resourceDetails, defaultUser);
149
150                         if (validateState) {
151                                 assertTrue("Create resource failed with error: " + resourceResp.getResponse(),resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
152                         }
153
154                         if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
155                                 Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
156                                 return Either.left(resourceResponseObject);
157                         }
158                         return Either.right(resourceResp);
159                 } catch (Exception e) {
160                         throw new AtomicOperationException(e);
161                 }
162         }
163
164         public static Either<Resource, RestResponse> createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, NormativeTypesEnum normativeTypes, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState)
165                         throws Exception {
166                 User defaultUser = ElementFactory.getDefaultUser(userRole);
167                 ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(resourceType, normativeTypes, resourceCategory, defaultUser);
168                 RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
169
170                 if (validateState) {
171                         assertTrue("Actual Response Code is: " + resourceResp.getErrorCode(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
172                 }
173
174                 if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
175                         // Resource resourceResponseObject = ResponseParser
176                         // .convertResourceResponseToJavaObject(resourceResp.getResponse());
177                         Resource resourceResponseObject = ResponseParser.parseToObjectUsingMapper(resourceResp.getResponse(), Resource.class);
178                         return Either.left(resourceResponseObject);
179                 }
180                 return Either.right(resourceResp);
181         }
182
183         public static Either<Resource, RestResponse> createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum resourceType, Resource resourceNormativeType, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState)
184                         throws Exception {
185                 User defaultUser = ElementFactory.getDefaultUser(userRole);
186                 ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(resourceType, resourceNormativeType, resourceCategory, defaultUser);
187                 RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
188
189                 if (validateState) {
190                         assertTrue("Create resource failed with error: " + resourceResp.getResponse(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
191                 }
192
193                 if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
194                         // Resource resourceResponseObject = ResponseParser
195                         // .convertResourceResponseToJavaObject(resourceResp.getResponse());
196                         Resource resourceResponseObject = ResponseParser.parseToObjectUsingMapper(resourceResp.getResponse(), Resource.class);
197                         return Either.left(resourceResponseObject);
198                 }
199                 return Either.right(resourceResp);
200         }
201
202         public static Either<Resource, RestResponse> updateResource(ResourceReqDetails resourceReqDetails, User defaultUser, Boolean validateState) {
203                 try {
204
205                         RestResponse resourceResp = ResourceRestUtils.updateResource(resourceReqDetails, defaultUser, resourceReqDetails.getUniqueId());
206
207                         if (validateState) {
208                                 assertTrue("Update resource failed with error: " + resourceResp.getResponse(),resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS);
209                         }
210
211                         if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS) {
212                                 Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
213                                 return Either.left(resourceResponseObject);
214                         }
215                         return Either.right(resourceResp);
216                 } catch (Exception e) {
217                         throw new AtomicOperationException(e);
218                 }
219         }
220
221         // *********** SERVICE ****************
222
223         public static Either<Service, RestResponse> createDefaultService(UserRoleEnum userRole, Boolean validateState) throws Exception {
224                 User defaultUser = ElementFactory.getDefaultUser(userRole);
225                 ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(defaultUser);
226                 RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
227
228                 if (validateState) {
229                         assertTrue("Create service failed with error: " + createServiceResp.getResponse(),createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
230                 }
231
232                 if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
233                         Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse());
234                         return Either.left(serviceResponseObject);
235                 }
236                 return Either.right(createServiceResp);
237         }
238
239         public static Either<Service, RestResponse> createServiceByCategory(ServiceCategoriesEnum category, UserRoleEnum userRole, Boolean validateState) throws Exception {
240                 User defaultUser = ElementFactory.getDefaultUser(userRole);
241                 ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(category, defaultUser);
242                 RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
243
244                 if (validateState) {
245                         assertTrue("Create service failed with error: " + createServiceResp.getResponse(),createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
246                 }
247
248                 if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
249                         Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse());
250                         return Either.left(serviceResponseObject);
251                 }
252                 return Either.right(createServiceResp);
253         }
254
255         public static Either<Service, RestResponse> createCustomService(ServiceReqDetails serviceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
256                 User defaultUser = ElementFactory.getDefaultUser(userRole);
257                 RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
258
259                 if (validateState) {
260                         assertTrue("Create service failed with error: " + createServiceResp.getResponse(),createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
261                 }
262
263                 if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
264                         Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse());
265                         return Either.left(serviceResponseObject);
266                 }
267                 return Either.right(createServiceResp);
268         }
269         // *********** PRODUCT ****************
270
271         public static Either<Product, RestResponse> createDefaultProduct(UserRoleEnum userRole, Boolean validateState) throws Exception {
272                 User defaultUser = ElementFactory.getDefaultUser(userRole);
273                 ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct();
274                 RestResponse createProductResp = ProductRestUtils.createProduct(defaultProduct, defaultUser);
275
276                 if (validateState) {
277                         assertTrue(createProductResp.getErrorCode() == ProductRestUtils.STATUS_CODE_CREATED);
278                 }
279
280                 if (createProductResp.getErrorCode() == ProductRestUtils.STATUS_CODE_CREATED) {
281                         Product productResponseJavaObject = ResponseParser.convertProductResponseToJavaObject(createProductResp.getResponse());
282                         return Either.left(productResponseJavaObject);
283                 }
284                 return Either.right(createProductResp);
285         }
286
287         // public static ComponentReqDetails
288         // convertCompoentToComponentReqDetails(Component component){
289         //
290         // ComponentReqDetails componentReqDetails =
291         // ElementFactory.getDefaultService();
292         // componentReqDetails.setName(component.getName());
293         // componentReqDetails.setDescription(component.getDescription());
294         // componentReqDetails.setTags(component.getTags());
295         // componentReqDetails.setContactId(component.getContactId());
296         // componentReqDetails.setIcon(component.getIcon());
297         // componentReqDetails.setUniqueId(component.getUniqueId());
298         // componentReqDetails.setCreatorUserId(component.getCreatorUserId());
299         // componentReqDetails.setCreatorFullName(component.getCreatorFullName());
300         // componentReqDetails.setLastUpdaterUserId(component.getLastUpdaterUserId());
301         // componentReqDetails.setLastUpdaterFullName(component.getLastUpdaterFullName());
302         // componentReqDetails.setCreationDate(component.getCreationDate());
303         // componentReqDetails.setLastUpdateDate(component.getLastUpdateDate());
304         // componentReqDetails.setLifecycleState(component.getLifecycleState());
305         // componentReqDetails.setVersion(component.getVersion());
306         // componentReqDetails.setUuid(component.getUUID());
307         // componentReqDetails.setCategories(component.getCategories());
308         // componentReqDetails.setProjectCode(component.getProjectCode());
309         //
310         // return componentReqDetails;
311         // }
312
313         // *********** LIFECYCLE ***************
314
315     public static Pair<Component, RestResponse> changeComponentState(Component component, UserRoleEnum userRole, LifeCycleStatesEnum targetState, Boolean validateState) throws Exception {
316
317         Boolean isValidationFailed = false;
318         RestResponse lifeCycleStatesResponse = null;
319         User defaultUser;
320
321         LifeCycleStatesEnum currentCompState = LifeCycleStatesEnum.findByCompState(component.getLifecycleState().toString());
322
323                 if (currentCompState == targetState) {
324                         component = getComponentObject(component, userRole);
325                         return Pair.of(component, null);
326                 }
327                 String componentType = component.getComponentType().getValue();
328                 ArrayList<String> lifeCycleStatesEnumList = new ArrayList<>();
329                 if (currentCompState.equals(LifeCycleStatesEnum.CHECKIN) && targetState.equals(LifeCycleStatesEnum.CHECKOUT)) {
330                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString());
331                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString());
332                 } else {
333                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString());
334                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString());
335                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFY.toString());
336                 }
337                 for (int i = 0; i < lifeCycleStatesEnumList.size(); i++) {
338                         if (lifeCycleStatesEnumList.get(i).equals(currentCompState.name())) {
339                                 int a;
340                                 a = (i == lifeCycleStatesEnumList.size() - 1) ? 0 : i + 1;
341                                 for (int n = a; n < lifeCycleStatesEnumList.size(); n++) {
342                                         defaultUser = ElementFactory.getDefaultUser(userRole);
343                                         lifeCycleStatesResponse = LifecycleRestUtils.changeComponentState(component, defaultUser, LifeCycleStatesEnum.findByState(lifeCycleStatesEnumList.get(n)));
344                                         if (lifeCycleStatesResponse.getErrorCode() != LifecycleRestUtils.STATUS_CODE_SUCCESS)
345                                                 isValidationFailed = true;
346                                         if (lifeCycleStatesEnumList.get(n).equals(targetState.toString()) || isValidationFailed) {
347                                                 break;
348                                         }
349                                 }
350                         }
351                 }
352                 Component componentJavaObject = getComponentObject(component, userRole);
353
354                 if (validateState && isValidationFailed) {
355                         assertTrue("change state to [" + targetState.getState() + "] failed" + lifeCycleStatesResponse.getResponse(), false);
356                         return Pair.of(componentJavaObject, lifeCycleStatesResponse);
357                 }
358
359                 if (isValidationFailed) {
360                         return Pair.of(componentJavaObject, lifeCycleStatesResponse);
361                 }
362
363                 return Pair.of(componentJavaObject, lifeCycleStatesResponse);
364         }
365
366         public static RestResponse distributeService(Component component, Boolean validateState) throws Exception {
367
368                 Service service = (Service) component;
369
370                 User opsUser = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
371                 User governotUser = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
372
373                 ServiceReqDetails serviceDetails = new ServiceReqDetails(service);
374                 RestResponse distributionService = null;
375
376                 RestResponse approveDistribution = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, governotUser, "approveService", DistributionStatusEnum.DISTRIBUTED);
377                 if (approveDistribution.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
378                         distributionService = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, opsUser, "approveService", DistributionStatusEnum.DISTRIBUTED);
379                 }
380
381                 if (validateState) {
382                         assertTrue("Distribution approve failed with error: " + approveDistribution.getResponse(),approveDistribution.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
383                         assertTrue("Distribute service failed with error: " + distributionService.getResponse(),distributionService.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
384                         return distributionService;
385                 }
386
387                 return distributionService;
388         }
389
390         public static void toscaValidation(Component component, String vnfFile) throws Exception {
391
392                 ISdcCsarHelper fdntCsarHelper;
393                 SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();
394                 File csarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.SERVICES, component.getUUID() , vnfFile);
395                 ExtentTestActions.log(Status.INFO, "Tosca parser is going to convert service csar file to ISdcCsarHelper object...");
396                 fdntCsarHelper = factory.getSdcCsarHelper(csarFile.getAbsolutePath());
397                 CsarToscaTester.processCsar(fdntCsarHelper);
398                 ExtentTestActions.log(Status.INFO, String.format("Tosca parser successfully parsed service CSAR"));
399
400         }
401
402         // *********** ARTIFACTS *****************
403
404         public static Either<ArtifactDefinition, RestResponse> uploadArtifactByType(ArtifactTypeEnum artifactType, Component component, UserRoleEnum userRole, Boolean deploymentTrue, Boolean validateState) throws Exception {
405
406                 User defaultUser = ElementFactory.getDefaultUser(userRole);
407                 ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(null, artifactType, deploymentTrue);
408                 if (!deploymentTrue)
409                         artifactDetails.setArtifactGroupType(ArtifactGroupTypeEnum.INFORMATIONAL.getType());
410                 RestResponse uploadArtifactResp = ArtifactRestUtils.uploadArtifact(artifactDetails, component, defaultUser);
411
412                 if (validateState) {
413                         assertTrue("artifact upload failed: " + artifactDetails.getArtifactName(), uploadArtifactResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
414                 }
415
416                 if (uploadArtifactResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
417                         ArtifactDefinition artifactJavaObject = ResponseParser.convertArtifactDefinitionResponseToJavaObject(uploadArtifactResp.getResponse());
418                         return Either.left(artifactJavaObject);
419                 }
420                 return Either.right(uploadArtifactResp);
421         }
422
423         // *********** CONTAINERS *****************
424         /**
425          * Adds Component instance to Component
426          *
427          * @param compInstParent
428          * @param compContainer
429          * @return
430          */
431         public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer) {
432                 return addComponentInstanceToComponentContainer(compInstParent, compContainer, UserRoleEnum.DESIGNER, false);
433         }
434
435     public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent,
436                                                                                                    Component compContainer,
437                                                                                                    UserRoleEnum userRole,
438                                                                                                    Boolean validateState) {
439         try {
440             User defaultUser = ElementFactory.getDefaultUser(userRole);
441             ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(compInstParent);
442             if (componentInstanceDetails.getOriginType() == null){
443                 componentInstanceDetails.setOriginType(((Resource) compInstParent).getResourceType().toString());
444             }
445             RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails,
446                     defaultUser, compContainer);
447
448             if (validateState) {
449                 if (createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_NOT_FOUND) {
450                     throw new SkipException("Open bug DE262001");
451                 } else {
452                     assertTrue("error - " + createComponentInstance.getErrorCode() + "instead - " +
453                             ServiceRestUtils.STATUS_CODE_CREATED,
454                             createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
455                 }
456             }
457
458             if (createComponentInstance.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
459                 ComponentInstance componentInstance = ResponseParser
460                         .convertComponentInstanceResponseToJavaObject(createComponentInstance.getResponse());
461                 return Either.left(componentInstance);
462             }
463             return Either.right(createComponentInstance);
464         } catch (Exception e) {
465             throw new AtomicOperationException(e);
466         }
467     }
468
469         public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer, UserRoleEnum userRole, Boolean validateState, String positionX, String positionY) {
470                 try {
471                         User defaultUser = ElementFactory.getDefaultUser(userRole);
472                         ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(compInstParent);
473                         componentInstanceDetails.setPosX(positionX);
474                         componentInstanceDetails.setPosY(positionY);
475                         if (componentInstanceDetails.getOriginType() == null){
476                                 componentInstanceDetails.setOriginType(((Resource) compInstParent).getResourceType().toString());
477                         }
478                         RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, defaultUser, compContainer);
479
480                         if (validateState) {
481                                 if (createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_NOT_FOUND)
482                                 {
483                                         throw new SkipException("Open bug DE262001");
484                                 }
485                                 else{
486                                         assertTrue("error - " + createComponentInstance.getErrorCode() + "instead - " + ServiceRestUtils.STATUS_CODE_CREATED, createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
487                                 }
488                         }
489
490                         if (createComponentInstance.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
491                                 ComponentInstance componentInstance = ResponseParser.convertComponentInstanceResponseToJavaObject(createComponentInstance.getResponse());
492                                 return Either.left(componentInstance);
493                         }
494                         return Either.right(createComponentInstance);
495                 } catch (Exception e) {
496                         throw new AtomicOperationException(e);
497                 }
498         }
499
500         public static Resource getResourceObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
501                 // User defaultUser = ElementFactory.getDefaultUser(userRole);
502                 RestResponse restResponse = ResourceRestUtils.getResource(containerDetails.getUniqueId());
503                 return ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
504         }
505
506         public static Resource getResourceObject(String uniqueId) throws Exception {
507                 RestResponse restResponse = ResourceRestUtils.getResource(uniqueId);
508                 return ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
509         }
510
511         public static Resource getResourceObjectByNameAndVersion(UserRoleEnum sdncModifierDetails, String resourceName, String resourceVersion) throws Exception {
512                 User defaultUser = ElementFactory.getDefaultUser(sdncModifierDetails);
513                 RestResponse resourceResponse = ResourceRestUtils.getResourceByNameAndVersion(defaultUser.getUserId(), resourceName, resourceVersion);
514                 return ResponseParser.convertResourceResponseToJavaObject(resourceResponse.getResponse());
515         }
516
517         public static Service getServiceObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
518                 User defaultUser = ElementFactory.getDefaultUser(userRole);
519                 RestResponse serviceResponse = ServiceRestUtils.getService(containerDetails.getUniqueId(), defaultUser);
520                 return ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
521         }
522
523         public static Service getServiceObjectByNameAndVersion(UserRoleEnum sdncModifierDetails, String serviceName, String serviceVersion) throws Exception {
524                 User defaultUser = ElementFactory.getDefaultUser(sdncModifierDetails);
525                 RestResponse serviceResponse = ServiceRestUtils.getServiceByNameAndVersion(defaultUser, serviceName, serviceVersion);
526                 return ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
527         }
528
529         public static Service getServiceObject(String uniqueId) throws Exception {
530                 RestResponse serviceResponse = ServiceRestUtils.getService(uniqueId);
531                 return ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
532         }
533
534         public static Product getProductObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
535                 User defaultUser = ElementFactory.getDefaultUser(userRole);
536                 RestResponse productRest = ProductRestUtils.getProduct(containerDetails.getUniqueId(), defaultUser.getUserId());
537                 return ResponseParser.convertProductResponseToJavaObject(productRest.getResponse());
538         }
539
540         public static Component getComponentObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
541                 User defaultUser = ElementFactory.getDefaultUser(userRole);
542
543                 switch (containerDetails.getComponentType()) {
544                         case RESOURCE:
545                                 RestResponse restResponse = ResourceRestUtils.getResource(containerDetails.getUniqueId());
546                                 containerDetails = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
547                                 break;
548                         case SERVICE:
549                                 RestResponse serviceResponse = ServiceRestUtils.getService(containerDetails.getUniqueId(), defaultUser);
550                                 containerDetails = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
551                                 break;
552                         case PRODUCT:
553                                 RestResponse productRest = ProductRestUtils.getProduct(containerDetails.getUniqueId(), defaultUser.getUserId());
554                                 containerDetails = ResponseParser.convertProductResponseToJavaObject(productRest.getResponse());
555                                 break;
556                         default:
557                                 break;
558                 }
559                 return containerDetails;
560         }
561
562         public static Component convertReposnseToComponentObject(Component containerDetails, RestResponse restresponse) {
563
564                 switch (containerDetails.getComponentType()) {
565                         case RESOURCE:
566                                 containerDetails = ResponseParser.convertResourceResponseToJavaObject(restresponse.getResponse());
567                                 break;
568                         case SERVICE:
569                                 containerDetails = ResponseParser.convertServiceResponseToJavaObject(restresponse.getResponse());
570                                 break;
571                         case PRODUCT:
572                                 containerDetails = ResponseParser.convertProductResponseToJavaObject(restresponse.getResponse());
573                                 break;
574                         default:
575                                 break;
576                 }
577                 return containerDetails;
578         }
579
580         public static Either<Component, RestResponse> associate2ResourceInstances(Component containerDetails, ComponentInstance fromNode, ComponentInstance toNode, String assocType, UserRoleEnum userRole, Boolean validateState) throws Exception {
581
582                 User defaultUser = ElementFactory.getDefaultUser(userRole);
583                 RestResponse associate2ResourceInstancesResponse = ResourceRestUtils.associate2ResourceInstances(containerDetails, fromNode, toNode, assocType, defaultUser);
584
585                 if (validateState) {
586                         assertTrue(associate2ResourceInstancesResponse.getErrorCode() == ServiceRestUtils.STATUS_CODE_SUCCESS);
587                 }
588
589                 if (associate2ResourceInstancesResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS) {
590
591                         switch (containerDetails.getComponentType()) {
592                                 case RESOURCE:
593                                         containerDetails = ResponseParser.convertResourceResponseToJavaObject(associate2ResourceInstancesResponse.getResponse());
594                                         break;
595                                 case SERVICE:
596                                         containerDetails = ResponseParser.convertServiceResponseToJavaObject(associate2ResourceInstancesResponse.getResponse());
597                                         break;
598                                 case PRODUCT:
599                                         containerDetails = ResponseParser.convertProductResponseToJavaObject(associate2ResourceInstancesResponse.getResponse());
600                                         break;
601                                 default:
602                                         break;
603                         }
604
605                         return Either.left(containerDetails);
606                 }
607                 return Either.right(associate2ResourceInstancesResponse);
608
609         }
610
611         public static Either<Pair<Component, ComponentInstance>, RestResponse> updateComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails, User sdncModifierDetails, Component container, boolean validateState) throws Exception {
612
613                 RestResponse updateComponentInstance = ComponentInstanceRestUtils.updateComponentInstance(componentInstanceReqDetails, sdncModifierDetails, container.getUniqueId(), container.getComponentType());
614                 if (validateState) {
615                         assertTrue("Update ComponentInstance failed: " + updateComponentInstance.getResponseMessage(), updateComponentInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
616                 }
617                 if (updateComponentInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
618                         String componentType = container.getComponentType().getValue();
619                         Component componentObject;
620                         if(componentType.equals("Resource")){
621                                 componentObject = getResourceObject(container.getUniqueId());
622                         }else{
623                                 componentObject = getServiceObject(container.getUniqueId());
624                         }
625                         ComponentInstance componentInstanceJavaObject = ResponseParser.convertComponentInstanceResponseToJavaObject(updateComponentInstance.getResponse());
626                         return Either.left(Pair.of(componentObject, componentInstanceJavaObject));
627                 }
628                 return Either.right(updateComponentInstance);
629         }
630
631         public static Either<Pair<Component, ComponentInstance>, RestResponse> changeComponentInstanceVersion(Component containerDetails, ComponentInstance componentInstanceToReplace, Component newInstance, UserRoleEnum userRole, Boolean validateState)
632                         throws Exception {
633                 User defaultUser = ElementFactory.getDefaultUser(userRole);
634
635                 RestResponse changeComponentInstanceVersionResp = ComponentInstanceRestUtils.changeComponentInstanceVersion(containerDetails, componentInstanceToReplace, newInstance, defaultUser);
636                 if (validateState) {
637                         assertTrue("change ComponentInstance version failed: " + changeComponentInstanceVersionResp.getResponseMessage(), changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
638                 }
639
640                 if (changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
641
642                         Component compoenntObject = AtomicOperationUtils.getComponentObject(containerDetails, userRole);
643                         ComponentInstance componentInstanceJavaObject = ResponseParser.convertComponentInstanceResponseToJavaObject(changeComponentInstanceVersionResp.getResponse());
644
645                         return Either.left(Pair.of(compoenntObject, componentInstanceJavaObject));
646                 }
647
648                 return Either.right(changeComponentInstanceVersionResp);
649         }
650
651         public static ComponentInstance getComponentInstanceByName(Component component, String name) {
652                 ComponentInstance componentInstance = component.getComponentInstances()
653                                 .stream()
654                                 .filter(ci->ci.getName().equals(name))
655                                 .findFirst()
656                                 .orElse(null);
657                 if (componentInstance == null) {
658                         List<String> componentInstancesNameList = component.getComponentInstances().stream().map(ComponentInstance::getName).collect(Collectors.toList());
659                         assertFalse("Instance name " + name + " not found in container " + component.getComponentType() + " named [" + component.getName()
660                                         + "]. Component instances available are: " + componentInstancesNameList.toString(),  true);
661                 }
662                 return componentInstance;
663         }
664
665         // *********** PROPERTIES *****************
666
667         public static Either<ComponentInstanceProperty, RestResponse> addCustomPropertyToResource(PropertyReqDetails propDetails, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
668
669                 User defaultUser = ElementFactory.getDefaultUser(userRole);
670                 Map<String, PropertyReqDetails> propertyToSend = new HashMap<>();
671                 propertyToSend.put(propDetails.getName(), propDetails);
672                 Gson gson = new Gson();
673                 RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser);
674
675                 if (validateState) {
676                         assertTrue("add property to resource failed: " + addPropertyResponse.getErrorCode(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED);
677                 }
678
679                 if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED) {
680                         ComponentInstanceProperty compInstProp = null;
681                         String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
682                         compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
683                         return Either.left(compInstProp);
684                 }
685                 return Either.right(addPropertyResponse);
686         }
687
688         // Benny
689         public static Either<ComponentInstanceProperty, RestResponse> updatePropertyOfResource(PropertyReqDetails propDetails, Resource resourceDetails, String propertyUniqueId, UserRoleEnum userRole, Boolean validateState) throws Exception {
690
691                 User defaultUser = ElementFactory.getDefaultUser(userRole);
692                 Map<String, PropertyReqDetails> propertyToSend = new HashMap<>();
693                 propertyToSend.put(propDetails.getName(), propDetails);
694                 Gson gson = new Gson();
695                 RestResponse addPropertyResponse = PropertyRestUtils.updateProperty(resourceDetails.getUniqueId(), propertyUniqueId, gson.toJson(propertyToSend), defaultUser);
696
697                 if (validateState) {
698                         assertTrue("add property to resource failed: " + addPropertyResponse.getResponseMessage(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
699                 }
700
701                 if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
702                         ComponentInstanceProperty compInstProp = null;
703                         String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
704                         compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
705                         return Either.left(compInstProp);
706                 }
707                 return Either.right(addPropertyResponse);
708         }
709
710         public static RestResponse deletePropertyOfResource(String resourceId, String propertyId, UserRoleEnum userRole) throws Exception {
711                 User defaultUser = ElementFactory.getDefaultUser(userRole);
712                 return PropertyRestUtils.deleteProperty(resourceId, propertyId, defaultUser);
713         }
714
715         public static Either<ComponentInstanceProperty, RestResponse> addDefaultPropertyToResource(PropertyTypeEnum propertyType, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
716
717                 User defaultUser = ElementFactory.getDefaultUser(userRole);
718                 PropertyReqDetails propDetails = ElementFactory.getPropertyDetails(propertyType);
719                 Map<String, PropertyReqDetails> propertyToSend = new HashMap<>();
720                 propertyToSend.put(propDetails.getName(), propDetails);
721                 Gson gson = new Gson();
722                 RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser);
723
724                 if (validateState) {
725                         assertTrue("add property to resource failed: " + addPropertyResponse.getResponseMessage(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED);
726                 }
727
728                 if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED) {
729                         ComponentInstanceProperty compInstProp = null;
730                         String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
731                         compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
732
733                         return Either.left(compInstProp);
734                 }
735                 return Either.right(addPropertyResponse);
736         }
737
738         public static Either<GroupDefinition, RestResponse> updateGroupPropertyOnResource(String maxVFModuleInstacesValue, Resource resource, String groupId, User user, Boolean validateState) throws Exception {
739
740 //              Gson gson = new Gson();
741         // Json group property object
742         String propertyObjectJson = "[{\"defaultValue\":null,\"description\":\"The maximum instances of this VF-Module\",\"name\":\"max_vf_module_instances\",\"parentUniqueId\":\"org.openecomp.groups.VfModule.1.0.grouptype.max_vf_module_instances\",\"password\":false,\"required\":false,\"schema\":{\"property\":{}},\"type\":\"integer\",\"uniqueId\":\"org.openecomp.groups.VfModule.1.0.grouptype.max_vf_module_instances.property.3\",\"value\":\"" + maxVFModuleInstacesValue + "\",\"definition\":false,\"getInputValues\":null,\"constraints\":null,\"valueUniqueUid\":null,\"ownerId\":\"org.openecomp.groups.VfModule.1.0.grouptype.max_vf_module_instances\"}]";
743 //        GroupProperty property = gson.fromJson(propertyObjectJson, GroupProperty.class);
744                 RestResponse updateGroupPropertyResponse = PropertyRestUtils.updateGroupProperty(resource, groupId, propertyObjectJson, user);
745
746                 if (validateState) {
747                         assertTrue("update group property to resource failed: " + updateGroupPropertyResponse.getResponseMessage(), updateGroupPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
748                 }
749
750                 if (updateGroupPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
751                         GroupDefinition responseGroupDefinition = ResponseParser.convertPropertyResponseToObject(updateGroupPropertyResponse.getResponse());
752                         return Either.left(responseGroupDefinition);
753                 }
754                 return Either.right(updateGroupPropertyResponse);
755         }
756
757
758         public static RestResponse createDefaultConsumer(Boolean validateState) {
759                 try {
760                         ConsumerDataDefinition defaultConsumerDefinition = ElementFactory.getDefaultConsumerDetails();
761                         RestResponse createResponse = ConsumerRestUtils.createConsumer(defaultConsumerDefinition, ElementFactory.getDefaultUser(UserRoleEnum.ADMIN));
762                         BaseRestUtils.checkCreateResponse(createResponse);
763
764                         if (validateState) {
765                                 assertTrue(createResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
766                         }
767                         return createResponse;
768                 } catch (Exception e) {
769                         throw new AtomicOperationException(e);
770                 }
771         }
772
773         /**
774          * Builds Resource From rest response
775          *
776          * @param resourceResp
777          * @return
778          */
779         public static Either<Resource, RestResponse> buildResourceFromResponse(RestResponse resourceResp) {
780                 Either<Resource, RestResponse> result;
781                 if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
782                         Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
783                         result = Either.left(resourceResponseObject);
784                 } else {
785                         result = Either.right(resourceResp);
786                 }
787                 return result;
788         }
789
790         private static class AtomicOperationException extends RuntimeException {
791                 private AtomicOperationException(Exception e) {
792                         super(e);
793                 }
794
795                 private static final long serialVersionUID = 1L;
796         }
797
798         /**
799          * Import resource from CSAR
800          *
801          * @param resourceType
802          * @param userRole
803          * @param fileName
804          * @param filePath
805          * @return Resource
806          * @throws Exception
807          */
808         public static Resource importResourceFromCsar(ResourceTypeEnum resourceType, UserRoleEnum userRole, String fileName, String... filePath) throws Exception {
809                 // Get the CSARs path
810                 String realFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "CI" + File.separator + "csars" ;
811                 if (filePath != null && filePath.length > 0) {
812                         StringBuilder result = new StringBuilder();
813                         for(String currStr: filePath){
814                                 result.append(currStr);
815                         }
816 //                      realFilePath = Arrays.toString(filePath);
817                         realFilePath = result.toString();
818                 }
819
820                 // Create default import resource & user
821                 return importResourceFromCsarFile(resourceType, userRole, fileName, realFilePath);
822         }
823
824         public static Resource importResourceFromCsarFile(ResourceTypeEnum resourceType, UserRoleEnum userRole, String csarFileName, String csarFilePath) throws Exception{
825                 RestResponse createResource = getCreateResourceRestResponse(resourceType, userRole, csarFileName, csarFilePath);
826                 BaseRestUtils.checkCreateResponse(createResource);
827                 return ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
828         }
829
830         public static Resource importCertifiedResourceFromCsar(ResourceTypeEnum resourceType, UserRoleEnum userRole,    String csarFileName, String csarFilePath) throws Exception{
831                 RestResponse createResource = getCreateCertifiedResourceRestResponse(resourceType, userRole, csarFileName, csarFilePath);
832                 BaseRestUtils.checkSuccess(createResource);
833                 return ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
834         }
835         public static RestResponse getCreateResourceRestResponse(ResourceTypeEnum resourceType, UserRoleEnum userRole,
836                                                                                                                          String csarFileName, String csarFilePath) throws IOException, Exception {
837
838                 ImportReqDetails resourceDetails = buildImportReqDetails(resourceType, csarFileName, csarFilePath);
839                 User sdncModifierDetails = ElementFactory.getDefaultUser(userRole);
840                 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
841                 return createResource;
842         }
843
844         public static RestResponse getCreateCertifiedResourceRestResponse(ResourceTypeEnum resourceType, UserRoleEnum userRole,
845                                                                                                                                                    String csarFileName, String csarFilePath) throws IOException, Exception {
846
847                 ImportReqDetails resourceDetails = buildImportReqDetails(resourceType, csarFileName, csarFilePath);
848                 User sdncModifierDetails = ElementFactory.getDefaultUser(userRole);
849                 RestResponse response = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
850                 BaseRestUtils.checkCreateResponse(response);
851                 return LCSbaseTest.certifyResource(resourceDetails, sdncModifierDetails);
852         }
853
854         private static ImportReqDetails buildImportReqDetails(ResourceTypeEnum resourceType, String csarFileName, String csarFilePath) throws IOException {
855                 ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
856                 Path path = Paths.get(csarFilePath + File.separator + csarFileName);
857                 byte[] data = Files.readAllBytes(path);
858                 String payloadName = csarFileName;
859                 String payloadData = Base64.encodeBase64String(data);
860                 resourceDetails.setPayloadData(payloadData);
861                 resourceDetails.setCsarUUID(payloadName);
862                 resourceDetails.setPayloadName(payloadName);
863                 resourceDetails.setResourceType(resourceType.name());
864                 return resourceDetails;
865         }
866
867         public static Resource updateResourceFromCsar(Resource resource, UserRoleEnum userRole, String csarFileName, String csarFilePath) throws Exception{
868                 User sdncModifierDetails = ElementFactory.getDefaultUser(userRole);
869
870                 byte[] data = null;
871                 Path path = Paths.get(csarFilePath + File.separator + csarFileName);
872                 data = Files.readAllBytes(path);
873                 String payloadName = csarFileName;
874                 String payloadData = Base64.encodeBase64String(data);
875                 ImportReqDetails resourceDetails = new ImportReqDetails(resource, payloadName, payloadData);
876                 resourceDetails.setPayloadData(payloadData);
877                 resourceDetails.setCsarUUID(payloadName);
878                 resourceDetails.setPayloadName(payloadName);
879
880                 String userId = sdncModifierDetails.getUserId();
881                 Config config = Utils.getConfig();
882                 String url = String.format(Urls.UPDATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resource.getUniqueId());
883
884                 Map<String, String> headersMap = ResourceRestUtils.prepareHeadersMap(userId);
885
886                 Gson gson = new Gson();
887                 String userBodyJson = gson.toJson(resourceDetails);
888                 String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(userBodyJson);
889                 headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5);
890                 HttpRequest http = new HttpRequest();
891                 RestResponse updateResourceResponse = http.httpSendPut(url, userBodyJson, headersMap);
892                 BaseRestUtils.checkSuccess(updateResourceResponse);
893                 return ResponseParser.parseToObjectUsingMapper(updateResourceResponse.getResponse(), Resource.class);
894         }
895
896         public static Either<Resource, RestResponse> importResourceByFileName(ResourceTypeEnum resourceType, UserRoleEnum userRole, String fileName, Boolean validateState, String... filePath) throws IOException {
897
898                 String realFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "CI" + File.separator + "csars" ;
899                 if (filePath != null && filePath.length > 0) {
900                         realFilePath = filePath.toString();
901                 }
902
903                 try {
904                         User defaultUser = ElementFactory.getDefaultUser(userRole);
905                         ResourceReqDetails defaultResource = ElementFactory.getDefaultResource(defaultUser);
906                         ImportReqDetails defaultImportResource = ElementFactory.getDefaultImportResource(defaultResource);
907                         ImportUtils.getImportResourceDetailsByPathAndName(defaultImportResource, realFilePath, fileName);
908                         RestResponse resourceResp = ResourceRestUtils.createResource(defaultImportResource, defaultUser);
909
910                         if (validateState) {
911                                 assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
912                         }
913
914                         if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
915                                 Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
916                                 return Either.left(resourceResponseObject);
917                         }
918                         return Either.right(resourceResp);
919                 } catch (Exception e) {
920                         throw new AtomicOperationException(e);
921                 }
922         }
923
924         public static Either<String, RestResponse> getComponenetArtifactPayload(Component component, String artifactType) throws Exception {
925
926                 String url;
927                 Config config = Utils.getConfig();
928                 if(component.getComponentType().toString().toUpperCase().equals(ComponentTypeEnum.SERVICE.getValue().toUpperCase())){
929                         url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), component.getToscaArtifacts().get(artifactType).getUniqueId());
930                 }else{
931                         url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), component.getToscaArtifacts().get(artifactType).getUniqueId());
932                 }
933                 String userId = component.getLastUpdaterUserId();
934                 Map<String, String> headersMap = new HashMap<>();
935                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
936                 headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), BaseRestUtils.cacheControlHeader);
937                 headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
938                 headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
939                 if (userId != null) {
940                         headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
941                 }
942                 HttpRequest http = new HttpRequest();
943                 RestResponse response = http.httpSendGet(url, headersMap);
944                 if (response.getErrorCode() != BaseRestUtils.STATUS_CODE_SUCCESS && response.getResponse().getBytes() == null && response.getResponse().getBytes().length == 0) {
945                         return Either.right(response);
946                 }
947                 return Either.left(response.getResponse());
948
949         }
950
951         public static RestResponse getDistributionStatusByDistributionId(String distributionId, Boolean validateState) {
952
953                 try {
954                         User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
955                         RestResponse response = DistributionUtils.getDistributionStatus(defaultUser, distributionId);
956
957                         if (validateState) {
958                                 assertTrue(response.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS);
959                         }
960                         return response;
961
962                 } catch (Exception e) {
963                         throw new AtomicOperationException(e);
964                 }
965         }
966
967         public static Either <RestResponse, Map<String, List<DistributionMonitorObject>>> getSortedDistributionStatusMap(Service service, Boolean validateState) {
968
969                 try {
970                         ServiceDistributionStatus serviceDistributionObject = DistributionUtils.getLatestServiceDistributionObject(service);
971                         RestResponse response = getDistributionStatusByDistributionId(serviceDistributionObject.getDistributionID(), true);
972                         if(validateState) {
973                                 assertTrue(response.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS);
974                         }
975                         if(response.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS){
976                                 Map<String, List<DistributionMonitorObject>> parsedDistributionStatus = DistributionUtils.getSortedDistributionStatus(response);
977                                 return Either.right(parsedDistributionStatus);
978                         }
979                         return Either.left(response);
980                 } catch (Exception e) {
981                         throw new AtomicOperationException(e);
982                 }
983
984         }
985
986
987         /**
988          * @param service
989          * @param pollingCount
990          * @param pollingInterval
991          * Recommended values for service distribution for pollingCount is 4 and for pollingInterval is 15000ms
992          * @throws Exception
993          */
994         public static Boolean distributeAndValidateService(Service service, int pollingCount, int pollingInterval) throws Exception {
995                 int firstPollingInterval = 30000; //this value define first be polling topic time, should change if DC configuration changed
996                 Boolean statusFlag = true;
997                 AtomicOperationUtils.distributeService(service,  true);
998                 TimeUnit.MILLISECONDS.sleep(firstPollingInterval);
999                 int timeOut = pollingCount * pollingInterval;
1000                 com.clearspring.analytics.util.Pair<Boolean,Map<String,List<String>>> verifyDistributionStatus = null;
1001
1002                 while (timeOut > 0) {
1003                         Map<String,List<DistributionMonitorObject>> sortedDistributionStatusMap = AtomicOperationUtils.getSortedDistributionStatusMap(service, true).right().value();
1004                         verifyDistributionStatus = DistributionUtils.verifyDistributionStatus(sortedDistributionStatusMap);
1005                         if(verifyDistributionStatus.left.equals(false)){
1006                                 TimeUnit.MILLISECONDS.sleep(pollingInterval);
1007                                 timeOut-=pollingInterval;
1008                         }else {
1009                                 timeOut = 0;
1010                         }
1011                 }
1012
1013                 if((verifyDistributionStatus.right != null && ! verifyDistributionStatus.right.isEmpty())){
1014                         for(Entry<String, List<String>> entry : verifyDistributionStatus.right.entrySet()){
1015                                 if(ComponentBaseTest.getExtendTest() != null){
1016                                         ComponentBaseTest.getExtendTest().log(Status.INFO, "Consumer: " + entry.getKey() + " failed on following: "+ entry.getValue());
1017                                 }else{
1018                                         System.out.println("Consumer: [" + entry.getKey() + "] failed on following: "+ entry.getValue());
1019                                 }
1020                         }
1021                         statusFlag = false;
1022                 }
1023                 return statusFlag;
1024         }
1025
1026         public static Boolean distributeAndValidateService(Service service) throws Exception {
1027                 return distributeAndValidateService(service, 10, 10000);
1028         }
1029         
1030           /**
1031      * @param resource to download csar file via API
1032      * @return Tosca definition object from main yaml file
1033      */
1034     public static ToscaDefinition downloadAndGetToscaMainYamlObjectApi(Resource resource, File filesFolder) throws Exception {
1035         File vfCsarFileName = new File(File.separator + "VfCsar_" + ElementFactory.generateUUIDforSufix() + ".csar");
1036         OnboardingUtillViaApis.downloadToscaCsarToDirectory(resource, new File(filesFolder.getPath() + vfCsarFileName));
1037         return ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + vfCsarFileName));
1038     }
1039
1040
1041     public static ComponentInstance getServiceComponentInstanceByName(Service service, String name, Boolean validateState){
1042         List<ComponentInstance> compInstances = service.getComponentInstances();
1043         for (ComponentInstance instance: compInstances){
1044             String compName = instance.getName();
1045             if (compName.equals(name))
1046                 return instance;
1047         }
1048         if (validateState) {
1049             assertEquals("Component instance name " + name + " not found", name, null);
1050         }
1051         return null;
1052     }
1053
1054         public static Pair<Component, ComponentInstance> updateComponentInstanceName(String newName, Component component, String canvasElementName, User user, Boolean validateState) throws Exception {
1055                 ComponentInstanceReqDetails componentInstanceReqDetails = ElementFactory.getDefaultComponentInstance();
1056                 ComponentInstance componentInstanceByName = AtomicOperationUtils.getComponentInstanceByName(component, canvasElementName);
1057                 componentInstanceReqDetails.setName(newName);
1058                 componentInstanceReqDetails.setComponentUid(componentInstanceByName.getComponentUid());
1059                 componentInstanceReqDetails.setUniqueId(componentInstanceByName.getUniqueId());
1060                 return AtomicOperationUtils.updateComponentInstance(componentInstanceReqDetails, user, component, validateState).left().value();
1061         }
1062
1063 }