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