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