function to run when a connection is acquired before returning it to caller.
166469
private void onAcquire(final PooledConnection conn, String httpMethod, String uriStr, 
                           int attemptNum, CurrentPassport passport)
    {
        passport.setOnChannel(conn.getChannel());
        removeIdleStateHandler(conn);

        conn.setInUse();
        if (LOG.isDebugEnabled()) LOG.debug("PooledConnection acquired: " + conn.toString());
    }
1215567
def connection_required(func):
        
        @functools.wraps(func)
        def wrapper(self, *args, **kwargs):
            """Wrapper function to check that the given ``JLink`` has been
            connected to a target.

            Args:
              self (JLink): the ``JLink`` instance
              args: list of arguments to pass to the wrapped function
              kwargs: key-word arguments dict to pass to the wrapped function

            Returns:
              The return value of the wrapped function.

            Raises:
              JLinkException: if the JLink's target is not connected.
            """
            if not self.target_connected():
                raise errors.JLinkException('Target is not connected.')
            return func(self, *args, **kwargs)
        return wrapper
1218324
def on_receive(self, message=None, wire=None, event_origin=None):

        

        self.trigger("before_call", message)

        fn_name = message.data
        pmsg = self.prepare_message

        try:
            for handler in self.handlers:
                handler.incoming(message, self)

            fn = self.get_function(fn_name, message.path)
        except Exception as inst:
            wire.respond(message, ErrorMessage(str(inst)))
            return

        if callable(fn) and getattr(fn, "exposed", False):
            try:
                r = fn(*message.args, **message.kwargs)
                if isinstance(r,Message):
                    wire.respond(message, pmsg(r))
                else:
                    wire.respond(message, pmsg(Message(r)))
            except Exception as inst:
                if self.debug:
                    wire.respond(message, pmsg(ErrorMessage(str(traceback.format_exc()))))
                else:
                    wire.respond(message, pmsg(ErrorMessage(str(inst))))
        else:
            wire.respond(
                message,
                pmsg(
                    ErrorMessage("action '%s' not exposed on API (%s)" % (fn_name, self.__class__.__name__)))
                )

        self.trigger("after_call", message)
1373744
def _on_connection_finished(self, result):
        

        success, retval, context = self._parse_return(result)
        conn_id = context['connection_id']
        callback = context['callback']

        if success is False:
            callback(conn_id, self.id, False, 'Timeout opening connection')

            with self.count_lock:
                self.connecting_count -= 1
            return

        handle = retval['handle']
        context['disconnect_handler'] = self._on_connection_failed
        context['connect_time'] = time.time()
        context['state'] = 'preparing'
        self._connections[handle] = context

        self.probe_services(handle, conn_id, self._probe_services_finished)
706461
def _on_progress(adapter, operation, conn_id, done, total):
    """"""

    conn_string = adapter._get_property(conn_id, 'connection_string')
    if conn_string is None:
        return

    adapter.notify_progress(conn_string, operation, done, total)
194079
def _try_trigger_before_first_request_funcs(self):  # pylint: disable=C0103
        """"""
        if self._after_first_request_handled:
            return
        else:
            with self._before_first_request_lock:
                if self._after_first_request_handled:
                    return
                for func in self._before_first_request_funcs:
                    func()
                self._after_first_request_handled = True
1256436
def release(self, conn):
        """"""
        if conn.in_transaction:
            raise InvalidRequestError(
                "Cannot release a connection with "
                "not finished transaction"
            )
        raw = conn.connection
        res = yield from self._pool.release(raw)
        return res
1130221
def get_connection_by_dest(self, dest):
        ''''''
        with self._mutex:
            for conn in self.connections:
                if conn.has_port(self) and conn.has_port(dest):
                    return conn
            return None
