Return connection
@param poolName The name of the pool
@param mcp The managed connection pool
@param cl The connection listener
@param connection The connection
774719
public static synchronized void returnConnection(String poolName, Object mcp, Object cl, Object connection)
   {
      log.tracef("%s", new TraceEvent(poolName,
                                      Integer.toHexString(System.identityHashCode(mcp)),
                                      TraceEvent.RETURN_CONNECTION,
                                      Integer.toHexString(System.identityHashCode(cl)),
                                      Integer.toHexString(System.identityHashCode(connection))));
   }
23148
public PooledConnection getPooledConnection(String user, String password) throws SQLException {
    return new PGPooledConnection(getConnection(user, password), defaultAutoCommit);
  }
318015
public static synchronized void closeCCMConnection(String poolName, Object mcp, Object cl,
                                                      Object connection, String key)
   {
      log.tracef("%s", new TraceEvent(poolName,
                                      Integer.toHexString(System.identityHashCode(mcp)),
                                      TraceEvent.CLOSE_CCM_CONNECTION,
                                      Integer.toHexString(System.identityHashCode(cl)),
                                      Integer.toHexString(System.identityHashCode(connection)),
                                      key));
   }
530873
public Connection getConnection(String username, String password)
	throws SQLException {
		try {
			return this.multiDataSource.get(new UsernamePassword(username, password)).getConnection();
		} catch (ExecutionException e) {
			throw PoolUtil.generateSQLException("Unable to obtain connection", e);

		}
	}
1106976
def connection_from_host(self, host, port=80, scheme='http'):
        
        pool_key = (scheme, host, port)

        # If the scheme, host, or port doesn't match existing open connections,
        # open a new ConnectionPool.
        pool = self.pools.get(pool_key)
        if pool:
            return pool

        # Make a fresh ConnectionPool of the desired type
        pool_cls = pool_classes_by_scheme[scheme]
        pool = pool_cls(host, port, **self.connection_pool_kw)

        self.pools[pool_key] = pool

        return pool
753440
private Connection getConnection(final ICommandLine cl) throws SQLException, InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        String database = DEFAULT_TABLE;
        if (cl.hasOption("database")) {
            database = cl.getOptionValue("database");
        }
        String hostname = DEFAULT_HOSTNAME;
        if (cl.hasOption("hostname") && !"".equals(cl.getOptionValue("hostname"))) {
            hostname = cl.getOptionValue("hostname");
        }
        String port = DEFAULT_PORT;
        if (cl.hasOption("port") && !"".equals(cl.getOptionValue("port"))) {
            port = cl.getOptionValue("port");
        }
        String password = "";
        if (cl.hasOption("password")) {
            password = cl.getOptionValue("password");
        }
        String username = "";
        if (cl.hasOption("logname")) {
            username = cl.getOptionValue("logname");
        }
        String timeout = DEFAULT_TIMEOUT;
        if (cl.getOptionValue("timeout") != null) {
            timeout = cl.getOptionValue("timeout");
        }
        Properties props = new Properties();
        props.setProperty("user", username);
        props.setProperty("password", password);
        props.setProperty("timeout", timeout);
        String url = "jdbc:postgresql://" + hostname + ":" + port + "/" + database;
        DriverManager.registerDriver((Driver) Class.forName("org.postgresql.Driver").newInstance());
        return DriverManager.getConnection(url, props);
    }
747327
public static synchronized void clearConnectionListener(String poolName, Object mcp, Object cl)
   {
      log.tracef("%s", new TraceEvent(poolName,
                                      Integer.toHexString(System.identityHashCode(mcp)),
                                      TraceEvent.CLEAR_CONNECTION_LISTENER,
                                      Integer.toHexString(System.identityHashCode(cl))));
   }
1122608
public synchronized Object verifyConnectionListener(ConnectionListener cl) throws ResourceException
   {
      for (Map.Entry<Object, Map<ManagedConnectionPool, ConnectionListener>> entry : transactionMap.entrySet())
      {
         if (entry.getValue().values().contains(cl))
         {
            try
            {
               TransactionalConnectionManager txCM = (TransactionalConnectionManager)cm;
               Transaction tx = txCM.getTransactionIntegration().getTransactionManager().getTransaction();
               Object id = txCM.getTransactionIntegration().getTransactionSynchronizationRegistry().getTransactionKey();

               if (!id.equals(entry.getKey()))
                  return entry.getKey();
            }
            catch (Exception e)
            {
               throw new ResourceException(e);
            }
         }
      }

      return null;
   }
