Initializes a DatastoreConnection, which will keep the connection open
506617
@Initialize
    public void init() {
        logger.info("Initializing dictionary: {}", this);
        Datastore datastore = getDatastore();
        DatastoreConnection dataContextProvider = datastore.openConnection();
        getDatastoreConnections().add(dataContextProvider);
    }
629143
private void initPool() {
        if (logger.isWarnEnabled()) {
            logger.warn("Start to initialize connection pool with url: " + url + " ...");
        }

        for (int i = 0; (i < initialSize) && (xpool.size() < initialSize); i++) {
            pool.lock();

            try {
                if (pool.isClosed()) {
                    break;
                }

                if ((i < initialSize) && (xpool.size() < initialSize)) {
                    PoolableConnection poolableConn = newConnection();

                    if (!pool.add(poolableConn)) {
                        detroyConnection(poolableConn);
                    }
                }
            } finally {
                pool.unlock();
            }
        }

        if (logger.isWarnEnabled()) {
            logger.warn("End to initialize connection pool with url: " + url + " ...");
        }
    }
1022899
@Override
    public void start() {
        if(null != entityManagerFactory) {
            throw new IllegalStateException("Persistence service was already initialized.");
        }

        final Configuration configuration = new Configuration();

        //
        // We'll want to map these to settings
        //
        configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "managed");
        configuration.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, TRUE_STRING);
        configuration.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER, TRUE_STRING);
        configuration.setProperty(AvailableSettings.ORDER_UPDATES, TRUE_STRING);
        configuration.setProperty(AvailableSettings.ORDER_INSERTS, TRUE_STRING);
        configuration.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, TRUE_STRING);
        configuration.setProperty("jadira.usertype.autoRegisterUserTypes", TRUE_STRING);
        configuration.setProperty(AvailableSettings.DIALECT, settings.getDatabaseSettings().getDialectClass());

        // turn on and off features based upon log level
        if(LOG.isDebugEnabled()) {
            configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, TRUE_STRING);
            configuration.setProperty(AvailableSettings.SHOW_SQL, TRUE_STRING);
        } else {
            configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, FALSE_STRING);
            configuration.setProperty(AvailableSettings.SHOW_SQL, FALSE_STRING);
        }

        // add in all the entities
        for (final Class<? extends Serializable> entity : settings.getDatabaseSettings().getEntities()) {
            LOG.debug("Adding entity: {}", entity.getCanonicalName());
            configuration.addAnnotatedClass(entity);
        }

        final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties())
            // set our connection provider
            .addService(ConnectionProvider.class, connectionProvider)
            .build();

        // create the actual entity manager
        this.entityManagerFactory = new EntityManagerFactoryImpl(PersistenceUnitTransactionType.RESOURCE_LOCAL,
                                                                 false,
                                                                 null,
                                                                 configuration,
                                                                 serviceRegistry,
                                                                 persistenceUnitName);

    }
381910
public void associateConnection(Object connection) throws ResourceException
   {
      if (connection == null)
         throw new ResourceException("Null connection handle");

      if (!(connection instanceof HelloWorldConnectionImpl))
         throw new ResourceException("Wrong connection handle");

      HelloWorldConnectionImpl handle = (HelloWorldConnectionImpl)connection;
      handle.setManagedConnection(this);
      connections.add(handle);
   }
1249244
void establishConnection () throws IOException {
        synchronized (operationOnConnectionMonitor) {
            if (state == State.CLOSED) {
                throw new IOException("Attempt to establish a connection with a closed connection factory");
            } else if (state == State.CONNECTED) {
                LOGGER.warn("Establishing new connection although a connection is already established");
            }
            try {
                LOGGER.info("Trying to establish connection to {}:{}", getHost(), getPort());
                connection = super.newConnection(executorService);
                connection.addShutdownListener(connectionShutdownListener);
                LOGGER.info("Established connection to {}:{}", getHost(), getPort());
                changeState(State.CONNECTED);
            } catch (IOException e) {
                LOGGER.error("Failed to establish connection to {}:{}", getHost(), getPort());
                throw e;
            }
        }
    }
