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