583696
public static synchronized void ccmUserTransaction(String poolName, Object mcp, Object cl,
                                                      Object connection, String key)
   {
      log.tracef("%s", new TraceEvent(poolName,
                                      Integer.toHexString(System.identityHashCode(mcp)),
                                      TraceEvent.CCM_USER_TRANSACTION,
                                      Integer.toHexString(System.identityHashCode(cl)),
                                      Integer.toHexString(System.identityHashCode(connection)),
                                      key));
   }
120839
@Override
    protected Object createPoolOrConnection()
    {
        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()
                .getPersistenceUnitMetadata(getPersistenceUnit());

        Properties props = persistenceUnitMetadata.getProperties();
        String keyspace = null;

        if (externalProperties != null)
        {
            keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);
        }

        if (keyspace == null)
        {
            keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);
        }

        for (Host host : ((CassandraHostConfiguration) configuration).getCassandraHosts())
        {
            PoolConfiguration prop = new PoolProperties();
            prop.setHost(host.getHost());
            prop.setPort(host.getPort());
            prop.setKeySpace(keyspace);

            CassandraUtilities.setPoolConfigPolicy((CassandraHost) host, prop);
            try
            {
                ConnectionPool pool = new ConnectionPool(prop);
                hostPools.put(host, pool);
            }
            catch (TException e)
            {
                logger.warn("Node {} are down, Caused by {} .", host.getHost(), e.getMessage());
                if (host.isRetryHost())
                {
                    logger.warn("Scheduling node for future retry");
                    ((CassandraRetryService) hostRetryService).add((CassandraHost) host);
                }
            }
        }
        return null;
    }
310960
private synchronized PoolableConnection newConnection() {
        synchronized (xpool) {
            if (xpool.size() >= maxActive) {
                return null;
            }

            try {
                PoolableConnection conn = null;

                if (xpool.size() < minIdle) {
                    conn = new PoolableConnection(this, ds.getConnection(), liveTime, Integer.MAX_VALUE, maxOpenPreparedStatementsPerConnection);
                } else if (xpool.size() < maxIdle) {
                    conn = new PoolableConnection(this, ds.getConnection(), liveTime, maxIdleTime, maxOpenPreparedStatementsPerConnection);
                } else {
                    conn = new PoolableConnection(this, ds.getConnection(), liveTime, 60 * 1000L, maxOpenPreparedStatementsPerConnection);
                }

                xpool.put(conn, conn);

                if (logger.isWarnEnabled()) {
                    logger.warn("The " + xpool.size() + "th of " + maxActive + " connections is created for data source: " + url);
                }

                return conn;
            } catch (SQLException e) {
                String msg = "Faied to create new connection for data source '" + url + "'." + " [Active connection number]: " + (xpool.size() + 1) + ". "
                        + AbacusException.getErrorMsg(e);
                logger.error(msg, e);
                throw new UncheckedSQLException(msg, e);
            }
        }
    }
570126
private MCWrapper getMCWrapperFromMatch(
                                            Subject subject,
                                            ConnectionRequestInfo cri,
                                            ManagedConnectionFactory managedFactory,
                                            MCWrapper mcWrapperTemp) throws ResourceAllocationException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "getMCWrapperFromMatch", mcWrapperTemp);
        }
        MCWrapper mcWrapper = null;
        ManagedConnection mc = null;
        /*
         * Create a new set for every matchManagedConnection. This currently is faster than having a object pool
         * of HashSet objects that would be require synchronization. In the future, we may need to use an object pool or
         * have a matchManagedConnection that support passing a managedConnection instead of a Set.
         */
        Set<ManagedConnection> freePoolMCSet = new HashSet<ManagedConnection>(1);
        try {
            freePoolMCSet.add(mcWrapperTemp.getManagedConnection());
        } catch (java.lang.IllegalStateException e) {
            /*
             * This was an addition to do to application threading issue,
             * where we had a problem with bad mcWrappers staying in the free pool.
             * Instead of leaving this bad mcWrapper in the free pool, we are going
             * to remove it and throw the same exception, This will reduce the chance
             * of bad mcWrappers staying in the pool resulting in an unrecoverable pool.
             */
            synchronized (freeConnectionLockObject) {
                mcWrapperList.remove(mcWrapperTemp);
            }
            throw e;
        }

        try {
            int poolState = mcWrapperTemp.getPoolState();
            mcWrapperTemp.setPoolState(50);
            mc = managedFactory.matchManagedConnections(freePoolMCSet, subject, cri);

            mcWrapperTemp.setPoolState(poolState);
        } catch (ResourceException exn1) {
            com.ibm.ws.ffdc.FFDCFilter.processException(exn1, "com.ibm.ejs.j2c.poolmanager.FreePool.getMCWrapperFromMatch", "786", this);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "datasource " + gConfigProps.cfName + ": ResourceException " + exn1);
                Tr.debug(this, tc, "Throwing ResourceAllocationException...");
                Tr.debug(this, tc, "match(), Pool contents ==> " + this);
            }
            ResourceAllocationException throwMe = new ResourceAllocationException(exn1.getMessage(), exn1.getErrorCode());
            throwMe.initCause(exn1.getCause());
            pm.activeRequest.decrementAndGet();
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                Tr.exit(this, tc, "getMCWrapperFromMatch", throwMe);
            throw (throwMe);
        }

        if (mc != null) {
            mcWrapper = mcWrapperTemp;
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "getMCWrapperFromMatch", mcWrapper);
        }

        return mcWrapper;
    }
