Establishes a Mongo connection.
It does nothing if a MongoDB connection has already been established.
@throws Exception if connection fails
17883
public function open()
    {
        if ($this->manager === null) {
            if (empty($this->dsn)) {
                throw new InvalidConfigException($this->className() . '::dsn cannot be empty.');
            }
            $token = 'Opening MongoDB connection: ' . $this->dsn;
            try {
                Yii::trace($token, __METHOD__);
                Yii::beginProfile($token, __METHOD__);
                $options = $this->options;

                $this->manager = new Manager($this->dsn, $options, $this->driverOptions);
                $this->manager->selectServer($this->manager->getReadPreference());

                $this->initConnection();
                Yii::endProfile($token, __METHOD__);
            } catch (\Exception $e) {
                Yii::endProfile($token, __METHOD__);
                throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
            }

            $this->typeMap = array_merge(
                $this->typeMap,
                [
                    'root' => 'array',
                    'document' => 'array'
                ]
            );
        }
    }
1061518
public static function dropDb($database = null)
		{
			if (empty($database)) {
				throw new Exception('Failed to drop MongoDB database because name is empty');
			} else {
				try {
					static::instance()->connection->{$database}->drop();

					return true;
				} catch (\Exception $e) {
					throw new Exception("Unable to drop Mongo database `{$database}`: {$e->getMessage()}", $e->getCode());
				}
			}
		}
292094
function(callback) {

  log('Connecting...');
  MongoClient.connect(dbUrl, dbOptions, function(err, dbConn) {
    
    if(err) {
      log('Cannot connect: ' + err);
      callback(err);
      return;
    } 
    
    log('Connected!');
    isConnected = true;
    db = dbConn;

    // http://stackoverflow.com/a/18715857/446681
    db.on('close', function() {
      log('Connection was closed!!!');
      isConnected = false;
    });

    log('Executing...');
    callback(null, db);
  
  });

}
925699
@Given("^I insert into MongoDB database '(.+?)' and collection '(.+?)' the document from schema '(.+?)'$")
    public void insertOnMongoTable(String dataBase, String collection, String document) throws Exception {
        String retrievedDoc = commonspec.retrieveData(document, "json");
        commonspec.getMongoDBClient().connectToMongoDBDataBase(dataBase);
        commonspec.getMongoDBClient().insertDocIntoMongoDBCollection(collection, retrievedDoc);
    }
