Binds the JNDI DataSource to proxy.

@throws SQLException
510900
protected synchronized void bindDataSource() throws SQLException {
    // we'll check in the synchronized section again (to prevent unnecessary reinitialization)
    if (null != realDataSource) {
      return;
    }

    final P6SpyLoadableOptions options = P6SpyOptions.getActiveInstance();

    // can be set when object is bound to JNDI, or
    // can be loaded from spy.properties
    if (rdsName == null) {
      rdsName = options.getRealDataSource();
    }
    if (rdsName == null) {
      throw new SQLException("P6DataSource: no value for Real Data Source Name, cannot perform jndi lookup");
    }

    // setup environment for the JNDI lookup
    Hashtable<String, String> env = null;
    String factory;

    if ((factory = options.getJNDIContextFactory()) != null) {
      env = new Hashtable<String, String>();
      env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
      String url = options.getJNDIContextProviderURL();
      if (url != null) {
        env.put(Context.PROVIDER_URL, url);
      }
      String custom = options.getJNDIContextCustom();
      if( custom != null ) {
        env.putAll(parseDelimitedString(custom));
      }
    }

    // lookup the real data source
    InitialContext ctx;
    try {
      if (env != null) {
        ctx = new InitialContext(env);
      } else {
        ctx = new InitialContext();
      }
      realDataSource = (CommonDataSource) ctx.lookup(rdsName);
    } catch (NamingException e) {
      throw new SQLException("P6DataSource: naming exception during jndi lookup of Real Data Source Name of '" + rdsName + "'. "
        + e.getMessage(), e);
    }

    // Set any properties that the spy.properties file contains
    // that are supported by set methods in this class
    Map<String, String> props = parseDelimitedString(options.getRealDataSourceProperties());
    if (props != null) {
      setDataSourceProperties(props);
    }

    if (realDataSource == null) {
      throw new SQLException("P6DataSource: jndi lookup for Real Data Source Name of '" + rdsName + "' failed, cannot bind named data source.");
    }
  }
37376
@Bean
    public DataSource dataSource() throws SQLException {
        Preconditions.checkState(isValidConfiguration(), "The orchestration configuration is invalid, please choose one from Sharding rule and Master-slave rule.");
        return isShardingRule() ? createShardingDataSource() : createMasterSlaveDataSource();
    }
454668
public ConnectedCrud<T, K> to(DataSource dataSource) throws SQLException {
        Connection connection = dataSource.getConnection();
        try {
            return new ConnectedCrud<T, K>(new DataSourceTransactionTemplate(dataSource), to(connection));
        } finally {
            connection.close();
        }
    }
1330708
private synchronized void open() throws DatabaseException {
        try {
            if (!isOpen()) {
                connection = connectionFactory.getConnection();
                final String databaseProductName = determineDatabaseProductName(this.connection);
                statementBundle = databaseProductName != null
                        ? ResourceBundle.getBundle("data/dbStatements", new Locale(databaseProductName))
                        : ResourceBundle.getBundle("data/dbStatements");
                prepareStatements();
                databaseProperties = new DatabaseProperties(this);
            }
        } catch (DatabaseException e) {
            releaseResources();
            throw e;
        }
    }
985863
void performPostExecute() throws SQLException {

        resultOut.clearLobResults();

        generatedResult = null;

        if (resultIn == null) {
            return;
        }

        Result current = resultIn;

        while (current.getChainedResult() != null) {
            current = current.getUnlinkChainedResult();

            if (current.getType() == ResultConstants.WARNING) {
                SQLWarning w = Util.sqlWarning(current);

                if (rootWarning == null) {
                    rootWarning = w;
                } else {
                    rootWarning.setNextWarning(w);
                }
            } else if (current.getType() == ResultConstants.ERROR) {
                errorResult = current;
            } else if (current.getType() == ResultConstants.DATA) {
                generatedResult = current;
            }
        }

        if (resultIn.isData()) {
            currentResultSet = new JDBCResultSet(connection.sessionProxy,
                    this, resultIn, resultIn.metaData,
                    connection.connProperties);
        }
    }
