Get the {@link DataSource} that hosts the specified {@link Connection}.

@param conn
@return
@since 0.8.2
12759
public static DataSource getDataSource(Connection conn) {
        if (conn == null) {
            return null;
        }
        String dsName = openConnDsName.get().get(conn);
        return getJdbcDataSource(dsName);
    }
1357060
public DataSource getDataSource() {
        if(dataSource == null) {
            LOG.info("Having to construct a new DataSource");

            dataSource = new DataSource();

            dataSource.setDriverClassName(dbSettings.getDriver());
            dataSource.setUrl(dbSettings.getJdbcUrl());
            dataSource.setUsername(dbSettings.getUser());
            dataSource.setPassword(dbSettings.getPass());

            dataSource.setMaxActive(dbSettings.getMaxActive());
            dataSource.setMaxIdle(dbSettings.getMaxIdle());
            dataSource.setMinIdle(dbSettings.getMinIdle());
            dataSource.setInitialSize(dbSettings.getInitialSize());
            dataSource.setTestOnBorrow(dbSettings.getTestOnBorrow());
            dataSource.setTestOnReturn(dbSettings.getTestOnReturn());
            dataSource.setTestWhileIdle(dbSettings.getTestWhileIdle());
            dataSource.setValidationQuery(dbSettings.getValidationQuery());
            dataSource.setLogValidationErrors(dbSettings.getLogValidationErrors());

            // a catch-all for any other properties that are needed
            dataSource.setDbProperties(dbSettings.getProperties());
        }

        return dataSource;
    }
1297632
public ConnectionPoolDataSource createConnectionPoolDataSource(Properties props, String dataSourceID) throws SQLException {
        lock.readLock().lock();
        try {
            if (!isInitialized)
                try {
                    // Switch to write lock for lazy initialization
                    lock.readLock().unlock();
                    lock.writeLock().lock();

                    if (!isInitialized) {
                        if (!loadFromApp())
                            classloader = AdapterUtil.getClassLoaderWithPriv(sharedLib);
                        isInitialized = true;
                    }
                } finally {
                    // Downgrade to read lock for rest of method
                    lock.readLock().lock();
                    lock.writeLock().unlock();
                }

            String className = (String) properties.get(ConnectionPoolDataSource.class.getName());
            if (className == null) {
                String vendorPropertiesPID = props instanceof PropertyService ? ((PropertyService) props).getFactoryPID() : PropertyService.FACTORY_PID;
                className = JDBCDrivers.getConnectionPoolDataSourceClassName(vendorPropertiesPID);
                if (className == null) {
                    //if properties.oracle.ucp is configured do not search based on classname or infer because the customer has indicated
                    //they want to use UCP, but this will likely pick up the Oracle driver instead of the UCP driver (since UCP has no ConnectionPoolDataSource)
                    if("com.ibm.ws.jdbc.dataSource.properties.oracle.ucp".equals(vendorPropertiesPID)) {
                        throw new SQLNonTransientException(AdapterUtil.getNLSMessage("DSRA4015.no.ucp.connection.pool.datasource", dataSourceID, ConnectionPoolDataSource.class.getName()));
                    }
                    className = JDBCDrivers.getConnectionPoolDataSourceClassName(getClasspath(sharedLib, true));
                    if (className == null) {
                        Set<String> packagesSearched = new LinkedHashSet<String>();
                        SimpleEntry<Integer, String> dsEntry = JDBCDrivers.inferDataSourceClassFromDriver //
                                        (classloader, packagesSearched, JDBCDrivers.CONNECTION_POOL_DATA_SOURCE); 
                        className = dsEntry == null ? null : dsEntry.getValue();
                        if (className == null)
                            throw classNotFound(ConnectionPoolDataSource.class.getName(), packagesSearched, dataSourceID, null);
                    }
                }
            }

            return create(className, props, dataSourceID);
        } finally {
            lock.readLock().unlock();
        }
    }
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);
    }
  }
