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