162400
function Open()
	{
		$this->Observe("DataAdapter ($this->_label) Opening Connection...",OBSERVE_DEBUG);
		
		if ($this->_dbopen)
		{
			$this->Observe("DataAdapter ($this->_label) Connection Already Open",OBSERVE_WARN);
		}
		else
		{
			if (!$this->_driver) $this->LoadDriver();
			
			try
			{
				$this->_dbconn = $this->_driver->Open(
					$this->ConnectionSetting->ConnectionString, 
					$this->ConnectionSetting->DBName, 
					$this->ConnectionSetting->Username, 
					$this->ConnectionSetting->Password,
					$this->ConnectionSetting->Charset,
					$this->ConnectionSetting->BootstrapSQL);
				
				$this->_num_retries = 0;
			}
			catch (Exception $ex)
			{
				// retry one time a communication error occurs
				if ($this->_num_retries == 0 && DataAdapter::$RETRY_ON_COMMUNICATION_ERROR && $this->IsCommunicationError($ex))
				{
					$this->_num_retries++;
					$this->Observe("DataAdapter ($this->_label) Communication error.  Retry attempt " . $this->_num_retries, OBSERVE_WARN);
					sleep(2); // slight delay to prevent throttling
					return $this->Open();
				}

				$msg = "DataAdapter ($this->_label) Error Opening DB: " . $ex->getMessage() . ' (retry attempts: '.$this->_num_retries.')';
					
				$this->Observe($msg,OBSERVE_FATAL);
				throw new Exception($msg,$ex->getCode());
			}
			
			$this->_dbopen = true;
			$this->Observe("DataAdapter ($this->_label) Connection Open",OBSERVE_DEBUG);
		}
	}
555560
private void initialize(CatalogContext catalogContext, List<Pair<Integer, Integer>> localPartitionsToSites,
            boolean isRejoin) {
        try {
            CatalogMap<Connector> connectors = CatalogUtil.getConnectors(catalogContext);
            if (exportLog.isDebugEnabled()) {
                exportLog.debug("initialize for " + connectors.size() + " connectors.");
                CatalogUtil.dumpConnectors(exportLog, connectors);
            }
            if (!CatalogUtil.hasExportedTables(connectors)) {
                return;
            }

            if (exportLog.isDebugEnabled()) {
                exportLog.debug("Creating processor " + m_loaderClass);
            }
            ExportDataProcessor newProcessor = getNewProcessorWithProcessConfigSet(m_processorConfig);
            m_processor.set(newProcessor);

            File exportOverflowDirectory = new File(VoltDB.instance().getExportOverflowPath());
            ExportGeneration generation = new ExportGeneration(exportOverflowDirectory, m_messenger);
            generation.initialize(m_hostId, catalogContext,
                    connectors, newProcessor, localPartitionsToSites, exportOverflowDirectory);

            m_generation.set(generation);
            newProcessor.setExportGeneration(generation);
            newProcessor.readyForData();
        }
        catch (final ClassNotFoundException e) {
            exportLog.l7dlog( Level.ERROR, LogKeys.export_ExportManager_NoLoaderExtensions.name(), e);
            throw new RuntimeException(e);
        }
        catch (final Exception e) {
            exportLog.error("Initialize failed with:", e);
            throw new RuntimeException(e);
        }
    }
1103371
public void init(HttpInboundConnection conn, SessionManager sessMgr) {
        this.connection = conn;
        this.request = conn.getRequest();
        this.sessionData = new SessionInfo(this, sessMgr);
    }
1308734
protected void postInit(Connection connection) throws SQLException
   {
      String select =
         "select * from " + DBInitializerHelper.getItemTableName(containerConfig) + " where ID='"
            + Constants.ROOT_PARENT_UUID + "' and PARENT_ID='" + Constants.ROOT_PARENT_UUID + "'";

      if (!connection.createStatement().executeQuery(select).next())
      {
         String insert = DBInitializerHelper.getRootNodeInitializeScript(containerConfig);
         connection.createStatement().executeUpdate(insert);
      }
   }
