[SDC-29] rebase continue work to align source
[sdc.git] / test-apis-ci / src / main / java / org / openecomp / sdc / ci / tests / utils / rest / ImportRestUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.ci.tests.utils.rest;
22
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertNotNull;
25
26 import java.io.File;
27 import java.io.FileNotFoundException;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.StringWriter;
31 import java.nio.file.FileSystems;
32 import java.nio.file.Files;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Properties;
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.ContentType;
46 import org.apache.http.entity.mime.MultipartEntityBuilder;
47 import org.apache.http.entity.mime.content.FileBody;
48 import org.apache.http.entity.mime.content.StringBody;
49 import org.apache.http.impl.client.CloseableHttpClient;
50 import org.apache.http.impl.client.HttpClients;
51 import org.codehaus.jettison.json.JSONException;
52 import org.openecomp.sdc.be.dao.rest.HttpRestClient;
53 import org.openecomp.sdc.be.model.User;
54 import org.openecomp.sdc.ci.tests.api.Urls;
55 import org.openecomp.sdc.ci.tests.config.Config;
56 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
57 import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
58 import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum;
59 import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
60 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
61 import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
62 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
63 import org.openecomp.sdc.ci.tests.utils.Utils;
64 import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
65 import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 public class ImportRestUtils extends BaseRestUtils {
70
71         private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName());
72         private static Properties downloadCsarHeaders = new Properties();
73
74         static {
75                 downloadCsarHeaders.put("Accept", "application/octet-stream");
76         }
77
78         @SuppressWarnings("unused")
79         private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole)
80                         throws IOException {
81                 Config config = Utils.getConfig();
82                 CloseableHttpResponse response = null;
83                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
84
85                 mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
86                 mpBuilder.addPart("resourceMetadata",
87                                 new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"),
88                                                 ContentType.APPLICATION_JSON));
89
90                 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
91                                 config.getCatalogBePort());
92
93                 CloseableHttpClient client = HttpClients.createDefault();
94                 try {
95                         HttpPost httpPost = new HttpPost(url);
96                         httpPost.addHeader("USER_ID", userRole.getUserId());
97                         httpPost.setEntity(mpBuilder.build());
98                         response = client.execute(httpPost);
99                         return response.getStatusLine().getStatusCode();
100                 } finally {
101                         closeResponse(response);
102                         closeHttpClient(client);
103
104                 }
105         }
106
107         /*
108          * public static RestResponse importResourceByName(String resourceName, User
109          * user) throws IOException { Config config = Utils.getConfig();
110          * CloseableHttpResponse response = null; MultipartEntityBuilder mpBuilder =
111          * MultipartEntityBuilder.create();
112          * 
113          * mpBuilder.addPart("resourceZip", new
114          * FileBody(getTestZipFile(resourceName)));
115          * mpBuilder.addPart("resourceMetadata", new
116          * StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"),
117          * ContentType.APPLICATION_JSON));
118          * 
119          * String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE,
120          * config.getCatalogBeHost(), config.getCatalogBePort());
121          * 
122          * CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost
123          * httpPost = new HttpPost(url); RestResponse restResponse = new
124          * RestResponse(); httpPost.addHeader("USER_ID", user.getUserId());
125          * httpPost.setEntity(mpBuilder.build()); response =
126          * client.execute(httpPost); HttpEntity entity = response.getEntity();
127          * String responseBody = null; if (entity != null) { InputStream instream =
128          * entity.getContent(); StringWriter writer = new StringWriter();
129          * IOUtils.copy(instream, writer); responseBody = writer.toString(); try {
130          * 
131          * } finally { instream.close(); } }
132          * 
133          * restResponse.setErrorCode(response.getStatusLine().getStatusCode());
134          * restResponse.setResponse(responseBody); if (restResponse.getErrorCode()
135          * == STATUS_CODE_CREATED ){
136          * 
137          * }
138          * 
139          * return restResponse;
140          * 
141          * } finally { closeResponse(response); closeHttpClient(client);
142          * 
143          * }
144          * 
145          * }
146          */
147
148         public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer)
149                         throws Exception {
150                 Config config = Utils.getConfig();
151                 CloseableHttpResponse response = null;
152                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
153
154                 mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceDetails.getName())));
155                 mpBuilder.addPart("resourceMetadata",
156                                 new StringBody(getTestJsonStringOfFile(resourceDetails.getName(), resourceDetails.getName() + ".json"),
157                                                 ContentType.APPLICATION_JSON));
158
159                 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
160                                 config.getCatalogBePort());
161
162                 CloseableHttpClient client = HttpClients.createDefault();
163                 try {
164                         HttpPost httpPost = new HttpPost(url);
165                         RestResponse restResponse = new RestResponse();
166                         httpPost.addHeader("USER_ID", importer.getUserId());
167                         httpPost.setEntity(mpBuilder.build());
168                         response = client.execute(httpPost);
169                         HttpEntity entity = response.getEntity();
170                         String responseBody = null;
171                         if (entity != null) {
172                                 InputStream instream = entity.getContent();
173                                 StringWriter writer = new StringWriter();
174                                 IOUtils.copy(instream, writer);
175                                 responseBody = writer.toString();
176                                 try {
177
178                                 } finally {
179                                         instream.close();
180                                 }
181                         }
182
183                         restResponse.setErrorCode(response.getStatusLine().getStatusCode());
184                         restResponse.setResponse(responseBody);
185
186                         if (restResponse.getErrorCode() == STATUS_CODE_CREATED) {
187                                 resourceDetails.setUUID(ResponseParser.getUuidFromResponse(restResponse));
188                                 resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
189                                 resourceDetails.setVersion(ResponseParser.getVersionFromResponse(restResponse));
190                                 resourceDetails.setCreatorUserId(importer.getUserId());
191                                 resourceDetails.setCreatorFullName(importer.getFullName());
192                         }
193
194                         return restResponse;
195
196                 } finally {
197                         closeResponse(response);
198                         closeHttpClient(client);
199
200                 }
201
202         }
203
204         public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
205                 Config config = Utils.getConfig();
206
207                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
208
209                 mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
210                 mpBuilder.addPart("resourceMetadata", new StringBody(
211                                 getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
212                 HttpEntity requestEntity = mpBuilder.build();
213                 String url = String.format(Urls.IMPORT_USER_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
214                 Map<String, String> headers = new HashMap<String, String>();
215                 headers.put("USER_ID", userRole.getUserId());
216
217                 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
218         }
219
220         public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole)
221                         throws IOException {
222                 Config config = Utils.getConfig();
223
224                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
225
226                 mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
227                 mpBuilder.addPart("resourceMetadata", new StringBody(
228                                 getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
229                 HttpEntity requestEntity = mpBuilder.build();
230                 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
231                                 config.getCatalogBePort());
232                 Map<String, String> headers = new HashMap<String, String>();
233                 headers.put("USER_ID", userRole.getUserId());
234
235                 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
236         }
237
238         public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole)
239                         throws IOException {
240                 Config config = Utils.getConfig();
241                 CloseableHttpResponse response = null;
242                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
243
244                 mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
245                 mpBuilder.addPart("resourceMetadata",
246                                 new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"),
247                                                 ContentType.APPLICATION_JSON));
248
249                 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
250                                 config.getCatalogBePort());
251
252                 CloseableHttpClient client = HttpClients.createDefault();
253                 try {
254                         HttpPost httpPost = new HttpPost(url);
255                         RestResponse restResponse = new RestResponse();
256                         httpPost.addHeader("USER_ID", UserRoleEnum.ADMIN.getUserId());
257                         httpPost.setEntity(mpBuilder.build());
258                         response = client.execute(httpPost);
259                         HttpEntity entity = response.getEntity();
260                         String responseBody = null;
261                         if (entity != null) {
262                                 InputStream instream = entity.getContent();
263                                 StringWriter writer = new StringWriter();
264                                 IOUtils.copy(instream, writer);
265                                 responseBody = writer.toString();
266                                 try {
267
268                                 } finally {
269                                         instream.close();
270                                 }
271                         }
272
273                         restResponse.setErrorCode(response.getStatusLine().getStatusCode());
274                         // restResponse.setResponse(response.getEntity().toString());
275                         restResponse.setResponse(responseBody);
276                         return restResponse;
277                 } finally {
278                         closeResponse(response);
279                         closeHttpClient(client);
280
281                 }
282         }
283
284         public static Boolean removeNormativeTypeResource(NormativeTypesEnum current)
285                         throws FileNotFoundException, IOException, ClientProtocolException {
286                 User user = new User(UserRoleEnum.ADMIN.getFirstName(), UserRoleEnum.ADMIN.getLastName(),
287                                 UserRoleEnum.ADMIN.getUserId(), null, null, null);
288                 RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(user, current.getNormativeName(),
289                                 "1.0");
290                 if (deleteResponse.getErrorCode() == 200) {
291                         return true;
292                 }
293                 return false;
294         }
295
296         public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse)
297                         throws IOException, JSONException {
298
299                 // assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS );
300
301                 ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
302
303                 assertNotNull("check response object is not null after create service", restResponse);
304                 assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
305                 assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
306
307                 // validate create service response vs actual
308                 List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams()
309                                 : new ArrayList<String>());
310                 if (restResponse.getErrorCode() != 200) {
311                         ErrorValidationUtils.checkBodyResponseOnError(currResource.getActionStatus().name(), variables,
312                                         restResponse.getResponse());
313                 }
314         }
315
316         private static String getTestJsonStringOfFile(String folderName, String fileName) throws IOException {
317                 // String sourceDir = "src/test/resources/CI/importResourceTests";
318                 Config config = Utils.getConfig();
319                 String sourceDir = config.getImportResourceTestsConfigDir();
320                 java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName,
321                                 fileName);
322                 byte[] fileContent = Files.readAllBytes(filePath);
323                 String content = new String(fileContent);
324                 return content;
325         }
326
327         private static File getTestZipFile(String elementName) throws IOException {
328                 Config config = Utils.getConfig();
329                 String sourceDir = config.getImportResourceTestsConfigDir();
330                 java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName,
331                                 "normative-types-new-" + elementName + ".zip");
332                 return filePath.toFile();
333         }
334
335         private static void closeHttpClient(CloseableHttpClient client) {
336                 try {
337                         if (client != null) {
338                                 client.close();
339                         }
340                 } catch (IOException e) {
341                         log.debug("failed to close client or response: ", e);
342                 }
343         }
344
345         private static void closeResponse(CloseableHttpResponse response) {
346                 try {
347                         if (response != null) {
348                                 response.close();
349                         }
350                 } catch (IOException e) {
351                         log.debug("failed to close client or response: {}", e);
352                 }
353         }
354
355         public static RestResponseAsByteArray getCsar(String csarUid, User sdncModifierDetails) throws Exception {
356
357                 Config config = Utils.getConfig();
358                 String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
359                                 csarUid);
360
361                 String userId = sdncModifierDetails.getUserId();
362
363                 Map<String, String> headersMap = prepareHeadersMap(userId);
364
365                 // Gson gson = new Gson();
366                 // String userBodyJson = gson.toJson(resourceDetails);
367                 HttpRequest http = new HttpRequest();
368                 // System.out.println(url);
369                 // System.out.println(userBodyJson);
370
371                 HttpRestClient httpRestClient = new HttpRestClient();
372
373                 for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
374
375                         downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue());
376                 }
377                 RestResponseAsByteArray doGetAsByteArray = httpRestClient.doGetAsByteArray(url, downloadCsarHeaders);
378                 // RestResponse getCsar = http.httpSendGet(url, headersMap);
379
380                 return doGetAsByteArray;
381
382         }
383
384         private static File getGroupTypeZipFile(String elementName) throws IOException {
385                 Config config = Utils.getConfig();
386                 String sourceDir = config.getImportResourceTestsConfigDir();
387                 sourceDir += File.separator + ".." + File.separator + "importTypesTest" + File.separator;
388                 java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName,
389                                 elementName + ".zip");
390                 return filePath.toFile();
391         }
392
393         public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole)
394                         throws IOException {
395                 Config config = Utils.getConfig();
396
397                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
398
399                 mpBuilder.addPart("groupTypesZip", new FileBody(getGroupTypeZipFile(groupTypeName)));
400                 HttpEntity requestEntity = mpBuilder.build();
401                 String url = String.format(Urls.IMPORT_GROUP_TYPE, config.getCatalogBeHost(), config.getCatalogBePort());
402                 Map<String, String> headers = new HashMap<String, String>();
403                 headers.put("USER_ID", userRole.getUserId());
404
405                 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
406         }
407
408 }