Initial OpenECOMP SDC commit
[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.FilenameFilter;
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.ArrayList;
32 import java.util.Arrays;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.UUID;
38 import java.util.zip.ZipFile;
39
40 import org.apache.commons.io.IOUtils;
41 import org.apache.http.HttpEntity;
42 import org.apache.http.client.methods.CloseableHttpResponse;
43 import org.apache.http.client.methods.HttpPost;
44 import org.apache.http.entity.mime.MultipartEntityBuilder;
45 import org.apache.http.entity.mime.content.FileBody;
46 import org.apache.http.impl.client.CloseableHttpClient;
47 import org.apache.http.impl.client.HttpClients;
48 import org.json.JSONObject;
49 import org.openecomp.sdc.be.model.User;
50 import org.openecomp.sdc.ci.tests.config.Config;
51 import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
52 import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
53 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
54 import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
55 import org.openecomp.sdc.ci.tests.utils.Utils;
56 import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
57 import org.testng.Assert;
58
59 import com.relevantcodes.extentreports.LogStatus;
60
61 public class OnboardingUtils {
62
63         public OnboardingUtils() {
64         }
65
66         private static String vendorId;
67         private static String vendorLicenseName;
68         private static String vendorLicenseAgreementId;
69         private static String featureGroupId;
70
71         public int countFilesInZipDirectory(String filepath, String filename) throws Exception, Throwable {
72                 ZipFile zipFile = new ZipFile(filepath + filename);
73                 return zipFile.size() - 1;
74         }
75
76         public static Object[] getZipFileNamesFromFolder(String filepath) {
77                 return FileHandling.getFileNamesFromFolder(filepath, ".zip");
78         }
79
80         public static String createVendorSoftwareProduct(String HeatFileName, String filepath, User user)
81                         throws Exception, Throwable {
82                 String vspName = handleFilename(HeatFileName);
83                 SetupCDTest.getExtendTest().log(LogStatus.INFO, "Starting to create vendor software product");
84
85                 RestResponse createNewVendorSoftwareProduct = createNewVendorSoftwareProduct(vspName, vendorLicenseName,
86                                 vendorId, vendorLicenseAgreementId, featureGroupId, user);
87                 assertEquals("did not succeed to create new VSP", 200,
88                                 createNewVendorSoftwareProduct.getErrorCode().intValue());
89                 String vspid = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "vspId");
90
91                 RestResponse uploadHeatPackage = uploadHeatPackage(filepath, HeatFileName, vspid, user);
92                 assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
93
94                 RestResponse checkin = checkinVendorSoftwareProduct(vspid, user);
95                 assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue());
96
97                 RestResponse submit = submitVendorSoftwareProduct(vspid, user);
98                 assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue());
99
100                 RestResponse createPackage = createPackageOfVendorSoftwareProduct(vspid, user);
101                 assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue());
102
103                 SetupCDTest.getExtendTest().log(LogStatus.INFO, "Succeeded to create vendor software product");
104
105                 return vspName;
106         }
107
108         private static String handleFilename(String heatFileName) {
109                 final String namePrefix = "ciVFOnboarded-";
110                 final String nameSuffix = "-" + getShortUUID();
111
112                 String subHeatFileName = heatFileName.substring(0, heatFileName.lastIndexOf("."));
113
114                 if ((namePrefix + subHeatFileName + nameSuffix).length() >= 50) {
115                         subHeatFileName = subHeatFileName.substring(0, 50 - namePrefix.length() - nameSuffix.length());
116                 }
117
118                 if (subHeatFileName.contains("(") || subHeatFileName.contains(")")) {
119                         subHeatFileName = subHeatFileName.replace("(", "-");
120                         subHeatFileName = subHeatFileName.replace(")", "-");
121                 }
122
123                 String vnfName = namePrefix + subHeatFileName + nameSuffix;
124                 return vnfName;
125         }
126
127         public static void createVendorLicense(User user) throws Exception {
128                 SetupCDTest.getExtendTest().log(LogStatus.INFO, "Starting to create vendor license");
129                 vendorLicenseName = "ciLicense" + getShortUUID();
130                 RestResponse vendorLicenseResponse = createVendorLicenseModels_1(vendorLicenseName, user);
131                 assertEquals("did not succeed to create vendor license model", 200,
132                                 vendorLicenseResponse.getErrorCode().intValue());
133                 vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "value");
134
135                 RestResponse vendorKeyGroupsResponse = createVendorKeyGroups_2(vendorId, user);
136                 assertEquals("did not succeed to create vendor key groups", 200,
137                                 vendorKeyGroupsResponse.getErrorCode().intValue());
138                 String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), "value");
139
140                 RestResponse vendorEntitlementPool = createVendorEntitlementPool_3(vendorId, user);
141                 assertEquals("did not succeed to create vendor entitlement pool", 200,
142                                 vendorEntitlementPool.getErrorCode().intValue());
143                 String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(),
144                                 "value");
145
146                 RestResponse vendorLicenseFeatureGroups = createVendorLicenseFeatureGroups_4(vendorId, keyGroupId,
147                                 entitlementPoolId, user);
148                 assertEquals("did not succeed to create vendor license feature groups", 200,
149                                 vendorLicenseFeatureGroups.getErrorCode().intValue());
150                 featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value");
151
152                 RestResponse vendorLicenseAgreement = createVendorLicenseAgreement_5(vendorId, featureGroupId, user);
153                 assertEquals("did not succeed to create vendor license agreement", 200,
154                                 vendorLicenseAgreement.getErrorCode().intValue());
155                 vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(),
156                                 "value");
157
158                 RestResponse checkinVendorLicense = checkinVendorLicense(vendorId, user);
159                 assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue());
160
161                 RestResponse submitVendorLicense = submitVendorLicense(vendorId, user);
162                 assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue());
163
164                 SetupCDTest.getExtendTest().log(LogStatus.INFO, "Succeeded to create vendor license");
165         }
166
167         private static String getShortUUID() {
168                 return UUID.randomUUID().toString().split("-")[0];
169         }
170
171         private static RestResponse actionOnComponent(String vspid, String action, String onboardComponent, User user) throws Exception {
172                 Config config = Utils.getConfig();
173                 String url = String.format("http://%s:%s/onboarding-api/v1.0/" + onboardComponent + "/%s/actions", config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
174                 String userId = user.getUserId();
175
176                 JSONObject jObject = new JSONObject();
177                 jObject.put("action", action);
178
179                 Map<String, String> headersMap = prepareHeadersMap(userId);
180
181                 HttpRequest http = new HttpRequest();
182                 RestResponse response = http.httpSendPut(url, jObject.toString(), headersMap);
183                 return response;
184         }
185
186         private static RestResponse checkinVendorLicense(String vspid, User user) throws Exception {
187                 return actionOnComponent(vspid, "Checkin", "vendor-license-models", user);
188         }
189
190         private static RestResponse submitVendorLicense(String vspid, User user) throws Exception {
191                 return actionOnComponent(vspid, "Submit", "vendor-license-models", user);
192         }
193
194         private static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception {
195                 Config config = Utils.getConfig();
196                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models", config.getCatalogBeHost(), config.getCatalogBePort());
197                 String userId = user.getUserId();
198                 JSONObject jObject = new JSONObject();
199                 jObject.put("vendorName", name);
200                 jObject.put("description", "new vendor license model");
201                 jObject.put("iconRef", "icon");
202
203                 Map<String, String> headersMap = prepareHeadersMap(userId);
204
205                 HttpRequest http = new HttpRequest();
206                 RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap);
207                 return response;
208
209         }
210
211         private static RestResponse createVendorLicenseAgreement_5(String vspid, String featureGroupId, User user)
212                         throws Exception {
213                 Config config = Utils.getConfig();
214                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/license-agreements",
215                                 config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
216
217                 String userId = user.getUserId();
218
219                 JSONObject licenseTermpObject = new JSONObject();
220                 licenseTermpObject.put("choice", "Fixed_Term");
221                 licenseTermpObject.put("other", "");
222
223                 JSONObject jObjectBody = new JSONObject();
224                 jObjectBody.put("name", "abc");
225                 jObjectBody.put("description", "new vendor license agreement");
226                 jObjectBody.put("requirementsAndConstrains", "abc");
227                 jObjectBody.put("licenseTerm", licenseTermpObject);
228                 jObjectBody.put("addedFeatureGroupsIds", Arrays.asList(featureGroupId).toArray());
229
230                 Map<String, String> headersMap = prepareHeadersMap(userId);
231
232                 HttpRequest http = new HttpRequest();
233                 RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
234                 return response;
235         }
236
237         private static RestResponse createVendorLicenseFeatureGroups_4(String vspid, String licenseKeyGroupId,
238                         String entitlementPoolId, User user) throws Exception {
239                 Config config = Utils.getConfig();
240                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/feature-groups",
241                                 config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
242
243                 String userId = user.getUserId();
244
245                 JSONObject jObject = new JSONObject();
246                 jObject.put("name", "xyz");
247                 jObject.put("description", "new vendor license feature groups");
248                 jObject.put("partNumber", "123abc456");
249                 jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray());
250                 jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray());
251
252                 Map<String, String> headersMap = prepareHeadersMap(userId);
253
254                 HttpRequest http = new HttpRequest();
255                 RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap);
256                 return response;
257
258         }
259
260         private static RestResponse createVendorEntitlementPool_3(String vspid, User user) throws Exception {
261                 Config config = Utils.getConfig();
262                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/entitlement-pools",
263                                 config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
264
265                 String userId = user.getUserId();
266
267                 JSONObject jEntitlementMetricObject = new JSONObject();
268                 jEntitlementMetricObject.put("choice", "CPU");
269                 jEntitlementMetricObject.put("other", "");
270
271                 JSONObject jAggregationFunctionObject = new JSONObject();
272                 jAggregationFunctionObject.put("choice", "Peak");
273                 jAggregationFunctionObject.put("other", "");
274
275                 JSONObject jOperationalScope = new JSONObject();
276                 jOperationalScope.put("choices", Arrays.asList("Availability_Zone").toArray());
277                 jOperationalScope.put("other", "");
278
279                 JSONObject jTimeObject = new JSONObject();
280                 jTimeObject.put("choice", "Hour");
281                 jTimeObject.put("other", "");
282
283                 JSONObject jObjectBody = new JSONObject();
284                 jObjectBody.put("name", "def");
285                 jObjectBody.put("description", "new vendor license entitlement pool");
286                 jObjectBody.put("thresholdValue", "23");
287                 jObjectBody.put("thresholdUnits", "Absolute");
288                 jObjectBody.put("entitlementMetric", jEntitlementMetricObject);
289                 jObjectBody.put("increments", "abcd");
290                 jObjectBody.put("aggregationFunction", jAggregationFunctionObject);
291                 jObjectBody.put("operationalScope", jOperationalScope);
292                 jObjectBody.put("time", jTimeObject);
293                 jObjectBody.put("manufacturerReferenceNumber", "123aaa");
294
295                 Map<String, String> headersMap = prepareHeadersMap(userId);
296
297                 HttpRequest http = new HttpRequest();
298                 RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
299                 return response;
300         }
301
302         private static RestResponse createVendorKeyGroups_2(String vspid, User user) throws Exception {
303                 Config config = Utils.getConfig();
304                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/license-key-groups",
305                                 config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
306
307                 String userId = user.getUserId();
308
309                 JSONObject jOperationalScope = new JSONObject();
310                 jOperationalScope.put("choices", Arrays.asList("Tenant").toArray());
311                 jOperationalScope.put("other", "");
312
313                 JSONObject jObjectBody = new JSONObject();
314                 jObjectBody.put("name", "keyGroup");
315                 jObjectBody.put("description", "new vendor license key group");
316                 jObjectBody.put("operationalScope", jOperationalScope);
317                 jObjectBody.put("type", "Universal");
318
319                 Map<String, String> headersMap = prepareHeadersMap(userId);
320
321                 HttpRequest http = new HttpRequest();
322                 RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
323                 return response;
324         }
325
326         private static RestResponse createNewVendorSoftwareProduct(String name, String vendorName, String vendorId,
327                         String licenseAgreementId, String featureGroupsId, User user) throws Exception {
328                 Config config = Utils.getConfig();
329                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products",
330                                 config.getCatalogBeHost(), config.getCatalogBePort());
331
332                 String userId = user.getUserId();
333
334                 JSONObject jlicensingDataObj = new JSONObject();
335                 jlicensingDataObj.put("licenseAgreement", licenseAgreementId);
336                 jlicensingDataObj.put("featureGroups", Arrays.asList(featureGroupsId).toArray());
337
338                 JSONObject jObject = new JSONObject();
339                 jObject.put("name", name);
340                 jObject.put("description", "new VSP description");
341                 jObject.put("category", "resourceNewCategory.generic");
342                 jObject.put("subCategory", "resourceNewCategory.generic.database");
343                 jObject.put("licensingVersion", "1.0");
344                 jObject.put("vendorName", vendorName);
345                 jObject.put("vendorId", vendorId);
346                 jObject.put("icon", "icon");
347                 jObject.put("licensingData", jlicensingDataObj);
348
349                 Map<String, String> headersMap = prepareHeadersMap(userId);
350                 HttpRequest http = new HttpRequest();
351
352                 RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap);
353
354                 return response;
355         }
356
357         private static RestResponse uploadHeatPackage(String filepath, String filename, String vspid, User user)
358                         throws Exception {
359                 Config config = Utils.getConfig();
360                 CloseableHttpResponse response = null;
361
362                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
363                 mpBuilder.addPart("upload", new FileBody(getTestZipFile(filepath, filename)));
364
365                 String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/upload", config.getCatalogBeHost(), config.getCatalogBePort(), vspid);
366
367                 Map<String, String> headersMap = prepareHeadersMap(user.getUserId());
368                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data");
369
370                 CloseableHttpClient client = HttpClients.createDefault();
371                 try {
372                         HttpPost httpPost = new HttpPost(url);
373                         RestResponse restResponse = new RestResponse();
374
375                         Iterator<String> iterator = headersMap.keySet().iterator();
376                         while (iterator.hasNext()) {
377                                 String key = iterator.next();
378                                 String value = headersMap.get(key);
379                                 httpPost.addHeader(key, value);
380                         }
381                         httpPost.setEntity(mpBuilder.build());
382                         response = client.execute(httpPost);
383                         HttpEntity entity = response.getEntity();
384                         String responseBody = null;
385                         if (entity != null) {
386                                 InputStream instream = entity.getContent();
387                                 StringWriter writer = new StringWriter();
388                                 IOUtils.copy(instream, writer);
389                                 responseBody = writer.toString();
390                                 try {
391
392                                 } finally {
393                                         instream.close();
394                                 }
395                         }
396
397                         restResponse.setErrorCode(response.getStatusLine().getStatusCode());
398                         restResponse.setResponse(responseBody);
399
400                         return restResponse;
401
402                 } finally {
403                         closeResponse(response);
404                         closeHttpClient(client);
405
406                 }
407         }
408
409         private static void closeResponse(CloseableHttpResponse response) {
410                 try {
411                         if (response != null) {
412                                 response.close();
413                         }
414                 } catch (IOException e) {
415                         System.out.println(String.format("failed to close client or response: %s", e.getMessage()));
416                 }
417         }
418
419         private static void closeHttpClient(CloseableHttpClient client) {
420                 try {
421                         if (client != null) {
422                                 client.close();
423                         }
424                 } catch (IOException e) {
425                         System.out.println(String.format("failed to close client or response: %s", e.getMessage()));
426                 }
427         }
428
429         private static File getTestZipFile(String filepath, String filename) throws IOException {
430                 Config config = Utils.getConfig();
431                 String sourceDir = config.getImportResourceTestsConfigDir();
432                 java.nio.file.Path filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename);
433                 return filePath.toFile();
434         }
435
436         private static RestResponse checkinVendorSoftwareProduct(String vspid, User user) throws Exception {
437                 return actionOnComponent(vspid, "Checkin", "vendor-software-products", user);
438         }
439
440         private static RestResponse submitVendorSoftwareProduct(String vspid, User user) throws Exception {
441                 return actionOnComponent(vspid, "Submit", "vendor-software-products", user);
442         }
443
444         private static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user) throws Exception {
445                 return actionOnComponent(vspid, "Create_Package", "vendor-software-products", user);
446         }
447
448         protected static Map<String, String> prepareHeadersMap(String userId) {
449                 Map<String, String> headersMap = new HashMap<String, String>();
450                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
451                 headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
452                 headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
453                 
454                 return headersMap;
455         }
456
457 }