Skip to content

Commit

Permalink
up reflects
Browse files Browse the repository at this point in the history
  • Loading branch information
youfanx committed Sep 27, 2023
1 parent 4fe5afd commit 0a5a713
Show file tree
Hide file tree
Showing 13 changed files with 84 additions and 30 deletions.
3 changes: 2 additions & 1 deletion rxlib/src/main/java/org/rx/bean/RandomList.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.rx.core.Cache;
import org.rx.core.CachePolicy;
import org.rx.core.Linq;
import org.rx.core.cache.MemoryCache;
import org.rx.util.function.BiFunc;

import java.io.Serializable;
Expand Down Expand Up @@ -63,7 +64,7 @@ public <S> T next(S steeringKey, int ttl) {
}

public <S> T next(S steeringKey, int ttl, boolean isSliding) {
Cache<S, T> cache = Cache.getInstance(Cache.MEMORY_CACHE);
Cache<S, T> cache = Cache.getInstance(MemoryCache.class);
return cache.get(steeringKey, k -> next(), isSliding ? CachePolicy.sliding(ttl) : CachePolicy.absolute(ttl));
}

Expand Down
9 changes: 7 additions & 2 deletions rxlib/src/main/java/org/rx/core/Cache.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
import static org.rx.core.Constants.NON_RAW_TYPES;

