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