651596
function Connection(conn) {
	if(!(this instanceof Connection)) {
		return new Connection(conn);
	}
	var self = this;
	if(!conn) { throw new TypeError("no connection set"); }
	self._connection = conn;
	self._connect    = Q.nfbind(self._connection.connect.bind(self._connection));
	self._query      = Q.nfbind(self._connection.query.bind(self._connection));

	// These do not have callbacks when PoolConnection is used
	//self._end        = Q.nfbind(self._connection.end.bind(self._connection));
	//self._release        = Q.nfbind(self._connection.release.bind(self._connection));

	self._changeUser = Q.nfbind(self._connection.changeUser.bind(self._connection));
	db.Connection.call(self, conn);
}
600756
function get_pool (port, host, local_addr, is_unix_socket, max) {
    port = port || 25;
    host = host || 'localhost';
    const name = `outbound::${port}:${host}:${local_addr}:${cfg.pool_timeout}`;
    if (!server.notes.pool) server.notes.pool = {};
    if (server.notes.pool[name]) return server.notes.pool[name];

    const pool = generic_pool.Pool({
        name,
        create: function (done) {
            _create_socket(this.name, port, host, local_addr, is_unix_socket, done);
        },
        validate: socket => socket.__fromPool && socket.writable,
        destroy: socket => {
            logger.logdebug(`[outbound] destroying pool entry ${socket.__uuid} for ${host}:${port}`);
            socket.removeAllListeners();
            socket.__fromPool = false;
            socket.on('line', line => {
                // Just assume this is a valid response
                logger.logprotocol(`[outbound] S: ${line}`);
            });
            socket.once('error', err => {
                logger.logwarn(`[outbound] Socket got an error while shutting down: ${err}`);
            });
            socket.once('end', () => {
                logger.loginfo("[outbound] Remote end half closed during destroy()");
                socket.destroy();
            })
            if (socket.writable) {
                logger.logprotocol(`[outbound] [${socket.__uuid}] C: QUIT`);
                socket.write("QUIT\r\n");
            }
            socket.end(); // half close
        },
        max: max || 10,
        idleTimeoutMillis: cfg.pool_timeout * 1000,
        log: (str, level) => {
            if (/this._availableObjects.length=/.test(str)) return;
            level = (level === 'verbose') ? 'debug' : level;
            logger[`log${level}`](`[outbound] [${name}] ${str}`);
        }
    });
    server.notes.pool[name] = pool;

    return pool;
}
483282
protected ConnectionListener findConnectionListener(ManagedConnection mc, Object c,
                                                       Collection<ConnectionListener> listeners)
   {
      for (ConnectionListener cl : listeners)
      {
         if (cl.getManagedConnection().equals(mc) && (c == null || cl.getConnections().contains(c)))
            return cl;
      }

      return null;
   }
969894
public ObjectPool createConnectionPool(JdbcConnectionDescriptor jcd)
    {
        if (log.isDebugEnabled()) log.debug("createPool was called");
        PoolableObjectFactory pof = new ConPoolFactory(this, jcd);
        GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig();
        return (ObjectPool)new GenericObjectPool(pof, conf);
    }
39691
private Connection getPooledConnection() throws SQLException {
    PooledConnection pc = null;
    synchronized (lock) {
      if (available == null) {
        throw new PSQLException(GT.tr("DataSource has been closed."),
            PSQLState.CONNECTION_DOES_NOT_EXIST);
      }
      while (true) {
        if (!available.isEmpty()) {
          pc = available.pop();
          used.push(pc);
          break;
        }
        if (maxConnections == 0 || used.size() < maxConnections) {
          pc = source.getPooledConnection();
          used.push(pc);
          break;
        } else {
          try {
            // Wake up every second at a minimum
            lock.wait(1000L);
          } catch (InterruptedException e) {
          }
        }
      }
    }
    pc.addConnectionEventListener(connectionEventListener);
    return pc.getConnection();
  }