public interface Cache<TK, TV> extends AbstractMap<TK, TV> {
Class<MemoryCache> MEMORY_CACHE = MemoryCache.class;
Class<DiskCache> DISK_CACHE = DiskCache.class;
Object NULL_VALUE = new Object();

static <TK, TV> TV getOrSet(TK key, BiFunc<TK, TV> loadingFunc) {
return getOrSet(key, loadingFunc, null);
Expand All @@ -25,6 +24,12 @@ static <TK, TV> Cache<TK, TV> getInstance() {
return IOC.get(Cache.class);
}

/**
* @param cacheType MEMORY_CACHE, DISK_CACHE
* @param <TK>
* @param <TV>
* @return
*/
@SuppressWarnings(NON_RAW_TYPES)
static <TK, TV> Cache<TK, TV> getInstance(Class<? extends Cache> cacheType) {
return IOC.get(cacheType, (Class) MemoryCache.class);
Expand Down
4 changes: 4 additions & 0 deletions rxlib/src/main/java/org/rx/core/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ enum MetricName {

String ENABLE_FLAG = "1";

String CACHE_REGION_ERROR_CODE = "ERR";
String CACHE_REGION_BEAN_PROPERTIES = "PROP";
String CACHE_REGION_INTERFACE_METHOD = "IM";
String CACHE_REGION_SKIP_SERIALIZE = "SS";
/**
* do not edit
*/
Expand Down
31 changes: 27 additions & 4 deletions rxlib/src/main/java/org/rx/core/Reflects.java
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ public static <T> T invokeDefaultMethod(Method method, Object instance, Object..

Class<?> declaringClass = method.getDeclaringClass();
MethodHandle methodHandle;
// if (App.IS_JAVA_11) {
// if (Sys.IS_JAVA_11) {
// methodHandle = MethodHandles.lookup()
// .findSpecial(
// method.getDeclaringClass(),
Expand Down Expand Up @@ -371,9 +371,32 @@ public static <T, TT> T invokeMethod(Method method, TT instance, Object... args)
return (T) method.invoke(instance, args);
}

public static Method getInterfaceMethod(Method method) {
Cache<Method, Object> cache = Cache.getInstance(MemoryCache.class);
Object v = cache.get(method, k -> {
Class<?> type = method.getDeclaringClass();
NoSuchMethodException lastEx = null;
for (Class<?> i : type.getInterfaces()) {
try {
return i.getMethod(method.getName(), method.getParameterTypes());
} catch (NoSuchMethodException e) {
lastEx = e;
}
}
if (lastEx != null) {
log.warn("getInterfaceMethod", lastEx);
}
return Cache.NULL_VALUE;
});
if (v == Cache.NULL_VALUE) {
return null;
}
return (Method) v;
}

public static Map<String, Linq<Method>> getMethodMap(Class<?> type) {
return methodCache.getValue().get(type, k -> {
List<Method> all = new ArrayList<>();
Set<Method> all = new HashSet<>();
for (Class<?> current = type; current != null; current = current.getSuperclass()) {
Method[] declared = type.getDeclaredMethods(); //can't get kotlin private methods
for (Method method : declared) {
Expand All @@ -397,8 +420,8 @@ public static Map<String, Linq<Method>> getMethodMap(Class<?> type) {

//region fields
public static Linq<PropertyNode> getProperties(Class<?> to) {
Cache<String, Linq<PropertyNode>> cache = Cache.getInstance(Cache.MEMORY_CACHE);
return cache.get(fastCacheKey("prop", to), k -> {
Cache<String, Linq<PropertyNode>> cache = Cache.getInstance(MemoryCache.class);
return cache.get(fastCacheKey(Constants.CACHE_REGION_BEAN_PROPERTIES, to), k -> {
Method getClass = Object.class.getDeclaredMethod("getClass");
Linq<Method> q = Linq.from(to.getMethods());
Linq<Tuple<String, Method>> setters = q.where(p -> p.getParameterCount() == 1 && p.getName().startsWith(SET_PROPERTY)).select(p -> Tuple.of(propertyName(p.getName()), p));
Expand Down
26 changes: 15 additions & 11 deletions rxlib/src/main/java/org/rx/core/YamlConfiguration.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.rx.core;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import lombok.Getter;
import lombok.NonNull;
Expand All @@ -17,6 +18,7 @@

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -159,17 +161,17 @@ public <T> T read(String key, T defaultVal) {
return val != null ? (T) val : defaultVal;
}

public <T> T readAs(Class<T> type) {
public <T> T readAs(Type type) {
return readAs(null, type, false);
}

public <T> T readAs(String key, Class<T> type) {
public <T> T readAs(String key, Type type) {
return readAs(key, type, false);
}

@ErrorCode("keyError")
@ErrorCode("partialKeyError")
public synchronized <T> T readAs(String key, Class<T> type, boolean throwOnEmpty) {
public synchronized <T> T readAs(String key, Type type, boolean throwOnEmpty) {
Map<String, Object> tmp = yaml;
if (key == null) {
return convert(tmp, type);
Expand Down Expand Up @@ -206,19 +208,21 @@ public synchronized <T> T readAs(String key, Class<T> type, boolean throwOnEmpty
return null;
}

<T> T convert(Object p, Class<T> type) {
<T> T convert(Object p, Type type) {
if (type == null) {
return null;
}
Map<String, Object> map = as(p, Map.class);
if (map != null) {
if (type.equals(Map.class)) {
return (T) map;
}
// new Yaml().loadAs()
boolean isProp = map != null;
if (isProp && type.equals(Map.class)) {
return (T) map;
}
Class<T> clz = as(type, Class.class);
if (isProp || clz == null) {
//new Yaml().loadAs() 不支持嵌套泛型
// return new JSONObject(map).to(type, JSONReader.Feature.SupportClassForName);
return JSON.parseObject(JSON.toJSONString(map), type, JSONReader.Feature.SupportClassForName);
return JSON.parseObject(JSON.toJSONString(p), type, JSONReader.Feature.SupportClassForName);
}
return Reflects.changeType(p, type);
return Reflects.changeType(p, clz);
}
}
5 changes: 3 additions & 2 deletions rxlib/src/main/java/org/rx/exception/YamlCodeHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.rx.annotation.ErrorCode;
import org.rx.bean.Tuple;
import org.rx.core.*;
import org.rx.core.cache.MemoryCache;

import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
Expand Down Expand Up @@ -66,13 +67,13 @@ public MessageFormatter messageFormatter() {
return;
}

Cache<String, Tuple<Class<?>, Method[]>> cache = Cache.getInstance(Cache.MEMORY_CACHE);
Cache<String, Tuple<Class<?>, Method[]>> cache = Cache.getInstance(MemoryCache.class);
for (StackTraceElement stack : e.getStacks()) {
Map<String, Object> messageSource = getMessageSource().readAs(stack.getClassName(), Map.class);
if (messageSource == null) {
continue;
}
Tuple<Class<?>, Method[]> caller = as(cache.get(fastCacheKey("STrace", stack.getClassName()), p -> {
Tuple<Class<?>, Method[]> caller = as(cache.get(fastCacheKey(Constants.CACHE_REGION_ERROR_CODE, stack.getClassName()), p -> {
Class<?> type = Reflects.loadClass(stack.getClassName(), false);
return Tuple.of(type, type.getDeclaredMethods());
}), Tuple.class);
Expand Down
10 changes: 4 additions & 6 deletions rxlib/src/main/java/org/rx/io/JdkAndJsonSerializer.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.rx.core.Cache;
import org.rx.core.JsonTypeInvoker;
import org.rx.core.Reflects;
import org.rx.core.Strings;
import org.rx.core.*;
import org.rx.core.cache.MemoryCache;
import org.rx.exception.TraceHandler;

import java.io.*;
Expand Down Expand Up @@ -51,9 +49,9 @@ public <T> void serialize(@NonNull T obj, IOStream stream) {

@SneakyThrows
public <T> void serialize(@NonNull T obj, @NonNull Type type, @NonNull IOStream stream) {
Cache<String, Object> cache = Cache.getInstance(Cache.MEMORY_CACHE);
Cache<String, Object> cache = Cache.getInstance(MemoryCache.class);
Class<?> objKls = obj.getClass();
String skipNS = fastCacheKey("skipNS", objKls);
String skipNS = fastCacheKey(Constants.CACHE_REGION_SKIP_SERIALIZE, objKls);
Object obj0 = !cache.containsKey(skipNS) && Serializable.class.isAssignableFrom(objKls) ? obj : new JsonWrapper(type, obj);

Compressible c0 = as(obj0, Compressible.class);
Expand Down
2 changes: 1 addition & 1 deletion rxlib/src/main/java/org/rx/net/dns/DnsServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public void setInterceptors(RandomList<ResolveInterceptor> interceptors) {
return;
}

DiskCache<Object, Object> cache = (DiskCache<Object, Object>) Cache.getInstance(Cache.DISK_CACHE);
DiskCache<Object, Object> cache = (DiskCache<Object, Object>) Cache.getInstance(DiskCache.class);
if (ENABLE_AUTO_RENEW) {
cache.onExpired.combine((s, e) -> {
Map.Entry<Object, Object> entry = e.getValue();
Expand Down
3 changes: 2 additions & 1 deletion rxlib/src/main/java/org/rx/net/support/EndpointTracer.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.rx.core.Cache;
import org.rx.core.cache.MemoryCache;

import java.net.SocketAddress;

import static org.rx.core.Sys.fastCacheKey;

@Slf4j
public final class EndpointTracer {
final Cache<String, SocketAddress> index = Cache.getInstance(Cache.MEMORY_CACHE);
final Cache<String, SocketAddress> index = Cache.getInstance(MemoryCache.class);

String key(SocketAddress sa) {
return fastCacheKey("EpTrace", sa);
Expand Down
3 changes: 2 additions & 1 deletion rxlib/src/main/java/org/rx/net/support/SocksSupport.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.rx.core.Arrays;
import org.rx.core.Cache;
import org.rx.core.cache.DiskCache;
import org.rx.net.dns.DnsServer;

import java.math.BigInteger;
Expand All @@ -20,7 +21,7 @@ public interface SocksSupport extends AutoCloseable, DnsServer.ResolveIntercepto
EndpointTracer ENDPOINT_TRACER = new EndpointTracer();

static Cache<BigInteger, UnresolvedEndpoint> fakeDict() {
return Cache.getInstance(Cache.DISK_CACHE);
return Cache.getInstance(DiskCache.class);
}

void fakeEndpoint(BigInteger hash, String realEndpoint);
Expand Down
3 changes: 3 additions & 0 deletions rxlib/src/main/java/org/rx/spring/Interceptors.java
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,9 @@ protected void onLog(Signature signature, ProceedEventArgs eventArgs, String par

protected boolean doValidate(Executable r) {
EnableTrace a = r.getAnnotation(EnableTrace.class);
if (a == null) {
a = r.getDeclaringClass().getAnnotation(EnableTrace.class);
}
return a != null && a.doValidate();
}
}
Expand Down
13 changes: 13 additions & 0 deletions rxlib/src/main/java/org/rx/util/Validator.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.rx.annotation.ValidRegex;
import org.rx.core.Linq;
import org.rx.core.Reflects;
import org.rx.util.function.Func;

import javax.validation.ConstraintValidator;
Expand Down Expand Up @@ -102,6 +103,13 @@ public static <T> T validateMethod(Method member, Object instance, Object[] para
for (ConstraintViolation<Object> violation : executableValidator.validateParameters(instance, member, parameterValues)) {
doThrow(violation);
}
// Method interfaceMethod = Reflects.getInterfaceMethod(member);
// boolean hasIM = interfaceMethod != null;
// if (hasIM) {
// for (ConstraintViolation<Object> violation : executableValidator.validateParameters(instance, interfaceMethod, parameterValues)) {
// doThrow(violation);
// }
// }

if (proceed == null) {
return null;
Expand All @@ -110,6 +118,11 @@ public static <T> T validateMethod(Method member, Object instance, Object[] para
for (ConstraintViolation<Object> violation : executableValidator.validateReturnValue(instance, member, retVal = proceed.get())) {
doThrow(violation);
}
// if (hasIM) {
// for (ConstraintViolation<Object> violation : executableValidator.validateReturnValue(instance, interfaceMethod, retVal)) {
// doThrow(violation);
// }
// }
return retVal;
}

Expand Down
2 changes: 1 addition & 1 deletion rxlib/src/test/java/org/rx/core/TestCore.java
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,7 @@ public void cache() {
// BiAction<Caffeine<Object, Object>> dump = b -> b.removalListener((k, v, c) -> log.info("onRemoval {} {} {}", k, v, c));
// testCache(new MemoryCache<>(dump));

DiskCache<Tuple<?, ?>, Integer> diskCache = (DiskCache) Cache.getInstance(Cache.DISK_CACHE);
DiskCache<Tuple<?, ?>, Integer> diskCache = (DiskCache) Cache.getInstance(DiskCache.class);
testCache(diskCache);

System.in.read();
Expand Down

0 comments on commit 0a5a713

Please sign in to comment.