2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.ci.tests.utils.rest;
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;
52 import java.nio.file.FileSystems;
53 import java.nio.file.Files;
56 import static org.testng.AssertJUnit.assertEquals;
57 import static org.testng.AssertJUnit.assertNotNull;
59 public class ImportRestUtils extends BaseRestUtils {
61 private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName());
62 private static Properties downloadCsarHeaders = new Properties();
65 downloadCsarHeaders.put("Accept", "application/octet-stream");
68 @SuppressWarnings("unused")
69 private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole)
71 Config config = Utils.getConfig();
72 CloseableHttpResponse response = null;
73 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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));
80 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
81 config.getCatalogBePort());
83 CloseableHttpClient client = HttpClients.createDefault();
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();
91 closeResponse(response);
92 closeHttpClient(client);
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();
103 * mpBuilder.addPart("resourceZip", new
104 * FileBody(getTestZipFile(resourceName)));
105 * mpBuilder.addPart("resourceMetadata", new
106 * StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"),
107 * ContentType.APPLICATION_JSON));
109 * String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE,
110 * config.getCatalogBeHost(), config.getCatalogBePort());
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 {
121 * } finally { instream.close(); } }
123 * restResponse.setErrorCode(response.getStatusLine().getStatusCode());
124 * restResponse.setResponse(responseBody); if (restResponse.getErrorCode()
125 * == STATUS_CODE_CREATED ){
129 * return restResponse;
131 * } finally { closeResponse(response); closeHttpClient(client);
138 public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer)
140 Config config = Utils.getConfig();
141 CloseableHttpResponse response = null;
142 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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));
149 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
150 config.getCatalogBePort());
152 CloseableHttpClient client = HttpClients.createDefault();
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();
173 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
174 restResponse.setResponse(responseBody);
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());
187 closeResponse(response);
188 closeHttpClient(client);
194 public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
195 Config config = Utils.getConfig();
197 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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());
207 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
210 public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole)
212 Config config = Utils.getConfig();
214 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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());
225 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
228 public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole)
230 Config config = Utils.getConfig();
231 CloseableHttpResponse response = null;
232 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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));
239 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
240 config.getCatalogBePort());
242 CloseableHttpClient client = HttpClients.createDefault();
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();
263 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
264 // restResponse.setResponse(response.getEntity().toString());
265 restResponse.setResponse(responseBody);
268 closeResponse(response);
269 closeHttpClient(client);
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(),
280 if (deleteResponse.getErrorCode() == 200) {
286 public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse)
287 throws IOException, JSONException {
289 // assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS );
291 ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
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());
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());
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,
312 byte[] fileContent = Files.readAllBytes(filePath);
313 String content = new String(fileContent);
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();
325 private static void closeHttpClient(CloseableHttpClient client) {
327 if (client != null) {
330 } catch (IOException e) {
331 log.debug("failed to close client or response: ", e);
335 private static void closeResponse(CloseableHttpResponse response) {
337 if (response != null) {
340 } catch (IOException e) {
341 log.debug("failed to close client or response: {}", e);
345 public static HttpResponse<byte []> getCsar(String csarUid, User sdncModifierDetails) throws Exception {
347 Config config = Utils.getConfig();
348 String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
351 String userId = sdncModifierDetails.getUserId();
353 Map<String, String> headersMap = prepareHeadersMap(userId);
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);
361 for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
363 downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue());
365 return org.openecomp.sdc.common.http.client.api.HttpRequest.getAsByteArray(url, downloadCsarHeaders);
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();
377 public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole)
379 Config config = Utils.getConfig();
381 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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());
389 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);