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