166513
def init_from_datastore(self):
    """"""
    self._data = {}
    for entity in self._datastore_client.query_fetch(
        kind=self._entity_kind_batches):
      batch_id = entity.key.flat_path[-1]
      self._data[batch_id] = dict(entity)
      self._data[batch_id]['images'] = {}
    for entity in self._datastore_client.query_fetch(
        kind=self._entity_kind_images):
      batch_id = entity.key.flat_path[-3]
      image_id = entity.key.flat_path[-1]
      self._data[batch_id]['images'][image_id] = dict(entity)
14563
static void attach(String dbName, Connection connection, String extraInfo) {
        if(ConnectionsAccess.getConnectionMap().get(dbName) != null){
            throw new InternalException("You are opening a connection " + dbName + " without closing a previous one. Check your logic. Connection still remains on thread: " + ConnectionsAccess.getConnectionMap().get(dbName));
        }
        ConnectionsAccess.getConnectionMap().put(dbName, connection);
        LogFilter.log(LOGGER, LogLevel.DEBUG, "Attached connection named: {}: to current thread: {}. Extra info: {}", dbName, connection, extraInfo);
    }
1318035
@Override
  public void initializeConnection() throws SQLException {
    super.initializeConnection();
    try {
      reconnectFailedConnection(new SearchFilter(true));
    } catch (SQLException e) {
      //initializeConnection failed
      checkInitialConnection(e);
    }
  }
609291
function _initDefaultConnection() {
  if ('CLOUD_STORAGE_ACCOUNT' in process.env) {
    var accountSettings = utils.parseAccountString(process.env.CLOUD_STORAGE_ACCOUNT);
    if (accountSettings !== null) {
      _defaultClientSetting = _.defaults(_defaultClientSetting, accountSettings);
    }
  }
}
718858
def init_db_conn(
        connection_name, HOST=None, PORT=None, DB=None, PASSWORD=None):
    
    rpool = redis.ConnectionPool(
        host=HOST, port=PORT, db=DB, password=PASSWORD)
    r = redis.Redis(connection_pool=rpool)
    redis_pool.connections[connection_name] = RedisClient(r)
477476
function Connection(log, firstStreamId, settings) {
  // * initializing the base class
  Flow.call(this, 0);

  // * logging: every method uses the common logger object
  this._log = log.child({ component: 'connection' });

  // * stream management
  this._initializeStreamManagement(firstStreamId);

  // * lifecycle management
  this._initializeLifecycleManagement();

  // * flow control
  this._initializeFlowControl();

  // * settings management
  this._initializeSettingsManagement(settings);

  this._initializeConnectionFlowControl();

  // * multiplexing
  this._initializeMultiplexing();
}
933383
private CloseableDataStore asCloseableDataStore(final DataStore dataStore, final Optional<Runnable> onClose) {
        return (CloseableDataStore) Proxy.newProxyInstance(
                DataStore.class.getClassLoader(), new Class[] { CloseableDataStore.class },
                new AbstractInvocationHandler() {
                    @Override
                    protected Object handleInvocation(Object proxy, Method method, Object[] args)
                            throws Throwable {
                        if ("close".equals(method.getName())) {
                            if (onClose.isPresent()) {
                                onClose.get().run();
                            }
                            return null;
                        } else {
                            return method.invoke(dataStore, args);
                        }
                    }
                });
    }
1117749
public void registerConnection(Connection connection, ConnectionDefinition connectionDefinition) {
        checkNotNull(connection);
        checkNotNull(connectionDefinition);

        if (this.connectionDefinitions.putIfAbsent(connectionDefinition.getName(), connectionDefinition) != null) {
            throw SeedException.createNew(JmsErrorCode.DUPLICATE_CONNECTION_NAME).put(ERROR_CONNECTION_NAME, connectionDefinition.getName());
        }

        if (this.connections.putIfAbsent(connectionDefinition.getName(), connection) != null) {
            throw SeedException.createNew(JmsErrorCode.DUPLICATE_CONNECTION_NAME).put(ERROR_CONNECTION_NAME, connectionDefinition.getName());
        }

        if (shouldStartConnections.get()) {
            try {
                connection.start();
            } catch (JMSException e) {
                throw SeedException.wrap(e, JmsErrorCode.UNABLE_TO_START_JMS_CONNECTION).put(ERROR_CONNECTION_NAME, connectionDefinition.getName());
            }
        }
    }