933232
public static void detectDeadConnections() {
        if (CONNECTION_DETECTOR_RUNNING) {
            return;
        }
        final Logger log = LoggerFactory.getLogger(ConnectionManager.class);
        Thread deadConnThread = new Thread(new Runnable() {
            public void run() {
                CONNECTION_DETECTOR_RUNNING = true;
                try {
                    log.debug("Starting dead connection detection thread");
                    while (detectDeadConnection) {
                        log.debug("Checking if there are any dead connections");
                        long now = DateTime.now().getMillis();
                        for (DataSiftConnection data : connections) {
                            if (data.lastSeen() != null) {
                                if (now - data.lastSeen().getMillis() >=
                                        TimeUnit.SECONDS.toMillis(CONNECTION_TIMEOUT_LIMIT)) {
                                    log.info("Dead connection found, triggering re-connection");
                                    data.closeAndReconnect();
                                }
                            }
                        }
                        log.debug(String.format("Checked %s connections", connections.size()));
                        try {
                            Thread.sleep(TimeUnit.SECONDS.toMillis(CONNECTION_TIMEOUT));
                        } catch (InterruptedException e) {
                            LoggerFactory.getLogger(getClass()).info("Interrupted while waiting to check conn");
                        }
                    }
                } finally {
                    CONNECTION_DETECTOR_RUNNING = false;
                }
            }
        }, "dead-connections-monitor");
        deadConnThread.setDaemon(true);
        deadConnThread.start();
    }
1121273
def connection(connection, without_connection_test):
    """"""
    database.set_connection(connection=connection)

    if not without_connection_test:
        test_connection(connection)
658851
def try_run(conn)
      return conn if conn.is_a? Exception
      begin
        arg = @arg
        arg = self.before_request_proc.call(conn) if self.before_request_proc

        start = Time.now
        response = self.run(conn, arg)
        time = Time.now - start
        response = self.before_tests_proc.call(response) if self.before_tests_proc
        return response, time
      rescue => e
        e
      end
    end
1196476
def _get_connection(self, handle, expect_state=None):
        

        conndata = self._connections.get(handle)

        if conndata and expect_state is not None and conndata['state'] != expect_state:
            self._logger.error("Connection in unexpected state, wanted=%s, got=%s", expect_state,
                               conndata['state'])
        return conndata
423715
def on_get(self, req, resp, **kwargs):
        """"""
        return super().on_get(
            req, resp, handler=self._retrieve, **kwargs
        )
1024517
def ensure(self, connection, func, *args, **kwargs):
        
        channel = None
        while 1:
            try:
                if channel is None:
                    channel = connection.channel()
                return func(channel, *args, **kwargs), channel
            except (connection.connection_errors, IOError):
                self._call_errback()

            channel = self.connect(connection)
1226022
function(self) {
  return function(err) {
    if (connectionAccounting) deleteConnection(self.id);
    // Debug information
    if (self.logger.isDebug())
      self.logger.debug(
        f(
          'connection %s for [%s:%s] errored out with [%s]',
          self.id,
          self.host,
          self.port,
          JSON.stringify(err)
        )
      );
    // Emit the error
    if (self.listeners('error').length > 0) self.emit('error', new MongoNetworkError(err), self);
  };
}
430898
function (connection, sessionRead) {
        connection = OT.Connection.fromHash(connection);
        if (sessionRead || session.connection && connection.id !== session.connection.id) {
          session.connections.add( connection );
          delayedSessionEvents.triggerConnectionCreated(connection);
        }

        OT.$.forEach(OT.$.keys(unconnectedStreams), function(streamId) {
          var stream = unconnectedStreams[streamId];
          if (stream && connection.id === stream.connection.id) {
            // dispatch streamCreated event now that the connectionCreated has been dispatched
            parseAndAddStreamToSession(stream, session);
            delete unconnectedStreams[stream.id];
            
            var payload = {
              debug: sessionRead ? 'connection came in session#read' :
                'connection came in connection#created',
              streamId : stream.id,
              connectionId : connection.id
            };
            session.logEvent('streamCreated', 'warning', payload);
          }
        });
        
        return connection;
      }
310867
function ReconnectingConnection(id, connection) {
  this.id = id;
  this.connection = null;
  this.closed = false;
  this.queue = [];

  this.setConnection(connection);
}