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