-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathSimpleHttpClient.java
More file actions
145 lines (124 loc) · 4.65 KB
/
SimpleHttpClient.java
File metadata and controls
145 lines (124 loc) · 4.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.contrib.aws.resource;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.WARNING;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.time.Duration;
import java.util.Collection;
import java.util.Map;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/** A simple HTTP client based on OkHttp. Not meant for high throughput. */
final class SimpleHttpClient {
private static final Logger logger = Logger.getLogger(SimpleHttpClient.class.getName());
private static final Duration TIMEOUT = Duration.ofSeconds(2);
private static final RequestBody EMPTY_BODY = RequestBody.create(new byte[0]);
/** Fetch a string from a remote server. */
public String fetchString(
String httpMethod, String urlStr, Map<String, String> headers, @Nullable String certPath) {
OkHttpClient.Builder clientBuilder =
new OkHttpClient.Builder()
.callTimeout(TIMEOUT)
.connectTimeout(TIMEOUT)
.readTimeout(TIMEOUT);
if (urlStr.startsWith("https") && certPath != null) {
KeyStore keyStore = getKeystoreForTrustedCert(certPath);
X509TrustManager trustManager = buildTrustManager(keyStore);
SSLSocketFactory socketFactory = buildSslSocketFactory(trustManager);
if (socketFactory != null) {
clientBuilder.sslSocketFactory(socketFactory, trustManager);
}
}
OkHttpClient client = clientBuilder.build();
// AWS incorrectly uses PUT despite having no request body, OkHttp will only allow us to send
// GET with null body or PUT with empty string body
RequestBody requestBody = null;
if (httpMethod.equals("PUT")) {
requestBody = EMPTY_BODY;
}
Request.Builder requestBuilder =
new Request.Builder().url(urlStr).method(httpMethod, requestBody);
headers.forEach(requestBuilder::addHeader);
try (Response response = client.newCall(requestBuilder.build()).execute()) {
int responseCode = response.code();
if (responseCode != 200) {
logger.log(
FINE,
"Error response from "
+ urlStr
+ " code ("
+ responseCode
+ ") text "
+ response.message());
return "";
}
return response.body().string();
} catch (IOException e) {
logger.log(FINE, "SimpleHttpClient fetch string failed.", e);
}
return "";
}
@Nullable
private static X509TrustManager buildTrustManager(@Nullable KeyStore keyStore) {
if (keyStore == null) {
return null;
}
try {
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
return (X509TrustManager) tmf.getTrustManagers()[0];
} catch (Exception e) {
logger.log(WARNING, "Build SslSocketFactory for K8s restful client exception.", e);
return null;
}
}
@Nullable
private static SSLSocketFactory buildSslSocketFactory(@Nullable TrustManager trustManager) {
if (trustManager == null) {
return null;
}
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] {trustManager}, null);
return context.getSocketFactory();
} catch (Exception e) {
logger.log(WARNING, "Build SslSocketFactory for K8s restful client exception.", e);
}
return null;
}
@Nullable
private static KeyStore getKeystoreForTrustedCert(String certPath) {
try (FileInputStream fis = new FileInputStream(certPath)) {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(fis);
int i = 0;
for (Certificate certificate : certificates) {
trustStore.setCertificateEntry("cert_" + i, certificate);
i++;
}
return trustStore;
} catch (Exception e) {
logger.log(WARNING, "Cannot load KeyStore from " + certPath);
return null;
}
}
}