
snaq.db.DBPoolServletContextListener Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of dbpool Show documentation
Show all versions of dbpool Show documentation
JDBC connection pooling utility, supporting time-based expiry, statement caching, connection validation, and easy configuration using a pool manager.
The newest version!
package snaq.db;
import javax.naming.InitialContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import snaq.db.DBPoolDataSource;
/**
* ServletContextListener implementation to handle connection pool shutdown.
* The JNDI name of the configured DBPoolDataSource should be assigned as a
* context parameter for the web application.
* For example, typically these lines might be added to {@code web.xml}:
*
* <listener>
* <listener-class>snaq.db.DBPoolServletContextListener</listener-class>
* </listener>
* <context-param>
* <param-name>name</param-name>
* <param-value>jdbc/pool-ds</param-value>
* </context-param>
*
* in the case that the DataSource has the JNDI name of jdbc/pool-ds.
*
* @author Giles Winstanley
*/
public class DBPoolServletContextListener implements ServletContextListener
{
/** SLF4J logger instance for writing log entries. */
private static final Logger log = LoggerFactory.getLogger(DBPoolServletContextListener.class);
@Override
public void contextInitialized(ServletContextEvent evt)
{
}
@Override
public void contextDestroyed(ServletContextEvent evt)
{
// Find configured parameter.
String name = evt.getServletContext().getInitParameter("name");
if (name == null || name.trim().isEmpty())
log.warn("Found invalid 'name' parameter in ServletContext");
try
{
// Find DataSource in JNDI context.
InitialContext ctx = new InitialContext();
Object o = ctx.lookup("java:comp/env/" + name);
if (o == null || !(o instanceof DataSource))
{
log.warn("ServletContext 'name' parameter doesn't refer to a DataSource: " + o);
return;
}
DBPoolDataSource ds = (DBPoolDataSource)o;
log.trace(String.format("Found compatible DBPoolDataSource (%s): releasing", ds.getName()));
ds.release();
}
catch (Throwable t)
{
log.warn(t.getMessage(), t);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy