net.java.ao.builder.DelegatingDisposableDataSourceHandler Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of activeobjects Show documentation
Show all versions of activeobjects Show documentation
This is the full Active Objects library, if you don't know which one to use, you probably want this one.
The newest version!
package net.java.ao.builder;
import net.java.ao.Disposable;
import net.java.ao.DisposableDataSource;
import javax.sql.DataSource;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Objects;
public final class DelegatingDisposableDataSourceHandler implements InvocationHandler {
private final DataSource dataSource;
private final Disposable disposable;
public DelegatingDisposableDataSourceHandler(DataSource dataSource, Disposable disposable) {
this.dataSource = Objects.requireNonNull(dataSource, "dataSource can't be null");
this.disposable = Objects.requireNonNull(disposable, "disposable can't be null");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (isDisposeMethod(method)) {
disposable.dispose();
return null;
}
return delegate(method, args);
}
private Object delegate(Method method, Object[] args) throws Throwable {
final Method m = dataSource.getClass().getMethod(method.getName(), method.getParameterTypes());
m.setAccessible(true);
try {
return m.invoke(dataSource, args);
} catch (IllegalAccessException e) {
// avoid UndeclaredThrowableExceptions
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
// avoid UndeclaredThrowableExceptions
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
// avoid UndeclaredThrowableExceptions
throw e.getCause();
}
}
public static DisposableDataSource newInstance(DataSource ds, Disposable disposable) {
return (DisposableDataSource) Proxy.newProxyInstance(
DelegatingDisposableDataSourceHandler.class.getClassLoader(),
new Class[]{DisposableDataSource.class},
new DelegatingDisposableDataSourceHandler(ds, disposable));
}
private static boolean isDisposeMethod(Method method) {
return method.getName().equals("dispose")
&& method.getParameterTypes().length == 0;
}
}