Skip to content

Instantly share code, notes, and snippets.

@bdemers
Created February 21, 2024 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdemers/ec2da73f8496fe1cc673619b84f3f450 to your computer and use it in GitHub Desktop.
Save bdemers/ec2da73f8496fe1cc673619b84f3f450 to your computer and use it in GitHub Desktop.
package org.apache.directory.scimple.example.spring.ldap;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionPool;
import java.io.Closeable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ReleasingLdapConnectionPool extends LdapConnectionPool {
public ReleasingLdapConnectionPool(PooledObjectFactory<LdapConnection> factory, GenericObjectPoolConfig poolConfig) {
super(factory, poolConfig);
}
@Override
public LdapConnection getConnection() throws LdapException {
return wrap(super.getConnection(), this);
}
private static LdapConnection wrap(LdapConnection ldapConnection, LdapConnectionPool ldapConnectionPool) {
return (LdapConnection) Proxy.newProxyInstance(ldapConnection.getClass().getClassLoader(), new Class[]{ LdapConnection.class, Closeable.class }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("close")) {
ldapConnectionPool.releaseConnection(ldapConnection);
return null;
} else {
return method.invoke(ldapConnection, args);
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment