A temporary hack to collect connectionSuccess events. Once we put in ACLs we won't need this hack anymore.
@param thaliReplicationManager
@constructor
772042
function ConnectionTable(thaliReplicationManager) {
  EventEmitter.call(this);
  var self = this;
  this.thaliReplicationManager = thaliReplicationManager;
  this.connectionTable = {};
  this.connectionSuccessListener = function (successObject) {
    self.connectionTable[successObject.peerIdentifier] = {
      muxPort: successObject.muxPort,
      time: Date.now()
    };

    self.emit(successObject.peerIdentifier, self.connectionTable[successObject.peerIdentifier]);
  };
  thaliReplicationManager.on(ThaliReplicationManager.events.CONNECTION_SUCCESS, this.connectionSuccessListener);
}
837091
@Override
    public void onAuthCreated(BoxAuthentication.BoxAuthenticationInfo info) {
        if (sameUser(info) || getUserId() == null) {
            BoxAuthentication.BoxAuthenticationInfo.cloneInfo(mAuthInfo, info);
            if (info.getUser() != null) {
                setUserId(info.getUser().getId());
            }
            if (sessionAuthListener != null) {
                sessionAuthListener.onAuthCreated(info);
            }
        }
    }
521602
protected void postDestroyConnection(ThriftConnectionHandle<T> handle) {
		ThriftConnectionPartition<T> partition = handle.getConnectionPartition();

		partition.updateCreatedConnections(-1);
		partition.setUnableToCreateMoreTransactions(false);
	}
330567
@Override
    public void closeStaleConnections() {

        logger.debug("closeStaleConnections() count before expiring: {}", getConnectionCount());

        connectionProvider.forEach((key, connection) -> {
            if (isStale(key)) {
                connectionProvider.close(key);
            }
        });

        logger.debug("closeStaleConnections() count after expiring: {}", getConnectionCount());
    }
1162834
protected void handleConnectionException(int errorCode, Throwable originalCause)
    throws ActivityException {
        InternalEvent message = InternalEvent.createActivityStartMessage(getActivityId(),
                getProcessInstanceId(), getWorkTransitionInstanceId(), getMasterRequestId(),
                COMPCODE_AUTO_RETRY);
        ScheduledEventQueue eventQueue = ScheduledEventQueue.getSingleton();
        int retry_interval = this.getRetryInterval();
        Date scheduledTime = new Date(DatabaseAccess.getCurrentTime()+retry_interval*1000);
        super.loginfo("The activity failed, set to retry at " + StringHelper.dateToString(scheduledTime));
        eventQueue.scheduleInternalEvent(ScheduledEvent.INTERNAL_EVENT_PREFIX+this.getActivityInstanceId(),
                scheduledTime, message.toString(), "procinst:"+this.getProcessInstanceId().toString());
        this.setReturnCode(COMPCODE_AUTO_RETRY);
        // the above is to prevent engine from making transitions (typically to exception handler)
        throw new ActivityException(errorCode, originalCause.getMessage(), originalCause);
    }
968070
public void syncConnection(Protocol from, Protocol to) throws SQLException {

    if (from != null) {

      proxy.lock.lock();
      try {
        to.resetStateAfterFailover(from.getMaxRows(), from.getTransactionIsolationLevel(),
            from.getDatabase(), from.getAutocommit());
      } finally {
        proxy.lock.unlock();
      }

    }
  }
512835
public Connections mergeWith(Connections discoveredConnections) {

        Map<RedisURI, StatefulRedisConnection<String, String>> result = new TreeMap<>(
                TopologyComparators.RedisURIComparator.INSTANCE);

        this.closed = true;
        discoveredConnections.closed = true;

        synchronized (this.connections) {
            synchronized (discoveredConnections.connections) {

                result.putAll(this.connections);
                result.putAll(discoveredConnections.connections);
            }
        }

        return new Connections(result);
    }
672214
public static void afterCompletion(TransactionImpl tran, int status, int syncLevel) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "afterCompletion", new Object[] { tran, status, syncLevel });

        if (syncLevel >= 0) {
            final ArrayList syncs = _syncLevels.get(syncLevel);

            if (syncs != null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "syncs.length=" + syncs.size());

                final int localID = (int) tran.getLocalTID();
                final byte[] globalID = tran.getTID();
                // d281425 - status maybe committed, unknown or rolledback
                final boolean committed = !(status == Status.STATUS_ROLLEDBACK); // @281425C
                final int numSyncs = syncs.size();

                for (int s = 0; s < numSyncs; s++) {
                    try {
                        ((SynchronizationCallback) syncs.get(s)).afterCompletion(localID, globalID, committed);
                    } catch (Throwable t) {
                        // No FFDC needed
                        Tr.error(tc, "WTRN0074_SYNCHRONIZATION_EXCEPTION", new Object[] { "afterCompletion", syncs.get(s), t });
                        // absorb and allow other afterCompletions to run.
                    }
                }
            } else if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "syncs is null");
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "afterCompletion");
    }
