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 String baseUrl;
52 private int timeout = DEFAULT_HTTP_TIMEOUT_MS;
53 private SSLContext sc = null;
55 public BaseHTTPClient(String base) {
59 public void setBaseUrl(String baseUrl) {
60 this.baseUrl = baseUrl;
62 sc = setupSsl(trustAll);
63 } catch (KeyManagementException | NoSuchAlgorithmException e) {
64 LOG.warn("problem ssl setup: " + e.getMessage());
68 public BaseHTTPClient(String base, boolean trustAllCerts) {
70 this.trustAll = trustAllCerts;
72 sc = setupSsl(trustAll);
73 } catch (KeyManagementException | NoSuchAlgorithmException e) {
74 LOG.warn("problem ssl setup: " + e.getMessage());
78 protected @Nonnull BaseHTTPResponse sendRequest(String uri, String method, String body, Map<String, String> headers)
80 return this.sendRequest(uri, method, body != null ? body.getBytes(CHARSET) : null, headers);
83 protected @Nonnull BaseHTTPResponse sendRequest(String uri, String method, byte[] body, Map<String, String> headers)
88 String surl = this.baseUrl;
89 if (!surl.endsWith("/") && uri.length() > 0) {
92 if (uri.startsWith("/")) {
93 uri = uri.substring(1);
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")) {
103 ((HttpsURLConnection) http).setSSLSocketFactory(sc.getSocketFactory());
105 LOG.debug("trusting all certs");
106 HostnameVerifier allHostsValid = (hostname, session) -> true;
107 ((HttpsURLConnection) http).setHostnameVerifier(allHostsValid);
109 } else // Should never happen
111 LOG.warn("No SSL context available");
112 return new BaseHTTPResponse(-1, "");
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));
123 byte[] buffer = new byte[BUFSIZE];
124 int len = 0, lensum = 0;
126 // Send the message to destination
127 if (!method.equals("GET") && body != null && body.length > 0) {
128 try (OutputStream output = http.getOutputStream()) {
133 int responseCode = ((HttpURLConnection) http).getResponseCode();
134 String sresponse = "";
135 InputStream response = null;
137 if (responseCode >= 200 && responseCode < 300) {
138 response = http.getInputStream();
140 response = ((HttpURLConnection) http).getErrorStream();
141 if (response == null) {
142 response = http.getInputStream();
145 if (response != null) {
147 len = response.read(buffer, 0, BUFSIZE);
152 sresponse += new String(buffer, 0, len, CHARSET);
155 LOG.debug("response is null");
157 } catch (Exception e) {
158 LOG.debug("No response. ", e);
160 if (response != null) {
164 LOG.debug("ResponseCode: " + responseCode);
165 LOG.trace("Response (len:{}): {}", String.valueOf(lensum), sresponse);
166 return new BaseHTTPResponse(responseCode, sresponse);
169 public static SSLContext setupSsl(boolean trustall) throws KeyManagementException, NoSuchAlgorithmException {
171 SSLContext sc = SSLContext.getInstance(SSLCONTEXT);
172 TrustManager[] trustCerts = null;
174 trustCerts = new TrustManager[] { new javax.net.ssl.X509TrustManager() {
176 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
181 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
185 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
190 KeyManager[] kms = null;
191 // Init the SSLContext with a TrustManager[] and SecureRandom()
192 sc.init(kms, trustCerts, new java.security.SecureRandom());
196 public static String getAuthorizationHeaderValue(String username, String password) {
197 return "Basic " + new String(Base64.getEncoder().encode((username + ":" + password).getBytes()));