Ensures database connection is still open.
497595
def ensure_connected(self):
        """"""
        if not self.is_connected():
            if not self._auto_connect:
                raise DBALConnectionError.connection_closed()
            self.connect()
114244
public synchronized void connect_db() {

	//
	// Try to connect to the database
	//

	if (_daemon == true) {
	    boolean connected = false;
	    while (connected == false) {
		try {
		    db = ApiUtil.get_db_obj();
		    if (db == null) {
			Util.out4.println("Can't contact db server, will try later");
			try {
			    wait(_sleep_between_connect * 1000);
			} catch (final InterruptedException ex) {
			}
		    } else {
			connected = true;
		    }
		} catch (final Exception e) {
		    Util.out4.println("Can't contact db server, will try later");
		    try {
			wait(_sleep_between_connect * 1000);
		    } catch (final InterruptedException ex) {
		    }
		}
	    }
	} else {
	    try {
		db = ApiUtil.get_db_obj();
		if (db == null) {
		    System.err.println("Can't build connection to TANGO database server, exiting");
		    System.err.println("DB server host = " + db_host);
		    System.exit(-1);
		}

	    } catch (final Exception ex) {
		System.err.println("Can't build connection to TANGO database server, exiting");
		System.err.println("DB server host = " + db_host);
		System.exit(-1);
	    }
	}
	Util.out4.println("Connected to database");
    }
381362
def lock(self):
    """"""
    if hasattr(self, 'session'):
      raise RuntimeError('Dead lock detected. Please do not try to lock the session when it is already locked!')

    if LooseVersion(sqlalchemy.__version__) < LooseVersion('0.7.8'):
      # for old sqlalchemy versions, in some cases it is required to re-generate the engine for each session
      self._engine = sqlalchemy.create_engine("sqlite:///"+self._database)
      self._session_maker = sqlalchemy.orm.sessionmaker(bind=self._engine)

    # create the database if it does not exist yet
    if not os.path.exists(self._database):
      self._create()

    # now, create a session
    self.session = self._session_maker()
    logger.debug("Created new database session to '%s'" % self._database)
    return self.session
1054655
private boolean enableKeepalive(PollController conn,
                                  boolean isNew)
      throws IOException
  {
    
    if (_selectMax <= _connectionCount.get()) {
      throw new IllegalStateException(this + " keepalive overflow "
                                      + _connectionCount + " max=" + _selectMax);

      /*
      conn.requestDestroy();

      return false;
      */
    }

    JniSocketImpl socket = (JniSocketImpl) conn.getSocket();

    if (socket == null) {
      throw new IllegalStateException(this + " socket empty for " + conn);
    }

    int nativeFd = socket.getNativeFd();

    if (nativeFd < 0) {
      throw new IllegalStateException(this + " attempted keepalive with closed file descriptor fd=" + nativeFd
                                      + "\n " + socket
                                      + "\n " + conn);
    }
    else if (_connections.length() <= nativeFd) {
      throw new IllegalStateException(this + " select overflow for file descriptor fd=" + nativeFd + " " + conn);
    }

    if (! _lifecycle.isActive()) {
      throw new IllegalStateException("inactive keepalive");
    }

    if (isNew) {
      setMaxConnection(nativeFd);

      _connections.set(nativeFd, conn);

      _connectionCount.incrementAndGet();
    }

    int result = addNative(_fd, nativeFd, isNew);

    // result < 0 would likely be a disconnect

    return result == 0;
  }
1185686
def verify_state(self):
        """"""
        if self.state == CONNECTING:
            self.state = OPEN

            self.conn.on_open(self.conn_info)
1239627
public void onOpened() {
        if (LOG.isDebugEnabled())
            LOG.debug("onOpened()");

        ConnectionState event = null;
        synchronized (this) {
            if (this.state == ConnectionState.OPEN) {
                // already opened
                return;
            }

            if (this.state != ConnectionState.CONNECTED) {
                LOG.debug("Unable to open, not in CONNECTED state: {}", this.state);
                return;
            }

            this.state = ConnectionState.OPEN;
            this.inputAvailable = true;
            this.outputAvailable = true;
            event = this.state;
        }
        notifyStateListeners(event);
    }
1023745
final public function openConnection ()
	{
		$this->connection = mysqli_connect(
			getConstant('DB_HOST', TRUE),
			getConstant('DB_USERNAME', TRUE),
			getConstant('DB_PASSWORD', TRUE),
			getConstant('DB_NAME', TRUE)
		);
		$errorMessage 	= "Database connection failed: ".mysqli_connect_error();
		$errorMessage 	.= " (" .mysqli_connect_errno(). ")";
		if (!$this->connection) die($errorMessage);
	}
846351
def with_connection
    connection_id = current_connection_id
    fresh_connection = true unless @reserved_connections[connection_id]
    yield connection
  ensure
    release_connection(connection_id) if fresh_connection
  end
801893
private function checkConnection()
    {
        if ($this->_databaseServer !== self::DB_MYSQL) {
            return;
        }

        $interval = (time() - (int)$this->_lastCheckTime);

        if ($interval >= self::MYSQL_CONNECTION_TIMEOUT) {
            $this->connect();
        }
    }
23994
def Close(self):
    
    if not self._connection:
      raise RuntimeError('Cannot close database not opened.')

    # We need to run commit or not all data is stored in the database.
    self._connection.commit()
    self._connection.close()

    self._connection = None
    self._cursor = None
    self.filename = None
    self.read_only = None
434826
async def on_open(self):
        """"""

        self.__ensure_barrier()
        while self.connected:
            try:
                if self.__lastping > self.__lastpong:
                    raise IOError("Last ping remained unanswered")

                self.send_message("2")
                self.send_ack()
                self.__lastping = time.time()
                await asyncio.sleep(self.ping_interval)
            except Exception as ex:
                LOGGER.exception("Failed to ping")
                try:
                    self.reraise(ex)
                except Exception:
                    LOGGER.exception(
                        "failed to force close connection after ping error"
                    )
                break
1354434
def _on_closed(self):
        """"""
        self._connected.clear()
        if not self._closing:
            if self._on_close_callback:
                self._on_close_callback()
            else:
                raise exceptions.ConnectionError('closed')
1338598
def steady_connection(self):
        """"""
        return connect(
            self._creator, self._maxusage, self._setsession,
            self._failures, self._ping, self._closeable,
            *self._args, **self._kwargs)
357138
def on_connection_open(self, connection):
        
        LOGGER.debug('Connection opened')
        connection.add_on_connection_blocked_callback(
            self.on_connection_blocked)
        connection.add_on_connection_unblocked_callback(
            self.on_connection_unblocked)
        connection.add_backpressure_callback(self.on_back_pressure_detected)
        self.channel = self._open_channel()
153241
def _connectionEstablished(self, transport):
        ''''''
        self.transport = transport
        self.transport.writeOpen()
        self.heartbeater.schedule()
349556
protected synchronized boolean checkConnection()
    {
        if (_connection==null)
        {
            try{
                _connection=_url.openConnection();
            }
            catch(IOException e)
            {
                LogSupport.ignore(log,e);
            }
        }
        return _connection!=null;
    }
489643
function isKeepalive(req) {
  var conn = req.headers.connection;
  if (typeof(conn) === 'undefined' || conn === null)
    conn = '';
  conn = conn.trim().toLowerCase();

  if (/\bclose\b/i.test(conn))
    return false;
  if (/\bkeep-alive\b/i.test(conn))
    return true;

  // No Connection header. Default to keepalive for 1.1, non for 1.0.
  if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) {
    return false;
  } else {
    return true;
  }
}