315169
public void setDatasource(Object datasource) throws PageException, ClassException, BundleException {
	if (datasource == null) return;
	data.rawDatasource = datasource;
	data.datasource = toDatasource(pageContext, datasource);
    }
996121
void setDataSourceLogWriter(PrintWriter writer) throws SQLException {
      for(ConnectionPoolSegment segment : segments) {
         if(segment.dbConnection.datasource != null) {
            segment.dbConnection.datasource.setLogWriter(writer);
         }
      }
   }
983416
public void initializeExtensions() throws SQLException {
        if (extensionsNeedInitialization) {
            for (EmbeddedDbExtension ext : MdwServiceRegistry.getInstance().getEmbeddedDbExtensions()) {
                logger.info("Initializing embedded db extension: " + ext);
                List<String> sources = ext.getSqlSourceAssets();
                if (sources != null) {
                    try {
                        for (String source : sources) {
                            String assetPath = source;
                            if (source.indexOf('/') == -1)
                                assetPath = ext.getClass().getPackage().getName() + "/" + source;
                            logger.info("Sourcing asset sql script: " + assetPath);
                            String contents = AssetCache.getAsset(assetPath).getStringContent();
                            embeddedDb.source(contents);
                        }
                    }
                    catch (Exception ex) {
                        throw new SQLException("Error processing db extension " + ext.getClass(), ex);
                    }
                }
                ext.initialize();
            }
            extensionsNeedInitialization = false;
        }
    }
9732
private void doGetDatasource() throws PageException {

	String name = getString("admin", action, "name");
	Map ds = config.getDataSourcesAsMap();
	Iterator it = ds.keySet().iterator();

	while (it.hasNext()) {
	    String key = (String) it.next();
	    if (key.equalsIgnoreCase(name)) {
		DataSource d = (DataSource) ds.get(key);
		Struct sct = new StructImpl();
		ClassDefinition cd = d.getClassDefinition();

		sct.setEL(KeyConstants._name, key);
		sct.setEL(KeyConstants._host, d.getHost());
		sct.setEL("classname", cd.getClassName());
		sct.setEL("class", cd.getClassName());
		sct.setEL("bundleName", cd.getName());
		sct.setEL("bundleVersion", cd.getVersionAsString());
		sct.setEL("dsn", d.getDsnOriginal());
		sct.setEL("database", d.getDatabase());
		sct.setEL("port", d.getPort() < 1 ? "" : Caster.toString(d.getPort()));
		sct.setEL("dsnTranslated", d.getDsnTranslated());
		sct.setEL("timezone", toStringTimeZone(d.getTimeZone()));
		sct.setEL("password", d.getPassword());
		sct.setEL("passwordEncrypted", ConfigWebUtil.encrypt(d.getPassword()));
		sct.setEL("username", d.getUsername());
		sct.setEL("readonly", Caster.toBoolean(d.isReadOnly()));
		sct.setEL("select", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_SELECT)));
		sct.setEL("delete", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DELETE)));
		sct.setEL("update", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_UPDATE)));
		sct.setEL("insert", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT)));
		sct.setEL("create", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_CREATE)));
		sct.setEL("insert", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT)));
		sct.setEL("drop", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DROP)));
		sct.setEL("grant", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_GRANT)));
		sct.setEL("revoke", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_REVOKE)));
		sct.setEL("alter", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_ALTER)));

		sct.setEL("connectionLimit", d.getConnectionLimit() < 1 ? "-1" : Caster.toString(d.getConnectionLimit()));
		sct.setEL("connectionTimeout", d.getConnectionTimeout() < 1 ? "" : Caster.toString(d.getConnectionTimeout()));
		sct.setEL("metaCacheTimeout", Caster.toDouble(d.getMetaCacheTimeout()));
		sct.setEL("custom", d.getCustoms());
		sct.setEL("blob", Boolean.valueOf(d.isBlob()));
		sct.setEL("clob", Boolean.valueOf(d.isClob()));
		sct.setEL("validate", Boolean.valueOf(d.validate()));
		sct.setEL("storage", Boolean.valueOf(d.isStorage()));
		if (d instanceof DataSourceImpl) {
		    DataSourceImpl di = ((DataSourceImpl) d);
		    sct.setEL("literalTimestampWithTSOffset", Boolean.valueOf(di.getLiteralTimestampWithTSOffset()));
		    sct.setEL("alwaysSetTimeout", Boolean.valueOf(di.getAlwaysSetTimeout()));

		    sct.setEL("dbdriver", Caster.toString(di.getDbDriver(), ""));
		}
		pageContext.setVariable(getString("admin", action, "returnVariable"), sct);
		return;
	    }
	}
	throw new ApplicationException("there is no datasource with name [" + name + "]");
    }
