Fix for radio buttons
[sdc.git] / asdc-tests / src / main / java / org / openecomp / sdc / ci / tests / utils / rest / ImportRestUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.ci.tests.utils.rest;
22
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertNotNull;
25
26 import java.io.File;
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;
36 import java.util.Map;
37 import java.util.Properties;
38
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;
67
68 public class ImportRestUtils extends BaseRestUtils {
69
70         private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName());
71         private static Properties downloadCsarHeaders = new Properties();
72
73         static {
74                 downloadCsarHeaders.put("Accept", "application/octet-stream");
75         }
76
77         @SuppressWarnings("unused")
78         private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole)
79                         throws IOException {
80                 Config config = Utils.getConfig();
81                 CloseableHttpResponse response = null;
82                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
83
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));
88
89                 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
90                                 config.getCatalogBePort());
91
92                 CloseableHttpClient client = HttpClients.createDefault();
93                 try {
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();
99                 } finally {
100                         closeResponse(response);
101                         closeHttpClient(client);
102
103                 }
104         }
105
106         /*
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();
111          * 
112          * mpBuilder.addPart("resourceZip", new
113          * FileBody(getTestZipFile(resourceName)));
114          * mpBuilder.addPart("resourceMetadata", new
115          * StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"),
116          * ContentType.APPLICATION_JSON));
117          * 
118          * String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE,
119          * config.getCatalogBeHost(), config.getCatalogBePort());
120          * 
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 {
129          * 
130          * } finally { instream.close(); } }
131          * 
132          * restResponse.setErrorCode(response.getStatusLine().getStatusCode());
133          * restResponse.setResponse(responseBody); if (restResponse.getErrorCode()
134          * == STATUS_CODE_CREATED ){
135          * 
136          * }
137          * 
138          * return restResponse;
139          * 
140          * } finally { closeResponse(response); closeHttpClient(client);
141          * 
142          * }
143          * 
144          * }
145          */
146
147         public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer)
148                         throws Exception {
149                 Config config = Utils.getConfig();
150                 CloseableHttpResponse response = null;
151                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
152
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));
157
158                 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
159                                 config.getCatalogBePort());
160
161                 CloseableHttpClient client = HttpClients.createDefault();
162                 try {
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();
175                                 try {
176
177                                 } finally {
178                                         instream.close();
179                                 }
180                         }
181
182                         restResponse.setErrorCode(response.getStatusLine().getStatusCode());
183                         restResponse.setResponse(responseBody);
184
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());
191                         }
192
193                         return restResponse;
194
195                 } finally {
196                         closeResponse(response);
197                         closeHttpClient(client);
198
199                 }
200
201         }
202
203         public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
204                 Config config = Utils.getConfig();
205
206                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
207
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());
215
216                 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
217         }
218
219         public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole)
220                         throws IOException {
221                 Config config = Utils.getConfig();
222
223                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
224
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());
233
234                 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
235         }
236
237         public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole)
238                         throws IOException {
239                 Config config = Utils.getConfig();
240                 CloseableHttpResponse response = null;
241                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
242
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));
247
248                 String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
249                                 config.getCatalogBePort());
250
251                 CloseableHttpClient client = HttpClients.createDefault();
252                 try {
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();
265                                 try {
266
267                                 } finally {
268                                         instream.close();
269                                 }
270                         }
271
272                         restResponse.setErrorCode(response.getStatusLine().getStatusCode());
273                         // restResponse.setResponse(response.getEntity().toString());
274                         restResponse.setResponse(responseBody);
275                         return restResponse;
276                 } finally {
277                         closeResponse(response);
278                         closeHttpClient(client);
279
280                 }
281         }
282
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(),
288                                 "1.0");
289                 if (deleteResponse.getErrorCode() == 200) {
290                         return true;
291                 }
292                 return false;
293         }
294
295         public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse)
296                         throws IOException, JSONException {
297
298                 // assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS );
299
300                 ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
301
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());
305
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());
312                 }
313         }
314
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,
320                                 fileName);
321                 byte[] fileContent = Files.readAllBytes(filePath);
322                 String content = new String(fileContent);
323                 return content;
324         }
325
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();
332         }
333
334         private static void closeHttpClient(CloseableHttpClient client) {
335                 try {
336                         if (client != null) {
337                                 client.close();
338                         }
339                 } catch (IOException e) {
340                         log.debug("failed to close client or response: ", e);
341                 }
342         }
343
344         private static void closeResponse(CloseableHttpResponse response) {
345                 try {
346                         if (response != null) {
347                                 response.close();
348                         }
349                 } catch (IOException e) {
350                         log.debug("failed to close client or response: {}", e);
351                 }
352         }
353
354         public static RestResponseAsByteArray getCsar(String csarUid, User sdncModifierDetails) throws Exception {
355
356                 Config config = Utils.getConfig();
357                 String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
358                                 csarUid);
359
360                 String userId = sdncModifierDetails.getUserId();
361                 Map<String, String> headersMap = prepareHeadersMap(userId);
362                 HttpRestClient httpRestClient = new HttpRestClient();
363
364                 for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
365
366                         downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue());
367                 }
368                 RestResponseAsByteArray doGetAsByteArray = httpRestClient.doGetAsByteArray(url, downloadCsarHeaders);
369                 // RestResponse getCsar = http.httpSendGet(url, headersMap);
370
371                 return doGetAsByteArray;
372
373         }
374
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();
382         }
383
384         public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole)
385                         throws IOException {
386                 Config config = Utils.getConfig();
387
388                 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
389
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());
395
396                 return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
397         }
398
399 }