/** Creates a Pooled connection and adds it to the connection pool. */
  private void installConnection() throws EmanagerDatabaseException {
    logger.debug("enter");

    PooledConnection connection;

    try {
      connection = poolDataSource.getPooledConnection();
      connection.addConnectionEventListener(this);
      connection.getConnection().setAutoCommit(false);
      synchronized (connectionPool) {
        connectionPool.add(connection);
        logger.debug("Database connection added.");
      }
    } catch (SQLException ex) {
      logger.fatal("exception caught while obtaining database " + "connection: ex = " + ex);
      SQLException ex1 = ex.getNextException();
      while (ex1 != null) {
        logger.fatal("chained sql exception ex1 = " + ex1);
        SQLException nextEx = ex1.getNextException();
        ex1 = nextEx;
      }
      String logString;
      EmanagerDatabaseException ede;

      logString =
          EmanagerDatabaseStatusCode.DatabaseConnectionFailure.getStatusCodeDescription()
              + ex.getMessage();

      logger.fatal(logString);
      ede =
          new EmanagerDatabaseException(
              EmanagerDatabaseStatusCode.DatabaseConnectionFailure, logString);
      throw ede;
    }
  }
 /**
  * Test pooled connetion for chinese database name, user and password.
  *
  * @throws SQLException
  */
 public void testCPDSConnect() throws SQLException {
   // Test chinese database name.
   ConnectionPoolDataSource ds = J2EEDataSource.getConnectionPoolDataSource();
   J2EEDataSource.setBeanProperty(ds, "databaseName", "\u4e10");
   J2EEDataSource.setBeanProperty(ds, "createDatabase", "create");
   try {
     PooledConnection poolConn = ds.getPooledConnection();
     Connection conn = poolConn.getConnection();
     conn.close();
   } catch (SQLException se) {
     if (usingEmbedded()) throw se;
     else assertSQLState("22005", se);
   }
   // Chinese user
   try {
     J2EEDataSource.setBeanProperty(ds, "user", "\u4e10");
     PooledConnection poolConn = ds.getPooledConnection();
     Connection conn = poolConn.getConnection();
     conn.close();
   } catch (SQLException se) {
     if (usingEmbedded()) throw se;
     else assertSQLState("22005", se);
   }
   // Chinese password
   try {
     J2EEDataSource.setBeanProperty(ds, "password", "\u4e10");
     PooledConnection poolConn = ds.getPooledConnection();
     Connection conn = poolConn.getConnection();
     conn.close();
   } catch (SQLException se) {
     if (usingEmbedded()) throw se;
     else assertSQLState("22005", se);
   }
 }
