Get the connection. If not connected, the {@code ConnectTask} will be used to establish a connection.

@return the connection
@throws IOException
760582
public Connection connect() throws IOException {
        Connection connection;
        synchronized (this) {
            if(shutdown) throw ProtocolLogger.ROOT_LOGGER.channelClosed();
            connection = this.connection;
            if(connection == null) {
                connection = connectTask.connect();
                if(connection == null) {
                    throw ProtocolLogger.ROOT_LOGGER.channelClosed();
                }
                boolean ok = false;
                try {
                    // Connection opened notification
                    final ConnectionOpenHandler openHandler = connectTask.getConnectionOpenedHandler();
                    openHandler.connectionOpened(connection);
                    ok = true;
                    this.connection = connection;
                    connection.addCloseHandler(new CloseHandler<Connection>() {
                        @Override
                        public void handleClose(Connection closed, IOException exception) {
                            onConnectionClose(closed);
                        }
                    });
                } finally {
                    if(!ok) {
                        StreamUtils.safeClose(connection);
                    }
                }
            }
        }
        return connection;
    }
443254
public PooledConnection getConnection(long wait) throws SQLException {
		try {
			return getConnectionDirect();
		} catch (Exception e) {
			ThreadUtil.sleep(wait);
		}
		return getConnectionDirect();
	}
730201
protected HttpURLConnection generateConn() throws IOException {
        HttpURLConnection conn;
        conn = (HttpURLConnection) new URL(url).openConnection();
        return conn;
    }
249815
synchronized boolean doReConnect() throws IOException {

        // In case we are still connected, test the connection and see if we can reuse it
        if(connectionManager.isConnected()) {
            try {
                final Future<Long> result = channelHandler.executeRequest(ManagementPingRequest.INSTANCE, null).getResult();
                result.get(15, TimeUnit.SECONDS); // Hmm, perhaps 15 is already too much
                return true;
            } catch (Exception e) {
                ServerLogger.AS_ROOT_LOGGER.debugf(e, "failed to ping the host-controller, going to reconnect");
            }
            // Disconnect - the HC might have closed the connection without us noticing and is asking for a reconnect
            final Connection connection = connectionManager.getConnection();
            StreamUtils.safeClose(connection);
            if(connection != null) {
                try {
                    // Wait for the connection to be closed
                    connection.awaitClosed();
                } catch (InterruptedException e) {
                    throw new InterruptedIOException();
                }
            }
        }

        boolean ok = false;
        final Connection connection = connectionManager.connect();
        try {
            // Reconnect to the host-controller
            final ActiveOperation<Boolean, Void> result = channelHandler.executeRequest(new ServerReconnectRequest(), null);
            try {
                boolean inSync = result.getResult().get();
                ok = true;
                reconnectRunner = null;
                return inSync;
            } catch (ExecutionException e) {
                throw new IOException(e);
            } catch (InterruptedException e) {
                throw new InterruptedIOException();
            }
        } finally {
            if(!ok) {
                StreamUtils.safeClose(connection);
            }
        }
    }
284912
@Override
    protected SshConnection getConnection() throws IOException {
        if (!isPersistedConnectionValid()) {
            activeConnection = super.getConnection();
            logger.trace("SSH connection is not valid anymore, a new one was created.");
        }
        return activeConnection;
    }
791668
public SICoreConnection getSICoreConnection() throws IllegalStateException {

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, "getSICoreConnection");
        }

        if (_sessionClosed) {
            throw new IllegalStateException(NLS.getFormattedMessage(
                    ("ILLEGAL_STATE_CWSJR1123"),
                    new Object[] { "getSICoreConnection"}, null));
        }
        if (_sessionInvalidated) {
            throw new IllegalStateException(NLS.getFormattedMessage(
                    ("ILLEGAL_STATE_CWSJR1124"),
                    new Object[] { "getSICoreConnection"}, null));
        }

        SICoreConnection coreConnection = null;
        if (_connection != null) {
            coreConnection = _connection.getSICoreConnection();
        }

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, "getSICoreConnection", coreConnection);
        }
        return coreConnection;

    }
511831
protected SshConnection getConnection() throws IOException {
        return SshConnectionFactory.getConnection(gerritHostName, gerritSshPort, gerritProxy,
                authentication, connectionTimeout);
    }
305551
public boolean connect() {
        if (client.isConnected()) {
            logger.warn("Already connected");
            return true;
        }
        try {
            logger.info("Connecting to remote host " + remoteHost);
            client.connect(remoteHost);
            client.rlogin(localUser, remoteUser, terminalType);
            writer = new OutputStreamWriter(client.getOutputStream());
            outputReaderThread = new Thread(new OutputReader());
            outputReaderThread.start();
            if (interactive) {
                standardInputReaderThread = new Thread(new StandardInputReader());
                standardInputReaderThread.start();
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException ex) {
            }
            if (client.isConnected()) {
                return true;
            } else {
                logger.fatal("Client has been immediately disconnected from remote host:" + remoteHost);
                return false;
            }
            //outputReaderThread.
        } catch (IOException e) {
            logger.fatal("Could not connect to remote host:" + remoteHost, e);
            return false;
        }
    }