334342
public boolean setupDataSourceConnection(String strDataSource) throws DBException
    {
        if (m_JDBCConnection != null)
            return true;
        if ((DBConstants.TRUE.equalsIgnoreCase(this.getProperty(DBParams.SERVLET)))
                || ((this.getDatabaseOwner() != null) && (DBConstants.TRUE.equalsIgnoreCase(this.getDatabaseOwner().getEnvironment().getProperty(DBParams.SERVLET)))))
        {   // Datasource connections are only for servlets (NOTE: Letting this code run otherwise messes stuff up)
            try {
                if (m_initialContext == null)
                    m_initialContext = new InitialContext();
                String strDatabaseName = this.getDatabaseName(true);
                strDataSource = Utility.replace(strDataSource, "${dbname}", strDatabaseName);
                DataSource ds = (DataSource)m_initialContext.lookup(strDataSource);
                if (ds == null)
                    return false;   // Failure
                m_JDBCConnection = ds.getConnection();
            } catch (NamingException e) {
                return false;   // Failure
            } catch (SQLException e) {
                return false;   // Failure
            } catch (NoClassDefFoundError e) {
                return false;   // Failure
            } catch (Exception e) {
                return false;   // Failure
            }
            return true;    // Success!
        }
        else
            return false;   // Not supported
    }
173066
@JsonCreator
    public static Datasource datasource(final String ds) {
        int colonPos = ds.indexOf(":");
        int slashPos = ds.indexOf("/");

        String nodeAndPort = ds;
        String node;
        int port = -1;
        String resource = "";

        if (slashPos != -1) {
            nodeAndPort = ds.substring(0, slashPos);
            resource = ds.substring(slashPos+1);
        }
        if (colonPos != -1) {
            node = nodeAndPort.substring(0, colonPos);
            port = valueOf(nodeAndPort.substring(colonPos+1));
            return datasource(node, port, resource);
        } else {
            return datasource(nodeAndPort, -1, resource);
        }
    }
991203
public DatasourceConnection getDatasourceConnection(Config config, DataSource datasource, String user, String pass) throws PageException {
	config = ThreadLocalPageContext.getConfig(config);

	if (StringUtil.isEmpty(user)) {
	    user = datasource.getUsername();
	    pass = datasource.getPassword();
	}
	if (pass == null) pass = "";

	// get stack
	DCStack stack = getDCStack(datasource, user, pass);
	int max = datasource.getConnectionLimit();

	// get an existing connection
	DatasourceConnection rtn;
	boolean wait = false;
	outer: while (true) {
	    rtn = null;

	    // wait until it is again my turn
	    if (wait) {
		SystemUtil.wait(waiter, WAIT);
		wait = false;
	    }

	    synchronized (stack) {
		// do we have already to many open connections?
		if (max != -1) {
		    RefInteger _counter = stack.getCounter();// _getCounter(stack,datasource,user,pass);
		    if (max <= _counter.toInt()) {// go back ant wait
			wait = true;
			continue outer;
		    }
		}

		// get an existing connection
		while (!stack.isEmpty()) {
		    DatasourceConnection dc = (DatasourceConnection) stack.get();
		    if (dc != null) {
			rtn = dc;
			break;
		    }
		}

		_inc(stack, datasource, user, pass); // if new or fine we
						     // increase in any case
		// create a new instance
		if (rtn == null) {
		    try {
			rtn = loadDatasourceConnection(config, datasource, user, pass);
		    }
		    catch (PageException pe) {
			_dec(stack, datasource, user, pass);
			throw pe;
		    }
		    if (rtn instanceof DatasourceConnectionImpl) ((DatasourceConnectionImpl) rtn).using();
		    return rtn;
		}
	    }

	    // we get us a fine connection (we do validation outside the
	    // synchronized to safe shared time)
	    if (isValid(rtn, Boolean.TRUE)) {
		if (rtn instanceof DatasourceConnectionImpl) ((DatasourceConnectionImpl) rtn).using();
		return rtn;
	    }

	    // we have an invalid connection (above check failed), so we have to
	    // start over
	    synchronized (stack) {
		_dec(stack, datasource, user, pass); // we already did increment
						     // in case we are fine
		SystemUtil.notify(waiter);
	    }
	    IOUtil.closeEL(rtn.getConnection());
	    rtn = null;
	}
    }
