864dd891acd1b8b918df0a4a92b4a058f5d0c51d
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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.clearspring.analytics.util.Pair;
25 import com.google.gson.Gson;
26 import org.apache.commons.io.IOUtils;
27 import org.apache.http.HttpEntity;
28 import org.apache.http.client.methods.CloseableHttpResponse;
29 import org.apache.http.client.methods.HttpPost;
30 import org.apache.http.entity.mime.MultipartEntityBuilder;
31 import org.apache.http.entity.mime.content.FileBody;
32 import org.apache.http.impl.client.CloseableHttpClient;
33 import org.apache.http.impl.client.HttpClients;
34 import org.json.simple.JSONArray;
35 import org.json.simple.JSONValue;
36 import org.openecomp.sdc.be.model.User;
37 import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
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.CvfcTypeEnum;
42 import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
43 import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
44 import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
45 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
46 import org.openecomp.sdc.ci.tests.utils.Utils;
47 import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
48 import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
49
50 import java.io.File;
51 import java.io.IOException;
52 import java.io.InputStream;
53 import java.io.StringWriter;
54 import java.nio.file.FileSystems;
55 import java.util.Arrays;
56 import java.util.HashMap;
57 import java.util.Iterator;
58 import java.util.Map;
59
60 import static org.testng.AssertJUnit.assertEquals;
61
62 public class VendorSoftwareProductRestUtils {
63
64     public static VendorSoftwareProductObject createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, VendorLicenseModel vendorLicenseModel, Map<CvfcTypeEnum, String> cvfcArtifacts)
65             throws Exception {
66
67         VendorSoftwareProductObject vendorSoftwareProductObject = createVSP(resourceReqDetails, heatFileName, filepath, user,
68             vendorLicenseModel);
69         if(cvfcArtifacts != null && ! cvfcArtifacts.isEmpty()){
70             addCvfcArtifacts(cvfcArtifacts, user, vendorSoftwareProductObject);
71         }
72         prepareVspForUse(user, vendorSoftwareProductObject, true);
73         return vendorSoftwareProductObject;
74     }
75
76     public static VendorSoftwareProductObject createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, VendorLicenseModel vendorLicenseModel)
77             throws Exception {
78
79         Map<CvfcTypeEnum, String> cvfcArtifacts = new HashMap<>();
80         return createVendorSoftwareProduct(resourceReqDetails, heatFileName, filepath, user, vendorLicenseModel, cvfcArtifacts);
81     }
82
83     /**
84      * @param user user
85      * @param vendorSoftwareProductObject vendorSoftwareProductObject
86      * @param isVspUpdated - in case isVspUpdated = false the commit API should not be issued
87      * the method do commit, submit and create package
88      * @throws Exception
89      */
90     public static void prepareVspForUse(User user, VendorSoftwareProductObject vendorSoftwareProductObject, Boolean isVspUpdated) throws Exception {
91
92         if(isVspUpdated) {
93             RestResponse commit = commitVendorSoftwareProduct(vendorSoftwareProductObject, user);
94             assertEquals("did not succeed to commit new VSP", 200, commit.getErrorCode().intValue());
95         }
96         RestResponse submit = submitVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getComponentId());
97         assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue());
98
99         RestResponse createPackage = createPackageOfVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getComponentId());
100         assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue());
101
102     }
103
104     public static VendorSoftwareProductObject createAndFillVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filePath, User user, VendorLicenseModel vendorLicenseModel, Map<CvfcTypeEnum, String> cvfcArtifacts)
105             throws Exception {
106
107         VendorSoftwareProductObject createVendorSoftwareProduct = createVendorSoftwareProduct(resourceReqDetails, heatFileName, filePath, user,
108             vendorLicenseModel, cvfcArtifacts);
109         VendorSoftwareProductObject vendorSoftwareProductObject = fillVendorSoftwareProductObjectWithMetaData(heatFileName, createVendorSoftwareProduct);
110         return vendorSoftwareProductObject;
111
112     }
113
114
115     public static VendorSoftwareProductObject createVSP(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, VendorLicenseModel vendorLicenseModel) throws Exception {
116         String vspName = handleFilename(heatFileName);
117
118         if(ComponentBaseTest.getExtendTest() != null){
119             ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor software product");
120         }
121
122         Pair<RestResponse, VendorSoftwareProductObject> createNewVspPair = createNewVendorSoftwareProduct(resourceReqDetails, vspName,
123             vendorLicenseModel, user);
124         assertEquals("did not succeed to create new VSP", 200,createNewVspPair.left.getErrorCode().intValue());
125
126         RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName,  createNewVspPair.right, user);
127         assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
128
129         RestResponse validateUpload = validateUpload(createNewVspPair.right, user);
130         assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue());
131
132         return createNewVspPair.right;
133     }
134
135     public static void updateVspWithVfcArtifacts(String filepath, String updatedSnmpPoll, String updatedSnmpTrap, String componentInstanceId, User user, VendorSoftwareProductObject vendorSoftwareProductObject) throws Exception{
136         RestResponse checkout = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user);
137         assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
138 //              ExtentTestActions.log(Status.INFO, "Deleting SNMP POLL");
139         deleteArtifactByType(componentInstanceId, vendorSoftwareProductObject, user, CvfcTypeEnum.SNMP_POLL);
140 //              ExtentTestActions.log(Status.INFO, "Deleting SNMP TRAP");
141         deleteArtifactByType(componentInstanceId, vendorSoftwareProductObject, user, CvfcTypeEnum.SNMP_TRAP);
142         addVFCArtifacts(filepath, updatedSnmpPoll, updatedSnmpTrap, vendorSoftwareProductObject, user, componentInstanceId);
143         prepareVspForUse(user, vendorSoftwareProductObject, true);
144     }
145
146     private static RestResponse deleteArtifactByType(String componentInstanceId, VendorSoftwareProductObject vendorSoftwareProductObject, User user, CvfcTypeEnum snmpType) throws Exception
147     {
148         Config config = Utils.getConfig();
149         String url = String.format(Urls.DELETE_AMDOCS_ARTIFACT_BY_TYPE, config.getOnboardingBeHost(), config.getOnboardingBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), componentInstanceId, snmpType.getValue());
150         String userId = user.getUserId();
151         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
152
153         HttpRequest http = new HttpRequest();
154         RestResponse response = http.httpSendDelete(url, headersMap);
155         return response;
156     }
157
158     public static void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject, User user, Boolean isVspUpdated) throws Throwable {
159
160         RestResponse createMethod = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user);
161         assertEquals("did not succeed to createMethod for new VSP", 200, createMethod.getErrorCode().intValue());
162         prepareVspForUse(user,vendorSoftwareProductObject, isVspUpdated);
163
164     }
165
166     public static String handleFilename(String heatFileName) {
167         final String namePrefix = String.format("%sVF%s", ElementFactory.getResourcePrefix(), "Onboarded-");
168         final String nameSuffix = "-" + OnboardingUtils.getShortUUID();
169
170         String subHeatFileName = heatFileName.substring(0, heatFileName.lastIndexOf("."));
171
172         if ((namePrefix + subHeatFileName + nameSuffix).length() >= 50) {
173             subHeatFileName = subHeatFileName.substring(0, 50 - namePrefix.length() - nameSuffix.length());
174         }
175
176         if (subHeatFileName.contains("(") || subHeatFileName.contains(")")) {
177             subHeatFileName = subHeatFileName.replace("(", "-");
178             subHeatFileName = subHeatFileName.replace(")", "-");
179         }
180
181         String vnfName = namePrefix + subHeatFileName + nameSuffix;
182         return vnfName;
183     }
184
185     public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, VendorSoftwareProductObject vendorSoftwareProductObject, User user, String componentInstanceId) throws Exception{
186         componentInstanceId = (componentInstanceId == null) ? getVspComponentId(vendorSoftwareProductObject, user) : componentInstanceId;
187         if (componentInstanceId != null){
188             if (snmpPoll != null){
189 //                              ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP POLL with the file " + snmpPoll);
190                 RestResponse uploadSnmpPollArtifact = uploadSnmpPollArtifact(filepath, snmpPoll, vendorSoftwareProductObject, user, componentInstanceId);
191                 assertEquals("Did not succeed to add SNMP POLL", 200, uploadSnmpPollArtifact.getErrorCode().intValue());
192             }
193             if (snmpTrap != null){
194 //                              ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP TRAP with the file " + snmpTrap);
195                 RestResponse uploadSnmpTrapArtifact = uploadSnmpTrapArtifact(filepath, snmpTrap, vendorSoftwareProductObject, user, componentInstanceId);
196                 assertEquals("Did not succeed to add SNMP TRAP", 200, uploadSnmpTrapArtifact.getErrorCode().intValue());
197             }
198         }
199
200         return componentInstanceId;
201     }
202
203     public static String addCvfcArtifacts(Map<CvfcTypeEnum, String> componentVfcArtifacts, User user, VendorSoftwareProductObject vendorSoftwareProductObject) throws Exception{
204         String componentInstanceId = getVspComponentId(vendorSoftwareProductObject, user);
205         if (componentInstanceId != null){
206             for(Map.Entry<CvfcTypeEnum, String> entry : componentVfcArtifacts.entrySet()){
207 //                              ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type " + entry.getKey().getValue() + " with the file " + entry.getValue());
208                 RestResponse uploadSnmpPollArtifact = uploadCvfcArtifact(entry.getValue(), entry.getKey().getValue(), user, vendorSoftwareProductObject, componentInstanceId);
209                 assertEquals("Did not succeed to add " + entry.getKey().getValue(), BaseRestUtils.STATUS_CODE_SUCCESS, uploadSnmpPollArtifact.getErrorCode().intValue());
210             }
211         }
212         return componentInstanceId;
213     }
214
215     public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception{
216         return addVFCArtifacts(filepath, snmpPoll, snmpTrap, vendorSoftwareProductObject, user, null);
217     }
218
219     public static RestResponse uploadCvfcArtifact(String filepath, String cvfcType, User user, VendorSoftwareProductObject vendorSoftwareProductObject, String componentInstanceId) throws IOException {
220         Config config = Utils.getConfig();
221         String snmpPollUrl = String.format(Urls.UPLOAD_AMDOCS_ARTIFACT, config.getOnboardingBeHost(),config.getOnboardingBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), componentInstanceId, cvfcType);
222         return uploadFile(filepath, null, snmpPollUrl, user);
223     }
224
225
226     private static RestResponse uploadSnmpPollArtifact(String filepath, String zipArtifact, VendorSoftwareProductObject vendorSoftwareProductObject, User user, String componentInstanceId) throws IOException {
227         Config config = Utils.getConfig();
228         String snmpPollUrl = String.format(Urls.UPLOAD_SNMP_POLL_ARTIFACT, config.getOnboardingBeHost(),config.getOnboardingBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), componentInstanceId);
229         return uploadFile(filepath, zipArtifact, snmpPollUrl, user);
230     }
231
232     private static RestResponse uploadSnmpTrapArtifact(String filepath, String zipArtifact, VendorSoftwareProductObject vendorSoftwareProductObject, User user, String vspComponentId) throws IOException {
233         Config config = Utils.getConfig();
234         String snmpTrapUrl = String.format(Urls.UPLOAD_SNMP_POLL_ARTIFACT, config.getOnboardingBeHost(),config.getOnboardingBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), vspComponentId);
235         return uploadFile(filepath, zipArtifact, snmpTrapUrl, user);
236     }
237
238     private static RestResponse deleteSnmpArtifact(String componentId, String vspId, User user, SnmpTypeEnum snmpType) throws Exception
239     {
240         Config config = Utils.getConfig();
241         String url = String.format(Urls.DELETE_AMDOCS_ARTIFACT_BY_TYPE, config.getOnboardingBeHost(),config.getOnboardingBePort(), vspId, componentId, snmpType.getValue());
242         String userId = user.getUserId();
243
244         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
245
246         HttpRequest http = new HttpRequest();
247         RestResponse response = http.httpSendDelete(url, headersMap);
248         return response;
249     }
250
251
252     /**
253      * @param vendorSoftwareProductObject VendorSoftwareProductObject
254      * @param user user object
255      * @return return first found component instance Id from list
256      * @throws Exception Exception
257      */
258     private static String getVspComponentId(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
259         RestResponse componentList = getVSPComponents(vendorSoftwareProductObject, user);
260         String response = componentList.getResponse();
261         Map<String, Object> responseMap = (Map<String, Object>) JSONValue.parse(response);
262         JSONArray results = (JSONArray)responseMap.get("results");
263         for (Object res : results){
264             Map<String, Object> componentMap = (Map<String, Object>) JSONValue.parse(res.toString());
265             String componentInstanceId = componentMap.get("id").toString();
266             return componentInstanceId;
267         }
268         return null;
269     }
270
271     private static RestResponse getVSPComponents(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception{
272         Config config = Utils.getConfig();
273         String url = String.format(Urls.GET_VSP_COMPONENTS, config.getOnboardingBeHost(),config.getOnboardingBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
274         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(user.getUserId());
275
276         HttpRequest http = new HttpRequest();
277         RestResponse response = http.httpSendGet(url, headersMap);
278         return response;
279     }
280
281
282
283     public static boolean validateVspExist(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
284         RestResponse restResponse = getVSPComponentByVersion(vendorSoftwareProductObject, user);
285         assertEquals(String.format("Vsp version not updated, reponse message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200);
286         return (restResponse.getErrorCode()==200);
287     }
288
289
290     private static RestResponse getVSPComponentByVersion(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception{
291         Config config = Utils.getConfig();
292         String url = String.format(Urls.GET_VSP_COMPONENT_BY_VERSION, config.getOnboardingBeHost(),config.getOnboardingBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
293         String userId = user.getUserId();
294
295         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
296
297         HttpRequest http = new HttpRequest();
298         RestResponse response = http.httpSendGet(url, headersMap);
299         return response;
300     }
301
302     private static RestResponse actionOnComponent(String vspid, String body, String onboardComponent, User user, String componentVersion) throws Exception {
303         Config config = Utils.getConfig();
304         String url = String.format(Urls.ACTION_ON_COMPONENT, config.getOnboardingBeHost(), config.getOnboardingBePort(), onboardComponent, vspid, componentVersion);
305         String userId = user.getUserId();
306         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
307
308         HttpRequest http = new HttpRequest();
309         RestResponse response = http.httpSendPut(url, body, headersMap);
310         return response;
311     }
312
313 //    TODO to check if for onboard API ACTION_ARCHIVE_RESTORE_COMPONENT format was added version parameter
314 //    if yes remove this method and use general actionOnComponent method
315     private static RestResponse actionOnComponent(String vspid, String body, String onboardComponent, User user) throws Exception {
316         Config config = Utils.getConfig();
317         String url = String.format(Urls.ACTION_ARCHIVE_RESTORE_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vspid);
318         String userId = user.getUserId();
319         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
320
321         HttpRequest http = new HttpRequest();
322         RestResponse response = http.httpSendPut(url, body, headersMap);
323         return response;
324     }
325
326     public static Pair<RestResponse, VendorSoftwareProductObject> createNewVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String vspName, VendorLicenseModel vendorLicenseModel, User user) throws Exception {
327
328         Config config = Utils.getConfig();
329         String url = String.format(Urls.CREATE_VENDOR_SOFTWARE_PRODUCT, config.getOnboardingBeHost(), config.getOnboardingBePort());
330         String userId = user.getUserId();
331         VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject();
332         LicensingData licensingData = new LicensingData(
333             vendorLicenseModel.getVendorLicenseAgreementId(), Arrays.asList(vendorLicenseModel.getFeatureGroupId()));
334         ResourceCategoryEnum resourceCategoryEnum = ResourceCategoryEnum.findEnumNameByValues(resourceReqDetails.getCategories().get(0).getName(), resourceReqDetails.getCategories().get(0).getSubcategories().get(0).getName());
335
336         vendorSoftwareProductObject.setName(vspName);
337         vendorSoftwareProductObject.setDescription(resourceReqDetails.getDescription());
338         vendorSoftwareProductObject.setCategory(resourceCategoryEnum.getCategoryUniqeId());
339         vendorSoftwareProductObject.setSubCategory(resourceCategoryEnum.getSubCategoryUniqeId());
340         vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage");
341         vendorSoftwareProductObject.setVendorName(vendorLicenseModel.getVendorLicenseName());
342         vendorSoftwareProductObject.setVendorId(vendorLicenseModel.getVendorId());
343         vendorSoftwareProductObject.setIcon("icon");
344         vendorSoftwareProductObject.setLicensingData(licensingData);
345         vendorSoftwareProductObject.setLicensingVersion(vendorLicenseModel.getVersion());
346
347         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
348         HttpRequest http = new HttpRequest();
349         Gson gson = new Gson();
350         String body = gson.toJson(vendorSoftwareProductObject);
351
352         RestResponse response = http.httpSendPost(url, body, headersMap);
353
354         vendorSoftwareProductObject.setVspId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "itemId"));
355         vendorSoftwareProductObject.setComponentId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "version:id"));
356 //              vendorSoftwareProductObject.setVersion(ResponseParser.getValueFromJsonResponse(response.getResponse(), "version:name"));
357         vendorSoftwareProductObject.setAttContact(user.getUserId());
358
359         return new Pair<>(response, vendorSoftwareProductObject);
360     }
361
362     public static RestResponse validateUpload(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
363         Config config = Utils.getConfig();
364         String url = String.format(Urls.VALIDATE_UPLOAD, config.getOnboardingBeHost(), config.getOnboardingBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
365         String userId = user.getUserId();
366
367         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
368         HttpRequest http = new HttpRequest();
369         RestResponse response = http.httpSendPut(url, null, headersMap);
370
371         return response;
372     }
373
374     public static RestResponse uploadHeatPackage(String filepath, String filename, VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
375         Config config = Utils.getConfig();
376         String url = String.format(Urls.UPLOAD_HEAT_PACKAGE, config.getOnboardingBeHost(), config.getOnboardingBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
377         return uploadFile(filepath, filename, url, user);
378     }
379
380     private static RestResponse uploadFile(String filepath, String filename, String url, User user) throws IOException{
381         CloseableHttpResponse response = null;
382
383         MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
384         mpBuilder.addPart("upload", new FileBody(getTestZipFile(filepath, filename)));
385
386         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(user.getUserId());
387         headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data");
388
389         CloseableHttpClient client = HttpClients.createDefault();
390         try {
391             HttpPost httpPost = new HttpPost(url);
392             RestResponse restResponse = new RestResponse();
393
394             Iterator<String> iterator = headersMap.keySet().iterator();
395             while (iterator.hasNext()) {
396                 String key = iterator.next();
397                 String value = headersMap.get(key);
398                 httpPost.addHeader(key, value);
399             }
400             httpPost.setEntity(mpBuilder.build());
401             response = client.execute(httpPost);
402             HttpEntity entity = response.getEntity();
403             String responseBody = null;
404             if (entity != null) {
405                 InputStream instream = entity.getContent();
406                 try {
407                     StringWriter writer = new StringWriter();
408                     IOUtils.copy(instream, writer);
409                     responseBody = writer.toString();
410                 } finally {
411                     instream.close();
412                 }
413             }
414
415             restResponse.setErrorCode(response.getStatusLine().getStatusCode());
416             restResponse.setResponse(responseBody);
417
418             return restResponse;
419
420         } finally {
421             closeResponse(response);
422             closeHttpClient(client);
423
424         }
425     }
426
427     private static void closeResponse(CloseableHttpResponse response) {
428         try {
429             if (response != null) {
430                 response.close();
431             }
432         } catch (IOException e) {
433             System.out.println(String.format("failed to close client or response: %s", e.getMessage()));
434         }
435     }
436
437     private static void closeHttpClient(CloseableHttpClient client) {
438         try {
439             if (client != null) {
440                 client.close();
441             }
442         } catch (IOException e) {
443             System.out.println(String.format("failed to close client or response: %s", e.getMessage()));
444         }
445     }
446
447     private static File getTestZipFile(String filepath, String filename) throws IOException {
448         Config config = Utils.getConfig();
449         String sourceDir = config.getImportResourceTestsConfigDir();
450         java.nio.file.Path filePath;
451         if(filename == null){
452             filePath = FileSystems.getDefault().getPath(filepath);
453         }else{
454             filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename);
455         }
456         return filePath.toFile();
457     }
458
459     public static RestResponse checkinVendorSoftwareProduct(User user, VendorSoftwareProductObject vendorSoftwareProductObject) throws Exception {
460         Config config = Utils.getConfig();
461         String url = String.format(Urls.UPDATE_VSP, config.getOnboardingBeHost(), config.getOnboardingBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
462
463         String userId = user.getUserId();
464         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
465 //              unset vspId, componentId, attContact, onboardingMethod
466         String vspId = vendorSoftwareProductObject.getVspId();
467         String componentId = vendorSoftwareProductObject.getComponentId();
468         String attContact = vendorSoftwareProductObject.getAttContact();
469         String onboardingMethod = vendorSoftwareProductObject.getOnboardingMethod();
470         vendorSoftwareProductObject.setVspId(null);
471         vendorSoftwareProductObject.setComponentId(null);
472         vendorSoftwareProductObject.setAttContact(null);
473         vendorSoftwareProductObject.setOnboardingMethod(null);
474         Gson gson = new Gson();
475         String body = gson.toJson(vendorSoftwareProductObject);
476         HttpRequest http = new HttpRequest();
477         RestResponse response = http.httpSendPut(url, body, headersMap);
478 //              set back vspId, componentId, attContact, onboardingMethod
479         vendorSoftwareProductObject.setVspId(vspId);
480         vendorSoftwareProductObject.setComponentId(componentId);
481         vendorSoftwareProductObject.setAttContact(attContact);
482         vendorSoftwareProductObject.setOnboardingMethod(onboardingMethod);
483
484         return response;
485     }
486
487     public static RestResponse commitVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
488         String messageBody = "{\"action\":\"Commit\",\"commitRequest\":{\"message\":\"commit\"}}";
489         return actionOnComponent(vendorSoftwareProductObject.getVspId(), messageBody, "items", user, vendorSoftwareProductObject.getComponentId());
490     }
491
492     public static RestResponse submitVendorSoftwareProduct(String vspid, User user, String componentId) throws Exception {
493         return actionOnComponent(vspid, "{\"action\":\"Submit\"}", "vendor-software-products", user, componentId);
494     }
495
496     public static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user, String componentId) throws Exception {
497         return actionOnComponent(vspid, "{\"action\":\"Create_Package\"}", "vendor-software-products", user, componentId);
498     }
499
500     public static RestResponse creationMethodVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
501         String messageBody = "{\"description\":\"2.0\",\"creationMethod\":\"major\"}";
502         return createMethodVendorSoftwareProduct(vendorSoftwareProductObject, messageBody, "items", user);
503     }
504
505     private static RestResponse createMethodVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, String body, String onboardComponent, User user) throws Exception {
506         Config config = Utils.getConfig();
507         String url = String.format(Urls.CREATE_METHOD, config.getOnboardingBeHost(), config.getOnboardingBePort(), onboardComponent, vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
508         String userId = user.getUserId();
509         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
510
511         HttpRequest http = new HttpRequest();
512         RestResponse response = http.httpSendPost(url, body, headersMap);
513         if(response.getErrorCode().intValue() == 200) {
514             vendorSoftwareProductObject.setComponentId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "id"));
515         }
516         return response;
517     }
518
519     public static VendorSoftwareProductObject updateVSPWithNewVLMParameters(VendorSoftwareProductObject vendorSoftwareProductObject, VendorLicenseModel vendorLicenseModel, User user) throws Exception {
520
521         RestResponse createMethod = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user);
522         assertEquals("did not succeed to checkout new VSP", 200, createMethod.getErrorCode().intValue());
523 //        vendorSoftwareProductObject.setComponentId(ResponseParser.getValueFromJsonResponse(createMethod.getResponse(), "id"));
524
525         String licensingVersion = vendorLicenseModel.getVersion();
526         LicensingData licensingData = new LicensingData(
527             vendorLicenseModel.getVendorLicenseAgreementId(), Arrays.asList(vendorLicenseModel.getFeatureGroupId()));
528         vendorSoftwareProductObject.setVendorId(vendorLicenseModel.getVendorId());
529         vendorSoftwareProductObject.setVendorName(vendorLicenseModel.getVendorLicenseName());
530         vendorSoftwareProductObject.setLicensingVersion(licensingVersion);
531         vendorSoftwareProductObject.setLicensingData(licensingData);
532
533         VendorSoftwareProductObjectReqDetails vendorSoftwareProductObjectReqDetails = new VendorSoftwareProductObjectReqDetails(
534                 vendorSoftwareProductObject.getName(), vendorSoftwareProductObject.getDescription(), vendorSoftwareProductObject.getCategory(),
535                 vendorSoftwareProductObject.getSubCategory(), vendorSoftwareProductObject.getVendorId(), vendorSoftwareProductObject.getVendorName(),
536                 vendorSoftwareProductObject.getLicensingVersion(), vendorSoftwareProductObject.getLicensingData(),
537                 null, null, null, vendorSoftwareProductObject.getIcon() );
538
539         Gson gson = new Gson();
540         String body = gson.toJson(vendorSoftwareProductObjectReqDetails);
541         RestResponse updateResponse = updateVendorSoftwareProduct(vendorSoftwareProductObject, body, user);
542         assertEquals("did not succeed to update VSP", 200, updateResponse.getErrorCode().intValue());
543
544         prepareVspForUse(user, vendorSoftwareProductObject, true);
545
546         return vendorSoftwareProductObject;
547     }
548
549     public static RestResponse updateVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, String body, User user) throws Exception {
550
551         Config config = Utils.getConfig();
552         String url = String.format(Urls.UPDATE_VSP, config.getOnboardingBeHost(), config.getOnboardingBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
553         String userId = user.getUserId();
554
555         Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
556         HttpRequest http = new HttpRequest();
557
558         RestResponse response = http.httpSendPut(url, body, headersMap);
559         return response;
560     }
561
562 //      private static void importUpdateVSP(Pair<String, Map<String, String>> vsp, boolean isUpdate) throws Exception{
563 //              String vspName = vsp.left;
564 //              Map<String, String> vspMetadata = vsp.right;
565 //              boolean vspFound = HomePage.searchForVSP(vspName);
566 //
567 //              if (vspFound){
568 //
569 //                      List<WebElement> elemenetsFromTable = HomePage.getElemenetsFromTable();
570 ////                    WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30);
571 ////                    WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1)));
572 ////                    findElement.click();
573 //                      elemenetsFromTable.get(1).click();
574 //                      GeneralUIUtils.waitForLoader();
575 //
576 //                      if (isUpdate){
577 //                              GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue());
578 //
579 //                      }
580 //                      else{
581 //                              GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue());
582 //                      }
583 //
584 //                      String lifeCycleState = ResourceGeneralPage.getLifeCycleState();
585 //                      boolean needCheckout = lifeCycleState.equals(LifeCycleStateEnum.CHECKIN.getValue()) || lifeCycleState.equals(LifeCycleStateEnum.CERTIFIED.getValue());
586 //                      if (needCheckout)
587 //                      {
588 //                              try {
589 //                                      ResourceGeneralPage.clickCheckoutButton();
590 //                                      Assert.assertTrue(ResourceGeneralPage.getLifeCycleState().equals(LifeCycleStateEnum.CHECKOUT.getValue()), "Did not succeed to checkout");
591 //
592 //                              } catch (Exception e) {
593 //                                      ExtentTestActions.log(Status.ERROR, "Did not succeed to checkout");
594 //                                      e.printStackTrace();
595 //                              }
596 //                              GeneralUIUtils.waitForLoader();
597 //                      }
598 //
599 //                      //Metadata verification
600 //                      VfVerificator.verifyOnboardedVnfMetadata(vspName, vspMetadata);
601 //
602 //                      ExtentTestActions.log(Status.INFO, "Clicking create/update VNF");
603 //                      String duration = GeneralUIUtils.getActionDuration(() -> waitUntilVnfCreated());
604 //                  ExtentTestActions.log(Status.INFO, "Succeeded in importing/updating " + vspName, duration);
605 //              }
606 //              else{
607 //                      Assert.fail("Did not find VSP named " + vspName);
608 //              }
609 //      }
610
611 //      private static void waitUntilVnfCreated() {
612 //              GeneralUIUtils.clickOnElementByTestIdWithoutWait(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue());
613 //              GeneralUIUtils.waitForLoader(60*10);
614 //              GeneralUIUtils.waitForAngular();
615 //              GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue());
616 //      }
617 //
618 //      public static void updateVSP(Pair<String, Map<String, String>> vsp) throws Exception{
619 //              ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left);
620 //              importUpdateVSP(vsp, true);
621 //      }
622 //
623 //      public static void importVSP(Pair<String, Map<String, String>> vsp) throws Exception{
624 //              ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left);
625 //              importUpdateVSP(vsp, false);
626 //      }
627 //
628 //      public static void updateVnfAndValidate(String filepath, Pair<String, Map<String, String>> vsp, String updatedVnfFile, User user) throws Exception, Throwable {
629 //              ExtentTestActions.log(Status.INFO, String.format("Going to update the VNF with %s......", updatedVnfFile));
630 //              System.out.println(String.format("Going to update the VNF with %s......", updatedVnfFile));
631 //
632 //              Map<String, String> vspMap = vsp.right;
633 //              String vspId = vspMap.get("vspId");
634 //
635 //              updateVendorSoftwareProduct(vspId, updatedVnfFile, filepath, user);
636 //              HomePage.showVspRepository();
637 //              updateVSP(vsp);
638 //              ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
639 //              DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, updatedVnfFile);
640 //      }
641 //
642 //      public static Pair<String, Map<String, String>> onboardAndValidate(String filepath, String vnfFile, User user) throws Exception {
643 //              ExtentTestActions.log(Status.INFO, String.format("Going to onboard the VNF %s", vnfFile));
644 //              System.out.println(String.format("Going to onboard the VNF %s", vnfFile));
645 //
646 //              AmdocsLicenseMembers amdocsLicenseMembers = createVendorLicense(user);
647 //              Pair<String, Map<String, String>> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user, amdocsLicenseMembers);
648 //              String vspName = createVendorSoftwareProduct.left;
649 //
650 //              DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId"));
651 //              File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir();
652 //
653 //              ExtentTestActions.log(Status.INFO, String.format("Searching for onboarded %s", vnfFile));
654 //              HomePage.showVspRepository();
655 //              ExtentTestActions.log(Status.INFO,String.format("Going to import %s", vnfFile.substring(0, vnfFile.indexOf("."))));
656 //              importVSP(createVendorSoftwareProduct);
657 //
658 //              ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
659 //
660 //              // Verify deployment artifacts
661 //              Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath());
662 //
663 //              LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment"));
664 //              ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts);
665 //
666 //              List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")).
667 //                                                                                                                                               map(e -> e.getFileName()).
668 //                                                                                                                                               collect(Collectors.toList());
669 //
670 //              validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR);
671 //
672 //              DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile);
673 //              return createVendorSoftwareProduct;
674 //      }
675 //
676 //      public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts,
677 //                      List<String> heatEnvFilesFromCSAR) {
678 //              String artifactVersion;
679 //              String artifactName;
680 //
681 //              for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) {
682 //                      artifactVersion = "1";
683 //
684 //                      if(deploymentArtifact.getType().equals("HEAT_ENV")) {
685 //                              continue;
686 //                      } else if(deploymentArtifact.getFileName().contains(".")) {
687 //                              artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf("."));
688 //                      } else {
689 //                              artifactName = deploymentArtifact.getFileName().trim();
690 //                      }
691 //
692 //                      if (heatEnvFilesFromCSAR.contains(artifactName + ".env")){
693 //                              artifactVersion = "2";
694 //                      }
695 //                      ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType());
696 //              }
697 //      }
698
699
700     private static VendorSoftwareProductObject fillVendorSoftwareProductObjectWithMetaData(String vnfFile, VendorSoftwareProductObject createVendorSoftwareProduct) {
701         VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject();
702         vendorSoftwareProductObject.setAttContact(createVendorSoftwareProduct.getAttContact());
703         vendorSoftwareProductObject.setCategory(createVendorSoftwareProduct.getCategory());
704         vendorSoftwareProductObject.setComponentId(createVendorSoftwareProduct.getComponentId());
705         vendorSoftwareProductObject.setDescription(createVendorSoftwareProduct.getDescription());
706         vendorSoftwareProductObject.setSubCategory(createVendorSoftwareProduct.getSubCategory());
707         vendorSoftwareProductObject.setVendorName(createVendorSoftwareProduct.getVendorName());
708         vendorSoftwareProductObject.setVspId(createVendorSoftwareProduct.getVspId());
709         vendorSoftwareProductObject.setName(createVendorSoftwareProduct.getName());
710         String[] arrFileNameAndExtension = vnfFile.split("\\.");
711         vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage");
712         vendorSoftwareProductObject.setNetworkPackageName(arrFileNameAndExtension[0]);
713         vendorSoftwareProductObject.setOnboardingOrigin(arrFileNameAndExtension[1]);
714
715         return vendorSoftwareProductObject;
716     }
717
718     public static void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject,
719                                                                 User user, String filepath,
720                                                                 String heatFileName) throws Exception {
721
722         RestResponse createMethod = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user);
723         assertEquals("did not succeed to createMethod for new VSP", 200, createMethod.getErrorCode().intValue());
724
725         RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName, vendorSoftwareProductObject, user);
726         assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
727
728         RestResponse validateUpload = validateUpload(vendorSoftwareProductObject, user);
729         assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue());
730
731         prepareVspForUse(user,vendorSoftwareProductObject, true);
732     }
733
734     public static RestResponse archiveVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
735         String messageBody = "{\"action\":\"ARCHIVE\"}";
736         return actionOnComponent(vendorSoftwareProductObject.getVspId(), messageBody, "items", user);
737     }
738
739     public static RestResponse restoreVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
740         String messageBody = "{\"action\":\"RESTORE\"}";
741         return actionOnComponent(vendorSoftwareProductObject.getVspId(), messageBody, "items", user);
742     }
743
744 }