912642
function CreateConnection (backend) {

    backend.Debug (4, "MongoDB creating connection [%s]", backend.uid);
    MongoClient.connect(backend.uid, function (err, db) {
        if (err) {
            backend.Debug (0, "Fail to connect to MongoDB: %s err=[%s]", backend.uid, err)
        } else {
            backend.Debug (4, "Connected to MongoDB: %s", backend.uid)
            backend.base = db;
        }
    });
}
500850
public void setupDB() throws Exception {

        if (m_bean.isInitialized()) {
            System.out.println("Setup-Bean initialized successfully.");
            CmsSetupDb db = new CmsSetupDb(m_bean.getWebAppRfsPath());
            try {
                // try to connect as the runtime user
                db.setConnection(
                    m_bean.getDbDriver(),
                    m_bean.getDbWorkConStr(),
                    m_bean.getDbConStrParams(),
                    m_bean.getDbWorkUser(),
                    m_bean.getDbWorkPwd(),
                    false);
                if (!db.noErrors()) {
                    // try to connect as the setup user
                    db.closeConnection();
                    db.clearErrors();
                    db.setConnection(
                        m_bean.getDbDriver(),
                        m_bean.getDbCreateConStr(),
                        m_bean.getDbConStrParams(),
                        m_bean.getDbCreateUser(),
                        m_bean.getDbCreatePwd());
                }
                if (!db.noErrors() || !m_bean.validateJdbc()) {
                    throw new Exception("DB Connection test faild.");
                }
            } finally {
                db.clearErrors();
                db.closeConnection();
            }
        }

        System.out.println("DB connection tested successfully.");

        CmsSetupDb db = null;
        boolean dbExists = false;
        if (m_bean.isInitialized()) {
            if (m_props.isCreateDb() || m_props.isCreateTables()) {
                db = new CmsSetupDb(m_bean.getWebAppRfsPath());
                // check if database exists
                if (m_bean.getDatabase().startsWith("oracle")
                    || m_bean.getDatabase().startsWith("db2")
                    || m_bean.getDatabase().startsWith("as400")) {
                    db.setConnection(
                        m_bean.getDbDriver(),
                        m_bean.getDbWorkConStr(),
                        m_bean.getDbConStrParams(),
                        m_bean.getDbWorkUser(),
                        m_bean.getDbWorkPwd());
                } else {
                    db.setConnection(
                        m_bean.getDbDriver(),
                        m_bean.getDbWorkConStr(),
                        m_bean.getDbConStrParams(),
                        m_bean.getDbCreateUser(),
                        m_bean.getDbCreatePwd(),
                        false);
                    dbExists = db.noErrors();
                    if (dbExists) {
                        db.closeConnection();
                    } else {
                        db.clearErrors();
                    }
                }
                if (!dbExists || m_props.isDropDb()) {
                    db.closeConnection();
                    if (!m_bean.getDatabase().startsWith("db2") && !m_bean.getDatabase().startsWith("as400")) {
                        db.setConnection(
                            m_bean.getDbDriver(),
                            m_bean.getDbCreateConStr(),
                            m_bean.getDbConStrParams(),
                            m_bean.getDbCreateUser(),
                            m_bean.getDbCreatePwd());
                    }
                }
            }
        }
        if (!m_props.isCreateDb() && !m_props.isCreateTables() && !dbExists) {
            throw new Exception("You have not created the Alkacon OpenCms database.");
        }
        if (dbExists && m_props.isCreateTables() && !m_props.isDropDb() && (db != null)) {
            throw new Exception("You have selected to not drop existing DBs, but a DB with the given name exists.");
        }
        if (dbExists && m_props.isCreateDb() && m_props.isDropDb() && (db != null)) {
            // drop the DB
            db.closeConnection();
            db.setConnection(
                m_bean.getDbDriver(),
                m_bean.getDbWorkConStr(),
                m_bean.getDbConStrParams(),
                m_bean.getDbCreateUser(),
                m_bean.getDbCreatePwd());
            db.dropDatabase(m_bean.getDatabase(), m_bean.getReplacer());
            if (!db.noErrors()) {
                for (String error : db.getErrors()) {
                    System.err.println(error + "\n");
                    System.err.println(HR + "\n");
                }
                db.clearErrors();
                throw new Exception("Error ocurred while dropping the DB!");
            }
            System.out.println("Database dropped successfully.");
        }

        if (m_props.isCreateDb() && (db != null)) {
            // Create Database
            db.createDatabase(m_bean.getDatabase(), m_bean.getReplacer());
            if (!db.noErrors()) {
                for (String error : db.getErrors()) {
                    System.err.println(error + "\n");
                    System.err.println(HR + "\n");
                }
                db.clearErrors();
                throw new Exception("Error ocurred while creating the DB!");
            }
            db.closeConnection();
            System.out.println("Database created successfully.");
        }

        if (m_props.isCreateTables() && (db != null)) {
            db.setConnection(
                m_bean.getDbDriver(),
                m_bean.getDbWorkConStr(),
                m_bean.getDbConStrParams(),
                m_bean.getDbWorkUser(),
                m_bean.getDbWorkPwd());
            //Drop Tables (intentionally quiet)
            db.dropTables(m_bean.getDatabase());
            db.clearErrors();
            db.closeConnection();
            // reopen the connection in order to display errors
            db.setConnection(
                m_bean.getDbDriver(),
                m_bean.getDbWorkConStr(),
                m_bean.getDbConStrParams(),
                m_bean.getDbWorkUser(),
                m_bean.getDbWorkPwd());
            //Create Tables
            db.createTables(m_bean.getDatabase(), m_bean.getReplacer());
            if (!db.noErrors()) {
                for (String error : db.getErrors()) {
                    System.err.println(error + "\n");
                    System.err.println(HR + "\n");
                }
                db.clearErrors();
                throw new Exception("Error ocurred while creating tables.");
            }
            db.closeConnection();
            System.out.println("Tables created successfully.");
        }
        if (db != null) {
            db.closeConnection();
        }
        System.out.println("Database setup was successful.");
    }
