package org.jdbi.v3.core;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.jdbi.v3.core.internal.JdbiThreadLocals;
class OnDemandExtensions {
private static final Method EQUALS_METHOD;
private static final Method HASHCODE_METHOD;
private static final Method TOSTRING_METHOD;
static {
try {
EQUALS_METHOD = Object.class.getMethod("equals", Object.class);
HASHCODE_METHOD = Object.class.getMethod("hashCode");
TOSTRING_METHOD = Object.class.getMethod("toString");
} catch (NoSuchMethodException wat) {
throw new IllegalStateException("JVM error", wat);
}
}
private OnDemandExtensions() {
throw new UnsupportedOperationException("utility class");
}
static <E> E create(Jdbi db, Class<E> extensionType) {
ThreadLocal<E> threadExtension = new ThreadLocal<>();
InvocationHandler handler = (proxy, method, args) -> {
if (EQUALS_METHOD.equals(method)) {
return proxy == args[0];
}
if (HASHCODE_METHOD.equals(method)) {
return System.identityHashCode(proxy);
}
if (TOSTRING_METHOD.equals(method)) {
return extensionType + "@" + Integer.toHexString(System.identityHashCode(proxy));
}
if (threadExtension.get() != null) {
return invoke(threadExtension.get(), method, args);
}
return db.withExtension(extensionType, extension ->
JdbiThreadLocals.invokeInContext(threadExtension, extension,
() -> invoke(extension, method, args)));
};
return extensionType.cast(
Proxy.newProxyInstance(
extensionType.getClassLoader(),
new Class[]{extensionType}, handler));
}
@SuppressWarnings("PMD.AvoidRethrowingException")
private static Object invoke(Object target, Method method, Object[] args) {
try {
if (Proxy.isProxyClass(target.getClass())) {
return Proxy.getInvocationHandler(target).invoke(target, method, args);
}
return MethodHandles.lookup().unreflect(method).bindTo(target).invokeWithArguments(args);
} catch (RuntimeException | Error e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}