Example usage for org.apache.commons.dbcp.datasources SharedPoolDataSource setTestOnBorrow

List of usage examples for org.apache.commons.dbcp.datasources SharedPoolDataSource setTestOnBorrow

Introduction

In this page you can find the example usage for org.apache.commons.dbcp.datasources SharedPoolDataSource setTestOnBorrow.

Prototype

public void setTestOnBorrow(boolean testOnBorrow) 

Source Link

Document

When true, objects will be {*link PoolableObjectFactory#validateObject validated} before being returned by the {*link #borrowObject} method.

Usage

From source file:hk.hku.cecid.piazza.commons.dao.ds.SimpleDSDAOFactory.java

/**
 * Initializes this DAOFactory./*from w w w.  j  a  va  2 s .  co  m*/
 */
public void initFactory() throws DAOException {
    try {
        String driver = null;
        String url = null;
        String username = null;
        String password = null;

        boolean isPooling = true;
        int maxIdle = 0;
        int maxActive = 10;
        int maxWait = 50;

        boolean testOnBorrow = false;
        boolean testOnReturn = false;
        boolean testWhileIdle = false;
        String validationQuery = null;

        try {
            driver = getParameter("driver");
            url = getParameter("url");
            username = getParameter("username", null);
            password = getParameter("password", null);

            maxIdle = StringUtilities.parseInt(getParameter("maxIdle", null), 0);
            maxActive = StringUtilities.parseInt(getParameter("maxActive", null), 0);
            maxWait = StringUtilities.parseInt(getParameter("maxWait", null), -1);

            validationQuery = StringUtilities.trim(getParameter("validationQuery", null));
            if (validationQuery != null) {
                testOnBorrow = StringUtilities.parseBoolean(getParameter("testOnBorrow", "false"));
                testOnReturn = StringUtilities.parseBoolean(getParameter("testOnReturn", "false"));
                testWhileIdle = StringUtilities.parseBoolean(getParameter("testWhileIdle", "false"));
            }

        } catch (Exception e) {
            throw new DAOException("Invalid parameter for SimpleDSDAOFactory.");
        }

        if (getParameter("pooling", null) != null) {
            if (!getParameter("pooling").equalsIgnoreCase("true")
                    && !getParameter("pooling").equalsIgnoreCase("false")) {
                throw new DAOException("Invalid parameter for SimpleDSDAOFactory.");
            }
            isPooling = StringUtilities.parseBoolean(getParameter("pooling", "true"));
        }

        DataSource datasource;

        if (isPooling) {
            DriverAdapterCPDS cpds = new DriverAdapterCPDS();
            cpds.setDriver(driver);
            cpds.setUrl(url);
            cpds.setUser(username);
            cpds.setPassword(password);

            SharedPoolDataSource sds = new SharedPoolDataSource();
            sds.setConnectionPoolDataSource(cpds);
            sds.setMaxIdle(maxIdle);
            sds.setMaxActive(maxActive);
            sds.setMaxWait(maxWait);

            sds.setTestOnBorrow(testOnBorrow);
            sds.setTestOnReturn(testOnReturn);
            sds.setTestWhileIdle(testWhileIdle);
            sds.setValidationQuery(validationQuery);

            datasource = sds;
        } else {
            datasource = new SimpleDataSource(driver, url, username, password);
        }

        setDataSource(datasource);
    } catch (Exception e) {
        throw new DAOException("Cannot initialize SimpleDSDAOFactory!", e);
    }
}

From source file:com.runwaysdk.dataaccess.database.general.SQLServer.java

/**
 * Initializes datasource to point to SQL Server
 *//*from   w w w  .j a  v a 2s  .  c  o m*/
@Inject
public SQLServer() {
    super();

    this.nextSequenceNumberLock = new ReentrantLock();
    this.objectSequenceTableName = "object_seq_table";
    this.transactionSequenceTableName = "transaction_seq_table";

    // The container is not providing a pooled datasource
    if (this.dataSource == null) {
        JtdsDataSource serverDataSource = new JtdsDataSource();
        serverDataSource.setServerName(DatabaseProperties.getServerName());
        serverDataSource.setPortNumber(DatabaseProperties.getPort());
        serverDataSource.setDatabaseName(DatabaseProperties.getDatabaseName());
        serverDataSource.setUser(DatabaseProperties.getUser());
        serverDataSource.setPassword(DatabaseProperties.getPassword());

        int maxDbConnections = DatabaseProperties.getMaxConnections() - 1;

        if (maxDbConnections < 2) {
            maxDbConnections = 2;
        }

        boolean pooling = DatabaseProperties.getConnectionPooling();
        if (pooling) {
            SharedPoolDataSource sharedPoolDataSource = new SharedPoolDataSource();
            sharedPoolDataSource.setConnectionPoolDataSource(serverDataSource);
            sharedPoolDataSource.setMaxActive(maxDbConnections);
            sharedPoolDataSource.setTestOnBorrow(true);
            sharedPoolDataSource.setValidationQuery("SELECT 1");
            this.dataSource = sharedPoolDataSource;
        } else {
            this.dataSource = serverDataSource;
        }
    }
}

From source file:com.runwaysdk.dataaccess.database.general.MySQL.java

/**
 * Initialize the datasource to point to a MySQL database.
 *//*  ww w .ja va  2  s  .c  om*/
@Inject
public MySQL() {
    super();

    this.nextSequenceNumberLock = new ReentrantLock();
    this.objectSequenceTableName = "object_seq_table";
    this.transactionSequenceTableName = "transaction_seq_table";

    // The container is not providing a pooled datasource
    if (this.dataSource == null) {
        // We subtract 1 because we'll reserve a connection for sequence numbers
        int maxDbConnections = DatabaseProperties.getMaxConnections() - 1;

        if (maxDbConnections < 2) {
            maxDbConnections = 2;
        }

        boolean pooling = DatabaseProperties.getConnectionPooling();

        MysqlDataSource mysqlDataSource = null;
        if (pooling) {
            mysqlDataSource = new MysqlConnectionPoolDataSource();
        } else {
            mysqlDataSource = new MysqlDataSource();
        }

        // useServerPrepStmts=false
        // jdbc:mysql://[host][,failoverhost...][:port]/[database]
        // [?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
        String url = "jdbc:mysql://" + DatabaseProperties.getServerName() + ":" + DatabaseProperties.getPort()
                + "/" + DatabaseProperties.getDatabaseName() + "?useServerPrepStmts=false";

        // is-connection-validation-required=true s
        // ?connectTimeout=1000"
        mysqlDataSource.setURL(url);
        mysqlDataSource.setUser(DatabaseProperties.getUser());
        mysqlDataSource.setPassword(DatabaseProperties.getPassword());

        /*
         * Alternate method for setting up the connection
         * mysqlDataSource.setServerName(vendorProps.getString(this.serverName));
         * mysqlDataSource.setPort(portNumber);
         * mysqlDataSource.setDatabaseName(vendorProps
         * .getString(this.databaseName));
         * mysqlDataSource.setUser(vendorProps.getString(this.user));
         * mysqlDataSource.setPassword(vendorProps.getString(this.password));
         */

        if (pooling) {
            SharedPoolDataSource sharedPoolDataSource = new SharedPoolDataSource();
            sharedPoolDataSource.setConnectionPoolDataSource((MysqlConnectionPoolDataSource) mysqlDataSource);
            sharedPoolDataSource.setMaxActive(maxDbConnections);
            sharedPoolDataSource.setTestOnBorrow(true);
            sharedPoolDataSource.setValidationQuery("SELECT 1");
            // sharedPoolDataSource.setMaxWait(50);
            this.dataSource = sharedPoolDataSource;
        }
        // If environment is not configured for connection pooling, do not pool
        // connections
        // This does not actually create connection pooling. It is used by the app
        // server.
        else {
            this.dataSource = mysqlDataSource;
        }
    }
}

From source file:net.sourceforge.myvd.inserts.jdbc.JdbcInsert.java

public void configure(String name, Properties props, NameSpace nameSpace) throws LDAPException {

    this.name = name;

    driver = props.getProperty("driver");
    logger.info("Driver : " + driver);
    url = props.getProperty("url");
    logger.info("URL : " + url);
    user = props.getProperty("user");
    logger.info("User : " + user);
    pwd = props.getProperty("password");
    logger.info("Password : **********");

    this.valQuery = props.getProperty("validationQuery");
    logger.info("Validation Query : '" + this.valQuery + "'");

    this.maxCons = Integer.parseInt(props.getProperty("maxCons", "5"));
    logger.info("Max Cons : " + this.maxCons);
    this.maxIdleCons = Integer.parseInt(props.getProperty("maxIdleCons", "5"));
    logger.info("maxIdleCons : " + this.maxIdleCons);

    DriverAdapterCPDS pool = new DriverAdapterCPDS();

    try {/*from w  w  w . j a v  a2  s .c  om*/
        pool.setDriver(driver);
    } catch (ClassNotFoundException e) {
        throw new LDAPException("Could not load JDBC Driver", LDAPException.OPERATIONS_ERROR, driver, e);
    }
    pool.setUrl(url);
    pool.setUser(user);
    pool.setPassword(pwd);
    pool.setMaxActive(maxCons);
    pool.setMaxIdle(maxIdleCons);

    SharedPoolDataSource tds = new SharedPoolDataSource();
    tds.setConnectionPoolDataSource(pool);
    tds.setMaxActive(maxCons);
    tds.setMaxWait(50);
    tds.setTestOnBorrow(true);

    if (this.valQuery != null) {
        tds.setValidationQuery(this.valQuery);
    }
    this.ds = tds;

    base = nameSpace.getBase().toString();

    rdn = props.getProperty("rdn");
    logger.info("RDN : " + rdn);

    String mapping = props.getProperty("mapping");
    logger.info("Mapping : " + mapping);
    StringTokenizer toker = new StringTokenizer(mapping, ",");

    this.ldap2db = new HashMap<String, String>();
    this.db2ldap = new HashMap<String, String>();

    while (toker.hasMoreTokens()) {
        String token = toker.nextToken();
        String ldap = token.substring(0, token.indexOf('='));
        String db = token.substring(token.indexOf('=') + 1);

        ldap2db.put(ldap.toLowerCase(), db.toLowerCase());
        db2ldap.put(db.toLowerCase(), ldap.toLowerCase());

    }

    this.objectClass = props.getProperty("objectClass");
    logger.info("objectClass : " + objectClass);
    this.rdn = props.getProperty("rdn");
    this.dbRdn = ldap2db.get(rdn);

    this.useSimple = props.getProperty("useSimple", "false").equalsIgnoreCase("true");
    logger.info("Use Simple : " + useSimple);
    this.SQL = props.getProperty("sql");
    logger.info("SQL : " + this.SQL);
    int whereEnd;

    String fields = this.SQL.substring(this.SQL.toLowerCase().indexOf("select") + "select".length() + 1,
            this.SQL.toLowerCase().indexOf("from"));
    logger.info("fields : " + fields);
    int where = this.SQL.toLowerCase().indexOf("where");
    String table = "";
    if (where == -1) {
        table = this.SQL.substring(this.SQL.toLowerCase().indexOf("from") + "from".length() + 1).trim();
    } else {
        table = this.SQL.substring(this.SQL.toLowerCase().indexOf("from") + "from".length() + 1, where).trim();
    }

    logger.info("table - " + table);

    try {
        Class.forName(this.driver).newInstance();
    } catch (Exception e) {

    }

    /*
    try {
       Connection con = DriverManager.getConnection(this.url,this.user,this.pwd);
               
       toker = new StringTokenizer(fields,",",false);
       while (toker.hasMoreTokens()) {
    String field = toker.nextToken();
    ResultSet rs = con.getMetaData().getColumns(null, null, table, field);
    rs.next();
    String type = rs.getString("TYPE_NAME");
    logger.info(field + " - " + type);
       }
               
       PreparedStatement ps = null;
       ps
               
       con.close();
    } catch (SQLException e) {
       logger.error("Error loading db schema",e);
    }
            
    */

    if (this.useSimple) {
        this.searchSQL = this.SQL.substring(this.SQL.toLowerCase().indexOf(" from "));

        int whereBegin = this.searchSQL.toLowerCase().indexOf(" where ");

        whereEnd = this.searchSQL.toLowerCase().indexOf(" order ");
        this.hasPostWhere = true;

        if (whereEnd == -1) {
            whereEnd = this.searchSQL.toLowerCase().indexOf(" group ");
        }

        if (whereEnd == -1) {
            this.hasPostWhere = false;
            whereEnd = this.searchSQL.length();
        }

        if (this.hasPostWhere) {
            this.postWhere = this.searchSQL.substring(whereEnd);
        }

        if (whereBegin != -1) {
            this.hasWhere = true;

            this.whereClause = "(" + this.searchSQL.substring(whereBegin + " where ".length(), whereEnd) + ") ";

            this.searchSQL = this.searchSQL.substring(0, whereBegin);
        } else {
            if (this.hasPostWhere) {
                this.searchSQL = this.searchSQL.substring(0, whereEnd);
            }
            this.hasWhere = false;
        }

    } else {
        this.searchSQL = "SELECT " + ldap2db.get(this.rdn.toLowerCase()) + " "
                + SQL.substring(SQL.indexOf(" FROM "));
    }

    this.baseDN = new DN(base);

    this.addBaseToFilter = Boolean.parseBoolean(props.getProperty("addBaseToFilter", "true"));
    logger.info("Add Base To Filter : " + this.addBaseToFilter);

    this.ns = nameSpace;

}