421388
@Override
    public void afterCompletion(int status) {

        if (tc.isEntryEnabled()) {
            Tr.entry(this, tc, "afterCompletion");
        }

        if (tc.isDebugEnabled()) {
            Tr.debug(
                     tc,
                     "Using transaction wrapper@" + Integer.toHexString(this.hashCode()));
        }

        if (mcWrapper.isMCAborted()) {
            Tr.exit(tc, "Connection was aborted. Exiting afterCompletion.");
            return;
        }

        // When afterCompletionCode is called we need to reset the registeredForSync flag.
        registeredForSync = false;
        this.hasRollbackOccured = false;
        /*
         * Mark the transaction complete in the wrapper
         */
        // Do NOT catch runtime exections here.  Let them flow out of the component.
        mcWrapper.transactionComplete();

        if (tc.isDebugEnabled()) {
            if (mcWrapper.getHandleCount() != 0) {
                // Issue warning that Connections have not been closed by the end of the current UOW
                //  scope and will be closed by the CM.
                //            Tr.warning(this, tc,"HANDLE_NOT_CLOSED_J2CA0055");
                Tr.debug(this, tc, "Information:  handle not closed at end of UOW. Connection from pool " + mcWrapper.gConfigProps.getXpathId());
            }
        }

        // Do NOT catch the runtime exception which getConnectionManager might throw.
        // If this is thrown it is an internal bug and needs to be fixed.
        // Allow the rte to flow up to the container.
        boolean shareable = mcWrapper.getConnectionManager().shareable();

        //  - Simplified the following if/else construct taking advantage of the
        //             new releaseToPoolManger call on mcWrapper.
        //
        // If the connection is shareable, or it is non-shareable and the handleCount is
        // zero, then release it back to the poolManger, otherwise simply reset the
        // transaction related variables.
        //
        // Note: shareable connections are released at the end of transactions regardless of
        //  outstanding handles because we don't supports handled being associated to an active
        //  managedConnection outside of a sharing boundary.
        //
        //  if the MCWrapper is stale we will release the connection to the pool.
        //
        if ((shareable) || (!shareable && mcWrapper.getHandleCount() == 0) || mcWrapper.isStale()) {

            if (tc.isDebugEnabled()) {
                Tr.debug(this, tc,
                         "Releasing the connection to the pool. shareable = " + shareable + "  handleCount = " + mcWrapper.getHandleCount() + "  isStale = " + mcWrapper.isStale());
            }

            try {
                mcWrapper.releaseToPoolManager();
            } catch (Exception e) {
                // No need to rethrow this exception since nothing can be done about it,
                //  and the application has successfully finished its use of the connection.
                com.ibm.ws.ffdc.FFDCFilter.processException(
                                                            e,
                                                            "com.ibm.ejs.j2c.LocalTransactionWrapper.afterCompletion",
                                                            "711",
                                                            this);
                if (tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "afterCompletionCode for datasource " + mcWrapper.gConfigProps.cfName + ":  caught Exception", e);
                }
            }

        } // end ((shareable) || (!shareable && mcWrapper.getHandleCount() == 0))
        else {
            /*
             * The cleanup of the coordinator enlisted flag should only be done for non sharable connections, in
             * other cases, the coord is set to null in mcWrapper.releaseToPoolManager(). We only need to worry about this
             * if the handleCount is greater than 0 (in which case the cleanup will be done by the poolManager). Same
             * thing for the tranFailed flag in the MCWrapper.
             */
            mcWrapper.setUOWCoordinator(null);
            // Reset the serialReuseCount since it is only valid for the duration of
            // the LTC. Note that the release path above will also reset it via mcWrapper.cleanup().
            enlisted = false;
        }

        if (tc.isEntryEnabled()) {
            Tr.exit(this, tc, "afterCompletion");
        }
    }
409000
function (callback) {
        var conn = this.connection(),
            id = this._id; // use the raw ID object

        // prevent new transactions from using this connection.
        this.disconnect();

        // if commit was called with no active conn, it implies, no transact action
        // was called. as such it is an error.
        if (!conn) {
            // allow one pseudo commit even without connection, so that programmatic call of repeated commits or
            // rollbacks can be trapped.
            // note that the absence of `_id` indicates that a `.disconnect` was called.
            return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_ROLL));
        }

        conn.rollback(function (error) {
            // try releasing the connection.
            // if that fails then treat it as a major error.
            try {
                conn.release();
            }
            // if there was an error during release, set that as the main error.
            catch (err) {
                !error && (error = err);
            }

            // disassociate the connection from transaction and execute callback
            Transaction.disassociateConnection(conn);
            callback && callback(error);
        });
    }
