Get connection listener
@param poolName The name of the pool
@param mcp The managed connection pool
@param cl The connection listener
@param pooled Is the connection pooled
@param interleaving Interleaving flag
@param callstack The call stack
178837
public static synchronized void getConnectionListener(String poolName, Object mcp, Object cl,
                                                         boolean pooled, boolean interleaving,
                                                         Throwable callstack)
   {
      if (!interleaving)
      {
         if (pooled)
         {
            log.tracef("%s", new TraceEvent(poolName, Integer.toHexString(System.identityHashCode(mcp)),
                                            TraceEvent.GET_CONNECTION_LISTENER,
                                            Integer.toHexString(System.identityHashCode(cl)),
                                            !confidential && callstack != null ? toString(callstack) : ""));
         }
         else
         {
            log.tracef("%s", new TraceEvent(poolName,
                                            Integer.toHexString(System.identityHashCode(mcp)),
                                            TraceEvent.GET_CONNECTION_LISTENER_NEW,
                                            Integer.toHexString(System.identityHashCode(cl)),
                                            !confidential && callstack != null ? toString(callstack) : ""));
         }
      }
      else
      {
         if (pooled)
         {
            log.tracef("%s", new TraceEvent(poolName,
                                            Integer.toHexString(System.identityHashCode(mcp)),
                                            TraceEvent.GET_INTERLEAVING_CONNECTION_LISTENER,
                                            Integer.toHexString(System.identityHashCode(cl)),
                                            !confidential && callstack != null ? toString(callstack) : ""));
         }
         else
         {
            log.tracef("%s", new TraceEvent(poolName,
                                            Integer.toHexString(System.identityHashCode(mcp)),
                                            TraceEvent.GET_INTERLEAVING_CONNECTION_LISTENER_NEW,
                                            Integer.toHexString(System.identityHashCode(cl)),
                                            !confidential && callstack != null ? toString(callstack) : ""));
         }
      }
   }
575162
protected void invokeCall(RTMPConnection conn, IServiceCall call) {
        final IScope scope = conn.getScope();
        if (scope != null) {
            if (scope.hasHandler()) {
                final IScopeHandler handler = scope.getHandler();
                log.debug("Scope: {} handler: {}", scope, handler);
                if (!handler.serviceCall(conn, call)) {
                    // XXX: What to do here? Return an error?
                    log.warn("Scope: {} handler failed on service call", scope.getName(), new Exception("Service call failed"));
                    return;
                }
            }
            final IContext context = scope.getContext();
            log.debug("Context: {}", context);
            context.getServiceInvoker().invoke(call, scope);
        } else {
            log.warn("Scope was null for invoke: {} connection state: {}", call.getServiceMethodName(), conn.getStateCode());
        }
    }
695538
final void connectionErrorOccurred(final Exception exception, boolean callJCAListener) {

        final String methodName = "connectionErrorOccurred";
        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, methodName, new Object[] {exception, Boolean.valueOf(callJCAListener)});
        }

        /*
         * Only send the event if the server isn't shutting down anyway
         */

        if (!SibRaEngineComponent.isServerStopping()) {

            final ConnectionEvent event = new ConnectionEvent(this,
                    ConnectionEvent.CONNECTION_ERROR_OCCURRED, exception);

            // Copy list to protect against concurrent modification by listener
            final List copy;
            synchronized (_eventListeners) {
                copy = new ArrayList(_eventListeners);
            }

            // We will probably want to look into some how figuring out that the listener
            // that we have is the JCA one and not some other one that is registered as we
            // want to call those ones regardless of the flag. Today we only expect JCA listeners
            // to be registered
            if (callJCAListener)
            {
              for (final Iterator iterator = copy.iterator(); iterator.hasNext();) {
                final Object object = iterator.next();
                if (object instanceof ConnectionEventListener) {
                    ((ConnectionEventListener) object)
                            .connectionErrorOccurred(event);
                }
              }
            }

        }

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, methodName);
        }

    }
252172
public static ListeningExecutorService getListeningSingleThreadExecutor(String name) {
        ExecutorService ste =
                new ThreadPoolExecutor(1, 1,
                        0L, TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue<Runnable>(),
                        CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null));
        return MoreExecutors.listeningDecorator(ste);
    }
449743
public static synchronized void unregisterCCMConnection(String poolName, Object mcp, Object cl,
                                                           Object connection, String key)
   {
      log.tracef("%s", new TraceEvent(poolName,
                                      Integer.toHexString(System.identityHashCode(mcp)),
                                      TraceEvent.UNREGISTER_CCM_CONNECTION,
                                      Integer.toHexString(System.identityHashCode(cl)),
                                      Integer.toHexString(System.identityHashCode(connection)),
                                      key));
   }
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;
   }
