Skip to content

Commit d164ebf

Browse files
committed
refactor: refactor http request code by http-facade
Signed-off-by: moxiaoying <[email protected]>
1 parent 7f741c1 commit d164ebf

File tree

10 files changed

+275
-297
lines changed

10 files changed

+275
-297
lines changed

pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
<!-- dependency -->
2626
<awaitility.version>4.2.2</awaitility.version>
2727
<embedded-pulsar.version>0.0.5</embedded-pulsar.version>
28+
<http-facade.version>0.3.0</http-facade.version>
2829
<jackson.version>2.17.2</jackson.version>
2930
<junit.version>5.11.0</junit.version>
3031
<log4j.version>2.20.0</log4j.version>

pulsar-admin-common/src/main/java/io/github/protocol/pulsar/admin/common/JacksonService.java

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@
77
import com.fasterxml.jackson.databind.ObjectMapper;
88
import com.fasterxml.jackson.databind.node.ArrayNode;
99
import com.fasterxml.jackson.databind.node.ObjectNode;
10+
import org.jetbrains.annotations.NotNull;
11+
import org.jetbrains.annotations.Nullable;
1012

13+
import java.io.IOException;
1114
import java.util.List;
1215

1316
public class JacksonService {
@@ -18,26 +21,26 @@ public class JacksonService {
1821
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1922
}
2023

21-
public static String toJson(Object o) throws JsonProcessingException {
22-
return MAPPER.writeValueAsString(o);
24+
public static byte[] toBytes(@Nullable Object o) throws JsonProcessingException {
25+
return o == null ? null : MAPPER.writeValueAsBytes(o);
2326
}
2427

25-
public static <T> T toObject(String json, Class<T> type) throws JsonProcessingException {
26-
if (json == null || json.isEmpty()) {
28+
public static <T> T toObject(@Nullable byte[] json, @NotNull Class<T> type) throws IOException {
29+
if (json == null || json.length == 0) {
2730
return null;
2831
}
2932
return MAPPER.readValue(json, type);
3033
}
3134

32-
public static <T> T toRefer(String json, TypeReference<T> ref) throws JsonProcessingException {
33-
if (json == null || json.isEmpty()) {
35+
public static <T> T toRefer(byte[] json, TypeReference<T> ref) throws IOException {
36+
if (json == null || json.length == 0) {
3437
return null;
3538
}
3639
return MAPPER.readValue(json, ref);
3740
}
3841

39-
public static <T> List<T> toList(String json, TypeReference<List<T>> typeRef) throws JsonProcessingException {
40-
if (json == null || json.isEmpty()) {
42+
public static <T> List<T> toList(byte[] json, TypeReference<List<T>> typeRef) throws IOException {
43+
if (json == null || json.length == 0) {
4144
return List.of();
4245
}
4346
return MAPPER.readValue(json, typeRef);

pulsar-admin-jdk/pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@
1717
<artifactId>pulsar-admin-common</artifactId>
1818
<version>${project.version}</version>
1919
</dependency>
20+
<dependency>
21+
<groupId>io.github.openfacade</groupId>
22+
<artifactId>http-facade</artifactId>
23+
<version>${http-facade.version}</version>
24+
</dependency>
2025
</dependencies>
2126

2227
<build>

pulsar-admin-jdk/src/main/java/io/github/protocol/pulsar/admin/jdk/BaseTopicsImpl.java

Lines changed: 63 additions & 62 deletions
Large diffs are not rendered by default.

pulsar-admin-jdk/src/main/java/io/github/protocol/pulsar/admin/jdk/Brokers.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package io.github.protocol.pulsar.admin.jdk;
22

3-
import java.net.http.HttpResponse;
3+
import io.github.openfacade.http.HttpResponse;
44

55
public class Brokers {
66
private final InnerHttpClient innerHttpClient;
@@ -15,12 +15,12 @@ public void healthcheck(TopicVersion topicVersion) throws PulsarAdminException {
1515
url += "?topicVersion=" + topicVersion;
1616
}
1717
try {
18-
HttpResponse<String> httpResponse = innerHttpClient.get(url);
18+
HttpResponse httpResponse = innerHttpClient.get(url);
1919
if (httpResponse.statusCode() != 200) {
2020
throw new PulsarAdminException("healthcheck failed, status code: " + httpResponse.statusCode(),
2121
httpResponse.statusCode());
2222
}
23-
if (!httpResponse.body().equals("ok")) {
23+
if (!httpResponse.bodyAsString().equals("ok")) {
2424
throw new PulsarAdminException("healthcheck failed, body: " + httpResponse.body());
2525
}
2626
} catch (Exception e) {

pulsar-admin-jdk/src/main/java/io/github/protocol/pulsar/admin/jdk/Clusters.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
package io.github.protocol.pulsar.admin.jdk;
22

33
import com.fasterxml.jackson.core.type.TypeReference;
4+
import io.github.openfacade.http.HttpResponse;
45
import io.github.protocol.pulsar.admin.common.JacksonService;
56

67
import java.io.IOException;
7-
import java.net.http.HttpResponse;
88
import java.util.List;
9+
import java.util.concurrent.ExecutionException;
910

1011
public class Clusters {
1112

@@ -17,15 +18,14 @@ public Clusters(InnerHttpClient httpClient) {
1718

1819
public List<String> getClusters() throws PulsarAdminException {
1920
try {
20-
HttpResponse<String> response = httpClient.get(UrlConst.CLUSTERS);
21+
HttpResponse response = httpClient.get(UrlConst.CLUSTERS);
2122
if (response.statusCode() != 200) {
2223
throw new PulsarAdminException(
2324
String.format("failed to get list of clusters, "
2425
+ "status code %s, body : %s", response.statusCode(), response.body()));
2526
}
26-
return JacksonService.toRefer(response.body(), new TypeReference<List<String>>() {
27-
});
28-
} catch (IOException | InterruptedException e) {
27+
return JacksonService.toRefer(response.body(), new TypeReference<>() {});
28+
} catch (IOException | InterruptedException | ExecutionException e) {
2929
throw new PulsarAdminException(e);
3030
}
3131
}
Lines changed: 77 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -1,128 +1,124 @@
11
package io.github.protocol.pulsar.admin.jdk;
22

33
import com.fasterxml.jackson.core.JsonProcessingException;
4+
import io.github.openfacade.http.HttpClient;
5+
import io.github.openfacade.http.HttpClientConfig;
6+
import io.github.openfacade.http.HttpClientEngine;
7+
import io.github.openfacade.http.HttpClientFactory;
8+
import io.github.openfacade.http.HttpMethod;
9+
import io.github.openfacade.http.HttpRequest;
10+
import io.github.openfacade.http.HttpResponse;
11+
import io.github.openfacade.http.HttpSchema;
12+
import io.github.openfacade.http.TlsConfig;
13+
import io.github.openfacade.http.UrlBuilder;
414
import io.github.protocol.pulsar.admin.api.Configuration;
515
import io.github.protocol.pulsar.admin.common.JacksonService;
616

717
import java.io.IOException;
8-
import java.net.URI;
9-
import java.net.URLEncoder;
10-
import java.net.http.HttpClient;
11-
import java.net.http.HttpRequest;
12-
import java.net.http.HttpResponse;
13-
import java.nio.charset.StandardCharsets;
18+
import java.util.ArrayList;
19+
import java.util.HashMap;
20+
import java.util.List;
21+
import java.util.Map;
22+
import java.util.concurrent.ExecutionException;
1423

1524
public class InnerHttpClient {
16-
private final Configuration conf;
17-
1825
private final HttpClient client;
1926

20-
private final String httpPrefix;
27+
private UrlBuilder templateUrlBuilder;
2128

2229
public InnerHttpClient(Configuration conf) {
23-
this.conf = conf;
24-
HttpClient.Builder builder = HttpClient.newBuilder()
25-
.version(HttpClient.Version.HTTP_1_1);
30+
HttpClientConfig.Builder clientConfigBuilder = new HttpClientConfig.Builder();
31+
clientConfigBuilder.engine(HttpClientEngine.JAVA);
2632
if (conf.tlsEnabled) {
27-
builder = builder
28-
.sslContext(SslContextUtil.build(conf.tlsConfig));
29-
this.httpPrefix = "https://" + conf.host + ":" + conf.port;
30-
} else {
31-
this.httpPrefix = "http://" + conf.host + ":" + conf.port;
33+
TlsConfig.Builder tlsConfigBuilder = new TlsConfig.Builder();
34+
io.github.protocol.pulsar.admin.api.TlsConfig tlsConfig = conf.tlsConfig;
35+
tlsConfigBuilder.cipherSuites(tlsConfig.cipherSuites);
36+
tlsConfigBuilder.hostnameVerifyDisabled(tlsConfig.hostnameVerifyDisabled);
37+
tlsConfigBuilder.keyStore(tlsConfig.keyStorePath, tlsConfig.keyStorePassword);
38+
tlsConfigBuilder.trustStore(tlsConfig.trustStorePath, tlsConfig.trustStorePassword);
39+
tlsConfigBuilder.verifyDisabled(tlsConfig.verifyDisabled);
40+
clientConfigBuilder.tlsConfig(tlsConfigBuilder.build());
3241
}
33-
this.client = builder.build();
42+
this.client = HttpClientFactory.createHttpClient(clientConfigBuilder.build());
43+
templateUrlBuilder = new UrlBuilder();
44+
templateUrlBuilder.setHttpSchema(conf.tlsEnabled ? HttpSchema.HTTPS : HttpSchema.HTTP).setHost(conf.host)
45+
.setPort(conf.port);
3446
}
3547

36-
public HttpResponse<String> get(String url) throws IOException, InterruptedException {
37-
return this.get(url, new String[0]);
48+
public HttpResponse post(String url) throws IOException, InterruptedException, ExecutionException {
49+
return this.innerPost(url, new byte[0]);
3850
}
3951

40-
public HttpResponse<String> get(String url, String... requestParams)
41-
throws IOException, InterruptedException {
42-
HttpRequest request = HttpRequest.newBuilder()
43-
.uri(getUri(url, requestParams))
44-
.GET()
45-
.build();
46-
return client.send(request, HttpResponse.BodyHandlers.ofString());
52+
public HttpResponse post(String url, Object body) throws IOException, InterruptedException, ExecutionException {
53+
return this.innerPost(url, objectToBytes(body));
4754
}
4855

49-
public HttpResponse<String> post(String url, Object body, String... params)
50-
throws IOException, InterruptedException {
51-
return this.post(url, objectToString(body), params);
56+
public HttpResponse post(String url, Object body, String... params)
57+
throws IOException, ExecutionException, InterruptedException {
58+
return this.innerPost(url, objectToBytes(body), params);
5259
}
5360

54-
public HttpResponse<String> post(String url, String body, String... params)
55-
throws IOException, InterruptedException {
56-
HttpRequest request = HttpRequest.newBuilder()
57-
.uri(getUri(url, params))
58-
.POST(HttpRequest.BodyPublishers.ofString(body == null ? "" : body))
59-
.setHeader("Content-Type", "application/json")
60-
.build();
61-
return client.send(request, HttpResponse.BodyHandlers.ofString());
61+
private HttpResponse innerPost(String url, byte[] body, String... params)
62+
throws InterruptedException, ExecutionException {
63+
Map<String, List<String>> headers = new HashMap<>();
64+
headers.put("Content-Type", List.of("application/json"));
65+
HttpRequest request = new HttpRequest(concatUrlWithParams(url, params), HttpMethod.POST, headers, body);
66+
return client.send(request).get();
6267
}
6368

64-
public HttpResponse<String> post(String url) throws IOException, InterruptedException {
65-
return this.post(url, "");
69+
public HttpResponse put(String url) throws IOException, InterruptedException, ExecutionException {
70+
return this.innerPut(url, new byte[0]);
6671
}
6772

68-
public HttpResponse<String> put(String url) throws IOException, InterruptedException {
69-
return this.put(url, "");
73+
public HttpResponse put(String url, Object body) throws IOException, InterruptedException, ExecutionException {
74+
return this.innerPut(url, objectToBytes(body));
7075
}
7176

72-
public HttpResponse<String> put(String url, Object body, String... params)
73-
throws IOException, InterruptedException {
74-
return this.put(url, objectToString(body), params);
77+
public HttpResponse put(String url, Object body, String... params)
78+
throws IOException, InterruptedException, ExecutionException {
79+
return this.innerPut(url, objectToBytes(body), params);
7580
}
7681

77-
public HttpResponse<String> put(String url, String body, String... params)
78-
throws IOException, InterruptedException {
79-
HttpRequest request = HttpRequest.newBuilder()
80-
.uri(getUri(url, params))
81-
.PUT(HttpRequest.BodyPublishers.ofString(body == null ? "" : body))
82-
.setHeader("Content-Type", "application/json")
83-
.build();
84-
return client.send(request, HttpResponse.BodyHandlers.ofString());
82+
private HttpResponse innerPut(String url, byte[] body, String... params)
83+
throws InterruptedException, ExecutionException {
84+
Map<String, List<String>> headers = new HashMap<>();
85+
headers.put("Content-Type", List.of("application/json"));
86+
HttpRequest request = new HttpRequest(concatUrlWithParams(url, params), HttpMethod.PUT, headers, body);
87+
return client.send(request).get();
8588
}
8689

87-
public HttpResponse<String> delete(String url, String... requestParams)
88-
throws IOException, InterruptedException {
89-
HttpRequest request = HttpRequest.newBuilder()
90-
.uri(getUri(url, requestParams))
91-
.DELETE()
92-
.build();
93-
return client.send(request, HttpResponse.BodyHandlers.ofString());
90+
public HttpResponse delete(String url, String... params)
91+
throws IOException, InterruptedException, ExecutionException {
92+
HttpRequest request = new HttpRequest(concatUrlWithParams(url, params), HttpMethod.DELETE);
93+
return client.send(request).get();
9494
}
9595

96-
private URI getUri(String url, String... params) {
97-
return URI.create(this.httpPrefix + url + mapToParams(params));
96+
public HttpResponse get(String url, String... params) throws IOException, InterruptedException, ExecutionException {
97+
HttpRequest request = new HttpRequest(concatUrlWithParams(url, params), HttpMethod.GET);
98+
return client.send(request).get();
9899
}
99100

100-
static String mapToParams(String... requestParams) {
101+
private List<UrlBuilder.Param> convertListToParams(String... requestParams) {
101102
if (requestParams.length % 2 != 0) {
102103
throw new IllegalArgumentException("params list length cannot be odd");
103104
}
104-
if (requestParams.length == 0) {
105-
return "";
106-
}
107-
StringBuilder res = new StringBuilder("?");
108-
res.append(requestParams[0]);
109-
res.append('=');
110-
res.append(requestParams[1]);
111-
for (int i = 2; i < requestParams.length; ) {
112-
res.append('&');
113-
res.append(encode(requestParams[i++]));
114-
res.append('=');
115-
res.append(encode(requestParams[i++]));
105+
List<UrlBuilder.Param> queryParams = new ArrayList<>();
106+
for (int i = 0; i < requestParams.length; i = i + 2) {
107+
queryParams.add(new UrlBuilder.Param(requestParams[i], requestParams[i + 1]));
116108
}
117-
return res.toString();
109+
return queryParams;
118110
}
119111

120-
private String objectToString(Object obj) throws JsonProcessingException {
121-
return obj == null ? "" : JacksonService.toJson(obj);
112+
private byte[] objectToBytes(Object obj) throws JsonProcessingException {
113+
return obj == null ? new byte[0] : JacksonService.toBytes(obj);
122114
}
123115

124-
private static String encode(String value) {
125-
return URLEncoder.encode(value, StandardCharsets.UTF_8);
116+
private String concatUrlWithParams(String url, String... params) {
117+
UrlBuilder urlBuilder = templateUrlBuilder.duplicate();
118+
urlBuilder.setPath(url);
119+
if (params != null && params.length > 0) {
120+
urlBuilder.setQueryParams(convertListToParams(params));
121+
}
122+
return urlBuilder.build();
126123
}
127-
128124
}

0 commit comments

Comments
 (0)