431599
def _connect(self):
        
        future = concurrent.Future()

        # Attempt to get a cached connection from the connection pool
        try:
            connection = self._pool_manager.get(self.pid, self)
            self._connections[connection.fileno()] = connection
            future.set_result(connection)

            # Add the connection to the IOLoop
            self._ioloop.add_handler(connection.fileno(),
                                     self._on_io_events,
                                     ioloop.IOLoop.WRITE)
        except pool.NoIdleConnectionsError:
            self._create_connection(future)

        return future
403743
protected Connection<MailResourcesHolder> getMailConnection()
    {
        Connection<MailResourcesHolder> mailConnection=null;
        if(this.usePersistentConnection)
        {
            synchronized(this)
            {
                if(this.connection==null)
                {
                    //create new connection
                    this.connection=this.createMailConnection();
                }
            }
            
            //get connection
            mailConnection=this.connection;
        }
        else
        {
            //create new connection
            mailConnection=this.createMailConnection();
        }
        
        return mailConnection;
    }
312172
public BoxSimpleMessage connect() {
        mRetries = 0;

        try {
            BoxIteratorRealTimeServers servers =  (BoxIteratorRealTimeServers)mRequest.send();
            mBoxRealTimeServer = servers.get(0);
        } catch (BoxException e){
           mChangeListener.onException(e, this);
           return null;
        }
        BoxRequestsEvent.LongPollMessageRequest messageRequest = new BoxRequestsEvent.LongPollMessageRequest(mBoxRealTimeServer.getUrl(),mSession);
        messageRequest.setTimeOut(mBoxRealTimeServer.getFieldRetryTimeout().intValue() * 1000 );
        boolean shouldRetry = true;
        do {
            BoxFutureTask<BoxSimpleMessage> task = null;
            try {
                task = messageRequest.toTask().addOnCompletedListener(this);
                mExecutor.submit(task);
                BoxResponse<BoxSimpleMessage> response = task.get(mBoxRealTimeServer.getFieldRetryTimeout().intValue(), TimeUnit.SECONDS);
                if (response.isSuccess() && !response.getResult().getMessage().equals(BoxSimpleMessage.MESSAGE_RECONNECT)){
                    return response.getResult();
                }
            } catch (TimeoutException e) {
                if (task != null) {
                    try {
                        // if the timeout is coming from the task then cancel the task (as httpurlconnection timeout is unreliable).
                        task.cancel(true);
                    } catch (CancellationException e1){
                    }
                }
            } catch (InterruptedException e){
                mChangeListener.onException(e,this);
            } catch (ExecutionException e){
                mChangeListener.onException(e,this);
            }
            mRetries++;
            if (mBoxRealTimeServer.getMaxRetries() < mRetries) {
                shouldRetry = false;
            }

        } while(shouldRetry);
        mChangeListener.onException(new BoxException.MaxAttemptsExceeded("Max retries exceeded, ", mRetries), this);
        return null;
    }
267016
private URLConnection openConnection() throws IOException {
		return (null == this.proxy) ? url.openConnection() : url.openConnection(this.proxy);
	}
1030901
public Connection getConnection() throws SQLException {
    try {
      if (urlParser == null) {
        initialize();
      }

      return MariaDbConnection.newConnection(urlParser, null);
    } catch (SQLException e) {
      throw ExceptionMapper.getException(e, null, null, false);
    }
  }
1262043
protected Connection getConnection() throws SQLException {
		logger.finest("Entering: " + CLASSNAME + ".getConnection");
		Connection connection = null;

		if(!batchConfig.isJ2seMode()) {
			logger.finest("J2EE mode, getting connection from data source");
			connection = dataSource.getConnection();
			logger.finest("autocommit="+connection.getAutoCommit());
		} else {
			try {
				Class.forName(driver);
			} catch (ClassNotFoundException e) {
				throw new PersistenceException(e);
			}
			logger.finest("JSE mode, getting connection from " + url);
			connection = DriverManager.getConnection(url, userId, pwd);
			logger.finest("autocommit="+connection.getAutoCommit());
		}
		setSchemaOnConnection(connection);

		logger.finest("Exiting: " + CLASSNAME + ".getConnection() with conn =" + connection);
		return connection;
	}
747068
protected Connection<CommPortAdapter> getCommPortConnection()
    {
        Connection<CommPortAdapter> connection=null;
        synchronized(this)
        {
            boolean connectionValid=true;
            //if no connection available
            if(this.commConnection==null)
            {
                connectionValid=false;
            }
            else
            {
                //get adapter
                CommPortAdapter adapter=this.commConnection.getResource();

                //if current adapter is not valid/open
                if(!adapter.isOpen())
                {
                    connectionValid=false;
                }
            }
            
            if(!connectionValid)
            {
                //release old connection
                this.releaseCommPortConnection();

                //create new connection
                this.commConnection=this.createCommPortConnection();
            }
        }
            
        //get connection
        connection=this.commConnection;
        
        return connection;
    }
179318
@Override
  public Connection getConnection() throws SQLException {
    return getConnection(
      new Callable<Connection>() {
        @Override
        public Connection call() throws SQLException {
          return MonitoringDataSource.this.original.getConnection();
        }
      },
      ".getConnection");
  }
10938
public static IoFuture<Connection> connect(final ProtocolConnectionConfiguration configuration) throws IOException {
        return connect(configuration.getCallbackHandler(), configuration);
    }