136429
def create_jdbc_connection_pool(name, server=None, **kwargs):
    '''
    
    '''
    defaults = {
        'allowNonComponentCallers': False,
        'associateWithThread': False,
        'connectionCreationRetryAttempts': '0',
        'connectionCreationRetryIntervalInSeconds': '10',
        'connectionLeakReclaim': False,
        'connectionLeakTimeoutInSeconds': '0',
        'connectionValidationMethod': 'table',
        'datasourceClassname': '',
        'description': '',
        'driverClassname': '',
        'failAllConnections': False,
        'idleTimeoutInSeconds': '300',
        'initSql': '',
        'isConnectionValidationRequired': False,
        'isIsolationLevelGuaranteed': True,
        'lazyConnectionAssociation': False,
        'lazyConnectionEnlistment': False,
        'matchConnections': False,
        'maxConnectionUsageCount': '0',
        'maxPoolSize': '32',
        'maxWaitTimeInMillis': 60000,
        'name': name,
        'nonTransactionalConnections': False,
        'ping': False,
        'poolResizeQuantity': '2',
        'pooling': True,
        'resType': '',
        'sqlTraceListeners': '',
        'statementCacheSize': '0',
        'statementLeakReclaim': False,
        'statementLeakTimeoutInSeconds': '0',
        'statementTimeoutInSeconds': '-1',
        'steadyPoolSize': '8',
        'target': 'server',
        'transactionIsolationLevel': '',
        'validateAtmostOncePeriodInSeconds': '0',
        'validationClassname': '',
        'validationTableName': '',
        'wrapJdbcObjects': True
    }

    # Data = defaults + merge kwargs + poolname
    data = defaults
    data.update(kwargs)

    # Check resType against acceptable values
    if data['resType'] not in (
            'javax.sql.DataSource',
            'javax.sql.XADataSource',
            'javax.sql.ConnectionPoolDataSource',
            'java.sql.Driver'
       ):
        raise CommandExecutionError('Invalid resource type')

    # Check connectionValidationMethod against acceptable velues
    if data['connectionValidationMethod'] not in (
            'auto-commit',
            'meta-data',
            'table',
            'custom-validation'
       ):
        raise CommandExecutionError('Invalid connection validation method')

    if data['transactionIsolationLevel'] \
       and data['transactionIsolationLevel'] not in (
               'read-uncommitted',
               'read-committed',
               'repeatable-read',
               'serializable'
       ):
        raise CommandExecutionError('Invalid transaction isolation level')

    if not data['datasourceClassname'] \
       and data['resType'] in (
               'javax.sql.DataSource',
               'javax.sql.ConnectionPoolDataSource',
               'javax.sql.XADataSource'
       ):
        raise CommandExecutionError('No datasource class name while using datasource resType')
    if not data['driverClassname'] and data['resType'] == 'java.sql.Driver':
        raise CommandExecutionError('No driver class nime while using driver resType')

    return _create_element(name, 'resources/jdbc-connection-pool', data, server)
625887
private void attachConnectionListener(Conversation conversation, SICoreConnection conn) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "attachConnectionListener",
                        new Object[]
                        {
                         conversation,
                         conn
                        });

        // The connection listener is saved in the link level attachement so that each connection that
        // uses the same physical link uses the same connection listener

        // So get the connection listener from the link level state and register ourselves with it
        ServerLinkLevelState linkState = (ServerLinkLevelState) conversation.getLinkLevelAttachment(); //d173544
        ServerSICoreConnectionListener listener = linkState.getSICoreConnectionListener();

        listener.addSICoreConnection(conn, conversation);
        // Finally attach it to the actual core connection
        // Start f173765.2
        try {
            conn.addConnectionListener(listener);
        } catch (SIException e) {
            FFDCFilter.processException(e,
                                        CLASS_NAME + ".attachConnectionListener",
                                        CommsConstants.SERVERTRANSPORTRECEIVELISTENER_CONNGET_01,
                                        this);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(this, tc, "Unable to register connection listener", e);
        }
        // End f173765.2

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "attachConnectionListener");
    }
1009159
Connection getConnection(ConnectionPool pool)
    {
        ConnectionPool connectionPool = pool;
        boolean success = false;
        while (!success)
        {
            try
            {
                success = true;
                Cassandra.Client client = connectionPool.getConnection();

                if (logger.isDebugEnabled())
                {
                    logger.debug("Returning connection of {} :{} .", pool.getPoolProperties().getHost(), pool
                            .getPoolProperties().getPort());
                }

                return new Connection(client, connectionPool);
            }
            catch (TException te)
            {
                success = false;
                logger.warn("{} :{}  host appears to be down, trying for next ", pool.getPoolProperties().getHost(),
                        pool.getPoolProperties().getPort());
                connectionPool = getNewPool(pool.getPoolProperties().getHost(), pool.getPoolProperties().getPort());
            }
        }

        throw new KunderaException("All hosts are down. please check servers manully.");
    }
296270
public void connectionClosed(Object linkLevelAttachement)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "connectionClosed", linkLevelAttachement);

      try
      {
         // Get hold of MFP and inform it of connection closure
         CompHandshake ch = (CompHandshake) CompHandshakeFactory.getInstance();
         ch.compClose(this);
      }
      catch (Exception e1)
      {
         // No FFDC code needed
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "MFP unable to create CompHandshake Singleton", e1);
      }

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "connectionClosed");
   }
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;
    }