179318
@Override
  public Connection getConnection() throws SQLException {
    return getConnection(
      new Callable<Connection>() {
        @Override
        public Connection call() throws SQLException {
          return MonitoringDataSource.this.original.getConnection();
        }
      },
      ".getConnection");
  }
910382
public Connection getConnection() throws SQLException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "getConnection : " + ivPuId);

        Connection result = new GenericConnection(ivPuId, ivDataSourceName);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "getConnection : " + result);

        return result;

    }
159509
@Override
    protected Object openConnection() throws ConnectionException {
        try {
            String dataSource = getDataSource();
            if (dataSource == null)
                throw new ConnectionException("Missing attribute: " + JDBC_DATASOURCE);

            DatabaseAccess dbAccess = new DatabaseAccess(dataSource);
            dbAccess.openConnection();
            return dbAccess;
        }
        catch (Exception ex) {
            throw new ConnectionException(ConnectionException.CONNECTION_DOWN, ex.getMessage(), ex);
        }
    }
64802
private static Connection getConnection(WorkspaceEntry wsEntry) throws DBCleanException
   {
      String dsName = getSourceNameParameter(wsEntry);

      DataSource ds;
      try
      {
         ds = (DataSource)new InitialContext().lookup(dsName);
      }
      catch (NamingException e)
      {
         throw new DBCleanException(e);
      }

      if (ds == null)
      {
         throw new DBCleanException("Data source " + dsName + " not found");
      }

      final DataSource dsF = ds;

      Connection jdbcConn;
      try
      {
         jdbcConn = SecurityHelper.doPrivilegedSQLExceptionAction(new PrivilegedExceptionAction<Connection>()
         {
            public Connection run() throws Exception
            {
               return dsF.getConnection();
            }
         });
      }
      catch (SQLException e)
      {
         throw new DBCleanException(e);
      }

      return jdbcConn;
   }
1309202
public Connection getConnection() throws SQLException {
        try {
            return new DrizzleConnection(new MySQLProtocol(hostname, port, database, null, null, new Properties()),
                    new DrizzleQueryFactory());
        } catch (QueryException e) {
            throw SQLExceptionMapper.get(e);
        }
    }
86988
public static ServiceAdapter<DataSource> forDataSource() {
		return new SimpleServiceAdapter<DataSource>(true, false) {
			@Override
			protected void start(DataSource instance) throws Exception {
				Connection connection = instance.getConnection();
				connection.close();
			}

			@Override
			protected void stop(DataSource instance) {
			}
		};
	}
753409
public void setDataSourceConnectionSource(ConnectionSource<DataSource, DataSourceSettings> connectionSource) {
        this.dataSourceName = connectionSource.getName();
        DataSource source = connectionSource.getSource();
        getProperties().put(Environment.DATASOURCE, source);
        getProperties().put(Environment.CURRENT_SESSION_CONTEXT_CLASS, GrailsSessionContext.class.getName());
        final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        if (contextClassLoader != null && contextClassLoader.getClass().getSimpleName().equalsIgnoreCase("RestartClassLoader")) {
            getProperties().put(AvailableSettings.CLASSLOADERS, contextClassLoader);
        } else {
            getProperties().put(AvailableSettings.CLASSLOADERS, connectionSource.getClass().getClassLoader());
        }
    }
708524
protected Stream<T> getAll(Connection conn) {
        return executeSelectAsStream(rowMapper, conn, true, calcSqlSelectAll());
    }
1102251
public static DB getConnection(String instance) {
        if(Objects.isNullOrEmpty(instance))
            instance = DEFAULT_INSTANCE;
        if(!connections.containsKey(instance)){
            initialize(instance);
        }
        return connections.get(instance);
    }
91053
public final Connection getConnection(final String dataSourceName) throws SQLException {
        return getConnections(ConnectionMode.MEMORY_STRICTLY, dataSourceName, 1).get(0);
    }