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.Properties;
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;
67 public class ImportRestUtils extends BaseRestUtils {
69 private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName());
70 private static Properties downloadCsarHeaders = new Properties();
73 downloadCsarHeaders.put("Accept", "application/octet-stream");
76 @SuppressWarnings("unused")
77 private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole)
79 Config config = Utils.getConfig();
80 CloseableHttpResponse response = null;
81 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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));
88 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
89 config.getCatalogBePort());
91 CloseableHttpClient client = HttpClients.createDefault();
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();
99 closeResponse(response);
100 closeHttpClient(client);
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();
111 * mpBuilder.addPart("resourceZip", new
112 * FileBody(getTestZipFile(resourceName)));
113 * mpBuilder.addPart("resourceMetadata", new
114 * StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"),
115 * ContentType.APPLICATION_JSON));
117 * String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE,
118 * config.getCatalogBeHost(), config.getCatalogBePort());
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 {
129 * } finally { instream.close(); } }
131 * restResponse.setErrorCode(response.getStatusLine().getStatusCode());
132 * restResponse.setResponse(responseBody); if (restResponse.getErrorCode()
133 * == STATUS_CODE_CREATED ){
137 * return restResponse;
139 * } finally { closeResponse(response); closeHttpClient(client);
146 public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer)
148 Config config = Utils.getConfig();
149 CloseableHttpResponse response = null;
150 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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));
157 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
158 config.getCatalogBePort());
160 CloseableHttpClient client = HttpClients.createDefault();
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();
181 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
182 restResponse.setResponse(responseBody);
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());
195 closeResponse(response);
196 closeHttpClient(client);
202 public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
203 Config config = Utils.getConfig();
205 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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());
215 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
218 public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole)
220 Config config = Utils.getConfig();
222 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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());
233 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
236 public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole)
238 Config config = Utils.getConfig();
239 CloseableHttpResponse response = null;
240 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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));
247 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
248 config.getCatalogBePort());
250 CloseableHttpClient client = HttpClients.createDefault();
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();
271 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
272 // restResponse.setResponse(response.getEntity().toString());
273 restResponse.setResponse(responseBody);
276 closeResponse(response);
277 closeHttpClient(client);
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(),
288 if (deleteResponse.getErrorCode() == 200) {
294 public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse)
295 throws IOException, JSONException {
297 // assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS );
299 ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
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());
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());
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,
320 byte[] fileContent = Files.readAllBytes(filePath);
321 String content = new String(fileContent);
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();
333 private static void closeHttpClient(CloseableHttpClient client) {
335 if (client != null) {
338 } catch (IOException e) {
339 log.debug("failed to close client or response: ", e);
343 private static void closeResponse(CloseableHttpResponse response) {
345 if (response != null) {
348 } catch (IOException e) {
349 log.debug("failed to close client or response: {}", e);
353 public static HttpResponse<byte []> getCsar(String csarUid, User sdncModifierDetails) throws Exception {
355 Config config = Utils.getConfig();
356 String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
359 String userId = sdncModifierDetails.getUserId();
361 Map<String, String> headersMap = prepareHeadersMap(userId);
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);
369 for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
371 downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue());
373 return org.openecomp.sdc.common.http.client.api.HttpRequest.getAsByteArray(url, downloadCsarHeaders);
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();
385 public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole)
387 Config config = Utils.getConfig();
389 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
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());
397 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);