private ConnectionPoolDataSource datasource() throws SQLException {
   if (ds == null) {
     if (realDataSourceClassName == null || realDataSourceClassName.length() == 0) {
       throw new SQLException("Property realdatasourceclassname is not set");
     }
     Object o;
     try {
       o = Class.forName(realDataSourceClassName).newInstance();
     } catch (Exception e) {
       throw new SQLException(e.getMessage());
     }
     if (o instanceof ConnectionPoolDataSource) {
       ds = (ConnectionPoolDataSource) o;
       try {
         for (Method m : ds.getClass().getMethods()) {
           String methodName = m.getName();
           if (methodName.equalsIgnoreCase("setUser")) {
             m.invoke(ds, user);
           } else if (methodName.equalsIgnoreCase("setPassword")) {
             m.invoke(ds, password);
           } else if (methodName.equalsIgnoreCase("setUrl")) {
             m.invoke(ds, url);
           }
         }
       } catch (Exception e) {
         throw new SQLException(e.getMessage());
       }
       ds.setLoginTimeout(loginTimeout);
     } else {
       throw new SQLException(
           "Class in realdatasourceclassname is not a ConnectionPoolDataSource");
     }
   }
   return ds;
 }
  /**
   * Creates a new {@link PooledConnectionAndInfo} from the given {@link UserPassKey}.
   *
   * @param upkey {@link UserPassKey} containing user credentials
   * @throws SQLException if the connection could not be created.
   * @see org.apache.tomcat.dbcp.pool2.KeyedPooledObjectFactory#makeObject(java.lang.Object)
   */
  @Override
  public synchronized PooledObject<PooledConnectionAndInfo> makeObject(UserPassKey upkey)
      throws Exception {
    PooledConnectionAndInfo pci = null;

    PooledConnection pc = null;
    String username = upkey.getUsername();
    String password = upkey.getPassword();
    if (username == null) {
      pc = _cpds.getPooledConnection();
    } else {
      pc = _cpds.getPooledConnection(username, password);
    }

    if (pc == null) {
      throw new IllegalStateException(
          "Connection pool data source returned null from getPooledConnection");
    }

    // should we add this object as a listener or the pool.
    // consider the validateObject method in decision
    pc.addConnectionEventListener(this);
    pci = new PooledConnectionAndInfo(pc, username, password);
    pcMap.put(pc, pci);

    return new DefaultPooledObject<>(pci);
  }
  /** 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;
    }
  }
  /**
   * @param key
   * @throws SQLException if the connection could not be created.
   * @see org.apache.commons.pool.KeyedPoolableObjectFactory#makeObject(java.lang.Object)
   */
  public synchronized Object makeObject(Object key) throws Exception {
    Object obj = null;
    UserPassKey upkey = (UserPassKey) key;

    PooledConnection pc = null;
    String username = upkey.getUsername();
    String password = upkey.getPassword();
    if (username == null) {
      pc = _cpds.getPooledConnection();
    } else {
      pc = _cpds.getPooledConnection(username, password);
    }

    if (pc == null) {
      throw new IllegalStateException(
          "Connection pool data source returned null from getPooledConnection");
    }

    // should we add this object as a listener or the pool.
    // consider the validateObject method in decision
    pc.addConnectionEventListener(this);
    obj = new PooledConnectionAndInfo(pc, username, password);
    pcMap.put(pc, obj);
    cleanupListeners();

    return obj;
  }
예제 #5
0
  public static void main(String[] argv) {
    try {

      String dmds_name = null;
      String cpds_name = null;
      String pbds_name = null;

      if (argv.length == 3) {
        dmds_name = argv[0];
        cpds_name = argv[1];
        pbds_name = argv[2];
      } else usage();

      InitialContext ctx = new InitialContext();
      DataSource dmds = (DataSource) ctx.lookup(dmds_name);
      dmds.getConnection().close();
      System.out.println(
          "DriverManagerDataSource " + dmds_name + " sucessfully looked up and checked.");
      ConnectionPoolDataSource cpds = (ConnectionPoolDataSource) ctx.lookup(cpds_name);
      cpds.getPooledConnection().close();
      System.out.println(
          "ConnectionPoolDataSource " + cpds_name + " sucessfully looked up and checked.");
      DataSource pbds = (DataSource) ctx.lookup(pbds_name);
      pbds.getConnection().close();
      System.out.println(
          "PoolBackedDataSource " + pbds_name + " sucessfully looked up and checked.");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /**
  * 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);
   }
 }
예제 #7
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;
   }
 }
  //
  // 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);
  }
  protected ConnectionPoolDataSource testCPDS(String username, String password)
      throws javax.naming.NamingException, SQLException {
    // The source of physical db connections
    ConnectionPoolDataSource cpds = this.dataSource;
    if (cpds == null) {
      Context ctx = null;
      if (jndiEnvironment == null) {
        ctx = new InitialContext();
      } else {
        ctx = new InitialContext(jndiEnvironment);
      }
      Object ds = ctx.lookup(dataSourceName);
      if (ds instanceof ConnectionPoolDataSource) {
        cpds = (ConnectionPoolDataSource) ds;
      } else {
        throw new SQLException(
            "Illegal configuration: "
                + "DataSource "
                + dataSourceName
                + " ("
                + ds.getClass().getName()
                + ")"
                + " doesn't implement javax.sql.ConnectionPoolDataSource");
      }
    }

    // try to get a connection with the supplied username/password
    PooledConnection conn = null;
    try {
      if (username != null) {
        conn = cpds.getPooledConnection(username, password);
      } else {
        conn = cpds.getPooledConnection();
      }
      if (conn == null) {
        throw new SQLException("Cannot connect using the supplied username/password");
      }
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException e) {
          // at least we could connect
        }
      }
    }
    return cpds;
  }
 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;
 }
 /**
  * Constructs a MiniConnectionPoolManager object.
  *
  * @param dataSource the data source for the connections.
  * @param maxConnections the maximum number of connections.
  * @param timeout the maximum time in seconds to wait for a free connection.
  */
 public MiniConnectionPoolManager(
     ConnectionPoolDataSource dataSource, int maxConnections, int timeout) {
   this.dataSource = dataSource;
   this.maxConnections = maxConnections;
   this.timeoutMs = timeout * 1000L;
   try {
     logWriter = dataSource.getLogWriter();
   } catch (SQLException e) {
   }
   if (maxConnections < 1) {
     throw new IllegalArgumentException("Invalid maxConnections value.");
   }
   semaphore = new Semaphore(maxConnections, true);
   recycledConnections = new LinkedList<PooledConnection>();
   poolConnectionEventListener = new PoolConnectionEventListener();
 }
  /**
   * @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;
  }
 private Connection getConnection() throws SQLException {
   Connection conn = dataSource.getPooledConnection().getConnection();
   conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
   return conn;
 }