aboutsummaryrefslogtreecommitdiffstats
path: root/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java
blob: 0edc2946939c4894888274d0fc5b18a1e275a8d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.ci.tests.utils.rest;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.codehaus.jettison.json.JSONException;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
import org.openecomp.sdc.common.http.client.api.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.*;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;

public class ImportRestUtils extends BaseRestUtils {

	private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName());
	private static Properties downloadCsarHeaders = new Properties();

	static {
		downloadCsarHeaders.put("Accept", "application/octet-stream");
	}

	@SuppressWarnings("unused")
	private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole)
			throws IOException {
		Config config = Utils.getConfig();
		CloseableHttpResponse response = null;
		MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

		mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
		mpBuilder.addPart("resourceMetadata",
				new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"),
						ContentType.APPLICATION_JSON));

		String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
				config.getCatalogBePort());

		CloseableHttpClient client = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("USER_ID", userRole.getUserId());
			httpPost.setEntity(mpBuilder.build());
			response = client.execute(httpPost);
			return response.getStatusLine().getStatusCode();
		} finally {
			closeResponse(response);
			closeHttpClient(client);

		}
	}

	/*
	 * public static RestResponse importResourceByName(String resourceName, User
	 * user) throws IOException { Config config = Utils.getConfig();
	 * CloseableHttpResponse response = null; MultipartEntityBuilder mpBuilder =
	 * MultipartEntityBuilder.create();
	 * 
	 * mpBuilder.addPart("resourceZip", new
	 * FileBody(getTestZipFile(resourceName)));
	 * mpBuilder.addPart("resourceMetadata", new
	 * StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"),
	 * ContentType.APPLICATION_JSON));
	 * 
	 * String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE,
	 * config.getCatalogBeHost(), config.getCatalogBePort());
	 * 
	 * CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost
	 * httpPost = new HttpPost(url); RestResponse restResponse = new
	 * RestResponse(); httpPost.addHeader("USER_ID", user.getUserId());
	 * httpPost.setEntity(mpBuilder.build()); response =
	 * client.execute(httpPost); HttpEntity entity = response.getEntity();
	 * String responseBody = null; if (entity != null) { InputStream instream =
	 * entity.getContent(); StringWriter writer = new StringWriter();
	 * IOUtils.copy(instream, writer); responseBody = writer.toString(); try {
	 * 
	 * } finally { instream.close(); } }
	 * 
	 * restResponse.setErrorCode(response.getStatusLine().getStatusCode());
	 * restResponse.setResponse(responseBody); if (restResponse.getErrorCode()
	 * == STATUS_CODE_CREATED ){
	 * 
	 * }
	 * 
	 * return restResponse;
	 * 
	 * } finally { closeResponse(response); closeHttpClient(client);
	 * 
	 * }
	 * 
	 * }
	 */

	public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer)
			throws Exception {
		Config config = Utils.getConfig();
		CloseableHttpResponse response = null;
		MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

		mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceDetails.getName())));
		mpBuilder.addPart("resourceMetadata",
				new StringBody(getTestJsonStringOfFile(resourceDetails.getName(), resourceDetails.getName() + ".json"),
						ContentType.APPLICATION_JSON));

		String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
				config.getCatalogBePort());

		CloseableHttpClient client = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(url);
			RestResponse restResponse = new RestResponse();
			httpPost.addHeader("USER_ID", importer.getUserId());
			httpPost.setEntity(mpBuilder.build());
			response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			String responseBody = null;
			if (entity != null) {
				InputStream instream = entity.getContent();
				StringWriter writer = new StringWriter();
				IOUtils.copy(instream, writer);
				responseBody = writer.toString();
				try {

				} finally {
					instream.close();
				}
			}

			restResponse.setErrorCode(response.getStatusLine().getStatusCode());
			restResponse.setResponse(responseBody);

			if (restResponse.getErrorCode() == STATUS_CODE_CREATED) {
				resourceDetails.setUUID(ResponseParser.getUuidFromResponse(restResponse));
				resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
				resourceDetails.setVersion(ResponseParser.getVersionFromResponse(restResponse));
				resourceDetails.setCreatorUserId(importer.getUserId());
				resourceDetails.setCreatorFullName(importer.getFullName());
			}

			return restResponse;

		} finally {
			closeResponse(response);
			closeHttpClient(client);

		}

	}

	public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
		Config config = Utils.getConfig();

		MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

		mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
		mpBuilder.addPart("resourceMetadata", new StringBody(
				getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
		HttpEntity requestEntity = mpBuilder.build();
		String url = String.format(Urls.IMPORT_USER_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("USER_ID", userRole.getUserId());

		return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
	}

	public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole)
			throws IOException {
		Config config = Utils.getConfig();

		MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

		mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
		mpBuilder.addPart("resourceMetadata", new StringBody(
				getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
		HttpEntity requestEntity = mpBuilder.build();
		String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
				config.getCatalogBePort());
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("USER_ID", userRole.getUserId());

		return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
	}

	public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole)
			throws IOException {
		Config config = Utils.getConfig();
		CloseableHttpResponse response = null;
		MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

		mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
		mpBuilder.addPart("resourceMetadata",
				new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"),
						ContentType.APPLICATION_JSON));

		String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
				config.getCatalogBePort());

		CloseableHttpClient client = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(url);
			RestResponse restResponse = new RestResponse();
			httpPost.addHeader("USER_ID", UserRoleEnum.ADMIN.getUserId());
			httpPost.setEntity(mpBuilder.build());
			response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			String responseBody = null;
			if (entity != null) {
				InputStream instream = entity.getContent();
				StringWriter writer = new StringWriter();
				IOUtils.copy(instream, writer);
				responseBody = writer.toString();
				try {

				} finally {
					instream.close();
				}
			}

			restResponse.setErrorCode(response.getStatusLine().getStatusCode());
			// restResponse.setResponse(response.getEntity().toString());
			restResponse.setResponse(responseBody);
			return restResponse;
		} finally {
			closeResponse(response);
			closeHttpClient(client);

		}
	}

	public static Boolean removeNormativeTypeResource(NormativeTypesEnum current)
			throws FileNotFoundException, IOException, ClientProtocolException {
		User user = new User(UserRoleEnum.ADMIN.getFirstName(), UserRoleEnum.ADMIN.getLastName(),
				UserRoleEnum.ADMIN.getUserId(), null, null, null);
		RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(user, current.getNormativeName(),
				"1.0");
		if (deleteResponse.getErrorCode() == 200) {
			return true;
		}
		return false;
	}

	public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse)
			throws IOException, JSONException {

		// assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS );

		ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());

		assertNotNull("check response object is not null after create service", restResponse);
		assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
		assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());

		// validate create service response vs actual
		List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams()
				: new ArrayList<String>());
		if (restResponse.getErrorCode() != 200) {
			ErrorValidationUtils.checkBodyResponseOnError(currResource.getActionStatus().name(), variables,
					restResponse.getResponse());
		}
	}

	private static String getTestJsonStringOfFile(String folderName, String fileName) throws IOException {
		// String sourceDir = "src/test/resources/CI/importResourceTests";
		Config config = Utils.getConfig();
		String sourceDir = config.getImportResourceTestsConfigDir();
		java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName,
				fileName);
		byte[] fileContent = Files.readAllBytes(filePath);
		String content = new String(fileContent);
		return content;
	}

	private static File getTestZipFile(String elementName) throws IOException {
		Config config = Utils.getConfig();
		String sourceDir = config.getImportResourceTestsConfigDir();
		java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName,
				"normative-types-new-" + elementName + ".zip");
		return filePath.toFile();
	}

	private static void closeHttpClient(CloseableHttpClient client) {
		try {
			if (client != null) {
				client.close();
			}
		} catch (IOException e) {
			log.debug("failed to close client or response: ", e);
		}
	}

	private static void closeResponse(CloseableHttpResponse response) {
		try {
			if (response != null) {
				response.close();
			}
		} catch (IOException e) {
			log.debug("failed to close client or response: {}", e);
		}
	}

	public static HttpResponse<byte []> getCsar(String csarUid, User sdncModifierDetails) throws Exception {

		Config config = Utils.getConfig();
		String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
				csarUid);

		String userId = sdncModifierDetails.getUserId();

		Map<String, String> headersMap = prepareHeadersMap(userId);

		// Gson gson = new Gson();
		// String userBodyJson = gson.toJson(resourceDetails);
		HttpRequest http = new HttpRequest();
		// System.out.println(url);
		// System.out.println(userBodyJson);

		for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {

			downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue());
		}
		return org.openecomp.sdc.common.http.client.api.HttpRequest.getAsByteArray(url, downloadCsarHeaders);
	}

	private static File getGroupTypeZipFile(String elementName) throws IOException {
		Config config = Utils.getConfig();
		String sourceDir = config.getImportResourceTestsConfigDir();
		sourceDir += File.separator + ".." + File.separator + "importTypesTest" + File.separator;
		java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName,
				elementName + ".zip");
		return filePath.toFile();
	}

	public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole)
			throws IOException {
		Config config = Utils.getConfig();

		MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();

		mpBuilder.addPart("groupTypesZip", new FileBody(getGroupTypeZipFile(groupTypeName)));
		HttpEntity requestEntity = mpBuilder.build();
		String url = String.format(Urls.IMPORT_GROUP_TYPE, config.getCatalogBeHost(), config.getCatalogBePort());
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("USER_ID", userRole.getUserId());

		return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
	}

}