f8f95b3867d18ac9dfabcb243236fd9144f2d053
[ccsdk/features.git] /
1 /*******************************************************************************
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.apigateway.database.http;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.net.HttpURLConnection;
24 import java.net.URL;
25 import java.net.URLConnection;
26 import java.nio.charset.Charset;
27 import java.nio.charset.StandardCharsets;
28 import java.security.KeyManagementException;
29 import java.security.NoSuchAlgorithmException;
30 import java.util.Base64;
31 import java.util.Map;
32 import javax.annotation.Nonnull;
33 import javax.net.ssl.HostnameVerifier;
34 import javax.net.ssl.HttpsURLConnection;
35 import javax.net.ssl.KeyManager;
36 import javax.net.ssl.SSLContext;
37 import javax.net.ssl.TrustManager;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public class BaseHTTPClient {
42
43     private static Logger LOG = LoggerFactory.getLogger(BaseHTTPClient.class);
44     private static final int BUFSIZE = 1024;
45     private static final Charset CHARSET = StandardCharsets.UTF_8;
46     private static final String SSLCONTEXT = "TLSv1.2";
47     private static final int DEFAULT_HTTP_TIMEOUT_MS = 30000; // in ms
48
49     private final boolean trustAll;
50     private final String baseUrl;
51
52     private int timeout = DEFAULT_HTTP_TIMEOUT_MS;
53     private SSLContext sc = null;
54
55     public BaseHTTPClient(String base) {
56         this(base, false);
57     }
58
59
60     public BaseHTTPClient(String base, boolean trustAllCerts) {
61         this.baseUrl = base;
62         this.trustAll = trustAllCerts;
63         try {
64             sc = setupSsl(trustAll);
65         } catch (KeyManagementException | NoSuchAlgorithmException e) {
66             LOG.warn("problem ssl setup: " + e.getMessage());
67         }
68     }
69
70     protected @Nonnull BaseHTTPResponse sendRequest(String uri, String method, String body, Map<String, String> headers)
71             throws IOException {
72         return this.sendRequest(uri, method, body != null ? body.getBytes(CHARSET) : null, headers);
73     }
74
75     protected @Nonnull BaseHTTPResponse sendRequest(String uri, String method, byte[] body, Map<String, String> headers)
76             throws IOException {
77         if (uri == null) {
78             uri = "";
79         }
80         String surl = this.baseUrl;
81         if (!surl.endsWith("/") && uri.length() > 0) {
82             surl += "/";
83         }
84         if (uri.startsWith("/")) {
85             uri = uri.substring(1);
86         }
87         surl += uri;
88         LOG.debug("try to send request with url=" + this.baseUrl + uri + " as method=" + method);
89         LOG.trace("body:" + (body == null ? "null" : new String(body, CHARSET)));
90         URL url = new URL(surl);
91         URLConnection http = url.openConnection();
92         http.setConnectTimeout(this.timeout);
93         if (surl.toString().startsWith("https")) {
94             if (sc != null) {
95                 ((HttpsURLConnection) http).setSSLSocketFactory(sc.getSocketFactory());
96                 if (trustAll) {
97                     LOG.debug("trusting all certs");
98                     HostnameVerifier allHostsValid = (hostname, session) -> true;
99                     ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid);
100                 }
101             } else // Should never happen
102             {
103                 LOG.warn("No SSL context available");
104                 return new BaseHTTPResponse(-1, "");
105             }
106         }
107         ((HttpURLConnection) http).setRequestMethod(method);
108         http.setDoOutput(true);
109         if (headers != null && headers.size() > 0) {
110             for (String key : headers.keySet()) {
111                 http.setRequestProperty(key, headers.get(key));
112                 LOG.trace("set http header " + key + ": " + headers.get(key));
113             }
114         }
115         byte[] buffer = new byte[BUFSIZE];
116         int len = 0, lensum = 0;
117         // send request
118         // Send the message to destination
119         if (!method.equals("GET") && body != null && body.length > 0) {
120             try (OutputStream output = http.getOutputStream()) {
121                 output.write(body);
122             }
123         }
124         // Receive answer
125         int responseCode = ((HttpURLConnection) http).getResponseCode();
126         String sresponse = "";
127         InputStream response = null;
128         try {
129             if (responseCode >= 200 && responseCode < 300) {
130                 response = http.getInputStream();
131             } else {
132                 response = ((HttpURLConnection) http).getErrorStream();
133                 if (response == null) {
134                     response = http.getInputStream();
135                 }
136             }
137             if (response != null) {
138                 while (true) {
139                     len = response.read(buffer, 0, BUFSIZE);
140                     if (len <= 0) {
141                         break;
142                     }
143                     lensum += len;
144                     sresponse += new String(buffer, 0, len, CHARSET);
145                 }
146             } else {
147                 LOG.debug("response is null");
148             }
149         } catch (Exception e) {
150             LOG.debug("No response. ", e);
151         } finally {
152             if (response != null) {
153                 response.close();
154             }
155         }
156         LOG.debug("ResponseCode: " + responseCode);
157         LOG.trace("Response (len:{}): {}", String.valueOf(lensum), sresponse);
158         return new BaseHTTPResponse(responseCode, sresponse);
159     }
160
161   
162     public static SSLContext setupSsl(boolean trustall) throws KeyManagementException, NoSuchAlgorithmException{
163
164         SSLContext sc = SSLContext.getInstance(SSLCONTEXT);
165         TrustManager[] trustCerts = null;
166         if (trustall) {
167             trustCerts = new TrustManager[] {new javax.net.ssl.X509TrustManager() {
168                 @Override
169                 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
170                     return null;
171                 }
172
173                 @Override
174                 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
175
176                 @Override
177                 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
178             }};
179
180         }
181         KeyManager[] kms = null;
182         // Init the SSLContext with a TrustManager[] and SecureRandom()
183         sc.init(kms, trustCerts, new java.security.SecureRandom());
184         return sc;
185     }
186
187     public static String getAuthorizationHeaderValue(String username, String password) {
188         return "Basic " + new String(Base64.getEncoder().encode((username + ":" + password).getBytes()));
189     }
190
191   
192   
193 }