javeme commented on code in PR #133: URL: https://github.com/apache/incubator-hugegraph-commons/pull/133#discussion_r1375237226
########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/RestHeaders.java: ########## @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to You under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package org.apache.hugegraph.rest; + +import java.util.Date; +import java.util.Iterator; + +import kotlin.Pair; +import okhttp3.Headers; + +public class RestHeaders { + + private final okhttp3.Headers.Builder headersBuilder = new okhttp3.Headers.Builder(); + + public String get(String key) { + return this.headersBuilder.get(key); + } + + public Date getDate(String key) { + return this.headersBuilder.build().getDate(key); + } + + public RestHeaders add(String key, String value) { + this.headersBuilder.add(key, value); + return this; + } + + public RestHeaders add(String key, Date value) { + this.headersBuilder.add(key, value); + return this; + } + + @Override + public int hashCode() { + return this.toOkhttpHeader().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof RestHeaders) { + return this.toOkhttpHeader().equals(((RestHeaders)obj).toOkhttpHeader()); + } + return false; + } + + public okhttp3.Headers toOkhttpHeader() { + return this.headersBuilder.build(); + } + + public static RestHeaders convertRestHeaders(Headers headers) { Review Comment: prefer convertToRestHeaders and okhttp3.Headers ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/RestHeaders.java: ########## @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to You under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package org.apache.hugegraph.rest; + +import java.util.Date; + +public class RestHeaders { + private final okhttp3.Headers.Builder headersBuilder = new okhttp3.Headers.Builder(); Review Comment: can we move into the constructor `RestHeaders()` ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/RestHeaders.java: ########## @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to You under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package org.apache.hugegraph.rest; + +import java.util.Date; +import java.util.Iterator; + +import kotlin.Pair; +import okhttp3.Headers; + +public class RestHeaders { + + private final okhttp3.Headers.Builder headersBuilder = new okhttp3.Headers.Builder(); + + public String get(String key) { + return this.headersBuilder.get(key); + } + + public Date getDate(String key) { + return this.headersBuilder.build().getDate(key); + } + + public RestHeaders add(String key, String value) { + this.headersBuilder.add(key, value); + return this; + } + + public RestHeaders add(String key, Date value) { + this.headersBuilder.add(key, value); + return this; + } + + @Override + public int hashCode() { + return this.toOkhttpHeader().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof RestHeaders) { + return this.toOkhttpHeader().equals(((RestHeaders)obj).toOkhttpHeader()); Review Comment: expect a space "(RestHeaders)obj" ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/AbstractRestClient.java: ########## @@ -241,7 +328,7 @@ public RestResult put(String path, String id, Object object) { @Override public RestResult put(String path, String id, Object object, - MultivaluedMap<String, Object> headers) { + RestHeaders headers) { Review Comment: seems one line is ok ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/AbstractRestClient.java: ########## @@ -360,132 +432,39 @@ public String getAuthContext() { return this.authContext.get(); } - private void attachAuthToRequest(Builder builder) { + public void setAuthContext(String auth) { + this.authContext.set(auth); + } + + private void attachAuthToRequest(Request.Builder builder) { // Add auth header String auth = this.getAuthContext(); if (StringUtils.isNotEmpty(auth)) { - builder.header(HttpHeaders.AUTHORIZATION, auth); + builder.addHeader("Authorization", auth); Review Comment: also add a const ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/RestHeaders.java: ########## @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to You under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package org.apache.hugegraph.rest; + +import java.util.Date; +import java.util.Iterator; + +import kotlin.Pair; +import okhttp3.Headers; + +public class RestHeaders { + + private final okhttp3.Headers.Builder headersBuilder = new okhttp3.Headers.Builder(); + + public String get(String key) { + return this.headersBuilder.get(key); + } + + public Date getDate(String key) { + return this.headersBuilder.build().getDate(key); + } + + public RestHeaders add(String key, String value) { + this.headersBuilder.add(key, value); + return this; + } + + public RestHeaders add(String key, Date value) { + this.headersBuilder.add(key, value); + return this; + } + + @Override + public int hashCode() { + return this.toOkhttpHeader().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof RestHeaders) { + return this.toOkhttpHeader().equals(((RestHeaders)obj).toOkhttpHeader()); + } + return false; + } + + public okhttp3.Headers toOkhttpHeader() { + return this.headersBuilder.build(); + } + + public static RestHeaders convertRestHeaders(Headers headers) { + RestHeaders restHeaders = new RestHeaders(); + + if(headers != null) { Review Comment: expect a space "if (" ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/AbstractRestClient.java: ########## @@ -251,19 +338,19 @@ public RestResult put(String path, String id, Object object, return this.put(path, id, object, null, params); } + @SneakyThrows @Override public RestResult put(String path, String id, Object object, - MultivaluedMap<String, Object> headers, + RestHeaders headers, Review Comment: seems one line is ok ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/RestHeaders.java: ########## @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to You under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package org.apache.hugegraph.rest; + +import java.util.Date; + +public class RestHeaders { + private final okhttp3.Headers.Builder headersBuilder = new okhttp3.Headers.Builder(); + + public String get(String key) { + return headersBuilder.get(key); + } + + public Date getDate(String key) { + return headersBuilder.build().getDate(key); + } + + public RestHeaders add(String key, String value) { + headersBuilder.add(key, value); + return this; + } + + public RestHeaders add(String key, Date value) { + headersBuilder.add(key, value); + return this; + } + + public okhttp3.Headers toOkhttpHeader() { Review Comment: OK, also rename to toOkHttpHeader ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/RestHeaders.java: ########## @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to You under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package org.apache.hugegraph.rest; + +import java.util.Date; +import java.util.Iterator; + +import kotlin.Pair; +import okhttp3.Headers; + +public class RestHeaders { + + private final okhttp3.Headers.Builder headersBuilder = new okhttp3.Headers.Builder(); + + public String get(String key) { + return this.headersBuilder.get(key); + } + + public Date getDate(String key) { + return this.headersBuilder.build().getDate(key); + } + + public RestHeaders add(String key, String value) { + this.headersBuilder.add(key, value); + return this; + } + + public RestHeaders add(String key, Date value) { + this.headersBuilder.add(key, value); + return this; + } + + @Override + public int hashCode() { + return this.toOkhttpHeader().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof RestHeaders) { + return this.toOkhttpHeader().equals(((RestHeaders)obj).toOkhttpHeader()); + } + return false; + } + + public okhttp3.Headers toOkhttpHeader() { + return this.headersBuilder.build(); + } + + public static RestHeaders convertRestHeaders(Headers headers) { + RestHeaders restHeaders = new RestHeaders(); + + if(headers != null) { + Iterator<Pair<String, String>> iter = headers.iterator(); + while(iter.hasNext()) { Review Comment: expect a space "while (" ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/AbstractRestClient.java: ########## @@ -207,31 +263,62 @@ public RestResult post(String path, Object object) { } @Override - public RestResult post(String path, Object object, - MultivaluedMap<String, Object> headers) { + public RestResult post(String path, Object object, RestHeaders headers) { return this.post(path, object, headers, null); } @Override - public RestResult post(String path, Object object, - Map<String, Object> params) { + public RestResult post(String path, Object object, Map<String, Object> params) { return this.post(path, object, null, params); } + private Request.Builder getRequestBuilder(String path, String id, RestHeaders headers, + Map<String, Object> params) { + HttpUrl.Builder urlBuilder = HttpUrl.parse(this.baseUrl).newBuilder() + .addPathSegments(path); + if (id != null) { + urlBuilder.addPathSegment(id); + } + + if (params != null) { + params.forEach((name, value) -> { + if (value == null) { + return; + } + + if (value instanceof Collection) { + for (Object i : (Collection<?>) value) { + urlBuilder.addQueryParameter(name, String.valueOf(i)); + } + } else { + urlBuilder.addQueryParameter(name, String.valueOf(value)); + } + }); + } + + Request.Builder builder = requestBuilder.url(urlBuilder.build()); + + if (headers != null) { + builder.headers(headers.toOkhttpHeader()); + } + + this.attachAuthToRequest(builder); + + return builder; + } + + @SneakyThrows @Override - public RestResult post(String path, Object object, - MultivaluedMap<String, Object> headers, + public RestResult post(String path, Object object, RestHeaders headers, Map<String, Object> params) { - Pair<Builder, Entity<?>> pair = this.buildRequest(path, null, object, - headers, params); - Response response = this.request(() -> { - // pair.getLeft() is builder, pair.getRight() is entity (http body) - return pair.getLeft().post(pair.getRight()); - }); - // If check status failed, throw client exception. - checkStatus(response, Response.Status.CREATED, - Response.Status.OK, Response.Status.ACCEPTED); - return new RestResult(response); + Request.Builder requestBuilder = getRequestBuilder(path, null, headers, params); + requestBuilder.post(buildRequestBody(object, headers)); + + try (Response response = this.request( + () -> client.newCall(requestBuilder.build()).execute())) { Review Comment: seems we don't need to callback anymore, just `this.request(requestBuilder)` is ok ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/AbstractRestClient.java: ########## @@ -17,188 +17,244 @@ package org.apache.hugegraph.rest; +import java.io.FileInputStream; +import java.io.IOException; import java.net.URI; -import java.security.KeyManagementException; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; +import java.security.KeyStore; +import java.util.Arrays; import java.util.Collection; -import java.util.List; import java.util.Map; import java.util.concurrent.Callable; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.http.HttpHeaders; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.pool.PoolStats; -import org.apache.hugegraph.util.E; -import org.apache.hugegraph.util.ExecutorUtil; -import org.glassfish.jersey.SslConfigurator; -import org.glassfish.jersey.apache.connector.ApacheClientProperties; -import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientProperties; -import org.glassfish.jersey.client.JerseyClientBuilder; -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import org.glassfish.jersey.internal.util.collection.Ref; -import org.glassfish.jersey.internal.util.collection.Refs; -import org.glassfish.jersey.message.GZipEncoder; -import org.glassfish.jersey.uri.UriComponent; +import org.apache.commons.lang3.StringUtils; +import org.apache.hugegraph.util.JsonUtil; import com.google.common.collect.ImmutableMap; -import jakarta.ws.rs.client.Client; -import jakarta.ws.rs.client.ClientRequestContext; -import jakarta.ws.rs.client.ClientRequestFilter; -import jakarta.ws.rs.client.Entity; -import jakarta.ws.rs.client.Invocation.Builder; -import jakarta.ws.rs.client.WebTarget; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.MultivaluedMap; -import jakarta.ws.rs.core.Response; -import jakarta.ws.rs.core.Variant; +import lombok.SneakyThrows; +import okhttp3.ConnectionPool; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okio.BufferedSink; +import okio.GzipSink; +import okio.Okio; public abstract class AbstractRestClient implements RestClient { - // Time unit: hours - private static final long TTL = 24L; - // Time unit: ms - private static final long IDLE_TIME = 40L * 1000L; - - private static final String TOKEN_KEY = "tokenKey"; - - private final Client client; - private final WebTarget target; - - private PoolingHttpClientConnectionManager pool; - private ScheduledExecutorService cleanExecutor; + private final ThreadLocal<String> authContext = new InheritableThreadLocal<>(); + private final OkHttpClient client; + private final String baseUrl; + private final Request.Builder requestBuilder = new Request.Builder(); Review Comment: also move into the constructor(line 149)? ########## hugegraph-common/src/main/java/org/apache/hugegraph/rest/AbstractRestClient.java: ########## @@ -17,188 +17,246 @@ package org.apache.hugegraph.rest; +import java.io.FileInputStream; +import java.io.IOException; import java.net.URI; -import java.security.KeyManagementException; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; +import java.security.KeyStore; +import java.util.Arrays; import java.util.Collection; -import java.util.List; import java.util.Map; import java.util.concurrent.Callable; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.http.HttpHeaders; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.pool.PoolStats; -import org.apache.hugegraph.util.E; -import org.apache.hugegraph.util.ExecutorUtil; -import org.glassfish.jersey.SslConfigurator; -import org.glassfish.jersey.apache.connector.ApacheClientProperties; -import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientProperties; -import org.glassfish.jersey.client.JerseyClientBuilder; -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import org.glassfish.jersey.internal.util.collection.Ref; -import org.glassfish.jersey.internal.util.collection.Refs; -import org.glassfish.jersey.message.GZipEncoder; -import org.glassfish.jersey.uri.UriComponent; +import org.apache.commons.lang3.StringUtils; +import org.apache.hugegraph.util.JsonUtil; import com.google.common.collect.ImmutableMap; -import jakarta.ws.rs.client.Client; -import jakarta.ws.rs.client.ClientRequestContext; -import jakarta.ws.rs.client.ClientRequestFilter; -import jakarta.ws.rs.client.Entity; -import jakarta.ws.rs.client.Invocation.Builder; -import jakarta.ws.rs.client.WebTarget; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.MultivaluedMap; -import jakarta.ws.rs.core.Response; -import jakarta.ws.rs.core.Variant; +import lombok.SneakyThrows; +import okhttp3.ConnectionPool; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okio.BufferedSink; +import okio.GzipSink; +import okio.Okio; public abstract class AbstractRestClient implements RestClient { - // Time unit: hours - private static final long TTL = 24L; - // Time unit: ms - private static final long IDLE_TIME = 40L * 1000L; - - private static final String TOKEN_KEY = "tokenKey"; - - private final Client client; - private final WebTarget target; - - private PoolingHttpClientConnectionManager pool; - private ScheduledExecutorService cleanExecutor; + private final ThreadLocal<String> authContext = + new InheritableThreadLocal<>(); + private final OkHttpClient client; + private final String baseUrl; + private final Request.Builder requestBuilder = new Request.Builder(); public AbstractRestClient(String url, int timeout) { - this(url, new ConfigBuilder().configTimeout(timeout).build()); + this(url, OkhttpConfig.builder() + .timeout(timeout) + .build()); } public AbstractRestClient(String url, String user, String password, - int timeout) { - this(url, new ConfigBuilder().configTimeout(timeout) - .configUser(user, password) - .build()); + Integer timeout) { + this(url, OkhttpConfig.builder() + .user(user).password(password) + .timeout(timeout) + .build()); } public AbstractRestClient(String url, int timeout, int maxTotal, int maxPerRoute) { - this(url, new ConfigBuilder().configTimeout(timeout) - .configPool(maxTotal, maxPerRoute) - .build()); + this(url, null, null, timeout, maxTotal, maxPerRoute); } public AbstractRestClient(String url, int timeout, int idleTime, int maxTotal, int maxPerRoute) { - this(url, new ConfigBuilder().configTimeout(timeout) - .configIdleTime(idleTime) - .configPool(maxTotal, maxPerRoute) - .build()); + this(url, OkhttpConfig.builder() + .idleTime(idleTime) + .timeout(timeout) + .maxTotal(maxTotal) + .maxPerRoute(maxPerRoute) + .build()); } public AbstractRestClient(String url, String user, String password, int timeout, int maxTotal, int maxPerRoute) { - this(url, new ConfigBuilder().configTimeout(timeout) - .configUser(user, password) - .configPool(maxTotal, maxPerRoute) - .build()); + this(url, OkhttpConfig.builder() + .user(user).password(password) + .timeout(timeout) + .maxTotal(maxTotal) + .maxPerRoute(maxPerRoute) + .build()); } public AbstractRestClient(String url, String user, String password, int timeout, int maxTotal, int maxPerRoute, String trustStoreFile, String trustStorePassword) { - this(url, new ConfigBuilder().configTimeout(timeout) - .configUser(user, password) - .configPool(maxTotal, maxPerRoute) - .configSSL(trustStoreFile, - trustStorePassword) - .build()); - } + this(url, OkhttpConfig.builder() + .user(user).password(password) + .timeout(timeout) + .maxTotal(maxTotal) + .maxPerRoute(maxPerRoute) + .trustStoreFile(trustStoreFile) + .trustStorePassword(trustStorePassword) + .build()); + } + + public AbstractRestClient(String url, String token, Integer timeout) { + this(url, OkhttpConfig.builder() + .token(token) + .timeout(timeout) + .build()); + } + + public AbstractRestClient(String url, String token, Integer timeout, + Integer maxTotal, Integer maxPerRoute) { + this(url, OkhttpConfig.builder() + .token(token) + .timeout(timeout) + .maxTotal(maxTotal) + .maxPerRoute(maxPerRoute) + .build()); + } + + public AbstractRestClient(String url, String token, Integer timeout, + Integer maxTotal, Integer maxPerRoute, + String trustStoreFile, + String trustStorePassword) { + this(url, OkhttpConfig.builder() + .token(token) + .timeout(timeout) + .maxTotal(maxTotal) + .maxPerRoute(maxPerRoute) + .trustStoreFile(trustStoreFile) + .trustStorePassword(trustStorePassword) + .build()); + } + + public AbstractRestClient(String url, OkhttpConfig okhttpConfig) { + this.baseUrl = url; + this.client = getOkhttpClient(okhttpConfig); + } + + private static RequestBody getRequestBody(Object object, RestHeaders headers) { + String contentType = parseContentType(headers); + String bodyContent; + if ("application/json".equals(contentType)) { + if (object == null) { + bodyContent = "{}"; + } else { + bodyContent = JsonUtil.toJson(object); + } + } else { + bodyContent = String.valueOf(object); + } + RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), bodyContent); - public AbstractRestClient(String url, String token, int timeout) { - this(url, new ConfigBuilder().configTimeout(timeout) - .configToken(token) - .build()); + if (headers != null && "gzip".equals(headers.get("Content-Encoding"))) { + requestBody = gzip(requestBody); + } + return requestBody; } - public AbstractRestClient(String url, String token, int timeout, - int maxTotal, int maxPerRoute) { - this(url, new ConfigBuilder().configTimeout(timeout) - .configToken(token) - .configPool(maxTotal, maxPerRoute) - .build()); + private static RequestBody gzip(final RequestBody body) { + return new RequestBody() { + @Override + public MediaType contentType() { + return body.contentType(); + } + + @Override + public long contentLength() { + return -1; // We don't know the compressed length in advance! + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); + body.writeTo(gzipSink); + gzipSink.close(); + } + }; } - public AbstractRestClient(String url, String token, int timeout, - int maxTotal, int maxPerRoute, - String trustStoreFile, - String trustStorePassword) { - this(url, new ConfigBuilder().configTimeout(timeout) - .configToken(token) - .configPool(maxTotal, maxPerRoute) - .configSSL(trustStoreFile, - trustStorePassword) - .build()); - } - - public AbstractRestClient(String url, ClientConfig config) { - configConnectionManager(url, config); - - this.client = JerseyClientBuilder.newClient(config); - this.client.register(GZipEncoder.class); - this.target = this.client.target(url); - this.pool = (PoolingHttpClientConnectionManager) config.getProperty( - ApacheClientProperties.CONNECTION_MANAGER); - if (this.pool != null) { - this.cleanExecutor = ExecutorUtil.newScheduledThreadPool( - "conn-clean-worker-%d"); - Number idleTimeProp = (Number) config.getProperty("idleTime"); - final long idleTime = idleTimeProp == null ? - IDLE_TIME : idleTimeProp.longValue(); - final long checkPeriod = idleTime / 2L; - this.cleanExecutor.scheduleWithFixedDelay(() -> { - PoolStats stats = this.pool.getTotalStats(); - int using = stats.getLeased() + stats.getPending(); - if (using > 0) { - // Do clean only when all connections are idle - return; - } - // Release connections when all clients are inactive - this.pool.closeIdleConnections(idleTime, TimeUnit.MILLISECONDS); - this.pool.closeExpiredConnections(); - }, checkPeriod, checkPeriod, TimeUnit.MILLISECONDS); + private static String parseContentType(RestHeaders headers) { + if (headers != null) { + String contentType = headers.get("Content-Type"); Review Comment: we can define a const var for header names like `RestHeaders.CONTENT_TYPE = "Content-Type"` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: dev-unsubscr...@hugegraph.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org