518249
public static Connection getConnection(String source) throws SQLException {
		DataSource ds = getDataSource(source);
		if (ds == null){
			throw new SQLException("ConnectionUtility cannot get data source: " + source);
		}
		return ds.getConnection();
	}
1306015
public void setDatasourceParams(JdbcDatabase database, ComboPooledDataSource dataSource)
    {
        if (dataSource != null)
        {   // Try pooled connection first
	        String strURL = database.getProperty(SQLParams.JDBC_URL_PARAM);
	        if ((strURL == null) || (strURL.length() == 0))
	            strURL = database.getProperty(SQLParams.DEFAULT_JDBC_URL_PARAM);    // Default
	        String strServer = database.getProperty(SQLParams.DB_SERVER_PARAM);
	        if ((strServer == null) || (strServer.length() == 0))
	            strServer = database.getProperty(SQLParams.DEFAULT_DB_SERVER_PARAM);    // Default
	        if ((strServer == null) || (strServer.length() == 0))
	            strServer = "localhost"; //this.getProperty(DBParams.SERVER);    // ??       
	        String strDatabaseName = database.getDatabaseName(true);
	        if (strURL != null)
	        {
	            if (strServer != null)
	                strURL = Utility.replace(strURL, "{dbserver}", strServer);
	            strURL = Utility.replace(strURL, "{dbname}", strDatabaseName);
	        }
	        String strUsername = database.getProperty(SQLParams.USERNAME_PARAM);
	        if ((strUsername == null) || (strUsername.length() == 0))
	            strUsername = database.getProperty(SQLParams.DEFAULT_USERNAME_PARAM); // Default
	        String strPassword = database.getProperty(SQLParams.PASSWORD_PARAM);
	        if ((strPassword == null) || (strPassword.length() == 0))
	            strPassword = database.getProperty(SQLParams.DEFAULT_PASSWORD_PARAM); // Default
	        
	        String strDriver = database.getProperty(SQLParams.JDBC_DRIVER_PARAM);
	
	    	try {
				dataSource.setDriverClass(strDriver); //loads the jdbc driver            
			} catch (PropertyVetoException e) {
				e.printStackTrace();
			}
	//        dataSource.setDatabaseName(strDatabaseName);
	//        if (strServer != null)
	//            dataSource.setServerName(strServer);
	//        else
	            dataSource.setJdbcUrl(strURL);
	        dataSource.setUser (strUsername);
	        dataSource.setPassword (strPassword);
	        
        	// the settings below are optional -- c3p0 can work with defaults
//?        	dataSource.setMinPoolSize(5);                                     
//?        	dataSource.setAcquireIncrement(5);
//?        	dataSource.setMaxPoolSize(20);
            //xMiniConnectionPoolManager poolMgr = new MiniConnectionPoolManager(poolDataSource, MAX_POOLED_CONNECTIONS, POOL_TIMEOUT);

        }
    }
