Skip to content

Commit

Permalink
refactor-proxy-manager
Browse files Browse the repository at this point in the history
  • Loading branch information
crossoverJie committed Sep 7, 2024
1 parent ab5f7a8 commit d5d4719
Show file tree
Hide file tree
Showing 6 changed files with 120 additions and 23 deletions.
6 changes: 6 additions & 0 deletions cim-common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@
<artifactId>junit</artifactId>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.crossoverjie.cim.common.core.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crossoverjie.cim.common.exception.CIMException;
import com.crossoverjie.cim.common.util.HttpClient;
Expand All @@ -9,6 +10,7 @@
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URI;
import okhttp3.Response;

import static com.crossoverjie.cim.common.enums.StatusEnum.VALIDATION_FAIL;

Expand All @@ -22,16 +24,15 @@
public final class ProxyManager<T> {


private Class<T> clazz;
private final Class<T> clazz;

private String url;
private final String url;

private OkHttpClient okHttpClient;
private final OkHttpClient okHttpClient;

/**
*
* @param clazz Proxied interface
* @param url server provider url
* @param clazz Proxied interface
* @param url server provider url
* @param okHttpClient http client
*/
public ProxyManager(Class<T> clazz, String url, OkHttpClient okHttpClient) {
Expand All @@ -40,38 +41,58 @@ public ProxyManager(Class<T> clazz, String url, OkHttpClient okHttpClient) {
this.okHttpClient = okHttpClient;
}


/**
* Get proxy instance of api.
*
* @return
*/
public T getInstance() {
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clazz}, new ProxyInvocation());
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clazz},
new ProxyInvocation());
}


private class ProxyInvocation implements InvocationHandler {

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
JSONObject jsonObject = new JSONObject();
String serverUrl = url + "/" + method.getName() ;

URI serverUri = new URI(serverUrl);
serverUrl = serverUri.normalize().toString();
Response result = null;
try {
Request annotation = method.getAnnotation(Request.class);
if (annotation != null && annotation.method().equals(Request.GET)) {
result = HttpClient.get(okHttpClient, url);
} else {
JSONObject jsonObject = new JSONObject();
String serverUrl = url + "/" + method.getName();
URI serverUri = new URI(serverUrl);
serverUrl = serverUri.normalize().toString();

if (args != null && args.length > 1) {
throw new CIMException(VALIDATION_FAIL);
}
if (args != null && args.length > 1) {
throw new CIMException(VALIDATION_FAIL);
}

if (method.getParameterTypes().length > 0){
Object para = args[0];
Class<?> parameterType = method.getParameterTypes()[0];
for (Field field : parameterType.getDeclaredFields()) {
field.setAccessible(true);
jsonObject.put(field.getName(), field.get(para));
if (method.getParameterTypes().length > 0) {
Object para = args[0];
Class<?> parameterType = method.getParameterTypes()[0];
for (Field field : parameterType.getDeclaredFields()) {
field.setAccessible(true);
jsonObject.put(field.getName(), field.get(para));
}
}
result = HttpClient.post(okHttpClient, jsonObject.toString(), serverUrl);
}
if (method.getReturnType() == void.class){
return null;
}
String json = result.body().string();
return JSON.parseObject(json, method.getReturnType());
} finally {
if (result != null) {
result.body().close();
}
}
return HttpClient.call(okHttpClient, jsonObject.toString(), serverUrl);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.crossoverjie.cim.common.core.proxy;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
* @author crossoverJie
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Request {
String method() default POST;

String GET = "GET";
String POST = "POST";
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
* Date: 2020-04-25 00:39
* @since JDK 1.8
*/
public final class HttpClient {
public final class HttpClient{

private static MediaType mediaType = MediaType.parse("application/json");

public static Response call(OkHttpClient okHttpClient, String params, String url) throws IOException {
public static Response post(OkHttpClient okHttpClient, String params, String url) throws IOException {
RequestBody requestBody = RequestBody.create(mediaType, params);

Request request = new Request.Builder()
Expand All @@ -34,4 +34,19 @@ public static Response call(OkHttpClient okHttpClient, String params, String url

return response;
}

public static Response get(OkHttpClient okHttpClient, String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.get()
.build();

Response response = okHttpClient.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}

return response;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.crossoverjie.cim.common.core.proxy;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import okhttp3.OkHttpClient;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class ProxyManagerTest {

@Test
public void testGet() {
OkHttpClient client = new OkHttpClient();
Github github =
new ProxyManager<>(Github.class, "https://api.github.com/users/crossoverjie",
client)
.getInstance();
GithubResponse githubResponse = github.userInfo();
Assertions.assertEquals(githubResponse.getName(), "crossoverJie");

github.userInfo2();
}

interface Github {
@Request(method = Request.GET)
GithubResponse userInfo();
@Request(method = Request.GET)
void userInfo2();
}

@NoArgsConstructor
@Data
public static class GithubResponse {
@JsonProperty("name")
private String name;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.crossoverjie.cim.route.api;

import com.crossoverjie.cim.common.core.proxy.Request;
import com.crossoverjie.cim.common.res.BaseResponse;
import com.crossoverjie.cim.route.api.vo.req.ChatReqVO;
import com.crossoverjie.cim.route.api.vo.req.LoginReqVO;
Expand Down Expand Up @@ -66,6 +67,7 @@ public interface RouteApi {
* @return
* @throws Exception
*/
@Request(method = Request.GET)
Object onlineUser() throws Exception;

// TODO: 2024/8/19 Get cache server & metastore server
Expand Down

0 comments on commit d5d4719

Please sign in to comment.