[SDC] rebase 1710 code
[sdc.git] / ui-ci / src / main / java / org / openecomp / sdc / ci / tests / execute / sanity / OnboardViaApis.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.execute.sanity;
22
23 import static org.testng.AssertJUnit.assertEquals;
24
25 import java.awt.AWTException;
26 import java.io.File;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.nio.charset.StandardCharsets;
30 import java.sql.Timestamp;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.UUID;
37
38 import org.bouncycastle.util.encoders.Base64;
39 import org.openecomp.sdc.be.model.ComponentInstance;
40 import org.openecomp.sdc.be.model.Resource;
41 import org.openecomp.sdc.be.model.Service;
42 import org.openecomp.sdc.be.model.User;
43 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
44 import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus;
45 import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
46 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
47 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
48 import org.openecomp.sdc.ci.tests.utilities.FileHandling;
49 import org.openecomp.sdc.ci.tests.utilities.OnboardingUtils;
50 import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
51 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
52 import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
53 import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
54 import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;
55 import org.openecomp.sdc.toscaparser.api.common.JToscaException;
56 import org.slf4j.LoggerFactory;
57 import org.testng.annotations.BeforeMethod;
58 import org.testng.annotations.DataProvider;
59 import org.testng.annotations.Test;
60
61 import com.clearspring.analytics.util.Pair;
62 import com.google.gson.Gson;
63
64 import ch.qos.logback.classic.Level;
65 import ch.qos.logback.classic.LoggerContext;
66 import fj.data.Either;
67
68 public class OnboardViaApis{
69         
70
71         private static final String FULL_PATH = "C://tmp//CSARs//";
72         
73         public static Object[][] provideData(Object[] fileNamesFromFolder, String filepath) {
74                 Object[][] arObject = new Object[fileNamesFromFolder.length][];
75
76                 int index = 0;
77                 for (Object obj : fileNamesFromFolder) {
78                         arObject[index++] = new Object[] { filepath, obj };
79                 }
80                 return arObject;
81         }
82
83         @DataProvider(name = "VNF_List" , parallel = false)
84         private static final Object[][] VnfList() throws Exception {
85                 String filepath = FileHandling.getVnfRepositoryPath();
86                 
87                 Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
88                 System.out.println(String.format("There are %s zip file(s) to test", fileNamesFromFolder.length));
89                 return provideData(fileNamesFromFolder, filepath);
90         }
91
92         
93 //-------------------------------------------------------------------------------------------------------
94         User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
95                 private static String vendorId;
96                 private static String vendorLicenseName;
97                 private static String vendorLicenseAgreementId;
98                 private static String featureGroupId;
99                 ResourceReqDetails resourceDetails;
100                 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
101         
102         
103                 @BeforeMethod
104                 public void before(){
105                         LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
106                         lc.getLogger("org.apache").setLevel(Level.OFF);
107                         lc.getLogger("org.*").setLevel(Level.OFF);
108                         lc.getLogger("org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest").setLevel(Level.OFF);
109                         resourceDetails = ElementFactory.getDefaultResource();
110                         
111                 }
112                 
113         @Test(dataProvider = "VNF_List")
114         public void onboardVNFTestViaApis(String filepath, String vnfFile) throws Exception, Throwable {
115                 Service service = null;
116                 String fullFileName = FULL_PATH + vnfFile + ".csar";
117                 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
118                 System.err.println(timestamp + " Starting test with VNF: " + vnfFile);
119                 service = runOnboardViaApisOnly(filepath, vnfFile);
120                 timestamp = new Timestamp(System.currentTimeMillis());
121                 System.err.println(timestamp + " Finished test with VNF: " + vnfFile);
122                 timestamp = new Timestamp(System.currentTimeMillis());
123                 System.err.println(timestamp + " Starting download service csar file: " + vnfFile);
124                 File file = new File(fullFileName);
125                 downloadToscaCsarToDirectory(service, file);
126                 timestamp = new Timestamp(System.currentTimeMillis());
127                 System.err.println(timestamp + " Finished download service csar file: " + vnfFile);
128                 System.out.println("end");
129                 
130         }
131         
132         
133         @Test
134         public void onboardingAndParser() throws Exception {
135                 Service service = null;
136                 String filepath = getFilePath();
137                 Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
138                 String vnfFile = fileNamesFromFolder[7].toString();
139                 System.err.println(timestamp + " Starting test with VNF: " + vnfFile);
140                 service = runOnboardViaApisOnly(filepath, vnfFile);
141                 
142 //              AtomicOperationUtils.getServiceObjectByNameAndVersion(sdncModifierDetails, serviceName, serviceVersion);
143 //        RestResponse distributeService = AtomicOperationUtils.distributeService(service, true);
144 //        Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject = ResponseParser.convertServiceDistributionStatusToObject(distributeService.getResponse());
145 //        convertServiceDistributionStatusToObject.
146         }
147         
148         public static String getFilePath() {
149                 String filepath = System.getProperty("filepath");
150                 if (filepath == null && System.getProperty("os.name").contains("Windows")) {
151                         filepath = FileHandling.getResourcesFilesPath() +"VNFs";
152                 }
153                 
154                 else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
155                                 filepath = FileHandling.getBasePath() + File.separator + "Files" + File.separator +"VNFs";
156                 }
157                 return filepath;
158         }
159         
160         public static void downloadToscaCsarToDirectory(Service service, File file) {
161                 try {
162                         Either<String,RestResponse> serviceToscaArtifactPayload = AtomicOperationUtils.getServiceToscaArtifactPayload(service, "assettoscacsar");
163                         if(serviceToscaArtifactPayload.left().value() != null){
164                                 Gson gson = new Gson();
165                                 @SuppressWarnings("unchecked")
166                                 Map<String, String> fromJson = gson.fromJson(serviceToscaArtifactPayload.left().value(), Map.class);
167                                 String string = fromJson.get("base64Contents").toString();
168                                 byte[] byteArray = Base64.decode(string.getBytes(StandardCharsets.UTF_8));
169                                 File downloadedFile = new File(file.getAbsolutePath());
170                                 FileOutputStream fos = new FileOutputStream(downloadedFile);
171                                 fos.write(byteArray);
172                                 fos.flush();
173                                 fos.close();
174                         }
175                         
176                 } catch (Exception e) {
177                         // TODO Auto-generated catch block
178                         e.printStackTrace();
179                 }
180                 
181         }
182         
183         public Service runOnboardViaApisOnly(String filepath, String vnfFile) throws Exception, AWTException {
184                 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
185                 System.err.println(timestamp + " Starting onboard VNF: " + vnfFile);
186                 Pair<String,Map<String,String>> onboardAndValidate = onboardAndValidateViaApi(filepath, vnfFile, sdncDesignerDetails1);
187                 String vspName = onboardAndValidate.left;
188                 timestamp = new Timestamp(System.currentTimeMillis());
189                 System.err.println(timestamp + " Finished onboard VNF: " + vnfFile);
190                 Resource resource = AtomicOperationUtils.getResourceObject(resourceDetails.getUniqueId());
191                 
192                 AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
193                 resource = AtomicOperationUtils.getResourceObject(resource.getUniqueId());
194                 // create service
195                 
196                 Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
197                 Either<ComponentInstance,RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
198                 service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
199                 return service;
200         }       
201         
202         
203         
204         public Pair<String, Map<String, String>> onboardAndValidateViaApi(String filepath, String vnfFile, User user) throws Exception {
205         
206                 createVendorLicense(user);
207                 Pair<String, Map<String, String>> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user);
208                 String vspName = createVendorSoftwareProduct.left;
209                 List<String> tags = new ArrayList<>();
210                 tags.add(vspName);
211                 Map<String, String> map = createVendorSoftwareProduct.right;
212                 
213                 resourceDetails.setCsarUUID(map.get("vspId"));
214                 resourceDetails.setCsarVersion("1.0");
215                 resourceDetails.setName(vspName);
216                 resourceDetails.setTags(tags);
217                 resourceDetails.setResourceType(map.get("componentType"));
218                 resourceDetails.setVendorName(map.get("vendorName"));
219                 resourceDetails.setVendorRelease("1.0");
220                 resourceDetails.setResourceType("VF");
221                 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails1);
222                 
223                 return createVendorSoftwareProduct;
224         }
225         
226         public static Pair<String, Map<String, String>> createVendorSoftwareProduct(String HeatFileName, String filepath, User user)
227                         throws Exception {
228                 Pair<String, Map<String, String>> pair = createVSP(HeatFileName, filepath, user);
229                 
230                 String vspid = pair.right.get("vspId");
231                                 
232                 prepareVspForUse(user, vspid);
233                 
234                 return pair;
235         }
236         
237         public static void prepareVspForUse(User user, String vspid) throws Exception {
238                 RestResponse checkin = OnboardingUtils.checkinVendorSoftwareProduct(vspid, user);
239                 assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue());
240
241                 RestResponse submit = OnboardingUtils.submitVendorSoftwareProduct(vspid, user);
242                 assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue());
243
244                 RestResponse createPackage = OnboardingUtils.createPackageOfVendorSoftwareProduct(vspid, user);
245                 assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue());
246
247         }
248         public static void createVendorLicense(User user) throws Exception {
249                 vendorLicenseName = "ciLicense" + UUID.randomUUID().toString().split("-")[0];
250                 RestResponse vendorLicenseResponse = OnboardingUtils.createVendorLicenseModels_1(vendorLicenseName, user);
251                 assertEquals("did not succeed to create vendor license model", 200,
252                                 vendorLicenseResponse.getErrorCode().intValue());
253                 vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "value");
254
255                 RestResponse vendorKeyGroupsResponse = OnboardingUtils.createVendorKeyGroups_2(vendorId, user);
256                 assertEquals("did not succeed to create vendor key groups", 200,
257                                 vendorKeyGroupsResponse.getErrorCode().intValue());
258                 String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), "value");
259
260                 RestResponse vendorEntitlementPool = OnboardingUtils.createVendorEntitlementPool_3(vendorId, user);
261                 assertEquals("did not succeed to create vendor entitlement pool", 200,
262                                 vendorEntitlementPool.getErrorCode().intValue());
263                 String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(),
264                                 "value");
265
266                 RestResponse vendorLicenseFeatureGroups = OnboardingUtils.createVendorLicenseFeatureGroups_4(vendorId, keyGroupId,
267                                 entitlementPoolId, user);
268                 assertEquals("did not succeed to create vendor license feature groups", 200,
269                                 vendorLicenseFeatureGroups.getErrorCode().intValue());
270                 featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value");
271
272                 RestResponse vendorLicenseAgreement = OnboardingUtils.createVendorLicenseAgreement_5(vendorId, featureGroupId, user);
273                 assertEquals("did not succeed to create vendor license agreement", 200,
274                                 vendorLicenseAgreement.getErrorCode().intValue());
275                 vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(),
276                                 "value");
277
278                 RestResponse checkinVendorLicense = OnboardingUtils.checkinVendorLicense(vendorId, user);
279                 assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue());
280
281                 RestResponse submitVendorLicense = OnboardingUtils.submitVendorLicense(vendorId, user);
282                 assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue());
283
284         }
285         
286         
287         public static Pair<String, Map<String, String>> createVSP(String HeatFileName, String filepath, User user) throws Exception {
288                 String vspName = OnboardingUtils.handleFilename(HeatFileName);
289                 
290                 Pair<RestResponse, Map<String, String>> createNewVspPair = OnboardingUtils.createNewVendorSoftwareProduct(vspName, vendorLicenseName, vendorId, vendorLicenseAgreementId, featureGroupId, user);
291                 RestResponse createNewVendorSoftwareProduct = createNewVspPair.left;
292                 assertEquals("did not succeed to create new VSP", 200,createNewVendorSoftwareProduct.getErrorCode().intValue());
293                 String vspid = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "vspId");
294                 String componentId = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "componentId");
295                 
296                 Map<String, String> vspMeta = createNewVspPair.right;
297                 Map<String, String> vspObject = new HashMap<String, String>();
298                 Iterator<String> iterator = vspMeta.keySet().iterator();
299                 while(iterator.hasNext()){
300                         Object key = iterator.next();
301                         Object value = vspMeta.get(key);
302                         vspObject.put(key.toString(), value.toString());
303                 }
304                 vspObject.put("vspId", vspid);
305                 vspObject.put("componentId", componentId);
306                 vspObject.put("vendorName", vendorLicenseName);
307                 vspObject.put("attContact", user.getUserId());
308                 
309                 RestResponse uploadHeatPackage = OnboardingUtils.uploadHeatPackage(filepath, HeatFileName, vspid, user);
310                 assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
311                 
312                 RestResponse validateUpload = OnboardingUtils.validateUpload(vspid, user);
313                 assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue());
314                 
315                 Pair<String, Map<String, String>> pair = new Pair<String, Map<String, String>>(vspName, vspObject);
316                 
317                 return pair;
318         }
319
320         
321         
322         
323         
324         
325         
326         
327         
328 //      ----------------------------------------------------------------------------------------------------------------------------------------
329         
330         
331         
332         
333
334
335 }