package com.axiomalaska.sos.injector.db;

import java.sql.Connection;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Strings;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

public class DatabaseConnectionHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseConnectionHelper.class);
    private static BoneCP connectionPool;
    
    private static BoneCP getConnectionPool() throws ClassNotFoundException, SQLException {
        if (connectionPool == null) {
            LOGGER.debug("Creating connection pool");
            BoneCPConfig config = new BoneCPConfig();
            config.setJdbcUrl(DatabaseSosInjectorConfig.instance().getJdbcUrl());
            if (!Strings.isNullOrEmpty(DatabaseSosInjectorConfig.instance().getJdbcUsername())) {
                config.setUsername(DatabaseSosInjectorConfig.instance().getJdbcUsername());
            }
            if (!Strings.isNullOrEmpty(DatabaseSosInjectorConfig.instance().getJdbcPassword())) {
                config.setPassword(DatabaseSosInjectorConfig.instance().getJdbcPassword());
            }
            connectionPool = new BoneCP(config);
        }
        return connectionPool;
    }

    public static Connection getConnection() throws SQLException, ClassNotFoundException {        
        return getConnectionPool().getConnection();
    }

    public static void shutdownConnectionPool() {
        if (connectionPool != null) {
            LOGGER.debug("Shutting down connection pool");
            connectionPool.shutdown();
        }
    }
}

@@ -79,24 +79,109 @@
 ava.sql.
-SQLExcep
+Driver;%0Aimport java.sql.DriverManager;%0Aimport java.sql.SQLException;%0Aimport java.util.Enumera
 tion;%0A%0Ai
@@ -626,16 +626,16 @@
 ption %7B%0A
-
         
@@ -656,32 +656,676 @@
 Pool == null) %7B%0A
+            //only keep the correct driver for the url in the classloader, since otherwise we'll get the error from%0A            //the first tried driver even if it's not the correct driver for our url.%0A            Driver correctDriver = DriverManager.getDriver(DatabaseSosInjectorConfig.instance().getJdbcUrl());%0A            Enumeration%3CDriver%3E drivers = DriverManager.getDrivers();%0A            while (drivers.hasMoreElements()) %7B%0A                Driver driver = drivers.nextElement();%0A                if (!driver.equals(correctDriver)) %7B%0A                    DriverManager.deregisterDriver(driver);%0A                %7D%0A            %7D%0A            %0A
             LOGG

Remove unused db drivers from classpath (fixes #3)