Connects to the database.

@throws Exception If connection is not possible, or failed to decrypt username/password if encryption was provided.
762565
protected void connect() throws Exception {
        String username = this.properties.getUsername();
        String password = this.properties.getPassword();

        if (this.properties.isEncryptedPassword() || this.properties.isEncryptedUsername()) {
            String privateKey = getPrivateKey();
            if (this.properties.isEncryptedUsername()) {
                final String decryptedUsername = AESHelper.decrypt(this.properties.getProperty(ENCRYPTED_USERNAME), privateKey);
                if (StringUtils.isEmpty(decryptedUsername)) {
                    throw new DatabaseEngineException("The encrypted username could not be decrypted.");
                }
                username = decryptedUsername;

            }

            if (this.properties.isEncryptedPassword()) {
                final String decryptedPassword = AESHelper.decrypt(this.properties.getProperty(ENCRYPTED_PASSWORD), privateKey);
                if (StringUtils.isEmpty(decryptedPassword)) {
                    throw new DatabaseEngineException("The encrypted password could not be decrypted.");
                }
                password = decryptedPassword;
            }
        }

        final String jdbc = getFinalJdbcConnection(this.properties.getJdbc());

        this.conn = DriverManager.getConnection(
                jdbc,
                username,
                password);

        if (this.properties.isSchemaSet()) {
            setSchema(this.properties.getSchema());
        }

        this.currentSchema = Optional.ofNullable(getSchema())
            .orElseThrow(() -> new DatabaseEngineException("Could not get current schema"));

        setTransactionIsolation();

        logger.debug("Connection successful.");
    }
1299440
public function connect()
  {
    if($this->stream !== null) return;

    $host = strval($this->config["host"]);
    $port = strval($this->config["port"]);

    $address = "tcp://" . (strstr($host, ":") !== FALSE ? "[" . $host . "]" : $host) . ":" . $port;
    $options = empty($this->config["tls"]) ? array() : array("ssl" => array("allow_self_signed" => TRUE, "verify_peer" => FALSE, "verify_peer_name" => FALSE));
    $timeout = (int) $this->config["timeout"];

    $this->stream = @stream_socket_client($address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options));

    if($this->stream === FALSE)
    {
      throw new Exception(Str::factory($errstr)->toUtf8()->toString(), $errno);
    }

    if(!empty($this->config["tls"]))
    {
      stream_socket_enable_crypto($this->stream, TRUE, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
    }

    @stream_set_timeout($this->stream, $timeout);
    @stream_set_blocking($this->stream, $this->config["blocking"] ? 1 : 0);
  }
192661
protected function connectToDb()
    {
        try {
            $this->db = new PDO("mysql:dbname=;" . $this->db_host, $this->db_user, $this->db_pass);
            $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
        } catch (\Exception $e) {
            $this->log("Cannot connect to database.  Are the credentials correct?");
            $this->log(print_r($e), 1);
            exit;
        }
    }
837226
public function connect()
    {
        list($host, $port) = explode(':', $this->getServer());
        if ($this->stream->open($host, $port, $this->getTimeout()) === false) {
            throw new Exception(sprintf('Cannot connect to server %s', $this->getServer()), Exception::SERVER_OFFLINE);
        }

        return true;
    }