756784
void indexPool() throws BadClassFile {
        poolIdx = new int[nextChar()];
        int i = 1;
        while (i < poolIdx.length) {
            poolIdx[i++] = bp;
            byte tag = buf[bp++];
            switch (tag) {
            case CONSTANT_Utf8: case CONSTANT_Unicode: {
                int len = nextChar();
                bp = bp + len;
                break;
            }
            case CONSTANT_Class:
            case CONSTANT_String:
            case CONSTANT_MethodType:
            case CONSTANT_Module:
            case CONSTANT_Package:
                bp = bp + 2;
                break;
            case CONSTANT_MethodHandle:
                bp = bp + 3;
                break;
            case CONSTANT_Fieldref:
            case CONSTANT_Methodref:
            case CONSTANT_InterfaceMethodref:
            case CONSTANT_NameandType:
            case CONSTANT_Integer:
            case CONSTANT_Float:
            case CONSTANT_InvokeDynamic:
                bp = bp + 4;
                break;
            case CONSTANT_Long:
            case CONSTANT_Double:
                bp = bp + 8;
                i++;
                break;
            default:
                throw new BadClassFile("malformed constant pool");
            }
        }
    }
447137
public void addCallbackToConnectionIndex(
    ConnectionImpl connection,
    String topicExpression,
    boolean isWildcarded,
    ConsumerSetChangeCallback callback)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        SibTr.entry(
          tc,
          "addCallbackToConnectionIndex",
          new Object[] {connection, topicExpression, new Boolean(isWildcarded), callback });

    // Map of callbacks-to-expressions for a connection
    Map connMap = null;
    if(_callbackIndex.containsKey(connection))
    {
      // Already have registered callbacks for this connection
      connMap = (HashMap)_callbackIndex.get(connection);
    }
    else
    {
      // No registered callbacks for this connection
      connMap = new HashMap();
      _callbackIndex.put(connection,connMap);
    }

    // Add the new callback to the index, so we can find it when we deregister
    TopicRecord tRecord = new TopicRecord(topicExpression, isWildcarded);
    connMap.put(callback, tRecord);

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "addCallbackToConnectionIndex");

  }
742605
public static PooledConnectionFactory newPooledConnectionFactory(final AbstractLdapProperties l) {
        final ConnectionPool cp = newBlockingConnectionPool(l);
        return new PooledConnectionFactory(cp);
    }
1081768
public ConnectionPool getPool(String poolName)
            throws ConnectionPoolNotFoundException {
        ConnectionPool connectionPool = null;

        try {
            if (h_ConnectionPools.containsKey(poolName)) {
                connectionPool = h_ConnectionPools.get(poolName);
            } else {
                // Error: pool was never initialized or name could not be found
                throw new ConnectionPoolNotFoundException("Connection pool "
                        + "not found: " + poolName);
            }
        } catch (Throwable th) {
            throw new ConnectionPoolNotFoundException("The specified connection "
                    + "pool \""
                    + poolName
                    + "\" could not be found. The underlying "
                    + "error was a "
                    + th.getClass().getName()
                    + "The message was \""
                    + th.getMessage() + "\".");
        }

        return connectionPool;
    }
341663
function PoolClusterCallback(args) {
  const cluster = new PoolCluster(args);
  cluster.setCallback();

  /**
   * Add a new pool node to cluster.
   *
   * @param id      identifier
   * @param config  pool configuration
   */
  this.add = (id, config) => {
    cluster.add(id, config);
  };

  /**
   * End cluster (and underlying pools).
   *
   * @param callback - not mandatory
   */
  this.end = callback => {
    if (callback && typeof callback !== 'function') {
      throw new Error('callback parameter must be a function');
    }
    const endingFct = callback ? callback : () => {};

    cluster
      .end()
      .then(() => {
        endingFct();
      })
      .catch(endingFct);
  };

  this.of = (pattern, selector) => {
    return cluster.of(pattern, selector);
  };

  /**
   * Remove nodes according to pattern.
   *
   * @param pattern  pattern
   */
  this.remove = pattern => {
    cluster.remove(pattern);
  };

  /**
   * Get connection from available pools matching pattern, according to selector
   *
   * @param pattern       pattern filter (not mandatory)
   * @param selector      node selector ('RR','RANDOM' or 'ORDER')
   * @param callback      callback function
   */
  this.getConnection = (pattern, selector, callback) => {
    let pat = pattern,
      sel = selector,
      cal = callback;
    if (typeof pattern === 'function') {
      pat = null;
      sel = null;
      cal = pattern;
    } else if (typeof selector === 'function') {
      sel = null;
      cal = selector;
    }
    const endingFct = cal ? cal : conn => {};

    cluster.getConnection(pat, sel, endingFct);
  };

  //*****************************************************************
  // internal public testing methods
  //*****************************************************************

  this.__tests = cluster.__tests;
}
324337
def pool_memcached_connections(func):
    
    if isgeneratorfunction(func):
        def wrapper(*nargs, **kwargs):
            with memcached_client():
                for result in func(*nargs, **kwargs):
                    yield result
    else:
        def wrapper(*nargs, **kwargs):
            with memcached_client():
                return func(*nargs, **kwargs)

    return update_wrapper(wrapper, func)