re base code
[sdc.git] / test-apis-ci / src / main / java / org / openecomp / sdc / ci / tests / datatypes / http / HttpRequest.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.datatypes.http;
22
23 import org.apache.commons.io.IOUtils;
24 import org.apache.http.HttpEntity;
25 import org.apache.http.annotation.NotThreadSafe;
26 import org.apache.http.client.methods.CloseableHttpResponse;
27 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
28 import org.apache.http.client.methods.HttpPost;
29 import org.apache.http.impl.client.CloseableHttpClient;
30 import org.apache.http.impl.client.HttpClients;
31 import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import sun.net.www.protocol.https.DefaultHostnameVerifier;
35
36 import javax.net.ssl.HostnameVerifier;
37 import javax.net.ssl.HttpsURLConnection;
38 import java.io.*;
39 import java.net.HttpURLConnection;
40 import java.net.URI;
41 import java.net.URL;
42 import java.nio.charset.Charset;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Map.Entry;
46
47 public class HttpRequest {
48         static Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName());
49
50 //      -----------------------------Http------------------------------------------------------------------------
51         public RestResponse httpSendGetInternal(String url, Map<String, String> headers) throws IOException {
52
53                 RestResponse restResponse = new RestResponse();
54                 url = url.replaceAll("\\s", "%20");
55                 URL obj = new URL(url);
56                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
57                 // optional default is GET
58                 con.setRequestMethod("GET");
59                 addHttpRequestHEaders(headers, con);
60
61                 int responseCode = con.getResponseCode();
62                 logger.debug("Send GET http request, url: {}",url);
63                 logger.debug("Response Code: {}",responseCode);
64
65                 StringBuffer response = new StringBuffer();
66                 String result;
67                 try {
68
69                         result = IOUtils.toString(con.getInputStream());
70                         response.append(result);
71                 } catch (Exception e) {
72                         logger.debug("Fail with exception", e);
73                 }
74                 try {
75                         result = IOUtils.toString(con.getErrorStream());
76                         response.append(result);
77                 } catch (Exception e) {
78 //                      logger.debug("Fail with exception", e);
79                 }
80
81                 logger.debug("Response body: {}" ,response);
82
83                 // print result
84                 setHttpResponseToObject(restResponse, con, responseCode, response);
85                 con.disconnect();
86
87                 return restResponse;
88         }
89
90         public RestResponse httpSendByMethodInternal(String url, String method, String body, Map<String, String> headers) throws IOException {
91
92                 RestResponse restResponse = new RestResponse();
93                 URL obj = new URL(url);
94                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
95 // add request method
96                 con.setRequestMethod(method);
97 // add request headers
98                 addHttpRequestHEaders(headers, con);
99                 if (body != null && !body.isEmpty() && !method.equals("DELETE")) {
100 // Send post request
101                         con.setDoOutput(true);
102                         DataOutputStream wr = new DataOutputStream(con.getOutputStream());
103                         wr.writeBytes(body);
104                         wr.flush();
105                         wr.close();
106                 }
107
108                 int responseCode = con.getResponseCode();
109                 logger.debug("Send {} http request, url: {}",method,url);
110                 logger.debug("Response Code: {}",responseCode);
111
112                 StringBuffer response = generateHttpResponse(con, false);
113                 String result;
114                 try {
115                         result = IOUtils.toString(con.getErrorStream());
116                         response.append(result);
117                 } catch (Exception e) {
118 //                      logger.debug("Fail with exception", e);
119                 }
120                 logger.debug("Response body: {}",response);
121 // print result
122                 setHttpResponseToObject(restResponse, con, responseCode, response);
123                 con.disconnect();
124
125                 return restResponse;
126         }
127
128         public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {
129                 if (url.matches("^(https)://.*$")){
130                         return httpsSendDelete(url, headers);
131                 }
132                 return httpSendDeleteInternal(url, headers);
133         }
134
135         public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException {
136                 if (url.matches("^(https)://.*$")){
137                         return httpsSendGet(url, headers);
138                 }
139                 return httpSendGetInternal(url, headers);
140         }
141
142         public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers) throws IOException {
143                 if (url.matches("^(https)://.*$")){
144                         return httpsSendByMethod(url, method, body, headers);
145                 }
146                 return httpSendByMethodInternal(url, method, body, headers);
147         }
148
149         public RestResponse httpSendPost(String url, String body, Map<String, String> headers) throws IOException {
150                 if (url.matches("^(https)://.*$")){
151                         return httpsSendByMethod(url, "POST", body, headers);
152                 }
153                 return httpSendByMethod(url, "POST", body, headers);
154         }
155
156         public RestResponse httpSendPut(String url, String body, Map<String, String> headers) throws IOException {
157                 if (url.matches("^(https)://.*$")){
158                         return httpsSendByMethod(url, "PUT", body, headers);
159                 }
160                 return httpSendByMethod(url, "PUT", body, headers);
161         }
162
163
164         public RestResponse httpSendDeleteInternal(String url, Map<String, String> headers) throws IOException {
165
166                 RestResponse restResponse = new RestResponse();
167                 URL obj = new URL(url);
168                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
169
170                 addHttpRequestHEaders(headers, con);
171
172                 con.setDoOutput(true);
173                 con.setRequestMethod("DELETE");
174                 int responseCode = con.getResponseCode();
175                 logger.debug("Send DELETE http request, url: {}",url);
176                 logger.debug("Response Code: {}",responseCode);
177
178                 StringBuffer response = generateHttpResponse(con, false);
179                 String result;
180                 try {
181                         result = IOUtils.toString(con.getErrorStream());
182                         response.append(result);
183                 } catch (Exception e) {
184 //                      logger.debug("Fail with exception", e);
185                 }
186                 logger.debug("Response body: {}",response);
187
188 // print result
189                 setHttpResponseToObject(restResponse, con, responseCode, response);
190                 con.disconnect();
191
192                 return restResponse;
193         }
194
195         public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map<String, String> headers) throws IOException {
196                 CloseableHttpResponse response = null;
197                 CloseableHttpClient client = HttpClients.createDefault();
198                 try {
199                         HttpPost httpPost = new HttpPost(url);
200                         RestResponse restResponse = new RestResponse();
201                         for (Entry<String, String> entry : headers.entrySet()) {
202                                 httpPost.addHeader(entry.getKey(), entry.getValue());
203                         }
204
205                         httpPost.setEntity(requestEntity);
206                         response = client.execute(httpPost);
207                         HttpEntity responseEntity = response.getEntity();
208                         String responseBody = null;
209                         if (responseEntity != null) {
210                                 InputStream instream = responseEntity.getContent();
211                                 StringWriter writer = new StringWriter();
212                                 IOUtils.copy(instream, writer);
213                                 responseBody = writer.toString();
214                                 try {
215
216                                 } finally {
217                                         instream.close();
218                                 }
219                         }
220
221                         restResponse.setErrorCode(response.getStatusLine().getStatusCode());
222                         restResponse.setResponse(responseBody);
223
224                         return restResponse;
225
226                 } finally {
227                         closeResponse(response);
228                         closeHttpClient(client);
229
230                 }
231         }
232
233         private static void closeHttpClient(CloseableHttpClient client) {
234                 try {
235                         if (client != null) {
236                                 client.close();
237                         }
238                 } catch (IOException e) {
239                         logger.debug("failed to close client or response: ", e);
240                 }
241         }
242
243         private static void closeResponse(CloseableHttpResponse response) {
244                 try {
245                         if (response != null) {
246                                 response.close();
247                         }
248                 } catch (IOException e) {
249                         logger.debug("failed to close client or response: ", e);
250                 }
251         }
252
253
254         //      -----------------------------Https------------------------------------------------------------------------
255         public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {
256
257                 RestResponse restResponse = new RestResponse();
258                 url = url.replaceAll("\\s", "%20");
259                 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
260                 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
261 // optional default is GET
262                 con.setRequestMethod("GET");
263                 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
264                 con.setHostnameVerifier(hostnameVerifier);
265                 addHttpsRequestHeaders(headers, con);
266                 Boolean multiPart = false;
267                 if(headers.get(HttpHeaderEnum.ACCEPT.getValue()) != null) {
268                         if (headers.get(HttpHeaderEnum.ACCEPT.getValue()).equals(BaseRestUtils.acceptMultipartHeader)) {
269                                 multiPart = true;
270                         }
271                 }
272                 int responseCode = con.getResponseCode();
273                 logger.debug("Send GET http request, url: {}",url);
274                 logger.debug("Response Code: {}",responseCode);
275
276                 StringBuffer response = generateHttpsResponse(con, multiPart);
277                 String result;
278                 try {
279                         if(con.getErrorStream()!=null) {
280                                 result = IOUtils.toString(con.getErrorStream());
281                                 response.append(result);
282                         }
283                 } catch (Exception e) {
284 //                      logger.debug("Fail with exception", e);
285                 }
286                 logger.debug("Response body: {}",response);
287 // print result
288                 setHttpsResponseToObject(restResponse, con, responseCode, response);
289                 con.disconnect();
290
291                 return restResponse;
292         }
293
294
295         public RestResponse httpsSendPost(String url, String body, Map<String, String> headers) throws IOException {
296
297                 RestResponse restResponse = new RestResponse();
298                 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
299                 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
300                 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
301                 con.setHostnameVerifier(hostnameVerifier);
302 // add request method
303                 con.setRequestMethod("POST");
304 // add request headers
305                 addHttpRequestHEaders(headers, con);
306 // Send post request
307                 if (body != null) {
308                         con.setDoOutput(true);
309                         DataOutputStream wr = new DataOutputStream(con.getOutputStream());
310                         wr.writeBytes(body);
311                         wr.flush();
312                         wr.close();
313                 }
314                 int responseCode = con.getResponseCode();
315                 logger.debug("Send POST http request, url: {}",url);
316                 logger.debug("Response Code: {}",responseCode);
317
318                 StringBuffer response = generateHttpsResponse(con, false);
319                 String result;
320                 try {
321                         if(con.getErrorStream()!=null) {
322                                 result = IOUtils.toString(con.getErrorStream());
323                                 response.append(result);
324                         }
325                 } catch (Exception e) {
326 //                      logger.debug("Fail with exception", e);
327                 }
328                 logger.debug("Response body: {}",response);
329 // print result
330                 setHttpResponseToObject(restResponse, con, responseCode, response);
331                 con.disconnect();
332
333                 return restResponse;
334         }
335
336         public RestResponse httpsSendByMethod(String url, String method, String body, Map<String, String> headers) throws IOException {
337
338                 RestResponse restResponse = new RestResponse();
339                 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
340                 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
341                 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
342                 con.setHostnameVerifier(hostnameVerifier);
343 // add request method
344                 con.setRequestMethod(method);
345 // add request headers
346                 addHttpRequestHEaders(headers, con);
347                 if (body != null && !body.isEmpty() && !method.equals("DELETE")) {
348 // Send post request
349                         con.setDoOutput(true);
350                         DataOutputStream wr = new DataOutputStream(con.getOutputStream());
351                         wr.writeBytes(body);
352                         wr.flush();
353                         wr.close();
354                 }
355
356                 int responseCode = con.getResponseCode();
357                 logger.debug("Send {} http request, url: {}",method,url);
358                 logger.debug("Response Code: {}",responseCode);
359
360                 StringBuffer response = generateHttpResponse(con, false);
361                 String result;
362                 try {
363                         if(con.getErrorStream()!=null) {
364                                 result = IOUtils.toString(con.getErrorStream());
365                                 response.append(result);
366                         }
367                 } catch (Exception e) {
368 //                      logger.debug("Fail with exception", e);
369                 }
370                 logger.debug("Response body: {}",response);
371 // print result
372                 setHttpResponseToObject(restResponse, con, responseCode, response);
373                 con.disconnect();
374
375                 return restResponse;
376         }
377
378
379         public RestResponse httpsSendDelete(String url, Map<String, String> headers) throws IOException {
380
381                 RestResponse restResponse = new RestResponse();
382                 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
383                 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
384                 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
385                 con.setHostnameVerifier(hostnameVerifier);
386 // add request headers
387                 addHttpRequestHEaders(headers, con);
388
389                 con.setDoOutput(true);
390                 con.setRequestMethod("DELETE");
391                 int responseCode = con.getResponseCode();
392                 logger.debug("Send DELETE http request, url: {}",url);
393                 logger.debug("Response Code: {}",responseCode);
394
395                 StringBuffer response = generateHttpsResponse(con, false);
396                 String result;
397                 try {
398                         if(con.getErrorStream()!=null) {
399                                 result = IOUtils.toString(con.getErrorStream());
400                                 response.append(result);
401                         }
402                 } catch (Exception e) {
403 //                      logger.debug("Fail with exception", e);
404                 }
405                 logger.debug("Response body: {}",response);
406 // print result
407                 setHttpResponseToObject(restResponse, con, responseCode, response);
408                 con.disconnect();
409
410                 return restResponse;
411         }
412
413         //      ---------------------------------------
414         private void addHttpsRequestHeaders(Map<String, String> headers, HttpsURLConnection con) {
415                 // add request header
416                 if (headers != null) {
417                         for (Entry<String, String> header : headers.entrySet()) {
418                                 String key = header.getKey();
419                                 String value = header.getValue();
420                                 con.setRequestProperty(key, value);
421                         }
422
423                 }
424         }
425
426         private void addHttpRequestHEaders(Map<String, String> headers, HttpURLConnection con) {
427                 // add request header
428                 if (headers != null) {
429                         for (Entry<String, String> header : headers.entrySet()) {
430                                 String key = header.getKey();
431                                 String value = header.getValue();
432                                 con.setRequestProperty(key, value);
433                         }
434
435                 }
436         }
437
438         private void setHttpResponseToObject(RestResponse restResponse, HttpURLConnection con, int responseCode, StringBuffer response) throws IOException {
439                 restResponse.setErrorCode(responseCode);
440
441                 if (response != null) {
442                         restResponse.setResponse(response.toString());
443                 }
444
445                 Map<String, List<String>> headerFields = con.getHeaderFields();
446                 restResponse.setHeaderFields(headerFields);
447                 String responseMessage = con.getResponseMessage();
448                 restResponse.setResponseMessage(responseMessage);
449         }
450
451         private StringBuffer generateHttpResponse(HttpURLConnection con, Boolean isMultiPart) {
452                 StringBuffer response = new StringBuffer();
453                 StringWriter writer = new StringWriter();
454                 try {
455                         if(isMultiPart) {
456                                 IOUtils.copy((con.getInputStream()), writer, Charset.forName("UTF-8"));
457                                 response = writer.getBuffer();
458                         }else {
459
460                                 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
461                                 String inputLine;
462                                 while ((inputLine = in.readLine()) != null) {
463                                         response.append(inputLine);
464                                 }
465                                 in.close();
466                         }
467                 } catch (Exception e) {
468                         logger.debug("response body is null");
469                 }
470
471                 return response;
472         }
473
474         private void setHttpsResponseToObject(RestResponse restResponse, HttpsURLConnection con, int responseCode, StringBuffer response) throws IOException {
475                 if (response != null) {
476                         restResponse.setResponse(response.toString());
477                 }
478
479                 restResponse.setErrorCode(responseCode);
480                 // restResponse.setResponse(result);
481                 Map<String, List<String>> headerFields = con.getHeaderFields();
482                 restResponse.setHeaderFields(headerFields);
483                 String responseMessage = con.getResponseMessage();
484                 restResponse.setResponseMessage(responseMessage);
485         }
486
487         private StringBuffer generateHttpsResponse(HttpsURLConnection con, Boolean isMultiPart) {
488                 StringBuffer response = new StringBuffer();
489                 StringWriter writer = new StringWriter();
490                 try {
491                         if(isMultiPart) {
492                                 IOUtils.copy((con.getInputStream()), writer, Charset.forName("UTF-8"));
493                                 response = writer.getBuffer();
494                         }else {
495
496                                 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
497                                 String inputLine;
498                                 while ((inputLine = in.readLine()) != null) {
499                                         response.append(inputLine);
500                                 }
501                                 in.close();
502                         }
503                 } catch (Exception e) {
504                         logger.debug("response body is null");
505                 }
506
507                 return response;
508         }
509
510
511         @NotThreadSafe
512         class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
513                 public static final String METHOD_NAME = "DELETE";
514
515                 public String getMethod() {
516                         return METHOD_NAME;
517                 }
518
519                 public HttpDeleteWithBody(final String uri) {
520                         super();
521                         setURI(URI.create(uri));
522                 }
523
524                 public HttpDeleteWithBody(final URI uri) {
525                         super();
526                         setURI(uri);
527                 }
528
529                 public HttpDeleteWithBody() {
530                         super();
531                 }
532         }
533
534 }