[SDC] rebase 1710 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 static org.testng.AssertJUnit.assertTrue;
24
25 import java.io.File;
26 import java.io.IOException;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.Map;
33
34 import javax.xml.bind.helpers.AbstractUnmarshallerImpl;
35 import javax.xml.ws.Response;
36
37 import org.apache.commons.codec.binary.Base64;
38 import org.apache.commons.lang3.tuple.Pair;
39 import org.aspectj.apache.bcel.classfile.Code;
40 import org.json.JSONException;
41 import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
42 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
43 import org.openecomp.sdc.be.model.ArtifactDefinition;
44 import org.openecomp.sdc.be.model.Component;
45 import org.openecomp.sdc.be.model.ComponentInstance;
46 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
47 import org.openecomp.sdc.be.model.DistributionStatusEnum;
48 import org.openecomp.sdc.be.model.Product;
49 import org.openecomp.sdc.be.model.Resource;
50 import org.openecomp.sdc.be.model.Service;
51 import org.openecomp.sdc.be.model.User;
52 import org.openecomp.sdc.ci.tests.api.Urls;
53 import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
54 import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
55 import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
56 import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
57 import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails;
58 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
59 import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
60 import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
61 import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
62 import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
63 import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum;
64 import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
65 import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
66 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
67 import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
68 import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
69 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
70 import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
71 import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
72 import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
73 import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils;
74 import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
75 import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
76 import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils;
77 import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
78 import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
79 import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
80 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
81 import org.testng.SkipException;
82
83 import com.google.gson.Gson;
84
85 import fj.data.Either;
86
87 public final class AtomicOperationUtils {
88
89         static final String basicAuthentication = "Basic Y2k6MTIzNDU2";
90         
91         private AtomicOperationUtils() {
92                 throw new UnsupportedOperationException();
93         }
94
95         // *********** RESOURCE ****************
96         /**
97          * Import a vfc From tosca file
98          * 
99          * @param filePath
100          * @param fileName
101          * @return
102          * @throws IOException
103          * @throws JSONException
104          */
105         public static Either<Resource, RestResponse> importResource(String filePath, String fileName) {
106                 try {
107                         User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
108                         ImportReqDetails importReqDetails = ElementFactory.getDefaultImportResource("ciTmpVFC");
109                         importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, filePath, fileName);
110                         RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, designer, null);
111                         return buildResourceFromResponse(importResourceResponse);
112                 } catch (Exception e) {
113                         throw new AtomicOperationException(e);
114                 }
115         }
116
117         public static Either<Resource, RestResponse> createResourceByType(ResourceTypeEnum resourceType, UserRoleEnum userRole, Boolean validateState) {
118                 try {
119                         User defaultUser = ElementFactory.getDefaultUser(userRole);
120                         ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByType(resourceType, defaultUser);
121                         RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
122
123                         if (validateState) {
124                                 assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
125                         }
126
127                         if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
128                                 Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
129                                 return Either.left(resourceResponseObject);
130                         }
131                         return Either.right(resourceResp);
132                 } catch (Exception e) {
133                         throw new AtomicOperationException(e);
134                 }
135         }
136
137         public static Either<Resource, RestResponse> createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, NormativeTypesEnum normativeTypes, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState)
138                         throws Exception {
139                 User defaultUser = ElementFactory.getDefaultUser(userRole);
140                 ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(resourceType, normativeTypes, resourceCategory, defaultUser);
141                 RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
142
143                 if (validateState) {
144                         assertTrue("Actual Response Code is: " + resourceResp.getErrorCode(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
145                 }
146
147                 if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
148                         // Resource resourceResponseObject = ResponseParser
149                         // .convertResourceResponseToJavaObject(resourceResp.getResponse());
150                         Resource resourceResponseObject = ResponseParser.parseToObjectUsingMapper(resourceResp.getResponse(), Resource.class);
151                         return Either.left(resourceResponseObject);
152                 }
153                 return Either.right(resourceResp);
154         }
155
156         public static Either<Resource, RestResponse> createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum resourceType, Resource resourceNormativeType, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState)
157                         throws Exception {
158                 User defaultUser = ElementFactory.getDefaultUser(userRole);
159                 ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(resourceType, resourceNormativeType, resourceCategory, defaultUser);
160                 RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
161
162                 if (validateState) {
163                         assertTrue("actual result: " + resourceResp.getResponseMessage(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
164                 }
165
166                 if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
167                         // Resource resourceResponseObject = ResponseParser
168                         // .convertResourceResponseToJavaObject(resourceResp.getResponse());
169                         Resource resourceResponseObject = ResponseParser.parseToObjectUsingMapper(resourceResp.getResponse(), Resource.class);
170                         return Either.left(resourceResponseObject);
171                 }
172                 return Either.right(resourceResp);
173         }
174
175         // *********** SERVICE ****************
176
177         public static Either<Service, RestResponse> createDefaultService(UserRoleEnum userRole, Boolean validateState) throws Exception {
178                 User defaultUser = ElementFactory.getDefaultUser(userRole);
179                 ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(defaultUser);
180                 RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
181
182                 if (validateState) {
183                         assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
184                 }
185
186                 if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
187                         Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse());
188                         return Either.left(serviceResponseObject);
189                 }
190                 return Either.right(createServiceResp);
191         }
192
193         public static Either<Service, RestResponse> createServiceByCategory(ServiceCategoriesEnum category, UserRoleEnum userRole, Boolean validateState) throws Exception {
194                 User defaultUser = ElementFactory.getDefaultUser(userRole);
195                 ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(category, defaultUser);
196                 RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
197
198                 if (validateState) {
199                         assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
200                 }
201
202                 if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
203                         Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse());
204                         return Either.left(serviceResponseObject);
205                 }
206                 return Either.right(createServiceResp);
207         }
208
209         // *********** PRODUCT ****************
210
211         public static Either<Product, RestResponse> createDefaultProduct(UserRoleEnum userRole, Boolean validateState) throws Exception {
212                 User defaultUser = ElementFactory.getDefaultUser(userRole);
213                 ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct();
214                 RestResponse createProductResp = ProductRestUtils.createProduct(defaultProduct, defaultUser);
215
216                 if (validateState) {
217                         assertTrue(createProductResp.getErrorCode() == ProductRestUtils.STATUS_CODE_CREATED);
218                 }
219
220                 if (createProductResp.getErrorCode() == ProductRestUtils.STATUS_CODE_CREATED) {
221                         Product productResponseJavaObject = ResponseParser.convertProductResponseToJavaObject(createProductResp.getResponse());
222                         return Either.left(productResponseJavaObject);
223                 }
224                 return Either.right(createProductResp);
225         }
226
227         // public static ComponentReqDetails
228         // convertCompoentToComponentReqDetails(Component component){
229         //
230         // ComponentReqDetails componentReqDetails =
231         // ElementFactory.getDefaultService();
232         // componentReqDetails.setName(component.getName());
233         // componentReqDetails.setDescription(component.getDescription());
234         // componentReqDetails.setTags(component.getTags());
235         // componentReqDetails.setContactId(component.getContactId());
236         // componentReqDetails.setIcon(component.getIcon());
237         // componentReqDetails.setUniqueId(component.getUniqueId());
238         // componentReqDetails.setCreatorUserId(component.getCreatorUserId());
239         // componentReqDetails.setCreatorFullName(component.getCreatorFullName());
240         // componentReqDetails.setLastUpdaterUserId(component.getLastUpdaterUserId());
241         // componentReqDetails.setLastUpdaterFullName(component.getLastUpdaterFullName());
242         // componentReqDetails.setCreationDate(component.getCreationDate());
243         // componentReqDetails.setLastUpdateDate(component.getLastUpdateDate());
244         // componentReqDetails.setLifecycleState(component.getLifecycleState());
245         // componentReqDetails.setVersion(component.getVersion());
246         // componentReqDetails.setUuid(component.getUUID());
247         // componentReqDetails.setCategories(component.getCategories());
248         // componentReqDetails.setProjectCode(component.getProjectCode());
249         //
250         // return componentReqDetails;
251         // }
252
253         // *********** LIFECYCLE ***************
254
255         public static Pair<Component, RestResponse> changeComponentState(Component component, UserRoleEnum userRole, LifeCycleStatesEnum targetState, Boolean validateState) throws Exception {
256
257                 Boolean isValidationFailed = false;
258                 RestResponse lifeCycleStatesResponse = null;
259                 User defaultUser = ElementFactory.getDefaultUser(userRole);
260
261                 LifeCycleStatesEnum curentCompState = LifeCycleStatesEnum.findByCompState(component.getLifecycleState().toString());
262
263                 if (curentCompState == targetState) {
264                         component = getComponentObject(component, userRole);
265                         return Pair.of(component, null);
266                 }
267                 // List<LifeCycleStatesEnum> lifeCycleStatesEnumOrigList = new
268                 // ArrayList<LifeCycleStatesEnum>(EnumSet.allOf(LifeCycleStatesEnum.class));
269
270                 ArrayList<String> lifeCycleStatesEnumList = new ArrayList<String>();
271                 if (curentCompState.equals(LifeCycleStatesEnum.CHECKIN) && targetState.equals(LifeCycleStatesEnum.CHECKOUT)) {
272                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString());
273                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString());
274                 } else {
275                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString());
276                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString());
277                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFICATIONREQUEST.toString());
278                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.STARTCERTIFICATION.toString());
279                         lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFY.toString());
280                 }
281                 for (int i = 0; i < lifeCycleStatesEnumList.size(); i++) {
282                         if (lifeCycleStatesEnumList.get(i).equals(curentCompState.name())) {
283                                 int a;
284                                 a = (i == lifeCycleStatesEnumList.size() - 1) ? 0 : i + 1;
285
286                                 for (int n = a; n < lifeCycleStatesEnumList.size(); n++) {
287                                         if (lifeCycleStatesEnumList.get(n).equals(LifeCycleStatesEnum.STARTCERTIFICATION.name()) || lifeCycleStatesEnumList.get(n).equals(LifeCycleStatesEnum.CERTIFY.name())) {
288                                                 defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
289                                         } else
290                                                 defaultUser = ElementFactory.getDefaultUser(userRole);
291
292                                         lifeCycleStatesResponse = LifecycleRestUtils.changeComponentState(component, defaultUser, LifeCycleStatesEnum.findByState(lifeCycleStatesEnumList.get(n)));
293                                         if (lifeCycleStatesResponse.getErrorCode() != LifecycleRestUtils.STATUS_CODE_SUCCESS)
294                                                 isValidationFailed = true;
295                                         if (lifeCycleStatesEnumList.get(n).equals(targetState.toString()) || isValidationFailed == true) {
296                                                 break;
297                                         }
298                                 }
299                         }
300
301                 }
302                 Component componentJavaObject = getComponentObject(component, userRole);
303
304                 if (validateState == true && isValidationFailed == true) {
305                         assertTrue("change state failed" + lifeCycleStatesResponse.getResponse(), false);
306
307                         return Pair.of(componentJavaObject, lifeCycleStatesResponse);
308                 }
309
310                 if (isValidationFailed == true) {
311                         return Pair.of(componentJavaObject, lifeCycleStatesResponse);
312                 }
313
314                 return Pair.of(componentJavaObject, lifeCycleStatesResponse);
315         }
316
317         public static RestResponse distributeService(Component component, Boolean validateState) throws Exception {
318
319                 Service service = (Service) component;
320
321                 User opsUser = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
322                 User governotUser = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
323
324                 ServiceReqDetails serviceDetails = new ServiceReqDetails(service);
325                 RestResponse distributionService = null;
326
327                 RestResponse approveDistribution = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, governotUser, "approveService", DistributionStatusEnum.DISTRIBUTION_APPROVED);
328                 if (approveDistribution.getErrorCode() == 200) {
329                         distributionService = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, opsUser, "approveService", DistributionStatusEnum.DISTRIBUTED);
330                 }
331
332                 if (validateState) {
333                         assertTrue(approveDistribution.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
334                         assertTrue(distributionService.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
335                         return distributionService;
336                 }
337
338                 return distributionService;
339
340         }
341
342         // *********** ARTIFACTS *****************
343
344         public static Either<ArtifactDefinition, RestResponse> uploadArtifactByType(ArtifactTypeEnum artifactType, Component component, UserRoleEnum userRole, Boolean deploymentTrue, Boolean validateState) throws Exception {
345
346                 User defaultUser = ElementFactory.getDefaultUser(userRole);
347                 ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(null, artifactType, deploymentTrue);
348                 if (deploymentTrue == false)
349                         artifactDetails.setArtifactGroupType(ArtifactGroupTypeEnum.INFORMATIONAL.getType());
350                 RestResponse uploadArtifactResp = ArtifactRestUtils.uploadArtifact(artifactDetails, component, defaultUser);
351
352                 if (validateState) {
353                         assertTrue("artifact upload failed: " + artifactDetails.getArtifactName(), uploadArtifactResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
354                 }
355
356                 if (uploadArtifactResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
357                         ArtifactDefinition artifactJavaObject = ResponseParser.convertArtifactDefinitionResponseToJavaObject(uploadArtifactResp.getResponse());
358                         return Either.left(artifactJavaObject);
359                 }
360                 return Either.right(uploadArtifactResp);
361         }
362
363         // *********** CONTAINERS *****************
364         /**
365          * Adds Component instance to Component
366          * 
367          * @param compInstParent
368          * @param compContainer
369          * @return
370          */
371         public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer) {
372                 return addComponentInstanceToComponentContainer(compInstParent, compContainer, UserRoleEnum.DESIGNER, false);
373         }
374
375         public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer, UserRoleEnum userRole, Boolean validateState) {
376                 try {
377                         User defaultUser = ElementFactory.getDefaultUser(userRole);
378                         ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(compInstParent);
379                         RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, defaultUser, compContainer);
380
381                         if (validateState) {
382                                 if (createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_NOT_FOUND)
383                                 {
384                                         throw new SkipException("Open bug DE262001");
385                                 }
386                                 else{
387                                 assertTrue("error - " + createComponentInstance.getErrorCode() + "instead - " + ServiceRestUtils.STATUS_CODE_CREATED, createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
388                                 }
389                         }
390
391                         if (createComponentInstance.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
392                                 ComponentInstance componentInstance = ResponseParser.convertComponentInstanceResponseToJavaObject(createComponentInstance.getResponse());
393                                 return Either.left(componentInstance);
394                         }
395                         return Either.right(createComponentInstance);
396                 } catch (Exception e) {
397                         throw new AtomicOperationException(e);
398                 }
399         }
400
401         public static Resource getResourceObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
402                 // User defaultUser = ElementFactory.getDefaultUser(userRole);
403                 RestResponse restResponse = ResourceRestUtils.getResource(containerDetails.getUniqueId());
404                 Resource container = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
405                 return container;
406         }
407         
408         public static Resource getResourceObject(String uniqueId) throws Exception {
409                 RestResponse restResponse = ResourceRestUtils.getResource(uniqueId);
410                 Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
411                 return resource;
412         }
413         
414         public static Resource getResourceObjectByNameAndVersion(UserRoleEnum sdncModifierDetails, String resourceName, String resourceVersion) throws Exception {
415                 User defaultUser = ElementFactory.getDefaultUser(sdncModifierDetails);
416                 RestResponse resourceResponse = ResourceRestUtils.getResourceByNameAndVersion(defaultUser.getUserId(), resourceName, resourceVersion);
417                 Resource container = ResponseParser.convertResourceResponseToJavaObject(resourceResponse.getResponse());
418                 return container;
419         }
420
421         public static Service getServiceObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
422                 User defaultUser = ElementFactory.getDefaultUser(userRole);
423                 RestResponse serviceResponse = ServiceRestUtils.getService(containerDetails.getUniqueId(), defaultUser);
424                 Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
425                 return container;
426         }
427         
428         public static Service getServiceObjectByNameAndVersion(UserRoleEnum sdncModifierDetails, String serviceName, String serviceVersion) throws Exception {
429                 User defaultUser = ElementFactory.getDefaultUser(sdncModifierDetails);
430                 RestResponse serviceResponse = ServiceRestUtils.getServiceByNameAndVersion(defaultUser, serviceName, serviceVersion);
431                 Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
432                 return container;
433         }
434         
435         public static Service getServiceObject(String uniqueId) throws Exception {
436                 RestResponse serviceResponse = ServiceRestUtils.getService(uniqueId);
437                 Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
438                 return container;
439         }
440
441         public static Product getProductObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
442                 User defaultUser = ElementFactory.getDefaultUser(userRole);
443                 RestResponse productRest = ProductRestUtils.getProduct(containerDetails.getUniqueId(), defaultUser.getUserId());
444                 Product container = ResponseParser.convertProductResponseToJavaObject(productRest.getResponse());
445                 return container;
446         }
447
448         public static Component getComponentObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
449                 User defaultUser = ElementFactory.getDefaultUser(userRole);
450
451                 switch (containerDetails.getComponentType()) {
452                 case RESOURCE:
453                         RestResponse restResponse = ResourceRestUtils.getResource(containerDetails.getUniqueId());
454                         containerDetails = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
455                         break;
456                 case SERVICE:
457                         RestResponse serviceResponse = ServiceRestUtils.getService(containerDetails.getUniqueId(), defaultUser);
458                         containerDetails = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
459                         break;
460                 case PRODUCT:
461                         RestResponse productRest = ProductRestUtils.getProduct(containerDetails.getUniqueId(), defaultUser.getUserId());
462                         containerDetails = ResponseParser.convertProductResponseToJavaObject(productRest.getResponse());
463                         break;
464                 default:
465                         break;
466                 }
467                 return containerDetails;
468         }
469
470         public static Component convertReposnseToComponentObject(Component containerDetails, RestResponse restresponse) throws Exception {
471
472                 switch (containerDetails.getComponentType()) {
473                 case RESOURCE:
474                         containerDetails = ResponseParser.convertResourceResponseToJavaObject(restresponse.getResponse());
475                         break;
476                 case SERVICE:
477                         containerDetails = ResponseParser.convertServiceResponseToJavaObject(restresponse.getResponse());
478                         break;
479                 case PRODUCT:
480                         containerDetails = ResponseParser.convertProductResponseToJavaObject(restresponse.getResponse());
481                         break;
482                 default:
483                         break;
484                 }
485                 return containerDetails;
486         }
487
488         public static Either<Component, RestResponse> associate2ResourceInstances(Component containerDetails, ComponentInstance fromNode, ComponentInstance toNode, String assocType, UserRoleEnum userRole, Boolean validateState) throws Exception {
489
490                 User defaultUser = ElementFactory.getDefaultUser(userRole);
491                 RestResponse associate2ResourceInstancesResponse = ResourceRestUtils.associate2ResourceInstances(containerDetails, fromNode, toNode, assocType, defaultUser);
492
493                 if (validateState) {
494                         assertTrue(associate2ResourceInstancesResponse.getErrorCode() == ServiceRestUtils.STATUS_CODE_SUCCESS);
495                 }
496
497                 if (associate2ResourceInstancesResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS) {
498
499                         switch (containerDetails.getComponentType()) {
500                         case RESOURCE:
501                                 containerDetails = ResponseParser.convertResourceResponseToJavaObject(associate2ResourceInstancesResponse.getResponse());
502                                 break;
503                         case SERVICE:
504                                 containerDetails = ResponseParser.convertServiceResponseToJavaObject(associate2ResourceInstancesResponse.getResponse());
505                                 break;
506                         case PRODUCT:
507                                 containerDetails = ResponseParser.convertProductResponseToJavaObject(associate2ResourceInstancesResponse.getResponse());
508                                 break;
509                         default:
510                                 break;
511                         }
512
513                         return Either.left(containerDetails);
514                 }
515                 return Either.right(associate2ResourceInstancesResponse);
516
517         }
518
519         public static Either<Pair<Component, ComponentInstance>, RestResponse> changeComponentInstanceVersion(Component containerDetails, ComponentInstance componentInstanceToReplace, Component newInstance, UserRoleEnum userRole, Boolean validateState)
520                         throws Exception {
521                 User defaultUser = ElementFactory.getDefaultUser(userRole);
522
523                 RestResponse changeComponentInstanceVersionResp = ComponentInstanceRestUtils.changeComponentInstanceVersion(containerDetails, componentInstanceToReplace, newInstance, defaultUser);
524                 if (validateState) {
525                         assertTrue("change ComponentInstance version failed: " + changeComponentInstanceVersionResp.getResponseMessage(), changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
526                 }
527
528                 if (changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
529
530                         Component compoenntObject = AtomicOperationUtils.getComponentObject(containerDetails, userRole);
531                         ComponentInstance componentInstanceJavaObject = ResponseParser.convertComponentInstanceResponseToJavaObject(changeComponentInstanceVersionResp.getResponse());
532
533                         return Either.left(Pair.of(compoenntObject, componentInstanceJavaObject));
534                 }
535
536                 return Either.right(changeComponentInstanceVersionResp);
537         }
538
539         // *********** PROPERTIES *****************
540
541         public static Either<ComponentInstanceProperty, RestResponse> addCustomPropertyToResource(PropertyReqDetails propDetails, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
542
543                 User defaultUser = ElementFactory.getDefaultUser(userRole);
544                 Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
545                 propertyToSend.put(propDetails.getName(), propDetails);
546                 Gson gson = new Gson();
547                 RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser);
548
549                 if (validateState) {
550                         assertTrue("add property to resource failed: " + addPropertyResponse.getErrorCode(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED);
551                 }
552
553                 if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED) {
554                         ComponentInstanceProperty compInstProp = null;
555                         String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
556                         compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
557                         return Either.left(compInstProp);
558                 }
559                 return Either.right(addPropertyResponse);
560         }
561
562         // Benny
563         public static Either<ComponentInstanceProperty, RestResponse> updatePropertyOfResource(PropertyReqDetails propDetails, Resource resourceDetails, String propertyUniqueId, UserRoleEnum userRole, Boolean validateState) throws Exception {
564
565                 User defaultUser = ElementFactory.getDefaultUser(userRole);
566                 Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
567                 propertyToSend.put(propDetails.getName(), propDetails);
568                 Gson gson = new Gson();
569                 RestResponse addPropertyResponse = PropertyRestUtils.updateProperty(resourceDetails.getUniqueId(), propertyUniqueId, gson.toJson(propertyToSend), defaultUser);
570
571                 if (validateState) {
572                         assertTrue("add property to resource failed: " + addPropertyResponse.getResponseMessage(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
573                 }
574
575                 if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
576                         ComponentInstanceProperty compInstProp = null;
577                         String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
578                         compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
579                         return Either.left(compInstProp);
580                 }
581                 return Either.right(addPropertyResponse);
582         }
583
584         public static RestResponse deletePropertyOfResource(String resourceId, String propertyId, UserRoleEnum userRole) throws Exception {
585                 User defaultUser = ElementFactory.getDefaultUser(userRole);
586                 return PropertyRestUtils.deleteProperty(resourceId, propertyId, defaultUser);
587         }
588
589         public static Either<ComponentInstanceProperty, RestResponse> addDefaultPropertyToResource(PropertyTypeEnum propertyType, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
590
591                 User defaultUser = ElementFactory.getDefaultUser(userRole);
592                 PropertyReqDetails propDetails = ElementFactory.getPropertyDetails(propertyType);
593                 Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
594                 propertyToSend.put(propDetails.getName(), propDetails);
595                 Gson gson = new Gson();
596                 RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser);
597
598                 if (validateState) {
599                         assertTrue("add property to resource failed: " + addPropertyResponse.getResponseMessage(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED);
600                 }
601
602                 if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED) {
603                         ComponentInstanceProperty compInstProp = null;
604                         String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
605                         compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
606
607                         return Either.left(compInstProp);
608                 }
609                 return Either.right(addPropertyResponse);
610         }
611
612         public static RestResponse createDefaultConsumer(Boolean validateState) {
613                 try {
614                         ConsumerDataDefinition defaultConsumerDefinition = ElementFactory.getDefaultConsumerDetails();
615                         RestResponse createResponse = ConsumerRestUtils.createConsumer(defaultConsumerDefinition, ElementFactory.getDefaultUser(UserRoleEnum.ADMIN));
616                         BaseRestUtils.checkCreateResponse(createResponse);
617
618                         if (validateState) {
619                                 assertTrue(createResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
620                         }
621                         return createResponse;
622                 } catch (Exception e) {
623                         throw new AtomicOperationException(e);
624                 }
625         }
626
627         /**
628          * Builds Resource From rest response
629          * 
630          * @param resourceResp
631          * @return
632          */
633         public static Either<Resource, RestResponse> buildResourceFromResponse(RestResponse resourceResp) {
634                 Either<Resource, RestResponse> result;
635                 if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
636                         Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
637                         result = Either.left(resourceResponseObject);
638                 } else {
639                         result = Either.right(resourceResp);
640                 }
641                 return result;
642         }
643
644         private static class AtomicOperationException extends RuntimeException {
645                 private AtomicOperationException(Exception e) {
646                         super(e);
647                 }
648
649                 private static final long serialVersionUID = 1L;
650         };
651         
652         /**
653          * Import resource from CSAR
654          * 
655          * @param resourceType
656          * @param userRole
657          * @param fileName
658          * @param filePath
659          * @return Resource
660          * @throws Exception
661          */
662         public static Resource importResourceFromCSAR(ResourceTypeEnum resourceType, UserRoleEnum userRole, String fileName, String... filePath) throws Exception {
663                 // Get the CSARs path
664                 String realFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "CI" + File.separator + "csars" ;
665                 if (filePath != null && filePath.length > 0) {
666                         realFilePath = filePath.toString();
667                 }
668                 
669                 // Create default import resource & user
670                 ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
671                 User sdncModifierDetails = ElementFactory.getDefaultUser(userRole);
672                 
673                 byte[] data = null;
674                 Path path = Paths.get(realFilePath + File.separator + fileName);
675                 data = Files.readAllBytes(path);
676                 String payloadName = fileName;
677                 String payloadData = Base64.encodeBase64String(data);
678                 resourceDetails.setPayloadData(payloadData);
679                 resourceDetails.setCsarUUID(payloadName);
680                 resourceDetails.setPayloadName(payloadName);
681                 resourceDetails.setResourceType(resourceType.name());
682                 
683                 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
684                 BaseRestUtils.checkCreateResponse(createResource);
685                 return ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);           
686         };
687         
688         public static Either<Resource, RestResponse> importResourceByFileName(ResourceTypeEnum resourceType, UserRoleEnum userRole, String fileName, Boolean validateState, String... filePath) throws IOException {
689
690                 String realFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "CI" + File.separator + "csars" ;
691                 if (filePath != null && filePath.length > 0) {
692                         realFilePath = filePath.toString();
693                 }
694
695                 try {
696                         User defaultUser = ElementFactory.getDefaultUser(userRole);
697                         ResourceReqDetails defaultResource = ElementFactory.getDefaultResource(defaultUser);                    
698                         ImportReqDetails defaultImportResource = ElementFactory.getDefaultImportResource(defaultResource);
699                         ImportUtils.getImportResourceDetailsByPathAndName(defaultImportResource, realFilePath, fileName);
700                         RestResponse resourceResp = ResourceRestUtils.createResource(defaultImportResource, defaultUser);
701
702                         if (validateState) {
703                                 assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
704                         }
705
706                         if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
707                                 Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
708                                 return Either.left(resourceResponseObject);
709                         }
710                         return Either.right(resourceResp);
711                 } catch (Exception e) {
712                         throw new AtomicOperationException(e);
713                 }
714         }
715         
716         public static Either<String, RestResponse> getServiceToscaArtifactPayload(Service service, String artifactType) throws Exception {
717
718                 String url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, "localhost", "8080", service.getUniqueId(), service.getToscaArtifacts().get(artifactType).getUniqueId());
719                 String userId = service.getLastUpdaterUserId();
720                 Map<String, String> headersMap = new HashMap<String, String>();
721                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
722                 headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache");
723                 headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
724                 headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
725 //              headersMap.put("X-ECOMP-InstanceID", "test");
726                 if (userId != null) {
727                         headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
728                 }
729                 HttpRequest http = new HttpRequest();
730                 RestResponse response = http.httpSendGet(url, headersMap);
731                 if (response.getErrorCode() != 200 && response.getResponse().getBytes() == null && response.getResponse().getBytes().length == 0) {
732                         return Either.right(response);
733                 }
734                 return Either.left(response.getResponse());
735
736         }
737
738 }