1264088
private void doVerifyDatasource() throws PageException {
	ClassDefinition cd = new ClassDefinitionImpl(Caster.toString(attributes.get("classname", null), null), Caster.toString(attributes.get("bundleName", null), null),
		Caster.toString(attributes.get("bundleVersion", null), null), config.getIdentification());

	String connStr = (String) attributes.get("connStr", null);
	if (StringUtil.isEmpty(connStr)) connStr = (String) attributes.get("dsn", null);
	if (cd.hasClass() && connStr != null) {
	    _doVerifyDatasource(cd, connStr, getString("admin", action, "dbusername"), getString("admin", action, "dbpassword"));
	}
	else {
	    _doVerifyDatasource(getString("admin", action, "name"), getString("admin", action, "dbusername"), getString("admin", action, "dbpassword"));
	}
    }
374555
public static void load(Connection connection) throws SQLException {
        Statement st = connection.createStatement();
        for (Function function : getBuiltInsFunctions()) {
            try {
                H2GISFunctions.registerFunction(st, function, "");
            } catch (SQLException ex) {
                // Catch to register other functions
                LOGGER.error(ex.getLocalizedMessage(), ex);
            }
        }
    }
531242
public DataSource createDataSourceFromConnectionInfo(final ConnectionInfo connectionInfo) throws SQLException
    {
        final PGSimpleDataSource ds = new PGSimpleDataSource();
        ds.setPortNumber(connectionInfo.getPort());
        ds.setDatabaseName(connectionInfo.getDbName());
        ds.setUser(connectionInfo.getUser());
        return ds;
    }
308503
public static DataSource createDataSource(Properties poolProperties) throws SQLException {
        try {
            return MidaoFrameworkPoolBinder.createDataSource(poolProperties);
        } catch (NoClassDefFoundError ex) {
            throw new NoClassDefFoundError(ERROR_COULDNT_FIND_POOL_PROVIDER);
        }
    }
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
    }
542393
protected void initDataSource() {
    if (dataSource == null) {
      if (dataSourceJndiName != null) {
        try {
          dataSource = (DataSource) new InitialContext().lookup(dataSourceJndiName);
        } catch (Exception e) {
          throw new ProcessEngineException("couldn't lookup datasource from " + dataSourceJndiName + ": " + e.getMessage(), e);
        }

      } else if (jdbcUrl != null) {
        if ((jdbcDriver == null) || (jdbcUrl == null) || (jdbcUsername == null)) {
          throw new ProcessEngineException("DataSource or JDBC properties have to be specified in a process engine configuration");
        }

        PooledDataSource pooledDataSource =
            new PooledDataSource(ReflectUtil.getClassLoader(), jdbcDriver, jdbcUrl, jdbcUsername, jdbcPassword);

        if (jdbcMaxActiveConnections > 0) {
          pooledDataSource.setPoolMaximumActiveConnections(jdbcMaxActiveConnections);
        }
        if (jdbcMaxIdleConnections > 0) {
          pooledDataSource.setPoolMaximumIdleConnections(jdbcMaxIdleConnections);
        }
        if (jdbcMaxCheckoutTime > 0) {
          pooledDataSource.setPoolMaximumCheckoutTime(jdbcMaxCheckoutTime);
        }
        if (jdbcMaxWaitTime > 0) {
          pooledDataSource.setPoolTimeToWait(jdbcMaxWaitTime);
        }
        if (jdbcPingEnabled == true) {
          pooledDataSource.setPoolPingEnabled(true);
          if (jdbcPingQuery != null) {
            pooledDataSource.setPoolPingQuery(jdbcPingQuery);
          }
          pooledDataSource.setPoolPingConnectionsNotUsedFor(jdbcPingConnectionNotUsedFor);
        }
        dataSource = pooledDataSource;
      }

      if (dataSource instanceof PooledDataSource) {
        // ACT-233: connection pool of Ibatis is not properely initialized if this is not called!
        ((PooledDataSource) dataSource).forceCloseAll();
      }
    }

    if (databaseType == null) {
      initDatabaseType();
    }
  }