Sync Integ to Master
[sdc.git] / test-apis-ci / src / main / java / org / openecomp / sdc / ci / tests / utils / rest / BaseRestUtils.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 java.io.BufferedReader;
24 import java.io.IOException;
25 import java.io.InputStreamReader;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import org.apache.commons.codec.binary.Base64;
31 import org.apache.http.HttpEntity;
32 import org.apache.http.client.methods.CloseableHttpResponse;
33 import org.apache.http.client.methods.HttpPost;
34 import org.apache.http.impl.client.CloseableHttpClient;
35 import org.apache.http.impl.client.HttpClients;
36 import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
37 import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
38 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
39 import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public class BaseRestUtils extends BaseValidationUtils {
44         public static final String contentTypeHeaderData = "application/json";
45         public static final String acceptHeaderData = "application/json";
46         public static final String acceptJsonHeader = "application/json";
47         public static final String acceptOctetHeader = "application/octet-stream";
48         public static final String acceptMultipartHeader = "application/octet-stream";
49         public static final String authorizationHeader = "Basic " + Base64.encodeBase64String("ci:123456".getBytes());
50         public static final String acceptOctetStream = "application/octet-stream";
51         public static final String ecomp = "ecomp";
52         public static final String authorizationPrefixString = "Basic ";
53         public static final String xEcompInstanceId = "a1bd39f6-d55e-45b2-9207-156216af5cb5";
54         public static final String cacheControlHeader = "no-cache";
55
56         public static final String RESOURCE_COMPONENT_TYPE = "resources";
57         public static final String PRODUCT_COMPONENT_TYPE = "products";
58         public static final String SERVICE_COMPONENT_TYPE = "services";
59
60         public static final int STATUS_CODE_SUCCESS = 200;
61         public static final int STATUS_CODE_CREATED = 201;
62         public static final int STATUS_CODE_DELETE = 204;
63         public static final int STATUS_CODE_NOT_FOUND = 404;
64         public static final int STATUS_CODE_SUCCESS_NO_CONTENT = 204;
65         public static final int STATUS_CODE_SUCCESS_DELETE = 204;
66         public static final int STATUS_CODE_INVALID_CONTENT = 400;
67         public static final int STATUS_CODE_MISSING_DATA = 400;
68         public static final int STATUS_CODE_MISSING_INFORMATION = 403;
69         public static final int STATUS_CODE_RESTRICTED_ACCESS = 403;
70         public static final int STATUS_CODE_ALREADY_EXISTS = 409;
71         public static final int STATUS_CODE_RESTRICTED_OPERATION = 409;
72         public static final int STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT = 400;
73         public static final int STATUS_CODE_MISSING_COMPONENT_NAME = 400;
74         public static final int STATUS_CODE_UNSUPPORTED_ERROR = 400;
75         public static final int STATUS_CODE_IMPORT_SUCCESS = 201;
76         public static final int STATUS_CODE_UPDATE_SUCCESS = 200;
77         public static final int RESTRICTED_OPERATION = 409;
78         public static final int STATUS_CODE_GET_SUCCESS = 200;
79
80         public static final String SUCCESS_MESSAGE = "OK";
81         private static Logger logger = LoggerFactory.getLogger(BaseRestUtils.class.getName());
82
83         private static byte[] encodeBase64;
84
85         // ************* PRIVATE METHODS ************************
86
87         protected static Map<String, String> prepareHeadersMap(String userId) {
88                 return prepareHeadersMap(userId, acceptHeaderData);
89         }
90
91         protected static Map<String, String> prepareHeadersMap(String userId, String accept) {
92                 Map<String, String> headersMap = new HashMap<>();
93                 if (contentTypeHeaderData != null) {
94                         headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
95                 }
96                 if (accept != null) {
97                         headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), accept);
98                 }
99                 if (userId != null) {
100                         headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
101                 }
102
103                 return headersMap;
104         }
105
106         // send request
107         // GET
108         protected static RestResponse sendGet(String url, String userId) throws IOException {
109                 return sendGet(url, userId, null);
110         }
111
112         protected static RestResponse sendGet(String url, String userId, Map<String, String> additionalHeaders)
113                         throws IOException {
114                 Map<String, String> headersMap = prepareHeadersMap(userId);
115                 if (additionalHeaders != null) {
116                         headersMap.putAll(additionalHeaders);
117                 }
118
119                 HttpRequest http = new HttpRequest();
120                 RestResponse getResourceResponse = http.httpSendGet(url, headersMap);
121                 return getResourceResponse;
122         }
123
124         public static RestResponse sendGetAndRemoveHeaders(String url, String userId, List<String> headersToRemove)
125                         throws IOException {
126                 Map<String, String> headersMap = prepareHeadersMap(userId);
127                 if (headersToRemove != null) {
128                         for (String header : headersToRemove) {
129                                 headersMap.remove(header);
130                         }
131                 }
132
133                 HttpRequest http = new HttpRequest();
134                 RestResponse getResourceResponse = http.httpSendGet(url, headersMap);
135                 return getResourceResponse;
136         }
137
138         // PUT
139         protected static RestResponse sendPut(String url, String userBodyJson, String userId, String cont)
140                         throws IOException {
141                 Map<String, String> headersMap = prepareHeadersMap(userId, cont);
142
143                 HttpRequest http = new HttpRequest();
144                 RestResponse updateResourceResponse = http.httpSendByMethod(url, "PUT", userBodyJson, headersMap);
145                 return updateResourceResponse;
146         }
147
148         // POST
149         public static RestResponse sendPost(String url, String userBodyJson, String userId, String accept)
150                         throws IOException {
151                 return sendPost(url, userBodyJson, userId, accept, null);
152         }
153
154         protected static RestResponse sendPost(String url, String userBodyJson, String userId, String accept,
155                         Map<String, String> additionalHeaders) throws IOException {
156                 Map<String, String> headersMap = prepareHeadersMap(userId, accept);
157                 if (additionalHeaders != null) {
158                         headersMap.putAll(additionalHeaders);
159                 }
160                 HttpRequest http = new HttpRequest();
161                 RestResponse postResourceResponse = http.httpSendPost(url, userBodyJson, headersMap);
162                 return postResourceResponse;
163         }
164
165         // used form complex requests like import categories..
166         protected static RestResponse sendPost(String url, HttpEntity entity, String userId, String accept)
167                         throws IOException {
168                 RestResponse postResponse = new RestResponse();
169                 CloseableHttpResponse response = null;
170                 CloseableHttpClient client = null;
171                 try {
172                         client = HttpClients.createDefault();
173                         HttpPost httpPost = new HttpPost(url);
174
175                         httpPost.addHeader("USER_ID", userId);
176                         httpPost.setEntity(entity);
177                         response = client.execute(httpPost);
178                         HttpEntity responseEntity = response.getEntity();
179                         int statusCode = response.getStatusLine().getStatusCode();
180
181                         postResponse.setErrorCode(statusCode);
182                         StringBuffer sb = new StringBuffer();
183                         try {
184                                 BufferedReader in = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
185                                 String inputLine;
186                                 while ((inputLine = in.readLine()) != null) {
187                                         sb.append(inputLine);
188                                 }
189                                 in.close();
190                         } catch (Exception e) {
191                                 logger.debug("response body is null");
192                         }
193                         postResponse.setResponse(sb.toString());
194                 } finally {
195                         try {
196                                 if (response != null) {
197                                         response.close();
198                                 }
199
200                         } catch (IOException e) {
201                                 logger.debug("failed to close client or response: ", e);
202                         }
203                         try {
204                                 if (client != null) {
205                                         client.close();
206                                 }
207                         } catch (IOException e) {
208                                 logger.debug("failed to close client or response: ", e);
209                         }
210                 }
211                 return postResponse;
212         }
213
214         // DELETE
215         protected static RestResponse sendDelete(String url, String userId) throws IOException {
216 //              Map<String, String> headersMap = prepareHeadersMap(userId);
217                 
218                 return sendDelete(url, userId, null);
219         }
220         
221         protected static RestResponse sendDelete(String url, String userId, Map<String, String> additionalHeaders) throws IOException {
222                 Map<String, String> headersMap = prepareHeadersMap(userId);
223                 if (additionalHeaders != null) {
224                         headersMap.putAll(additionalHeaders);
225                 }
226                 
227                 HttpRequest http = new HttpRequest();
228                 RestResponse deleteResourceResponse = http.httpSendDelete(url, headersMap);
229                 return deleteResourceResponse;
230         }
231
232         /*
233          * // ------ protected static Boolean checkErrorCode(RestResponse
234          * deleteResponse) { if (deleteResponse.getErrorCode() ==
235          * STATUS_CODE_SUCCESS || deleteResponse.getErrorCode() ==
236          * STATUS_CODE_DELETE) { return true; } return false; }
237          * 
238          * // *** STATUS CODE VALIDATION UTIITIES **** public static void
239          * checkStatusCode(RestResponse response, String assertMessage, boolean AND,
240          * int... statuses) { int statusCode = response.getErrorCode(); for (int
241          * status : statuses) { if (AND && statusCode != status) {
242          * Assert.fail(assertMessage + " status: " + statusCode); } else if
243          * (statusCode == status) { return; } } if (!AND) {
244          * Assert.fail(assertMessage + " status: " + statusCode); } }
245          * 
246          * public static void checkDeleteResponse(RestResponse response) {
247          * checkStatusCode(response,"delete request failed",false,STATUS_CODE_DELETE
248          * ,STATUS_CODE_NOT_FOUND, STATUS_CODE_SUCCESS); // STATUS_CODE_SUCCESS for
249          * deActivate user }
250          * 
251          * public static void checkCreateResponse(RestResponse response) {
252          * checkStatusCode(response, "create request failed", false,
253          * STATUS_CODE_CREATED); }
254          */
255         public static String encodeUrlForDownload(String url) {
256                 return url.replaceAll(" ", "%20");
257         }
258
259         public static Map<String, String> addAuthorizeHeader(String userName, String password) {
260                 String userCredentials = userName + ":" + password;
261                 encodeBase64 = Base64.encodeBase64(userCredentials.getBytes());
262                 String encodedUserCredentials = authorizationPrefixString + new String(encodeBase64);
263                 Map<String, String> authorizationHeader = new HashMap<>();
264                 authorizationHeader.put(HttpHeaderEnum.AUTHORIZATION.getValue(), encodedUserCredentials);
265                 return authorizationHeader;
266         }
267
268 }