Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. public abstract class InterceptorDataSource {
  2. private final InvocationHandler handler;
  3.  
  4. protected InterceptorDataSource(final DataSource delegate) {
  5. this.handler = new InvocationHandler() {
  6. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  7. return (method.getName().equals("getConnection")) ? getConnection(delegate) : method.invoke(delegate, args);
  8. }
  9. };
  10. }
  11.  
  12. protected Connection getConnection(final DataSource delegate) throws SQLException {
  13. return delegate.getConnection();
  14. }
  15.  
  16. public static DataSource wrapInterceptor(InterceptorDataSource instance) {
  17. return (DataSource) Proxy.newProxyInstance(instance.getClass().getClassLoader(), new Class[] { DataSource.class }, instance.handler);
  18. }
  19. }
  20.  
  21. // Use case for intercepting getConnection() from HikariDataSource to do something on every
  22. // borrow from the pool
  23. //
  24. HikariDataSource hikariDS = new HikariDataSource();
  25. ...
  26. DataSource wrappedDS = InterceptorDataSource.wrapInterceptor(new InterceptorDataSource(hikariDS) {
  27. @Override
  28. protected Connection getConnection(DataSource delegate) throws SQLException {
  29. final Connection c = super.getConnection(delegate);
  30. System.out.println("Look mom, I'm wrapping HikariDataSource.getConnection() before it is given to the user");
  31. return c;
  32. }
  33. });
  34. ...
  35.  
  36. // Use case for intercepting getConnection() from the real DataSource to do something on every
  37. // connection creation (before be added to the pool)
  38. PGSimpleDataSource realDS = new PGSimpleDataSource(); // real DataSource to intercept
  39. DataSource wrappedDS = InterceptorDataSource.wrapInterceptor(new InterceptorDataSource(realDS) {
  40. @Override
  41. protected Connection getConnection(DataSource delegate) throws SQLException {
  42. final Connection c = super.getConnection(delegate);
  43. System.out.println("Look mom, I'm intercepting PGSimpleDataSource.getConnection() before it reaches the pool");
  44. return c;
  45. }
  46. });
  47.  
  48. HikariDataSource hikariDS = new HikariDataSource();
  49. hikariDS.setDataSource(wrappedDS);
  50. ...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement