Build sanity docker execute automation
[sdc.git] / test-apis-ci / src / main / java / org / openecomp / sdc / ci / tests / utils / general / OnboardingUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.ci.tests.utils.general;
22
23 import com.aventstack.extentreports.Status;
24 import com.clearspring.analytics.util.Pair;
25 import org.apache.commons.io.IOUtils;
26 import org.apache.http.HttpEntity;
27 import org.apache.http.client.ClientProtocolException;
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.JSONException;
35 import org.json.JSONObject;
36 import org.json.simple.JSONArray;
37 import org.json.simple.JSONValue;
38 import org.openecomp.sdc.be.model.User;
39 import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
40 import org.openecomp.sdc.ci.tests.api.ExtentTestActions;
41 import org.openecomp.sdc.ci.tests.config.Config;
42 import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers;
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.ResponseParser;
48
49 import java.io.*;
50 import java.nio.file.FileSystems;
51 import java.util.*;
52
53 import static org.testng.AssertJUnit.assertEquals;
54
55 public class OnboardingUtils {
56
57         protected static List<String> exludeVnfList = Arrays.asList("2016-197_vscp_vscp-fw_1610_e2e.zip", "2016-281_vProbes_BE_11_1_f_30_1610_e2e.zip", 
58                         "2016-282_vProbes_FE_11_1_f_30_1610_e2e.zip", "2016-044_vfw_fnat_30_1607_e2e.zip", "2017-376_vMOG_11_1.zip", "vMOG.zip", 
59                         
60                         
61                         "vMRF_USP_AIC3.0_1702.zip", "2016-211_vprobesbe_vprobes_be_30_1610_e2e.zip", "2016-005_vprobesfe_vprobes_fe_30_1607_e2e.zip", 
62                         "vMRF_RTT.zip", "2016-006_vvm_vvm_30_1607_e2e.zip", "2016-001_vvm_vvm_30_1607_e2e.zip");
63
64         protected static List<String> exludeVnfListForToscaParser = Arrays.asList("2016-043_vsaegw_fdnt_30_1607_e2e.zip", "vIRC_CC.zip", 
65                         "2016-045_vlb_lmsp_30_1607_e2e.zip", "2016-050_vdns_vmdns_30_1607_e2e.zip", 
66                         "2016-247_mns_mns_30_1610_e2e.zip", "2016-044_vfw_fcgi_30_1607_e2e.zip");
67         
68         public OnboardingUtils() {
69         }
70
71         public static Pair<String, Map<String, String>> createVendorSoftwareProduct(String HeatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers)
72                         throws Exception {
73                 Pair<String, Map<String, String>> pair = createVSP(HeatFileName, filepath, user, amdocsLicenseMembers);
74                 
75                 String vspid = pair.right.get("vspId");
76                                 
77                 prepareVspForUse(user, vspid);
78                 
79                 return pair;
80         }
81
82         public static void prepareVspForUse(User user, String vspid) throws Exception {
83                 RestResponse checkin = checkinVendorSoftwareProduct(vspid, user);
84                 assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue());
85
86                 RestResponse submit = submitVendorSoftwareProduct(vspid, user);
87                 assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue());
88
89                 RestResponse createPackage = createPackageOfVendorSoftwareProduct(vspid, user);
90                 assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue());
91
92                 ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor software product");
93         }
94
95         public static Pair<String, Map<String, String>> createVSP(String HeatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers) throws Exception {
96                 String vspName = handleFilename(HeatFileName);
97                 
98                 ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor software product");
99                 
100                 Pair<RestResponse, Map<String, String>> createNewVspPair = createNewVendorSoftwareProduct(vspName, amdocsLicenseMembers, user);
101                 RestResponse createNewVendorSoftwareProduct = createNewVspPair.left;
102                 assertEquals("did not succeed to create new VSP", 200,createNewVendorSoftwareProduct.getErrorCode().intValue());
103                 String vspid = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "vspId");
104                 String componentId = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "componentId");
105                 
106                 Map<String, String> vspMeta = createNewVspPair.right;
107                 Map<String, String> vspObject = new HashMap<String, String>();
108                 Iterator<String> iterator = vspMeta.keySet().iterator();
109                 while(iterator.hasNext()){
110                         Object key = iterator.next();
111                         Object value = vspMeta.get(key);
112                         vspObject.put(key.toString(), value.toString());
113                 }
114                 vspObject.put("vspId", vspid);
115                 vspObject.put("componentId", componentId);
116                 vspObject.put("vendorName", amdocsLicenseMembers.getVendorLicenseName());
117                 vspObject.put("attContact", user.getUserId());
118                 
119                 RestResponse uploadHeatPackage = uploadHeatPackage(filepath, HeatFileName, vspid, user);
120                 assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
121                 
122                 RestResponse validateUpload = validateUpload(vspid, user);
123                 assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue());
124                 
125                 Pair<String, Map<String, String>> pair = new Pair<String, Map<String, String>>(vspName, vspObject);
126                 
127                 return pair;
128         }
129         
130         public static void updateVspWithVfcArtifacts(String filepath, String vspId, String updatedSnmpPoll, String updatedSnmpTrap, String componentId, User user) throws Exception{
131                 RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user);
132                 assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
133                 ExtentTestActions.log(Status.INFO, "Deleting SNMP POLL");
134                 deleteSnmpArtifact(componentId, vspId, user, SnmpTypeEnum.SNMP_POLL);
135                 ExtentTestActions.log(Status.INFO, "Deleting SNMP TRAP");
136                 deleteSnmpArtifact(componentId, vspId, user, SnmpTypeEnum.SNMP_TRAP);
137                 addVFCArtifacts(filepath, updatedSnmpPoll, updatedSnmpTrap, vspId, user, componentId);
138                 prepareVspForUse(user, vspId);
139         }
140         
141         public static String updateVendorSoftwareProduct(String vspId, String HeatFileName, String filepath, User user)
142                         throws Exception, Throwable {
143                 String vspName = handleFilename(HeatFileName);
144                 ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to update the vendor software product");
145
146                 RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user);
147                 assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
148
149                 RestResponse uploadHeatPackage = uploadHeatPackage(filepath, HeatFileName, vspId, user);
150                 assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
151                 
152                 RestResponse validateUpload = validateUpload(vspId, user);
153                 assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue());
154                 
155                 RestResponse checkin = checkinVendorSoftwareProduct(vspId, user);
156                 assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue());
157
158
159                 RestResponse submit = submitVendorSoftwareProduct(vspId, user);
160                 assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue());
161
162                 RestResponse createPackage = createPackageOfVendorSoftwareProduct(vspId, user);
163                 assertEquals("did not succeed to update package of VSP ", 200, createPackage.getErrorCode().intValue());
164
165                 ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in updating the vendor software product");
166
167                 return vspName;
168         }
169
170         public static String handleFilename(String heatFileName) {
171                 final String namePrefix = "ciVFOnboarded-";
172                 final String nameSuffix = "-" + getShortUUID();
173
174                 String subHeatFileName = heatFileName.substring(0, heatFileName.lastIndexOf("."));
175
176                 if ((namePrefix + subHeatFileName + nameSuffix).length() >= 50) {
177                         subHeatFileName = subHeatFileName.substring(0, 50 - namePrefix.length() - nameSuffix.length());
178                 }
179
180                 if (subHeatFileName.contains("(") || subHeatFileName.contains(")")) {
181                         subHeatFileName = subHeatFileName.replace("(", "-");
182                         subHeatFileName = subHeatFileName.replace(")", "-");
183                 }
184
185                 String vnfName = namePrefix + subHeatFileName + nameSuffix;
186                 return vnfName;
187         }
188         
189         public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, String vspid, User user, String vspComponentId) throws Exception{
190                 vspComponentId = (vspComponentId == null) ? getVSPComponentId(vspid, user) : vspComponentId;
191                 if (vspComponentId != null){
192                         if (snmpPoll != null){
193                                 ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP POLL with the file " + snmpPoll);
194                                 RestResponse uploadSnmpPollArtifact = uploadSnmpPollArtifact(filepath, snmpPoll, vspid, user, vspComponentId);
195                                 assertEquals("Did not succeed to add SNMP POLL", 200, uploadSnmpPollArtifact.getErrorCode().intValue());
196                         }
197                         if (snmpTrap != null){
198                                 ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP TRAP with the file " + snmpTrap);
199                                 RestResponse uploadSnmpTrapArtifact = uploadSnmpTrapArtifact(filepath, snmpTrap, vspid, user, vspComponentId);
200                                 assertEquals("Did not succeed to add SNMP TRAP", 200, uploadSnmpTrapArtifact.getErrorCode().intValue());
201                         }
202                 }
203                 
204                 return vspComponentId;
205         }
206         
207         public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, String vspid, User user) throws Exception{
208                 return addVFCArtifacts(filepath, snmpPoll, snmpTrap, vspid, user, null);
209         }
210
211         private static RestResponse uploadSnmpPollArtifact(String filepath, String zipArtifact, String vspid, User user,
212                         String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException {
213                 Config config = Utils.getConfig();
214                 String snmpPollUrl = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/snmp/upload", 
215                                 config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId);
216                 return uploadFile(filepath, zipArtifact, snmpPollUrl, user);
217         }
218         
219         private static RestResponse uploadSnmpTrapArtifact(String filepath, String zipArtifact, String vspid, User user,
220                         String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException {
221                 Config config = Utils.getConfig();
222                 String snmpTrapUrl = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/snmp-trap/upload", 
223                                 config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId);
224                 return uploadFile(filepath, zipArtifact, snmpTrapUrl, user);
225         }
226         
227         private static RestResponse deleteSnmpArtifact(String componentId, String vspId, User user, SnmpTypeEnum snmpType) throws Exception
228         {
229                 Config config = Utils.getConfig();
230                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/%s", 
231                                 config.getCatalogBeHost(),config.getCatalogBePort(), vspId, componentId, snmpType.getValue());
232                 String userId = user.getUserId();
233
234                 Map<String, String> headersMap = prepareHeadersMap(userId);
235
236                 HttpRequest http = new HttpRequest();
237                 RestResponse response = http.httpSendDelete(url, headersMap);
238                 return response;
239         }
240         
241         
242
243         private static String getVSPComponentId(String vspid, User user) throws Exception, JSONException {
244                 RestResponse components = getVSPComponents(vspid, user);
245                 String response = components.getResponse();
246                 Map<String, Object> responseMap = (Map<String, Object>) JSONValue.parse(response);
247                 JSONArray results = (JSONArray)responseMap.get("results");
248                 for (Object res : results){
249                         Map<String, Object> compMap= (Map<String, Object>) JSONValue.parse(res.toString());
250                         String componentId = compMap.get("id").toString();
251                         return componentId;
252                 }
253                 return null;
254         }
255         
256         private static RestResponse getVSPComponents(String vspid, User user) throws Exception{
257                 Config config = Utils.getConfig();
258                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components", config.getCatalogBeHost(),config.getCatalogBePort(), vspid);
259                 String userId = user.getUserId();
260
261                 Map<String, String> headersMap = prepareHeadersMap(userId);
262
263                 HttpRequest http = new HttpRequest();
264                 RestResponse response = http.httpSendGet(url, headersMap);
265                 return response;
266         }
267
268         public static AmdocsLicenseMembers createVendorLicense(User user) throws Exception {
269                 
270                 AmdocsLicenseMembers amdocsLicenseMembers;
271                 ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor license");
272                 String vendorLicenseName = "ciLicense" + getShortUUID();
273                 RestResponse vendorLicenseResponse = createVendorLicenseModels_1(vendorLicenseName, user);
274                 assertEquals("did not succeed to create vendor license model", 200, vendorLicenseResponse.getErrorCode().intValue());
275                 String vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "value");
276
277                 RestResponse vendorKeyGroupsResponse = createVendorKeyGroups_2(vendorId, user);
278                 assertEquals("did not succeed to create vendor key groups", 200, vendorKeyGroupsResponse.getErrorCode().intValue());
279                 String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), "value");
280
281                 RestResponse vendorEntitlementPool = createVendorEntitlementPool_3(vendorId, user);
282                 assertEquals("did not succeed to create vendor entitlement pool", 200, vendorEntitlementPool.getErrorCode().intValue());
283                 String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(), "value");
284
285                 RestResponse vendorLicenseFeatureGroups = createVendorLicenseFeatureGroups_4(vendorId, keyGroupId, entitlementPoolId, user);
286                 assertEquals("did not succeed to create vendor license feature groups", 200, vendorLicenseFeatureGroups.getErrorCode().intValue());
287                 String featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value");
288
289                 RestResponse vendorLicenseAgreement = createVendorLicenseAgreement_5(vendorId, featureGroupId, user);
290                 assertEquals("did not succeed to create vendor license agreement", 200, vendorLicenseAgreement.getErrorCode().intValue());
291                 String vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), "value");
292
293                 RestResponse checkinVendorLicense = checkinVendorLicense(vendorId, user);
294                 assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue());
295
296                 RestResponse submitVendorLicense = submitVendorLicense(vendorId, user);
297                 assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue());
298
299                 ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor license");
300
301                 amdocsLicenseMembers = new AmdocsLicenseMembers(vendorId, vendorLicenseName, vendorLicenseAgreementId, featureGroupId);
302                 
303                 return amdocsLicenseMembers;
304         }
305
306         private static String getShortUUID() {
307                 return UUID.randomUUID().toString().split("-")[0];
308         }
309
310         private static RestResponse actionOnComponent(String vspid, String action, String onboardComponent, User user)
311                         throws Exception {
312                 Config config = Utils.getConfig();
313                 String url = String.format("http://%s:%s/onboarding-api/v1.0/" + onboardComponent + "/%s/versions/0.1/actions",
314                                 config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
315                 String userId = user.getUserId();
316
317                 JSONObject jObject = new JSONObject();
318                 jObject.put("action", action);
319
320                 Map<String, String> headersMap = prepareHeadersMap(userId);
321
322                 HttpRequest http = new HttpRequest();
323                 RestResponse response = http.httpSendPut(url, jObject.toString(), headersMap);
324                 return response;
325         }
326
327         public static RestResponse checkinVendorLicense(String vspid, User user) throws Exception {
328                 return actionOnComponent(vspid, "Checkin", "vendor-license-models", user);
329         }
330
331         public static RestResponse submitVendorLicense(String vspid, User user) throws Exception {
332                 return actionOnComponent(vspid, "Submit", "vendor-license-models", user);
333         }
334
335         public static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception {
336                 Config config = Utils.getConfig();
337                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models", config.getCatalogBeHost(),
338                                 config.getCatalogBePort());
339                 String userId = user.getUserId();
340
341                 JSONObject jObject = new JSONObject();
342                 jObject.put("vendorName", name);
343                 jObject.put("description", "new vendor license model");
344                 jObject.put("iconRef", "icon");
345
346                 Map<String, String> headersMap = prepareHeadersMap(userId);
347
348                 HttpRequest http = new HttpRequest();
349                 RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap);
350                 return response;
351
352         }
353
354         public static RestResponse createVendorLicenseAgreement_5(String vspid, String featureGroupId, User user)
355                         throws Exception {
356                 Config config = Utils.getConfig();
357                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/license-agreements",
358                                 config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
359                 String userId = user.getUserId();
360
361                 JSONObject licenseTermpObject = new JSONObject();
362                 licenseTermpObject.put("choice", "Fixed_Term");
363                 licenseTermpObject.put("other", "");
364
365                 JSONObject jObjectBody = new JSONObject();
366                 jObjectBody.put("name", "abc");
367                 jObjectBody.put("description", "new vendor license agreement");
368                 jObjectBody.put("requirementsAndConstrains", "abc");
369                 jObjectBody.put("licenseTerm", licenseTermpObject);
370                 jObjectBody.put("addedFeatureGroupsIds", Arrays.asList(featureGroupId).toArray());
371
372                 Map<String, String> headersMap = prepareHeadersMap(userId);
373
374                 HttpRequest http = new HttpRequest();
375                 RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
376                 return response;
377         }
378
379         public static RestResponse createVendorLicenseFeatureGroups_4(String vspid, String licenseKeyGroupId,
380                         String entitlementPoolId, User user) throws Exception {
381                 Config config = Utils.getConfig();
382                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/feature-groups",
383                                 config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
384                 String userId = user.getUserId();
385
386                 JSONObject jObject = new JSONObject();
387                 jObject.put("name", "xyz");
388                 jObject.put("description", "new vendor license feature groups");
389                 jObject.put("partNumber", "123abc456");
390                 jObject.put("manufacturerReferenceNumber", "5");
391                 jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray());
392                 jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray());
393
394                 Map<String, String> headersMap = prepareHeadersMap(userId);
395
396                 HttpRequest http = new HttpRequest();
397                 RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap);
398                 return response;
399
400         }
401
402         public static RestResponse createVendorEntitlementPool_3(String vspid, User user) throws Exception {
403                 Config config = Utils.getConfig();
404                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/entitlement-pools",
405                                 config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
406                 String userId = user.getUserId();
407
408                 JSONObject jEntitlementMetricObject = new JSONObject();
409                 jEntitlementMetricObject.put("choice", "CPU");
410                 jEntitlementMetricObject.put("other", "");
411
412                 JSONObject jAggregationFunctionObject = new JSONObject();
413                 jAggregationFunctionObject.put("choice", "Peak");
414                 jAggregationFunctionObject.put("other", "");
415
416                 JSONObject jOperationalScope = new JSONObject();
417                 jOperationalScope.put("choices", Arrays.asList("Availability_Zone").toArray());
418                 jOperationalScope.put("other", "");
419
420                 JSONObject jTimeObject = new JSONObject();
421                 jTimeObject.put("choice", "Hour");
422                 jTimeObject.put("other", "");
423
424                 JSONObject jObjectBody = new JSONObject();
425                 jObjectBody.put("name", "def"+ getShortUUID());
426                 jObjectBody.put("description", "new vendor license entitlement pool");
427                 jObjectBody.put("thresholdValue", "23");
428                 jObjectBody.put("thresholdUnits", "Absolute");
429                 jObjectBody.put("entitlementMetric", jEntitlementMetricObject);
430                 jObjectBody.put("increments", "abcd");
431                 jObjectBody.put("aggregationFunction", jAggregationFunctionObject);
432                 jObjectBody.put("operationalScope", jOperationalScope);
433                 jObjectBody.put("time", jTimeObject);
434                 jObjectBody.put("manufacturerReferenceNumber", "123aaa");
435
436                 Map<String, String> headersMap = prepareHeadersMap(userId);
437
438                 HttpRequest http = new HttpRequest();
439                 RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
440                 return response;
441         }
442
443         public static RestResponse createVendorKeyGroups_2(String vspid, User user) throws Exception {
444                 Config config = Utils.getConfig();
445                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/license-key-groups",
446                                 config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
447                 String userId = user.getUserId();
448
449                 JSONObject jOperationalScope = new JSONObject();
450                 jOperationalScope.put("choices", Arrays.asList("Tenant").toArray());
451                 jOperationalScope.put("other", "");
452
453                 JSONObject jObjectBody = new JSONObject();
454                 jObjectBody.put("name", "keyGroup" + getShortUUID());
455                 jObjectBody.put("description", "new vendor license key group");
456                 jObjectBody.put("operationalScope", jOperationalScope);
457                 jObjectBody.put("type", "Universal");
458
459                 Map<String, String> headersMap = prepareHeadersMap(userId);
460
461                 HttpRequest http = new HttpRequest();
462                 RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
463                 return response;
464         }
465
466         public static Pair<RestResponse, Map<String, String>> createNewVendorSoftwareProduct(String name, AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception {
467                 Map<String, String> vspMetadta = new HashMap<String, String>();
468                 
469                 Config config = Utils.getConfig();
470                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products",
471                                 config.getCatalogBeHost(), config.getCatalogBePort());
472
473                 String userId = user.getUserId();
474
475                 JSONObject jlicensingDataObj = new JSONObject();
476                 jlicensingDataObj.put("licenseAgreement", amdocsLicenseMembers.getVendorLicenseAgreementId());
477                 jlicensingDataObj.put("featureGroups", Arrays.asList(amdocsLicenseMembers.getFeatureGroupId()).toArray());
478                 
479                 JSONObject jlicensingVersionObj = new JSONObject();
480                 jlicensingVersionObj.put("id", "1.0");
481                 jlicensingVersionObj.put("label", "1.0");
482
483                 JSONObject jObject = new JSONObject();
484                 jObject.put("name", name);
485                 jObject.put("description", "new VSP description");
486                 jObject.put("category", "resourceNewCategory.generic");
487                 jObject.put("subCategory", "resourceNewCategory.generic.database");
488                 jObject.put("onboardingMethod", "NetworkPackage");
489                 jObject.put("licensingVersion", jlicensingVersionObj);
490                 jObject.put("vendorName", amdocsLicenseMembers.getVendorLicenseName());
491                 jObject.put("vendorId", amdocsLicenseMembers.getVendorId());
492                 jObject.put("icon", "icon");
493                 jObject.put("licensingData", jlicensingDataObj);
494                 
495                 vspMetadta.put("description", jObject.getString("description"));
496                 vspMetadta.put("category", jObject.getString("category"));
497                 vspMetadta.put("subCategory", jObject.getString("subCategory").split("\\.")[2]);
498                 
499                 Map<String, String> headersMap = prepareHeadersMap(userId);
500                 HttpRequest http = new HttpRequest();
501
502                 RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap);
503                 return new Pair<RestResponse, Map<String, String>>(response, vspMetadta);
504         }
505         
506         public static RestResponse validateUpload(String vspid, User user) throws Exception {
507                 Config config = Utils.getConfig();
508                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/orchestration-template-candidate/process",
509                                 config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
510
511                 String userId = user.getUserId();
512
513                 Map<String, String> headersMap = prepareHeadersMap(userId);
514                 HttpRequest http = new HttpRequest();
515                 
516                 String body =null;
517
518                 RestResponse response = http.httpSendPut(url, body, headersMap);
519
520                 return response;
521         }
522
523         public static RestResponse uploadHeatPackage(String filepath, String filename, String vspid, User user) throws Exception {
524                 Config config = Utils.getConfig();
525                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/orchestration-template-candidate", config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
526                 return uploadFile(filepath, filename, url, user);
527         }
528
529         private static RestResponse uploadFile(String filepath, String filename, String url, User user)
530                         throws FileNotFoundException, IOException, ClientProtocolException {
531                 CloseableHttpResponse response = null;
532
533                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
534                 mpBuilder.addPart("upload", new FileBody(getTestZipFile(filepath, filename)));
535
536                 Map<String, String> headersMap = prepareHeadersMap(user.getUserId());
537                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data");
538
539                 CloseableHttpClient client = HttpClients.createDefault();
540                 try {
541                         HttpPost httpPost = new HttpPost(url);
542                         RestResponse restResponse = new RestResponse();
543
544                         Iterator<String> iterator = headersMap.keySet().iterator();
545                         while (iterator.hasNext()) {
546                                 String key = iterator.next();
547                                 String value = headersMap.get(key);
548                                 httpPost.addHeader(key, value);
549                         }
550                         httpPost.setEntity(mpBuilder.build());
551                         response = client.execute(httpPost);
552                         HttpEntity entity = response.getEntity();
553                         String responseBody = null;
554                         if (entity != null) {
555                                 InputStream instream = entity.getContent();
556                                 StringWriter writer = new StringWriter();
557                                 IOUtils.copy(instream, writer);
558                                 responseBody = writer.toString();
559                                 try {
560
561                                 } finally {
562                                         instream.close();
563                                 }
564                         }
565
566                         restResponse.setErrorCode(response.getStatusLine().getStatusCode());
567                         restResponse.setResponse(responseBody);
568
569                         return restResponse;
570
571                 } finally {
572                         closeResponse(response);
573                         closeHttpClient(client);
574
575                 }
576         }
577
578         private static void closeResponse(CloseableHttpResponse response) {
579                 try {
580                         if (response != null) {
581                                 response.close();
582                         }
583                 } catch (IOException e) {
584                         System.out.println(String.format("failed to close client or response: %s", e.getMessage()));
585                 }
586         }
587
588         private static void closeHttpClient(CloseableHttpClient client) {
589                 try {
590                         if (client != null) {
591                                 client.close();
592                         }
593                 } catch (IOException e) {
594                         System.out.println(String.format("failed to close client or response: %s", e.getMessage()));
595                 }
596         }
597
598         private static File getTestZipFile(String filepath, String filename) throws IOException {
599                 Config config = Utils.getConfig();
600                 String sourceDir = config.getImportResourceTestsConfigDir();
601                 java.nio.file.Path filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename);
602                 return filePath.toFile();
603         }
604
605         public static RestResponse checkinVendorSoftwareProduct(String vspid, User user) throws Exception {
606                 return actionOnComponent(vspid, "Checkin", "vendor-software-products", user);
607         }
608         
609         private static RestResponse checkoutVendorSoftwareProduct(String vspid, User user) throws Exception {
610                 return actionOnComponent(vspid, "Checkout", "vendor-software-products", user);
611         }
612
613         public static RestResponse submitVendorSoftwareProduct(String vspid, User user) throws Exception {
614                 return actionOnComponent(vspid, "Submit", "vendor-software-products", user);
615         }
616
617         public static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user) throws Exception {
618                 return actionOnComponent(vspid, "Create_Package", "vendor-software-products", user);
619         }
620
621         protected static Map<String, String> prepareHeadersMap(String userId) {
622                 Map<String, String> headersMap = new HashMap<String, String>();
623                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
624                 headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
625                 headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
626                 return headersMap;
627         }
628
629         
630 //      private static void importUpdateVSP(Pair<String, Map<String, String>> vsp, boolean isUpdate) throws Exception{
631 //              String vspName = vsp.left;
632 //              Map<String, String> vspMetadata = vsp.right;
633 //              boolean vspFound = HomePage.searchForVSP(vspName);
634 //
635 //              if (vspFound){
636 //
637 //                      List<WebElement> elemenetsFromTable = HomePage.getElemenetsFromTable();
638 ////                    WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30);
639 ////                    WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1)));
640 ////                    findElement.click();
641 //                      elemenetsFromTable.get(1).click();
642 //                      GeneralUIUtils.waitForLoader();
643 //
644 //                      if (isUpdate){
645 //                              GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue());
646 //
647 //                      }
648 //                      else{
649 //                              GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue());
650 //                      }
651 //
652 //                      String lifeCycleState = ResourceGeneralPage.getLifeCycleState();
653 //                      boolean needCheckout = lifeCycleState.equals(LifeCycleStateEnum.CHECKIN.getValue()) || lifeCycleState.equals(LifeCycleStateEnum.CERTIFIED.getValue());
654 //                      if (needCheckout)
655 //                      {
656 //                              try {
657 //                                      ResourceGeneralPage.clickCheckoutButton();
658 //                                      Assert.assertTrue(ResourceGeneralPage.getLifeCycleState().equals(LifeCycleStateEnum.CHECKOUT.getValue()), "Did not succeed to checkout");
659 //
660 //                              } catch (Exception e) {
661 //                                      ExtentTestActions.log(Status.ERROR, "Did not succeed to checkout");
662 //                                      e.printStackTrace();
663 //                              }
664 //                              GeneralUIUtils.waitForLoader();
665 //                      }
666 //
667 //                      //Metadata verification
668 //                      VfVerificator.verifyOnboardedVnfMetadata(vspName, vspMetadata);
669 //
670 //                      ExtentTestActions.log(Status.INFO, "Clicking create/update VNF");
671 //                      String duration = GeneralUIUtils.getActionDuration(() -> waitUntilVnfCreated());
672 //                  ExtentTestActions.log(Status.INFO, "Succeeded in importing/updating " + vspName, duration);
673 //              }
674 //              else{
675 //                      Assert.fail("Did not find VSP named " + vspName);
676 //              }
677 //      }
678
679 //      private static void waitUntilVnfCreated() {
680 //              GeneralUIUtils.clickOnElementByTestIdWithoutWait(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue());
681 //              GeneralUIUtils.waitForLoader(60*10);
682 //              GeneralUIUtils.waitForAngular();
683 //              GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue());
684 //      }
685 //
686 //      public static void updateVSP(Pair<String, Map<String, String>> vsp) throws Exception{
687 //              ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left);
688 //              importUpdateVSP(vsp, true);
689 //      }
690 //
691 //      public static void importVSP(Pair<String, Map<String, String>> vsp) throws Exception{
692 //              ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left);
693 //              importUpdateVSP(vsp, false);
694 //      }
695 //
696 //      public static void updateVnfAndValidate(String filepath, Pair<String, Map<String, String>> vsp, String updatedVnfFile, User user) throws Exception, Throwable {
697 //              ExtentTestActions.log(Status.INFO, String.format("Going to update the VNF with %s......", updatedVnfFile));
698 //              System.out.println(String.format("Going to update the VNF with %s......", updatedVnfFile));
699 //
700 //              Map<String, String> vspMap = vsp.right;
701 //              String vspId = vspMap.get("vspId");
702 //
703 //              updateVendorSoftwareProduct(vspId, updatedVnfFile, filepath, user);
704 //              HomePage.showVspRepository();
705 //              updateVSP(vsp);
706 //              ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
707 //              DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, updatedVnfFile);
708 //      }
709 //
710 //      public static Pair<String, Map<String, String>> onboardAndValidate(String filepath, String vnfFile, User user) throws Exception {
711 //              ExtentTestActions.log(Status.INFO, String.format("Going to onboard the VNF %s", vnfFile));
712 //              System.out.println(String.format("Going to onboard the VNF %s", vnfFile));
713 //
714 //              AmdocsLicenseMembers amdocsLicenseMembers = createVendorLicense(user);
715 //              Pair<String, Map<String, String>> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user, amdocsLicenseMembers);
716 //              String vspName = createVendorSoftwareProduct.left;
717 //
718 //              DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId"));
719 //              File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir();
720 //
721 //              ExtentTestActions.log(Status.INFO, String.format("Searching for onboarded %s", vnfFile));
722 //              HomePage.showVspRepository();
723 //              ExtentTestActions.log(Status.INFO,String.format("Going to import %s", vnfFile.substring(0, vnfFile.indexOf("."))));
724 //              importVSP(createVendorSoftwareProduct);
725 //
726 //              ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
727 //
728 //              // Verify deployment artifacts
729 //              Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath());
730 //
731 //              LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment"));
732 //              ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts);
733 //
734 //              List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")).
735 //                                                                                                                                               map(e -> e.getFileName()).
736 //                                                                                                                                               collect(Collectors.toList());
737 //
738 //              validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR);
739 //
740 //              DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile);
741 //              return createVendorSoftwareProduct;
742 //      }
743 //
744 //      public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts,
745 //                      List<String> heatEnvFilesFromCSAR) {
746 //              String artifactVersion;
747 //              String artifactName;
748 //
749 //              for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) {
750 //                      artifactVersion = "1";
751 //
752 //                      if(deploymentArtifact.getType().equals("HEAT_ENV")) {
753 //                              continue;
754 //                      } else if(deploymentArtifact.getFileName().contains(".")) {
755 //                              artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf("."));
756 //                      } else {
757 //                              artifactName = deploymentArtifact.getFileName().trim();
758 //                      }
759 //
760 //                      if (heatEnvFilesFromCSAR.contains(artifactName + ".env")){
761 //                              artifactVersion = "2";
762 //                      }
763 //                      ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType());
764 //              }
765 //      }
766         
767         
768         /**
769          * @return
770          * The method returns VNF names list from Files directory under sdc-vnfs repository
771          */
772         public static List<String> getVnfNamesFileList() {
773                 String filepath = FileHandling.getVnfRepositoryPath();
774                 List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
775                 fileNamesFromFolder.removeAll(exludeVnfList);
776                 return fileNamesFromFolder;
777         }
778
779         /**
780          * @return
781          * The method returns VNF names list from Files directory under sdc-vnfs repository excluding zip files that known as failed in tosca parser
782          */
783         public static List<String> getVnfNamesFileListExcludeToscaParserFailure() {
784                 List<String> fileNamesFromFolder = getVnfNamesFileList();
785                 fileNamesFromFolder.removeAll(exludeVnfListForToscaParser);
786                 return fileNamesFromFolder;
787         }
788         
789 }
790
791