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 static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertNotNull;
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;
37 import java.util.Map.Entry;
38 import java.util.Properties;
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;
69 public class ImportRestUtils extends BaseRestUtils {
71 private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName());
72 private static Properties downloadCsarHeaders = new Properties();
75 downloadCsarHeaders.put("Accept", "application/octet-stream");
78 @SuppressWarnings("unused")
79 private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole)
81 Config config = Utils.getConfig();
82 CloseableHttpResponse response = null;
83 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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));
90 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
91 config.getCatalogBePort());
93 CloseableHttpClient client = HttpClients.createDefault();
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();
101 closeResponse(response);
102 closeHttpClient(client);
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();
113 * mpBuilder.addPart("resourceZip", new
114 * FileBody(getTestZipFile(resourceName)));
115 * mpBuilder.addPart("resourceMetadata", new
116 * StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"),
117 * ContentType.APPLICATION_JSON));
119 * String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE,
120 * config.getCatalogBeHost(), config.getCatalogBePort());
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 {
131 * } finally { instream.close(); } }
133 * restResponse.setErrorCode(response.getStatusLine().getStatusCode());
134 * restResponse.setResponse(responseBody); if (restResponse.getErrorCode()
135 * == STATUS_CODE_CREATED ){
139 * return restResponse;
141 * } finally { closeResponse(response); closeHttpClient(client);
148 public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer)
150 Config config = Utils.getConfig();
151 CloseableHttpResponse response = null;
152 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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));
159 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
160 config.getCatalogBePort());
162 CloseableHttpClient client = HttpClients.createDefault();
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();
183 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
184 restResponse.setResponse(responseBody);
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());
197 closeResponse(response);
198 closeHttpClient(client);
204 public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
205 Config config = Utils.getConfig();
207 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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());
217 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
220 public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole)
222 Config config = Utils.getConfig();
224 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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());
235 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
238 public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole)
240 Config config = Utils.getConfig();
241 CloseableHttpResponse response = null;
242 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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));
249 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
250 config.getCatalogBePort());
252 CloseableHttpClient client = HttpClients.createDefault();
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();
273 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
274 // restResponse.setResponse(response.getEntity().toString());
275 restResponse.setResponse(responseBody);
278 closeResponse(response);
279 closeHttpClient(client);
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(),
290 if (deleteResponse.getErrorCode() == 200) {
296 public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse)
297 throws IOException, JSONException {
299 // assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS );
301 ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
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());
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());
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,
322 byte[] fileContent = Files.readAllBytes(filePath);
323 String content = new String(fileContent);
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();
335 private static void closeHttpClient(CloseableHttpClient client) {
337 if (client != null) {
340 } catch (IOException e) {
341 log.debug("failed to close client or response: ", e);
345 private static void closeResponse(CloseableHttpResponse response) {
347 if (response != null) {
350 } catch (IOException e) {
351 log.debug("failed to close client or response: {}", e);
355 public static RestResponseAsByteArray getCsar(String csarUid, User sdncModifierDetails) throws Exception {
357 Config config = Utils.getConfig();
358 String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
361 String userId = sdncModifierDetails.getUserId();
363 Map<String, String> headersMap = prepareHeadersMap(userId);
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);
371 HttpRestClient httpRestClient = new HttpRestClient();
373 for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
375 downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue());
377 RestResponseAsByteArray doGetAsByteArray = httpRestClient.doGetAsByteArray(url, downloadCsarHeaders);
378 // RestResponse getCsar = http.httpSendGet(url, headersMap);
380 return doGetAsByteArray;
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();
393 public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole)
395 Config config = Utils.getConfig();
397 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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());
405 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);