662241
private void init() throws Exception {
        this.useCertAuth = (((Boolean) props.get(USE_CERTIFICATE_AUTHENTICATION)) == null) ? false : (Boolean) props.get(USE_CERTIFICATE_AUTHENTICATION);

        ClassLoader loader = libraryRef.getServiceWithException().getClassLoader();

        // Lazy initialization for version 2.x of the Mongo Java driver.

        boolean sslEnabled = (((Boolean) props.get(SSL_ENABLED)) == null) ? false : (Boolean) props.get(SSL_ENABLED);

        assertLibrary(loader, sslEnabled);
        assertValidSSLConfig();

        // Initialize List<ServerAddress>
        List<Object> serverAddresses = new LinkedList<Object>();
        Constructor<?> ServerAddress_constructor = loader.loadClass("com.mongodb.ServerAddress").getConstructor(String.class, int.class);
        String[] hosts = (String[]) props.get(HOST_NAMES);
        int[] ports = (int[]) props.get(PORTS);
        int numServerAddresses = hosts.length;
        if (hosts.length != ports.length) {
            IllegalArgumentException failure = ignoreWarnOrFail(null, IllegalArgumentException.class, "CWKKD0011.hosts.ports.mismatch",
                                                                MONGO, id, hosts.length, ports.length);
            if (failure == null) // tolerate the error and keep going
                numServerAddresses = hosts.length < ports.length ? hosts.length : ports.length;
            else
                throw failure;
        }

        //Initialise URI. Only used when constructing mongo with the default SSL turned on.
        StringBuilder uriBuilder = new StringBuilder();
        uriBuilder.append("mongodb://");
        for (int i = 0; i < numServerAddresses; i++) {
            serverAddresses.add(ServerAddress_constructor.newInstance(hosts[i], ports[i]));
            //Add server addresses to URI
            uriBuilder.append(hosts[i] + ":" + ports[i]);
            if (i != numServerAddresses - 1) {
                uriBuilder.append(",");
            }
        }

        // Initialize MongoOptions
        Class<?> MongoClientOptions = loader.loadClass("com.mongodb.MongoClientOptions");
        Class<?> MongoClientOptions_Builder = loader.loadClass("com.mongodb.MongoClientOptions$Builder");

        Object optionsBuilder = MongoClientOptions_Builder.newInstance();
        for (Map.Entry<String, Object> prop : props.entrySet()) {
            String name = prop.getKey();
            Object value = prop.getValue();
            if (value != null && name.indexOf('.') < 0 && !NOT_MONGO_CLIENT_OPTIONS.contains(name))
                set(MongoClientOptions_Builder, optionsBuilder, name, value);
        }

        String value = (String) props.get(READ_PREFERENCE);
        if (value != null) {
            setReadPreference(MongoClientOptions_Builder, optionsBuilder, value);
        }
        value = (String) props.get(WRITE_CONCERN);
        if (value != null) {
            setWriteConcern(MongoClientOptions_Builder, optionsBuilder, value);
        }

        //SSL setup
        boolean sslRefExists = props.containsKey(SSL_REF);
        Properties sslProperties = null;
        if (sslEnabled) {
            Map<String, Object> connectionInfo = getConnectionInfo();
            setSocketFactory(MongoClientOptions_Builder, optionsBuilder, connectionInfo);
            sslProperties = sslHelper.getSSLProperties(sslConfigurationRef.getService(), connectionInfo, this);
        }
        // Initialize the Mongo instance
        Class<?> MongoClient = loader.loadClass(com_mongodb_MongoClient);
        Class<?> MongoClientURI = loader.loadClass("com.mongodb.MongoClientURI");
        if (sslEnabled && !sslRefExists && !useCertAuth) {
            // TODO check if this is still needed as we are setting the socket factory above
            uriBuilder.append("/?ssl=true");
            String uri = uriBuilder.toString();
            Constructor<?> MongoClientURI_constructor = MongoClientURI.getConstructor(String.class, MongoClientOptions_Builder);
            Object uriObject = MongoClientURI_constructor.newInstance(uri, optionsBuilder);
            Constructor<?> MongoClient_constructor = MongoClient.getConstructor(MongoClientURI);
            mongoClient = MongoClient_constructor.newInstance(uriObject);

        } else if (sslEnabled && useCertAuth) {
            // get the name from the certificate and handle exceptions / null
            String certificateDN = getCerticateSubject(keyStoreServiceRef, sslProperties);

            // Create an x509 credential calling the MongoCredential class reflectively passing the DN
            Class<?> MongoCredential = loader.loadClass("com.mongodb.MongoCredential");
            Method MongoCredential_createCertificate = MongoCredential.getMethod("createMongoX509Credential", String.class);
            Object credential = MongoCredential_createCertificate.invoke(null, certificateDN);

            // create a client authenticated using this credential
            Constructor<?> MongoClient_constructor = MongoClient.getConstructor(List.class, List.class, MongoClientOptions);
            Object mongoClientOptions = MongoClientOptions_Builder.getMethod("build").invoke(optionsBuilder);
            mongoClient = MongoClient_constructor.newInstance(serverAddresses, Arrays.asList(credential), mongoClientOptions);
        } else {
            Constructor<?> MongoClient_constructor = MongoClient.getConstructor(List.class, MongoClientOptions);
            Object mongoClientOptions = MongoClientOptions_Builder.getMethod("build").invoke(optionsBuilder);
            mongoClient = MongoClient_constructor.newInstance(serverAddresses, mongoClientOptions);
        }

        // Methods that we need each each time a DB instance is created
        MongoClient_getDB = MongoClient.getMethod("getDB", String.class);
        Class<?> DB = loader.loadClass("com.mongodb.DB");
        DB_authenticate = DB.getMethod("authenticate", String.class, char[].class);
        DB_isAuthenticated = DB.getMethod("isAuthenticated");
    }