610645
@Override
    protected void loadMorselQueueFromSource(Queue<DuplicationMorsel> morselQueue) {
        //generate set of morsels based on duplication policy
        for (String account : this.policyManager.getDuplicationAccounts()) {
            DuplicationPolicy policy = this.policyManager.getDuplicationPolicy(account);
            try {
                final CredentialsRepo credRepo = getCredentialsRepo();
                if (getCredentialsRepo().isAccountActive(account)) {
                    AccountCredentials accountCreds = credRepo.getAccountCredentials(account);
                    for (StorageProviderCredentials cred : accountCreds.getProviderCredentials()) {
                        if (cred.isPrimary()) {
                            StorageProvider provider = getStorageProvider(cred);
                            Iterator<String> spaces = provider.getSpaces();
                            while (spaces.hasNext()) {
                                String spaceId = spaces.next();
                                Set<DuplicationStorePolicy> storePolicies = policy.getDuplicationStorePolicies(spaceId);
                                for (DuplicationStorePolicy storePolicy : storePolicies) {
                                    morselQueue.add(new DuplicationMorsel(account, spaceId, null, storePolicy));
                                }
                            }
                        }
                    }
                }
            } catch (AccountCredentialsNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }
453292
public void updateReplicasForJoin(TransactionState snapshotTransactionState) {
        long[] replicasAdded = new long[0];
        if (m_term != null) {
            replicasAdded = ((SpTerm) m_term).updateReplicas(snapshotTransactionState);
        }
        m_scheduler.forwardPendingTaskToRejoinNode(replicasAdded, snapshotTransactionState.m_spHandle);
    }
620967
function ConnectionManager(namespace) {
  this.namespace = namespace;
  this.clients = new ArrayKeys({
    identifier: 'id'
  });

  var reconnecting = false;
  var self = this;

  if (! reportingActive) {
    reportingActive = true;

    setInterval(function __report() {
      self.clients.forEachRecord(function (client) {
        var count = client.references.getCount();

        if ((count > 0) && ((typeof client.isConnected !== 'function') || (! client.isConnected())) && (! reconnecting)) {
          debug('client ' + client.id + ' is disconnected, but reference count: ' + count + ', reconnecting...');

          var scopes   = client.references.getIdentifiers();
          var scope    = client.references.getRecord(scopes[0]);
          reconnecting = true;

          client.connect.call(buildScope(scope, client), function (err, c) {
            if (err) {
              debug('failed reconnecting: ', err);
              throw new Error(err);
            }
            debug('client successfully reconnected.');
            client.connection = c;
            client = registerListeners(scope, client);
            reconnecting = false;
          });

          for (var i = 1, len = scopes.length; i < len; i++) {
            client = registerListeners(client.references.getRecord(scopes[i]), client);
          }
        }
      });
    }, 60000);
  }
}
977779
protected void processAuthedConnections (long iterStamp)
    {
        AuthingConnection conn;
        while ((conn = _authq.getNonBlocking()) != null) {
            try {
                // construct a new running connection to handle this connections network traffic
                // from here on out
                PresentsConnection rconn = new PresentsConnection();
                rconn.init(this, conn.getChannel(), iterStamp);
                rconn.selkey = conn.selkey;

                // we need to keep using the same object input and output streams from the
                // beginning of the session because they have context that needs to be preserved
                rconn.inheritStreams(conn);

                // replace the mapping in the handlers table from the old conn with the new one
                _handlers.put(rconn.selkey, rconn);

                // add a mapping for the connection id and set the datagram secret
                _connections.put(rconn.getConnectionId(), rconn);
                rconn.setDatagramSecret(conn.getAuthRequest().getCredentials().getDatagramSecret());

                // transfer any overflow queue for that connection
                OverflowQueue oflowHandler = _oflowqs.remove(conn);
                if (oflowHandler != null) {
                    _oflowqs.put(rconn, oflowHandler);
                }

                // and let the client manager know about our new connection
                _clmgr.connectionEstablished(rconn, conn.getAuthName(), conn.getAuthRequest(),
                                             conn.getAuthResponse());

            } catch (IOException ioe) {
                log.warning("Failure upgrading authing connection to running.", ioe);
            }
        }
    }
348826
public static ClientInterfaceHandleManager makeThreadSafeCIHM(
            boolean isAdmin, Connection connection, ClientInterfaceRepairCallback callback, AdmissionControlGroup acg)
    {
        return new ClientInterfaceHandleManager(isAdmin, connection, callback, acg) {
            @Override
            synchronized long getHandle(boolean isSinglePartition, int partitionId,
                    long clientHandle, int messageSize, long creationTimeNanos, String procName, long initiatorHSId,
                    boolean isShortCircuitRead) {
                return super.getHandle(isSinglePartition, partitionId,
                        clientHandle, messageSize, creationTimeNanos, procName, initiatorHSId, isShortCircuitRead);
            }
            @Override
            synchronized Iv2InFlight findHandle(long ciHandle) {
                return super.findHandle(ciHandle);
            }
            @Override
            synchronized Iv2InFlight removeHandle(long ciHandle) {
                return super.removeHandle(ciHandle);
            }
            @Override
            synchronized long getOutstandingTxns() {
                return super.getOutstandingTxns();
            }
            @Override
            synchronized void freeOutstandingTxns() {
                super.freeOutstandingTxns();
            }

            @Override
            synchronized List<Iv2InFlight> removeHandlesForPartitionAndInitiator(Integer partitionId,
                    Long initiatorHSId) {
                return super.removeHandlesForPartitionAndInitiator(partitionId, initiatorHSId);
            }

            @Override
            synchronized boolean shouldCheckThreadIdAssertion()
            {
                return false;
            }
        };
    }
138206
@Override
	public void connectionFreed(IManagedConnectionEvent<C> event) {
		// physical connection is already set free
		if (!event.getManagedConnection().hasCoreConnection()) {
			return;
		}
		C con = event.getManagedConnection().getCoreConnection();
		if (con == null || !(con instanceof IXADataRecorderAware)) {
			return;
		}

		IXADataRecorderAware messageAwareConnection = (IXADataRecorderAware) con;
		// Transaction is closed and the xaDataRecorder is destroyed ...
		IXADataRecorder xaDataRecorder = messageAwareConnection
				.getXADataRecorder();
		if (xaDataRecorder == null) {
			return;
		}

		// if commit/rollback was performed, nothing happend. If no the logged
		// data is closed but not destroy. So recovery can happen

		if (event.getManagedConnection().hasTransactionalData()) {
			xaRecorderRepository.close(); // close without removing the recover
											// data
		} else {
			xaDataRecorder.destroy();
		}
		messageAwareConnection.setXADataRecorder(null);

	}
727732
private <K, V, T extends RedisChannelHandler<K, V>, S> ConnectionFuture<S> connectStatefulAsync(T connection,
            RedisCodec<K, V> codec,
            DefaultEndpoint endpoint, RedisURI connectionSettings, Mono<SocketAddress> socketAddressSupplier,
            Supplier<CommandHandler> commandHandlerSupplier) {

        ConnectionBuilder connectionBuilder = createConnectionBuilder(connection, endpoint, connectionSettings,
                socketAddressSupplier, commandHandlerSupplier);

        if (clientOptions.isPingBeforeActivateConnection()) {
            if (hasPassword(connectionSettings)) {
                connectionBuilder.enableAuthPingBeforeConnect();
            } else {
                connectionBuilder.enablePingBeforeConnect();
            }
        }

        ConnectionFuture<RedisChannelHandler<K, V>> future = initializeChannelAsync(connectionBuilder);
        ConnectionFuture<?> sync = future;

        if (!clientOptions.isPingBeforeActivateConnection() && hasPassword(connectionSettings)) {

            sync = sync.thenCompose(channelHandler -> {

                CommandArgs<K, V> args = new CommandArgs<>(codec).add(connectionSettings.getPassword());
                AsyncCommand<K, V, String> command = new AsyncCommand<>(new Command<>(CommandType.AUTH, new StatusOutput<>(
                        codec), args));

                if (connection instanceof StatefulRedisClusterConnectionImpl) {
                    ((StatefulRedisClusterConnectionImpl) connection).dispatch(command);
                }

                if (connection instanceof StatefulRedisConnectionImpl) {
                    ((StatefulRedisConnectionImpl) connection).dispatch(command);
                }

                return command;
            });

        }

        if (LettuceStrings.isNotEmpty(connectionSettings.getClientName())) {
            sync = sync.thenApply(channelHandler -> {

                if (connection instanceof StatefulRedisClusterConnectionImpl) {
                    ((StatefulRedisClusterConnectionImpl) connection).setClientName(connectionSettings.getClientName());
                }

                if (connection instanceof StatefulRedisConnectionImpl) {
                    ((StatefulRedisConnectionImpl) connection).setClientName(connectionSettings.getClientName());
                }
                return channelHandler;
            });
        }

        return sync.thenApply(channelHandler -> (S) connection);
    }