Пример #3
0
  /**
   * Tests whether Connection.changeUser() (and thus pooled connections) restore character set
   * information correctly.
   *
   * @throws Exception if the test fails.
   */
  public void testChangeUserAndCharsets() throws Exception {
    if (versionMeetsMinimum(4, 1)) {
      MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource();
      ds.setURL(BaseTestCase.dbUrl);
      ds.setCharacterEncoding("utf-8");
      PooledConnection pooledConnection = ds.getPooledConnection();

      Connection connToMySQL = pooledConnection.getConnection();
      this.rs = connToMySQL.createStatement().executeQuery("SELECT @@character_set_results");
      assertTrue(this.rs.next());

      String toCheck = null;

      if (versionMeetsMinimum(4, 1, 15)) {
        if (versionMeetsMinimum(5, 0)) {
          if (versionMeetsMinimum(5, 0, 13)) {
            toCheck = null;
          } else {
            toCheck = "NULL";
          }
        } else {
          toCheck = null;
        }
      } else {
        toCheck = "NULL";
      }

      assertEquals(toCheck, this.rs.getString(1));

      this.rs =
          connToMySQL
              .createStatement()
              .executeQuery("SHOW SESSION VARIABLES LIKE 'character_set_client'");
      assertTrue(this.rs.next());

      // Cause of utf8mb4
      assertEquals(0, this.rs.getString(2).indexOf("utf8"));

      connToMySQL.close();

      connToMySQL = pooledConnection.getConnection();
      this.rs = connToMySQL.createStatement().executeQuery("SELECT @@character_set_results");
      assertTrue(this.rs.next());
      assertEquals(toCheck, this.rs.getString(1));

      this.rs =
          connToMySQL
              .createStatement()
              .executeQuery("SHOW SESSION VARIABLES LIKE 'character_set_client'");
      assertTrue(this.rs.next());

      // Cause of utf8mb4
      assertEquals(0, this.rs.getString(2).indexOf("utf8"));

      pooledConnection.getConnection().close();
    }
  }
 /**
  * Validates a pooled connection.
  *
  * @param key ignored
  * @param p wrapped {@link PooledConnectionAndInfo} containing the connection to validate
  * @return true if validation succeeds
  */
 @Override
 public boolean validateObject(UserPassKey key, PooledObject<PooledConnectionAndInfo> p) {
   try {
     validateLifetime(p);
   } catch (Exception e) {
     return false;
   }
   boolean valid = false;
   PooledConnection pconn = p.getObject().getPooledConnection();
   if (null == _validationQuery) {
     int timeout = _validationQueryTimeout;
     if (timeout < 0) {
       timeout = 0;
     }
     try {
       valid = pconn.getConnection().isValid(timeout);
     } catch (SQLException e) {
       valid = false;
     }
   } else {
     Connection conn = null;
     Statement stmt = null;
     ResultSet rset = null;
     // logical Connection from the PooledConnection must be closed
     // before another one can be requested and closing it will
     // generate an event. Keep track so we know not to return
     // the PooledConnection
     validatingSet.add(pconn);
     try {
       conn = pconn.getConnection();
       stmt = conn.createStatement();
       rset = stmt.executeQuery(_validationQuery);
       if (rset.next()) {
         valid = true;
       } else {
         valid = false;
       }
       if (_rollbackAfterValidation) {
         conn.rollback();
       }
     } catch (Exception e) {
       valid = false;
     } finally {
       Utils.closeQuietly(rset);
       Utils.closeQuietly(stmt);
       Utils.closeQuietly(conn);
       validatingSet.remove(pconn);
     }
   }
   return valid;
 }
 public boolean validateObject(Object key, Object obj) {
   boolean valid = false;
   if (obj instanceof PooledConnectionAndInfo) {
     PooledConnection pconn = ((PooledConnectionAndInfo) obj).getPooledConnection();
     String query = _validationQuery;
     if (null != query) {
       Connection conn = null;
       Statement stmt = null;
       ResultSet rset = null;
       // logical Connection from the PooledConnection must be closed
       // before another one can be requested and closing it will
       // generate an event. Keep track so we know not to return
       // the PooledConnection
       muteMap.put(pconn, null);
       try {
         conn = pconn.getConnection();
         stmt = conn.createStatement();
         rset = stmt.executeQuery(query);
         if (rset.next()) {
           valid = true;
         } else {
           valid = false;
         }
         if (_rollbackAfterValidation) {
           conn.rollback();
         }
       } catch (Exception e) {
         valid = false;
       } finally {
         if (rset != null) {
           try {
             rset.close();
           } catch (Throwable t) {
             // ignore
           }
         }
         if (stmt != null) {
           try {
             stmt.close();
           } catch (Throwable t) {
             // ignore
           }
         }
         if (conn != null) {
           try {
             conn.close();
           } catch (Throwable t) {
             // ignore
           }
         }
         muteMap.remove(pconn);
       }
     } else {
       valid = true;
     }
   } else {
     valid = false;
   }
   return valid;
 }
 private synchronized Connection getConnection3() throws SQLException {
   if (isDisposed) { // test again within synchronized lock
     throw new IllegalStateException("Connection pool has been disposed.");
   }
   PooledConnection pconn;
   if (!recycledConnections.isEmpty()) {
     pconn = recycledConnections.remove();
   } else {
     pconn = dataSource.getPooledConnection();
     pconn.addConnectionEventListener(poolConnectionEventListener);
   }
   Connection conn;
   try {
     // The JDBC driver may call ConnectionEventListener.connectionErrorOccurred()
     // from within PooledConnection.getConnection(). To detect this within
     // disposeConnection(), we temporarily set connectionInTransition.
     connectionInTransition = pconn;
     conn = pconn.getConnection();
   } finally {
     connectionInTransition = null;
   }
   activeConnections++;
   assertInnerState();
   return conn;
 }
    private void testBug62452WithConnection(PooledConnection con) throws Exception {
        this.pstmt = con.getConnection().prepareStatement("SELECT 1");
        this.rs = this.pstmt.executeQuery();
        con.close();

        // If PooledConnection is already closed by some reason a NullPointerException was thrown on the next line
        // because the closed connection has nulled out the list that it synchronises on when the closed event is fired.
        this.pstmt.close();
    }
