Skip to content

Commit

Permalink
fix: code issue
Browse files Browse the repository at this point in the history
  • Loading branch information
zhenyuT committed Oct 29, 2023
1 parent 53b57fa commit 945005a
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@

public abstract class AbstractRestClient implements RestClient {

private final ThreadLocal<String> authContext = new InheritableThreadLocal<>();
private final ThreadLocal<String> authContext;
private final OkHttpClient client;
private final String baseUrl;
private final Request.Builder requestBuilder = new Request.Builder();
private final Request.Builder requestBuilder;

public AbstractRestClient(String url, int timeout) {
this(url, OkHttpConfig.builder()
Expand Down Expand Up @@ -147,12 +147,14 @@ public AbstractRestClient(String url, String token, Integer timeout,
public AbstractRestClient(String url, OkHttpConfig okhttpConfig) {
this.baseUrl = url;
this.client = buildOkHttpClient(okhttpConfig);
this.requestBuilder = new Request.Builder();
this.authContext = new InheritableThreadLocal<>();
}

private static RequestBody buildRequestBody(Object body, RestHeaders headers) {
String contentType = parseContentType(headers);
String bodyContent;
if ("application/json".equals(contentType)) {
if (RequestHeaders.APPLICATION_JSON.equals(contentType)) {
if (body == null) {
bodyContent = "{}";
} else {
Expand All @@ -163,7 +165,7 @@ private static RequestBody buildRequestBody(Object body, RestHeaders headers) {
}
RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), bodyContent);

if (headers != null && "gzip".equals(headers.get("Content-Encoding"))) {
if (headers != null && "gzip".equals(headers.get(RequestHeaders.CONTENT_ENCODING))) {
requestBody = gzip(requestBody);
}
return requestBody;
Expand Down Expand Up @@ -192,12 +194,12 @@ public void writeTo(BufferedSink sink) throws IOException {

private static String parseContentType(RestHeaders headers) {
if (headers != null) {
String contentType = headers.get("Content-Type");
String contentType = headers.get(RequestHeaders.CONTENT_TYPE);
if (contentType != null) {
return contentType;
}
}
return "application/json";
return RequestHeaders.APPLICATION_JSON;
}

private OkHttpClient buildOkHttpClient(OkHttpConfig okHttpConfig) {
Expand Down Expand Up @@ -299,7 +301,7 @@ private Request.Builder getRequestBuilder(String path, String id, RestHeaders he
Request.Builder builder = requestBuilder.url(urlBuilder.build());

if (headers != null) {
builder.headers(headers.toOkhttpHeader());
builder.headers(headers.toOkHttpHeader());
}

this.attachAuthToRequest(builder);
Expand Down Expand Up @@ -327,14 +329,12 @@ public RestResult put(String path, String id, Object object) {
}

@Override
public RestResult put(String path, String id, Object object,
RestHeaders headers) {
public RestResult put(String path, String id, Object object, RestHeaders headers) {
return this.put(path, id, object, headers, null);
}

@Override
public RestResult put(String path, String id, Object object,
Map<String, Object> params) {
public RestResult put(String path, String id, Object object, Map<String, Object> params) {
return this.put(path, id, object, null, params);
}

Expand Down Expand Up @@ -440,7 +440,7 @@ private void attachAuthToRequest(Request.Builder builder) {
// Add auth header
String auth = this.getAuthContext();
if (StringUtils.isNotEmpty(auth)) {
builder.addHeader("Authorization", auth);
builder.addHeader(RequestHeaders.AUTHORIZATION, auth);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ public OkhttpBasicAuthInterceptor(String user, String password) {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (request.header("Authorization") == null) {
if (request.header(RequestHeaders.AUTHORIZATION) == null) {
Request authenticatedRequest = request.newBuilder()
.header("Authorization", credentials).build();
.header(RequestHeaders.AUTHORIZATION, credentials)
.build();
return chain.proceed(authenticatedRequest);
}
return chain.proceed(request);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ public OkhttpTokenInterceptor(String token) {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (request.header("Authorization") == null) {
if (request.header(RequestHeaders.AUTHORIZATION) == null) {
Request authenticatedRequest = request.newBuilder()
.header("Authorization", "Bearer " + this.token)
.header(RequestHeaders.AUTHORIZATION, "Bearer " + this.token)
.build();
return chain.proceed(authenticatedRequest);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* 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;

public class RequestHeaders {

public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String APPLICATION_JSON = "application/json";
public static final String AUTHORIZATION = "Authorization";
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,27 @@
import java.util.Iterator;

import kotlin.Pair;
import okhttp3.Headers;

public class RestHeaders {

private final okhttp3.Headers.Builder headersBuilder = new okhttp3.Headers.Builder();
private final okhttp3.Headers.Builder headersBuilder;

public RestHeaders() {
this.headersBuilder = new okhttp3.Headers.Builder();
}

public static RestHeaders convertToRestHeaders(okhttp3.Headers headers) {
RestHeaders restHeaders = new RestHeaders();

if (headers != null) {
Iterator<Pair<String, String>> iter = headers.iterator();
while (iter.hasNext()) {
Pair<String, String> pair = iter.next();
restHeaders.add(pair.getFirst(), pair.getSecond());
}
}
return restHeaders;
}

public String get(String key) {
return this.headersBuilder.get(key);
Expand All @@ -47,31 +63,18 @@ public RestHeaders add(String key, Date value) {

@Override
public int hashCode() {
return this.toOkhttpHeader().hashCode();
return this.toOkHttpHeader().hashCode();
}

@Override
public boolean equals(Object obj) {
if(obj instanceof RestHeaders) {
return this.toOkhttpHeader().equals(((RestHeaders)obj).toOkhttpHeader());
if (obj instanceof RestHeaders) {
return this.toOkHttpHeader().equals(((RestHeaders) obj).toOkHttpHeader());
}
return false;
}

public okhttp3.Headers toOkhttpHeader() {
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()) {
Pair<String, String> pair = iter.next();
restHeaders.add(pair.getFirst(), pair.getSecond());
}
}
return restHeaders;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public class RestResult {
private final String content;

public RestResult(Response response) {
this(response.code(), getResponseContent(response), RestHeaders.convertRestHeaders(response.headers()));
this(response.code(), getResponseContent(response),
RestHeaders.convertToRestHeaders(response.headers()));
}

public RestResult(int status, String content, RestHeaders headers) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

import org.apache.hugegraph.rest.AbstractRestClient;
import org.apache.hugegraph.rest.ClientException;
import org.apache.hugegraph.rest.RequestHeaders;
import org.apache.hugegraph.rest.RestClient;
import org.apache.hugegraph.rest.RestHeaders;
import org.apache.hugegraph.rest.RestResult;
Expand Down Expand Up @@ -321,7 +322,7 @@ public void testRequest() {
Response response = Mockito.mock(Response.class, Mockito.RETURNS_DEEP_STUBS);
Mockito.when(response.code()).thenReturn(200);
Mockito.when(response.headers())
.thenReturn(new RestHeaders().toOkhttpHeader());
.thenReturn(new RestHeaders().toOkHttpHeader());
Mockito.when(response.body().string()).thenReturn("content");

Mockito.when(requestBuilder.delete()).thenReturn(requestBuilder);
Expand All @@ -341,99 +342,86 @@ public void testRequest() {
client.setAuthContext("token1");
result = client.delete("test", ImmutableMap.of());
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader("Authorization",
"token1");
Mockito.verify(requestBuilder).addHeader(RequestHeaders.AUTHORIZATION,"token1");

client.resetAuthContext();

client.setAuthContext("token2");
result = client.delete("test", "id");
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token2");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token2");
client.resetAuthContext();

// Test get
client.setAuthContext("token3");
result = client.get("test");
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token3");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token3");
client.resetAuthContext();

client.setAuthContext("token4");
result = client.get("test", ImmutableMap.of());
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token4");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token4");
client.resetAuthContext();

client.setAuthContext("token5");
result = client.get("test", "id");
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token5");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token5");
client.resetAuthContext();

// Test put
client.setAuthContext("token6");
// result = client.post("test", new Object()); //why use new Object() as args here?
result = client.post("test", null);
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token6");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token6");
client.resetAuthContext();

client.setAuthContext("token7");
result = client.post("test", null, new RestHeaders());
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token7");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token7");
client.resetAuthContext();

client.setAuthContext("token8");
result = client.post("test", null, ImmutableMap.of());
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token8");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token8");
client.resetAuthContext();

client.setAuthContext("token9");
result = client.post("test", null, new RestHeaders(),
ImmutableMap.of());
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token9");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token9");
client.resetAuthContext();

// Test post
client.setAuthContext("token10");
result = client.post("test", null);
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token10");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token10");
client.resetAuthContext();

client.setAuthContext("token11");
result = client.post("test", null, new RestHeaders());
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token11");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token11");
client.resetAuthContext();

client.setAuthContext("token12");
result = client.post("test", null, ImmutableMap.of());
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token12");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token12");
client.resetAuthContext();

client.setAuthContext("token13");
result = client.post("test", null, new RestHeaders(),
ImmutableMap.of());
Assert.assertEquals(200, result.status());
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,
"token13");
Mockito.verify(requestBuilder).addHeader(HttpHeaders.AUTHORIZATION,"token13");
client.resetAuthContext();
}

Expand Down Expand Up @@ -532,7 +520,7 @@ public RestClientImpl(String url, int timeout, int status,
protected Response request(Callable<Response> method) {
Response response = Mockito.mock(Response.class, Mockito.RETURNS_DEEP_STUBS);
Mockito.when(response.code()).thenReturn(this.status);
Mockito.when(response.headers()).thenReturn(this.headers.toOkhttpHeader());
Mockito.when(response.headers()).thenReturn(this.headers.toOkHttpHeader());
Mockito.when(response.body().string())
.thenReturn(this.content);
return response;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ private static RestResult newRestResult(int status, String content,
RestHeaders headers) {
Response response = Mockito.mock(Response.class, Mockito.RETURNS_DEEP_STUBS);
Mockito.when(response.code()).thenReturn(status);
Mockito.when(response.headers()).thenReturn(headers.toOkhttpHeader());
Mockito.when(response.headers()).thenReturn(headers.toOkHttpHeader());
Mockito.when(response.body().string())
.thenReturn(content);
return new RestResult(response);
Expand Down

0 comments on commit 945005a

Please sign in to comment.