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