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