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