Пример #8
0
 private void getPooledConnection() throws Exception {
   Context ctx = new InitialContext();
   ConnectionPoolDataSource ds = (ConnectionPoolDataSource) ctx.lookup(DATA_SOURCE);
   PooledConnection pooledConnection = ds.getPooledConnection();
   connection = pooledConnection.getConnection(); // Obtain connection from pool
   if (connection == null) {
     throw new Exception("Failed to get database connection.");
   } else {
     return;
   }
 }
  /** @roseuid 3F3A89D40175 */
  public void shutdown() {
    logger.debug("Enter");

    Iterator iter;
    PooledConnection pooledConnection;

    SHUTTING_DOWN = true;
    iter = connectionPool.iterator();
    while (iter.hasNext()) {
      pooledConnection = (PooledConnection) iter.next();

      try {
        if (!pooledConnection.getConnection().isClosed()) {
          pooledConnection.getConnection().close();
        }
      } catch (Exception ex) {
        // We don't care what happens here, we're on the way out!
      }
    }

    connectionPool.clear();
  }
  //
  // Find all the objects inside the ConnectionPooledDataSource and vet them.
  //
  private void vetConnectionPooledDataSource(
      HashSet<String> unsupportedList, HashSet<String> notUnderstoodList) throws Exception {
    ConnectionPoolDataSource ds = J2EEDataSource.getConnectionPoolDataSource();
    PooledConnection pc =
        ds.getPooledConnection(
            getTestConfiguration().getUserName(), getTestConfiguration().getUserPassword());
    Connection conn = pc.getConnection();

    vetObject(ds, unsupportedList, notUnderstoodList);
    vetObject(pc, unsupportedList, notUnderstoodList);

    connectionWorkhorse(conn, unsupportedList, notUnderstoodList);
  }
 public Connection getConnection(String username, String password) throws SQLException {
   PooledConnection pc = getPoolManager().getPool(username, password).checkoutPooledConnection();
   return pc.getConnection();
 }
 // implementation of javax.sql.DataSource
 public Connection getConnection() throws SQLException {
   PooledConnection pc = getPoolManager().getPool().checkoutPooledConnection();
   return pc.getConnection();
 }
  /**
   * @return Connection
   * @roseuid 3F3A5FFD0338
   */
  public Connection getConnection() throws EmanagerDatabaseException {
    long connectionId;
    Connection connection;
    PooledConnection pooledConnection;

    connection = null;
    pooledConnection = null;
    connectionId = InvalidConnectionId;

    try {
      synchronized (connectionPool) {
        if (!connectionPool.isEmpty()) {
          try {
            boolean connectionClosed;

            connectionClosed = false;

            pooledConnection = (PooledConnection) connectionPool.remove(0);
            connection = pooledConnection.getConnection();
            connection.clearWarnings();
            connectionId = getConnectionID(connection);
            connectionClosed = connection.isClosed();
            if (connectionId == InvalidConnectionId || connectionClosed == true) {
              logger.debug("Pooled connection closed.");
              connection = null;
            }
          } catch (SQLException sqe) {
            logger.debug("Pooled connection closed.");
            connection = null;
          }
        }
      }

      if (connection == null) {
        logger.debug("Getting a new connection.");
        pooledConnection = poolDataSource.getPooledConnection();
        pooledConnection.addConnectionEventListener(this);
        connection = pooledConnection.getConnection();
        connection.clearWarnings();
        connectionId = getConnectionID(connection);
      }
    } catch (SQLException sqe) {
      String logString;
      EmanagerDatabaseException ede;

      logString =
          EmanagerDatabaseStatusCode.UnableToGetPooledConnection.getStatusCodeDescription()
              + sqe.getMessage();

      logger.error(logString);
      ede =
          new EmanagerDatabaseException(
              EmanagerDatabaseStatusCode.UnableToGetPooledConnection, logString);
      throw ede;
    }

    if (connectionId == InvalidConnectionId) {
      EmanagerDatabaseException ede;
      ede =
          new EmanagerDatabaseException(
              EmanagerDatabaseStatusCode.UnableToGetPooledConnection,
              EmanagerDatabaseStatusCode.UnableToGetPooledConnection.getStatusCodeDescription());
      throw ede;
    }

    logger.debug(
        "\n*****************************"
            + "\nPooled Connection Init"
            + "\nCon ID:"
            + connectionId
            + "\nCon Object:"
            + pooledConnection
            + "\nPool Object:"
            + connection
            + "\n*****************************");

    return connection;
  }
  /** Attempt to establish a database connection. */
  public synchronized Connection getConnection(String username, String password)
      throws SQLException {
    if (isNew) {
      throw new SQLException(
          "Must set the ConnectionPoolDataSource "
              + "through setDataSourceName or setConnectionPoolDataSource"
              + " before calling getConnection.");
    }

    getConnectionCalled = true;
    Map pools = (Map) dsInstanceMap.get(instanceKey);
    PoolKey key = getPoolKey(username);
    Object pool = pools.get(key);
    if (pool == null) {
      try {
        registerPool(username, password);
        pool = pools.get(key);
      } catch (Exception e) {
        e.printStackTrace();
        throw new SQLException(e.getMessage());
      }
    }

    PooledConnectionAndInfo info = null;
    if (pool instanceof ObjectPool) {
      try {
        info = (PooledConnectionAndInfo) ((ObjectPool) pool).borrowObject();
      } catch (NoSuchElementException e) {
        closeDueToException(info);
        throw new SQLException(e.getMessage());
      } catch (RuntimeException e) {
        closeDueToException(info);
        throw e;
      } catch (SQLException e) {
        closeDueToException(info);
        throw e;
      } catch (Exception e) {
        closeDueToException(info);
        throw new SQLException(e.getMessage());
      }
    } else {
      // assume KeyedObjectPool
      try {
        UserPassKey upkey = getUserPassKey(username, password);
        info = (PooledConnectionAndInfo) ((KeyedObjectPool) pool).borrowObject(upkey);
      } catch (NoSuchElementException e) {
        closeDueToException(info);
        throw new SQLException(e.getMessage());
      } catch (RuntimeException e) {
        closeDueToException(info);
        throw e;
      } catch (SQLException e) {
        closeDueToException(info);
        throw e;
      } catch (Exception e) {
        closeDueToException(info);
        throw new SQLException(e.getMessage());
      }
    }
    if (!(null == password ? null == info.getPassword() : password.equals(info.getPassword()))) {
      closeDueToException(info);
      throw new SQLException(
          "Given password did not match password used " + "to create the PooledConnection.");
    }
    PooledConnection pc = info.getPooledConnection();

    boolean defaultAutoCommit = isDefaultAutoCommit();
    if (username != null) {
      Boolean userMax = getPerUserDefaultAutoCommit(username);
      if (userMax != null) {
        defaultAutoCommit = userMax.booleanValue();
      }
    }

    boolean defaultReadOnly = isDefaultReadOnly();
    if (username != null) {
      Boolean userMax = getPerUserDefaultReadOnly(username);
      if (userMax != null) {
        defaultReadOnly = userMax.booleanValue();
      }
    }

    Connection con = pc.getConnection();
    con.setAutoCommit(defaultAutoCommit);
    con.setReadOnly(defaultReadOnly);
    return con;
  }
Пример #15
0
 @Override
 public Connection getConnection() throws SQLException {
   return P6Core.wrapConnection(passthru.getConnection());
 }