9c89eeff36583bf5586497206119413882e7cd77
[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 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         public void setBaseUrl(String baseUrl) {
60                 this.baseUrl = baseUrl;
61                 try {
62                         sc = setupSsl(trustAll);
63                 } catch (KeyManagementException | NoSuchAlgorithmException e) {
64                         LOG.warn("problem ssl setup: " + e.getMessage());
65                 }
66         }
67
68         public BaseHTTPClient(String base, boolean trustAllCerts) {
69                 this.baseUrl = base;
70                 this.trustAll = trustAllCerts;
71                 try {
72                         sc = setupSsl(trustAll);
73                 } catch (KeyManagementException | NoSuchAlgorithmException e) {
74                         LOG.warn("problem ssl setup: " + e.getMessage());
75                 }
76         }
77
78         protected @Nonnull BaseHTTPResponse sendRequest(String uri, String method, String body, Map<String, String> headers)
79                         throws IOException {
80                 return this.sendRequest(uri, method, body != null ? body.getBytes(CHARSET) : null, headers);
81         }
82
83         protected @Nonnull BaseHTTPResponse sendRequest(String uri, String method, byte[] body, Map<String, String> headers)
84                         throws IOException {
85                 if (uri == null) {
86                         uri = "";
87                 }
88                 String surl = this.baseUrl;
89                 if (!surl.endsWith("/") && uri.length() > 0) {
90                         surl += "/";
91                 }
92                 if (uri.startsWith("/")) {
93                         uri = uri.substring(1);
94                 }
95                 surl += uri;
96                 LOG.debug("try to send request with url=" + this.baseUrl + uri + " as method=" + method);
97                 LOG.trace("body:" + (body == null ? "null" : new String(body, CHARSET)));
98                 URL url = new URL(surl);
99                 URLConnection http = url.openConnection();
100                 http.setConnectTimeout(this.timeout);
101                 if (surl.toString().startsWith("https")) {
102                         if (sc != null) {
103                                 ((HttpsURLConnection) http).setSSLSocketFactory(sc.getSocketFactory());
104                                 if (trustAll) {
105                                         LOG.debug("trusting all certs");
106                                         HostnameVerifier allHostsValid = (hostname, session) -> true;
107                                         ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid);
108                                 }
109                         } else // Should never happen
110                         {
111                                 LOG.warn("No SSL context available");
112                                 return new BaseHTTPResponse(-1, "");
113                         }
114                 }
115                 ((HttpURLConnection) http).setRequestMethod(method);
116                 http.setDoOutput(true);
117                 if (headers != null && headers.size() > 0) {
118                         for (String key : headers.keySet()) {
119                                 http.setRequestProperty(key, headers.get(key));
120                                 LOG.trace("set http header " + key + ": " + headers.get(key));
121                         }
122                 }
123                 byte[] buffer = new byte[BUFSIZE];
124                 int len = 0, lensum = 0;
125                 // send request
126                 // Send the message to destination
127                 if (!method.equals("GET") && body != null && body.length > 0) {
128                         try (OutputStream output = http.getOutputStream()) {
129                                 output.write(body);
130                         }
131                 }
132                 // Receive answer
133                 int responseCode = ((HttpURLConnection) http).getResponseCode();
134                 String sresponse = "";
135                 InputStream response = null;
136                 try {
137                         if (responseCode >= 200 && responseCode < 300) {
138                                 response = http.getInputStream();
139                         } else {
140                                 response = ((HttpURLConnection) http).getErrorStream();
141                                 if (response == null) {
142                                         response = http.getInputStream();
143                                 }
144                         }
145                         if (response != null) {
146                                 while (true) {
147                                         len = response.read(buffer, 0, BUFSIZE);
148                                         if (len <= 0) {
149                                                 break;
150                                         }
151                                         lensum += len;
152                                         sresponse += new String(buffer, 0, len, CHARSET);
153                                 }
154                         } else {
155                                 LOG.debug("response is null");
156                         }
157                 } catch (Exception e) {
158                         LOG.debug("No response. ", e);
159                 } finally {
160                         if (response != null) {
161                                 response.close();
162                         }
163                 }
164                 LOG.debug("ResponseCode: " + responseCode);
165                 LOG.trace("Response (len:{}): {}", String.valueOf(lensum), sresponse);
166                 return new BaseHTTPResponse(responseCode, sresponse);
167         }
168
169         public static SSLContext setupSsl(boolean trustall) throws KeyManagementException, NoSuchAlgorithmException {
170
171                 SSLContext sc = SSLContext.getInstance(SSLCONTEXT);
172                 TrustManager[] trustCerts = null;
173                 if (trustall) {
174                         trustCerts = new TrustManager[] { new javax.net.ssl.X509TrustManager() {
175                                 @Override
176                                 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
177                                         return null;
178                                 }
179
180                                 @Override
181                                 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
182                                 }
183
184                                 @Override
185                                 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
186                                 }
187                         } };
188
189                 }
190                 KeyManager[] kms = null;
191                 // Init the SSLContext with a TrustManager[] and SecureRandom()
192                 sc.init(kms, trustCerts, new java.security.SecureRandom());
193                 return sc;
194         }
195
196         public static String getAuthorizationHeaderValue(String username, String password) {
197                 return "Basic " + new String(Base64.getEncoder().encode((username + ":" + password).getBytes()));
198         }
199
200 }