183859
@Override
   public void connect() throws IOException
   {
      if (connected)
         return;

      try
      {
         session =
            sessionProvider.getSession(sessionProvider.getCurrentWorkspace(), sessionProvider.getCurrentRepository());

         Node node = null;
         if (nodeReference.isPath())
         {
            node = (Node)session.getItem(nodeReference.getPath());
         }
         else if (nodeReference.isIdentitifier())
         {
            node = session.getNodeByUUID(nodeReference.getIdentitifier().getString());
         }
         else
         {
            throw new IllegalArgumentException("Absolute path or Identifier was not found!");
         }

         nodeRepresentation = nodeRepresentationService.getNodeRepresentation(node, "text/xml");
         connected = true;
      }
      catch (Exception e)
      {
         //e.printStackTrace();
         throw new IOException("Connection refused!", e);
      }
   }
635852
def connect(self, host=None, port=None, connect=False, **kwargs):
        
        try:
            self.__connection = MongoClient(host=host, port=port, connect=connect, **kwargs)
        except (AutoReconnect, ConnectionFailure, ServerSelectionTimeoutError):
            raise DatabaseIsDownError("No mongod process is running.")
373000
public void connect(Object context) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "connect");
        }

        this.syncObject = new SimpleSync();

        // reset proxy response object
        if (this.proxy != null) {
            this.proxy.setIsProxyResponseValid(false);
        }

        this.syncError = null;
        connectCommon((TCPConnectRequestContext) context);

        if (this.syncError != null) {
            throw this.syncError;
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "connect");
        }
    }