90280
boolean connect() throws SQLException {
    try {
      if (driver != null && driver.length() != 0) {
        Class.forName(driver);
      }
    } catch (ClassNotFoundException cnfe) {
      return sqlLine.error(cnfe);
    }

    boolean foundDriver = false;
    Driver theDriver = null;
    try {
      theDriver = DriverManager.getDriver(url);
      foundDriver = theDriver != null;
    } catch (Exception e) {
      // ignore
    }

    if (!foundDriver) {
      sqlLine.output(sqlLine.loc("autoloading-known-drivers", url));
      sqlLine.registerKnownDrivers();
      theDriver = DriverManager.getDriver(url);
    }

    try {
      close();
    } catch (Exception e) {
      return sqlLine.error(e);
    }

    // Avoid using DriverManager.getConnection(). It is a synchronized
    // method and thus holds the lock while making the connection.
    // Deadlock can occur if the driver's connection processing uses any
    // synchronized DriverManager methods.  One such example is the
    // RMI-JDBC driver, whose RJDriverServer.connect() method uses
    // DriverManager.getDriver(). Because RJDriverServer.connect runs in
    // a different thread (RMI) than the getConnection() caller (here),
    // this sequence will hang every time.
/*
          connection = DriverManager.getConnection (url, username, password);
*/
    // Instead, we use the driver instance to make the connection

    connection = theDriver.connect(url, info);
    meta = (DatabaseMetaData) Proxy.newProxyInstance(
        DatabaseMetaData.class.getClassLoader(),
        new Class[] {DatabaseMetaData.class},
        new DatabaseMetaDataHandler(connection.getMetaData()));
    try {
      sqlLine.debug(
          sqlLine.loc("connected",
              meta.getDatabaseProductName(),
              meta.getDatabaseProductVersion()));
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    try {
      sqlLine.debug(
          sqlLine.loc("driver",
              meta.getDriverName(),
              meta.getDriverVersion()));
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    try {
      connection.setAutoCommit(sqlLine.getOpts().getAutoCommit());
      sqlLine.autocommitStatus(connection);
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    try {
      // nothing is done off of this command beyond the handle so no
      // need to use the callback.
      sqlLine.getCommands().isolation("isolation: " + sqlLine.getOpts()
          .getIsolation(),
          new DispatchCallback());
      initSyntaxRule();
    } catch (Exception e) {
      sqlLine.handleException(e);
    }

    sqlLine.showWarnings();

    return true;
  }
718368
private function __connect() {
        if (!is_null($db)) return true;

        $config = Config::get('db');

        if (is_null($config)) {
            throw new \Lollipop\Exception\Configuration('Lollipop is initialized with wrong database configuration');
        }

        $host = isset($config->host) ?  $config->host : 'localhost';
        $uid = isset($config->username) ?  $config->username : 'root';
        $pwd = isset($config->password) ?  $config->password : '';
        $db = isset($config->database) ?  $config->database : 'lollipop';
        
        // Instantiate MySQLi
        $this->db = new \mysqli($host, $uid, $pwd, $db);
        
        if ($this->db->connect_errno > 0) {
            throw new \Lollipop\Exception\Connection($this->db->connect_error);
        }

        return true;
    }
1200074
public function connect()
  {
    try {
      $this->cnx = new SQLitePDO($this->fileName);
      $this->cnx->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
      return true;
    } catch (\Exception $e) {
      return false;
    }
  }
1048822
public function connect()
    {
        try {
            $this->_connection = new PDO(
                $this->_type .":host=". $this->_host .";dbname=". $this->_database .";port=". $this->_port,
                $this->_username,
                $this->_password
            );
        } catch(PDOException $e) {
            $code    = $e->getCode();
            $message = $e->getMessage();

            throw new ConnectionFailed($code, $message);
        }
    }
1178210
public function connect()
    {
        try {
            $this->pdo = new \PDO(
                $this->datasource->getDsn(),
                $this->datasource->getUser(),
                $this->datasource->getPassword(),
                $this->datasource->getOption()
            );
            return true;
        } catch (PDOException $e) {
            throw new \Exception($e->getMessage());
            return false;
        }
    }
888376
private function connect()
    {

        if ($this->config['host'] && $this->config['port']) {
            // establish the memcache connection
            $this->memcache = new \Memcache;
            $this->memcache->pconnect(
                $this->config['host'],
                $this->config['port']
            );

        } else {
            throw new \Exception('Insufficient connection parameters');
        }
    }
1045661
public void connect() throws Exception {		
		// Start up our MINA stuff 
		// Setup MINA codecs
		final IT100CodecFactory it100CodecFactory = new IT100CodecFactory();
		final ProtocolCodecFilter protocolCodecFilter = new ProtocolCodecFilter(it100CodecFactory);
		final CommandLogFilter loggingFilter = new CommandLogFilter(LOGGER, Level.DEBUG);
		final PollKeepAliveFilter pollKeepAliveFilter = new PollKeepAliveFilter(KeepAliveRequestTimeoutHandler.EXCEPTION);
		
		// Connect to system serial port.
		connector = configuration.getConnector();
		
		// Typical configuration
		connector.setConnectTimeoutMillis(configuration.getConnectTimeout());
		connector.getSessionConfig().setUseReadOperation(true);

		// Add IT100 codec to MINA filter chain to interpret messages.
		connector.getFilterChain().addLast("codec", protocolCodecFilter);
		connector.getFilterChain().addLast("logger", loggingFilter);   
	    connector.getFilterChain().addLast("keepalive", pollKeepAliveFilter);
	    
	    
	    if (configuration.getStatusPollingInterval() != -1) {
	    	connector.getFilterChain().addLast("statusrequest", new StatusRequestFilter(configuration.getStatusPollingInterval()));
	    }
	    
	    final DemuxingIoHandler demuxIoHandler = new DemuxingIoHandler();
	    
	    // Setup a read message handler
		// OnSubscribe will allow us to create an Observable to received messages.
		final ReadCommandOnSubscribe readCommandObservable = new ReadCommandOnSubscribe();
		demuxIoHandler.addReceivedMessageHandler(ReadCommand.class, readCommandObservable);
		demuxIoHandler.addExceptionHandler(Exception.class, readCommandObservable);
	    
	    // Handle Envisalink 505 request for password events
	    if (configuration.getEnvisalinkPassword() != null) {
	    	final EnvisalinkLoginHandler envisalinkLoginHandler = new EnvisalinkLoginHandler(configuration.getEnvisalinkPassword());
	    	demuxIoHandler.addReceivedMessageHandler(EnvisalinkLoginInteractionCommand.class, envisalinkLoginHandler);
	    }
	    
	    // We don't need to subscribe to the messages we sent.
		demuxIoHandler.addSentMessageHandler(Object.class, MessageHandler.NOOP);		

		connector.setHandler(demuxIoHandler);
		 
		// Connect now
		final ConnectFuture future = connector.connect(configuration.getAddress()); 
		future.awaitUninterruptibly();

		// Get a reference to the session
		session = future.getSession(); 
		
		// Create and return our Observable for received IT-100 commands.
		final ConnectableObservable<ReadCommand> connectableReadObservable = Observable.create(readCommandObservable).publish();
		connectableReadObservable.connect();
		readObservable = connectableReadObservable.share().asObservable();
		
		// Create a write observer.
		writeObservable = PublishSubject.create();
		writeObservable.subscribe(new Observer<WriteCommand>() {

			@Override
			public void onCompleted() {
			}

			@Override
			public void onError(Throwable e) {
			}

			@Override
			public void onNext(WriteCommand command) {
				session.write(command);
			}
		});
		
		
	}
1171720
public Login login(String username, String password) throws Exception {
    return login(username, password, null);
  }
487949
@Override
  public void connect() {
    if (!canRun.compareAndSet(true, false) || clientBase.isDone()) {
      throw new IllegalStateException("There is already a connection thread running for " + this.clientBase);
    }
    executorService.execute(clientBase);
    logger.info("New connection executed: {}", this.clientBase);
  }
66971
@Override
    public synchronized void connect() throws IOException {
        logger.debug("connecting...");
        Authentication auth = authentication;
        if (updater != null) {
            Authentication updatedAuth = updater.updateAuthentication(authentication);
            if (updatedAuth != null && auth != updatedAuth) {
                auth = updatedAuth;
            }
        }
        try {
            client = new JSch();
            if (auth.getPrivateKeyPhrase() == null) {
                client.addIdentity(auth.getPrivateKeyFile().getAbsolutePath(),
                        auth.getPrivateKeyFilePassword());
            } else {
                client.addIdentity(auth.getUsername(), auth.getPrivateKeyPhrase(), null,
                        auth.getPrivateKeyFilePassword().getBytes("UTF-8"));
            }
            client.setHostKeyRepository(new BlindHostKeyRepository());
            connectSession = client.getSession(auth.getUsername(), host, port);
            connectSession.setConfig("PreferredAuthentications", "publickey");
            if (proxy != null && !proxy.isEmpty()) {
                String[] splitted = proxy.split(":");
                if (splitted.length > 2 && splitted[1].length() >= PROTO_HOST_DELIM_LENGTH) {
                    String pproto = splitted[0];
                    String phost = splitted[1].substring(2);
                    int pport = Integer.parseInt(splitted[2]);
                    if (pproto.equals("socks5") || pproto.equals("http")) {
                        if (pproto.equals("socks5")) {
                             connectSession.setProxy(new ProxySOCKS5(phost, pport));
                        } else {
                             connectSession.setProxy(new ProxyHTTP(phost, pport));
                        }
                    } else {
                        throw new MalformedURLException("Only http and socks5 protocols are supported");
                    }
                } else {
                    throw new MalformedURLException(proxy);
                }
            }
            connectSession.connect(this.connectionTimeout);
            logger.debug("Connected: {}", connectSession.isConnected());
            connectSession.setServerAliveInterval(ALIVE_INTERVAL);
        } catch (JSchException ex) {
            throw new SshException(ex);
        }
    }
1028565
public function connect() {
        if (!class_exists('SQLite3')) throw new RuntimeException('Undefined class \SQLite3, sqlite3 extension is not available');

        try {                                                                   // available flags:
            $flags  = SQLITE3_OPEN_READWRITE;                                   // SQLITE3_OPEN_CREATE
            $sqlite = new \SQLite3($this->file, $flags);                        // SQLITE3_OPEN_READONLY
        }                                                                       // SQLITE3_OPEN_READWRITE
        catch (\Exception $ex) {
            if (!$ex instanceof IRosasurferException)
                $ex = new DatabaseException($ex->getMessage(), $ex->getCode(), $ex);
            $file = $this->file;
            $what = $where = null;
            if (file_exists($file)) {
                $what = 'open';
                if (is_dir($file=realpath($file)))
                    $where = ' (directory)';
            }
            else {
                $what = ($flags & SQLITE3_OPEN_CREATE) ? 'create':'find';
                isRelativePath($file) && $where=' in "'.getcwd().'"';
            }
            throw $ex->addMessage('Cannot '.$what.' database file "'.$file.'"'.$where);
        }

        $this->sqlite = $sqlite;
        $this->setConnectionOptions();
        return $this;
    }
465802
private function _connect() 
    {

        if ($this->config['host'] && $this->config['port']) {
            // establish the memcache connection
            $this->memcache = new Memcache;
            $this->memcache->pconnect(
            	$this->config['host'], 
                $this->config['port']
            );

        } else {
            throw new Exception('Insufficient connection parameters');
        }
    }
398766
public function connect()
    {
        //test to see if driver exists
        if (! function_exists('mysqli_connect')) {
            throw new Exception('The MySQL adapter "mysqli" is not available!');
        }
        
        $db = new mysqli(
            $this->_options->host,
            $this->_options->username,
            $this->_options->password,
            $this->_options->database,
            $this->_options->port,
            $this->_options->socket
        );
        
        $db->set_charset("utf8mb4");
        
        $database = $this->_options->database;
        
        if (!$db->select_db($database)) {
            throw new Exception("The database \"$database\" doesn't seem to exist!");
        }
        
        if (mysqli_connect_errno()) {
            throw new AnDatabaseAdapterException('Connect failed: (' . mysqli_connect_errno() . ') ' . mysqli_connect_error(), mysqli_connect_errno());
        }
        
        $this->_setSQLMode($db);
        
        // If supported, request real datatypes from MySQL instead of returning everything as a string.
        if (defined('MYSQLI_OPT_INT_AND_FLOAT_NATIVE')) {
            $db->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true);
        }
        
        $this->_connection = $db;
        $this->_connected = true;
        $this->_database = $database;
        
        return $this;
    }