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.dao.rest.HttpRestClient;
52 import org.openecomp.sdc.be.model.User;
53 import org.openecomp.sdc.ci.tests.api.Urls;
54 import org.openecomp.sdc.ci.tests.config.Config;
55 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
56 import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
57 import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum;
58 import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
59 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
60 import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
61 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
62 import org.openecomp.sdc.ci.tests.utils.Utils;
63 import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
64 import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 public class ImportRestUtils extends BaseRestUtils {
70 private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName());
71 private static Properties downloadCsarHeaders = new Properties();
74 downloadCsarHeaders.put("Accept", "application/octet-stream");
77 @SuppressWarnings("unused")
78 private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole)
80 Config config = Utils.getConfig();
81 CloseableHttpResponse response = null;
82 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
84 mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
85 mpBuilder.addPart("resourceMetadata",
86 new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"),
87 ContentType.APPLICATION_JSON));
89 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
90 config.getCatalogBePort());
92 CloseableHttpClient client = HttpClients.createDefault();
94 HttpPost httpPost = new HttpPost(url);
95 httpPost.addHeader("USER_ID", userRole.getUserId());
96 httpPost.setEntity(mpBuilder.build());
97 response = client.execute(httpPost);
98 return response.getStatusLine().getStatusCode();
100 closeResponse(response);
101 closeHttpClient(client);
107 * public static RestResponse importResourceByName(String resourceName, User
108 * user) throws IOException { Config config = Utils.getConfig();
109 * CloseableHttpResponse response = null; MultipartEntityBuilder mpBuilder =
110 * MultipartEntityBuilder.create();
112 * mpBuilder.addPart("resourceZip", new
113 * FileBody(getTestZipFile(resourceName)));
114 * mpBuilder.addPart("resourceMetadata", new
115 * StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"),
116 * ContentType.APPLICATION_JSON));
118 * String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE,
119 * config.getCatalogBeHost(), config.getCatalogBePort());
121 * CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost
122 * httpPost = new HttpPost(url); RestResponse restResponse = new
123 * RestResponse(); httpPost.addHeader("USER_ID", user.getUserId());
124 * httpPost.setEntity(mpBuilder.build()); response =
125 * client.execute(httpPost); HttpEntity entity = response.getEntity();
126 * String responseBody = null; if (entity != null) { InputStream instream =
127 * entity.getContent(); StringWriter writer = new StringWriter();
128 * IOUtils.copy(instream, writer); responseBody = writer.toString(); try {
130 * } finally { instream.close(); } }
132 * restResponse.setErrorCode(response.getStatusLine().getStatusCode());
133 * restResponse.setResponse(responseBody); if (restResponse.getErrorCode()
134 * == STATUS_CODE_CREATED ){
138 * return restResponse;
140 * } finally { closeResponse(response); closeHttpClient(client);
147 public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer)
149 Config config = Utils.getConfig();
150 CloseableHttpResponse response = null;
151 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
153 mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceDetails.getName())));
154 mpBuilder.addPart("resourceMetadata",
155 new StringBody(getTestJsonStringOfFile(resourceDetails.getName(), resourceDetails.getName() + ".json"),
156 ContentType.APPLICATION_JSON));
158 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
159 config.getCatalogBePort());
161 CloseableHttpClient client = HttpClients.createDefault();
163 HttpPost httpPost = new HttpPost(url);
164 RestResponse restResponse = new RestResponse();
165 httpPost.addHeader("USER_ID", importer.getUserId());
166 httpPost.setEntity(mpBuilder.build());
167 response = client.execute(httpPost);
168 HttpEntity entity = response.getEntity();
169 String responseBody = null;
170 if (entity != null) {
171 InputStream instream = entity.getContent();
172 StringWriter writer = new StringWriter();
173 IOUtils.copy(instream, writer);
174 responseBody = writer.toString();
182 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
183 restResponse.setResponse(responseBody);
185 if (restResponse.getErrorCode() == STATUS_CODE_CREATED) {
186 resourceDetails.setUUID(ResponseParser.getUuidFromResponse(restResponse));
187 resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
188 resourceDetails.setVersion(ResponseParser.getVersionFromResponse(restResponse));
189 resourceDetails.setCreatorUserId(importer.getUserId());
190 resourceDetails.setCreatorFullName(importer.getFullName());
196 closeResponse(response);
197 closeHttpClient(client);
203 public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
204 Config config = Utils.getConfig();
206 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
208 mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
209 mpBuilder.addPart("resourceMetadata", new StringBody(
210 getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
211 HttpEntity requestEntity = mpBuilder.build();
212 String url = String.format(Urls.IMPORT_USER_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
213 Map<String, String> headers = new HashMap<String, String>();
214 headers.put("USER_ID", userRole.getUserId());
216 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
219 public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole)
221 Config config = Utils.getConfig();
223 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
225 mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
226 mpBuilder.addPart("resourceMetadata", new StringBody(
227 getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
228 HttpEntity requestEntity = mpBuilder.build();
229 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
230 config.getCatalogBePort());
231 Map<String, String> headers = new HashMap<String, String>();
232 headers.put("USER_ID", userRole.getUserId());
234 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
237 public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole)
239 Config config = Utils.getConfig();
240 CloseableHttpResponse response = null;
241 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
243 mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
244 mpBuilder.addPart("resourceMetadata",
245 new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"),
246 ContentType.APPLICATION_JSON));
248 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
249 config.getCatalogBePort());
251 CloseableHttpClient client = HttpClients.createDefault();
253 HttpPost httpPost = new HttpPost(url);
254 RestResponse restResponse = new RestResponse();
255 httpPost.addHeader("USER_ID", UserRoleEnum.ADMIN.getUserId());
256 httpPost.setEntity(mpBuilder.build());
257 response = client.execute(httpPost);
258 HttpEntity entity = response.getEntity();
259 String responseBody = null;
260 if (entity != null) {
261 InputStream instream = entity.getContent();
262 StringWriter writer = new StringWriter();
263 IOUtils.copy(instream, writer);
264 responseBody = writer.toString();
272 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
273 // restResponse.setResponse(response.getEntity().toString());
274 restResponse.setResponse(responseBody);
277 closeResponse(response);
278 closeHttpClient(client);
283 public static Boolean removeNormativeTypeResource(NormativeTypesEnum current)
284 throws FileNotFoundException, IOException, ClientProtocolException {
285 User user = new User(UserRoleEnum.ADMIN.getFirstName(), UserRoleEnum.ADMIN.getLastName(),
286 UserRoleEnum.ADMIN.getUserId(), null, null, null);
287 RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(user, current.getNormativeName(),
289 if (deleteResponse.getErrorCode() == 200) {
295 public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse)
296 throws IOException, JSONException {
298 // assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS );
300 ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
302 assertNotNull("check response object is not null after create service", restResponse);
303 assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
304 assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
306 // validate create service response vs actual
307 List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams()
308 : new ArrayList<String>());
309 if (restResponse.getErrorCode() != 200) {
310 ErrorValidationUtils.checkBodyResponseOnError(currResource.getActionStatus().name(), variables,
311 restResponse.getResponse());
315 private static String getTestJsonStringOfFile(String folderName, String fileName) throws IOException {
316 // String sourceDir = "src/test/resources/CI/importResourceTests";
317 Config config = Utils.getConfig();
318 String sourceDir = config.getImportResourceTestsConfigDir();
319 java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName,
321 byte[] fileContent = Files.readAllBytes(filePath);
322 String content = new String(fileContent);
326 private static File getTestZipFile(String elementName) throws IOException {
327 Config config = Utils.getConfig();
328 String sourceDir = config.getImportResourceTestsConfigDir();
329 java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName,
330 "normative-types-new-" + elementName + ".zip");
331 return filePath.toFile();
334 private static void closeHttpClient(CloseableHttpClient client) {
336 if (client != null) {
339 } catch (IOException e) {
340 log.debug("failed to close client or response: ", e);
344 private static void closeResponse(CloseableHttpResponse response) {
346 if (response != null) {
349 } catch (IOException e) {
350 log.debug("failed to close client or response: {}", e);
354 public static RestResponseAsByteArray getCsar(String csarUid, User sdncModifierDetails) throws Exception {
356 Config config = Utils.getConfig();
357 String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
360 String userId = sdncModifierDetails.getUserId();
361 Map<String, String> headersMap = prepareHeadersMap(userId);
362 HttpRestClient httpRestClient = new HttpRestClient();
364 for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
366 downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue());
368 RestResponseAsByteArray doGetAsByteArray = httpRestClient.doGetAsByteArray(url, downloadCsarHeaders);
369 // RestResponse getCsar = http.httpSendGet(url, headersMap);
371 return doGetAsByteArray;
375 private static File getGroupTypeZipFile(String elementName) throws IOException {
376 Config config = Utils.getConfig();
377 String sourceDir = config.getImportResourceTestsConfigDir();
378 sourceDir += File.separator + ".." + File.separator + "importTypesTest" + File.separator;
379 java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName,
380 elementName + ".zip");
381 return filePath.toFile();
384 public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole)
386 Config config = Utils.getConfig();
388 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
390 mpBuilder.addPart("groupTypesZip", new FileBody(getGroupTypeZipFile(groupTypeName)));
391 HttpEntity requestEntity = mpBuilder.build();
392 String url = String.format(Urls.IMPORT_GROUP_TYPE, config.getCatalogBeHost(), config.getCatalogBePort());
393 Map<String, String> headers = new HashMap<String, String>();
394 headers.put("USER_ID", userRole.getUserId());
396 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);