1166996
function connect(uri, callback) {
  console.log('connecting to database (' + uri + ')');
  mongo.MongoClient.connect(uri, {safe: true}, function (err, client) {
    if (err) return callback(err);

    db = client;
    db.addListener("error", function (error) {
      console.log("mongo client error: " + error);
    });

    callback(null, db);
  });
}
1318035
@Override
  public void initializeConnection() throws SQLException {
    super.initializeConnection();
    try {
      reconnectFailedConnection(new SearchFilter(true));
    } catch (SQLException e) {
      //initializeConnection failed
      checkInitialConnection(e);
    }
  }
1247561
private void createConnection() throws IOException {
		client = new Socket(hostName, port);
		client.setKeepAlive(true);
		client.setTcpNoDelay(true);

		outputStream = client.getOutputStream();
	}
1314400
private void setupConnection(final Connection connection) throws ConnectionSetupException
   {
      try {
         if (networkTimeout == UNINITIALIZED) {
            networkTimeout = getAndSetNetworkTimeout(connection, validationTimeout);
         }
         else {
            setNetworkTimeout(connection, validationTimeout);
         }

         if (connection.isReadOnly() != isReadOnly) {
            connection.setReadOnly(isReadOnly);
         }

         if (connection.getAutoCommit() != isAutoCommit) {
            connection.setAutoCommit(isAutoCommit);
         }

         checkDriverSupport(connection);

         if (transactionIsolation != defaultTransactionIsolation) {
            connection.setTransactionIsolation(transactionIsolation);
         }

         if (catalog != null) {
            connection.setCatalog(catalog);
         }

         if (schema != null) {
            connection.setSchema(schema);
         }

         executeSql(connection, config.getConnectionInitSql(), true);

         setNetworkTimeout(connection, networkTimeout);
      }
      catch (SQLException e) {
         throw new ConnectionSetupException(e);
      }
   }
640432
public function connect(): DriverInterface
    {
        // URL options
        $options = $this->getConfig()->get();

        // TODO: This option should be optional, in addition, it may not be an array
        // Driver options
        $optionsDriver = $options['driver_options']->get();

        try {
            $connection = new MongoManager(
                $this->getDsn(),
                $this->getOptions($options, self::AVAILABLE_OPTIONS),
                $this->getOptions($optionsDriver, self::AVAILABLE_DRIVER_OPTIONS)
            );
            $this->setInstance($connection);

        } catch (RuntimeException $e) {
            new Exception('Unable to connect');
        } catch (InvalidArgumentException $e) {
            new Exception('Invalid argument provided');
        }

        return $this;
    }
404735
public void connect() throws IOException {
        if (isConnected() && tree.session.transport.tconHostName == null) {
            /* Tree thinks it is connected but transport disconnected
             * under it, reset tree to reflect the truth.
             */
            tree.treeDisconnect(true);
        }

        if( isConnected() ) {
            return;
        }

        getUncPath0();
        getFirstAddress();
        for ( ;; ) {
            try {
                doConnect();
                return;
            } catch(SmbAuthException sae) {
                throw sae; // Prevents account lockout on servers with multiple IPs
            } catch(SmbException se) {
                if (getNextAddress() == null) 
                    throw se;
                if (log.level >= 3)
                    se.printStackTrace(log);
            }
        }
    }
944800
function getMongodbConnection(mongoDbUrl, logger, cb) {
  logger.debug("creating mongodb connection for data_source_update job", {mongoDbUrl: mongoDbUrl});
  MongoClient.connect(mongoDbUrl, cb);
}