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