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
10 * http://www.apache.org/licenses/LICENSE-2.0
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
16 * ============LICENSE_END==========================================================================
17 ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.apigateway.database.http;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.net.HttpURLConnection;
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;
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;
41 public class BaseHTTPClient {
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
49 private final boolean trustAll;
50 private final String baseUrl;
52 private int timeout = DEFAULT_HTTP_TIMEOUT_MS;
53 private SSLContext sc = null;
55 public BaseHTTPClient(String base) {
60 public BaseHTTPClient(String base, boolean trustAllCerts) {
62 this.trustAll = trustAllCerts;
64 sc = setupSsl(trustAll);
65 } catch (KeyManagementException | NoSuchAlgorithmException e) {
66 LOG.warn("problem ssl setup: " + e.getMessage());
70 protected @Nonnull BaseHTTPResponse sendRequest(String uri, String method, String body, Map<String, String> headers)
72 return this.sendRequest(uri, method, body != null ? body.getBytes(CHARSET) : null, headers);
75 protected @Nonnull BaseHTTPResponse sendRequest(String uri, String method, byte[] body, Map<String, String> headers)
80 String surl = this.baseUrl;
81 if (!surl.endsWith("/") && uri.length() > 0) {
84 if (uri.startsWith("/")) {
85 uri = uri.substring(1);
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")) {
95 ((HttpsURLConnection) http).setSSLSocketFactory(sc.getSocketFactory());
97 LOG.debug("trusting all certs");
98 HostnameVerifier allHostsValid = (hostname, session) -> true;
99 ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid);
101 } else // Should never happen
103 LOG.warn("No SSL context available");
104 return new BaseHTTPResponse(-1, "");
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));
115 byte[] buffer = new byte[BUFSIZE];
116 int len = 0, lensum = 0;
118 // Send the message to destination
119 if (!method.equals("GET") && body != null && body.length > 0) {
120 try (OutputStream output = http.getOutputStream()) {
125 int responseCode = ((HttpURLConnection) http).getResponseCode();
126 String sresponse = "";
127 InputStream response = null;
129 if (responseCode >= 200 && responseCode < 300) {
130 response = http.getInputStream();
132 response = ((HttpURLConnection) http).getErrorStream();
133 if (response == null) {
134 response = http.getInputStream();
137 if (response != null) {
139 len = response.read(buffer, 0, BUFSIZE);
144 sresponse += new String(buffer, 0, len, CHARSET);
147 LOG.debug("response is null");
149 } catch (Exception e) {
150 LOG.debug("No response. ", e);
152 if (response != null) {
156 LOG.debug("ResponseCode: " + responseCode);
157 LOG.trace("Response (len:{}): {}", String.valueOf(lensum), sresponse);
158 return new BaseHTTPResponse(responseCode, sresponse);
162 public static SSLContext setupSsl(boolean trustall) throws KeyManagementException, NoSuchAlgorithmException{
164 SSLContext sc = SSLContext.getInstance(SSLCONTEXT);
165 TrustManager[] trustCerts = null;
167 trustCerts = new TrustManager[] {new javax.net.ssl.X509TrustManager() {
169 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
174 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
177 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
181 KeyManager[] kms = null;
182 // Init the SSLContext with a TrustManager[] and SecureRandom()
183 sc.init(kms, trustCerts, new java.security.SecureRandom());
187 public static String getAuthorizationHeaderValue(String username, String password) {
188 return "Basic " + new String(Base64.getEncoder().encode((username + ":" + password).getBytes()));