Example usage for org.apache.commons.dbcp BasicDataSource setDefaultReadOnly

List of usage examples for org.apache.commons.dbcp BasicDataSource setDefaultReadOnly

Introduction

In this page you can find the example usage for org.apache.commons.dbcp BasicDataSource setDefaultReadOnly.

Prototype

public synchronized void setDefaultReadOnly(boolean defaultReadOnly) 

Source Link

Document

Sets defaultReadonly property.

Note: this method currently has no effect once the pool has been initialized.

Usage

From source file:com.googlecode.wmbutil.cache.LookupDataSourceFactory.java

public static synchronized LookupDataSource getDataSource() throws CacheRefreshException {
    if (dataSource == null) {
        try {//from  ww w. ja  v  a  2  s .  com
            Properties config = new Properties();
            config.load(new FileInputStream("lookup-connection.properties"));

            BasicDataSource ds = new BasicDataSource();
            ds.setDriverClassName(config.getProperty("lookup.class"));
            ds.setUrl(config.getProperty("lookup.url"));
            ds.setUsername(config.getProperty("lookup.username"));
            ds.setPassword(config.getProperty("lookup.password"));
            ds.setDefaultReadOnly(false);

            dataSource = new JdbcLookupDataSource(ds);
        } catch (FileNotFoundException e) {
            throw new CacheRefreshException("Could not find lookup-connection.properties file", e);
        } catch (IOException e) {
            throw new CacheRefreshException("Found, but could not read from lookup-connection.properties file",
                    e);
        } catch (RuntimeException e) {
            throw new CacheRefreshException("Could not create data source", e);
        }
    }

    return dataSource;
}

From source file:com.pinterest.deployservice.db.DatabaseUtil.java

/**
 * Create a MySQL datasource./*from   w  w w .  j a  va2s .c  o  m*/
 *
 * @param url             the url of the DB.
 * @param user            the user name to connect to MySQL as.
 * @param passwd          the password for the corresponding MySQL user.
 * @param poolSize        the connection pool size string, in the format of
 *                        initialSize:maxActive:maxIdle:minIdle.
 * @param maxWaitInMillis the max wait time in milliseconds to get a connection from the pool.
 * @return a BasicDataSource for the target MySQL instance.
 */
public static BasicDataSource createDataSource(String driverClassName, String url, String user, String passwd,
        String poolSize, int maxWaitInMillis) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(passwd);
    dataSource.setDefaultAutoCommit(true);
    dataSource.setDefaultReadOnly(false);

    // poolSize parsing, the poolsize string passed in the following format
    // initialSize:maxActive:maxIdle:minIdle
    String[] sizeStrs = poolSize.split(":");
    dataSource.setInitialSize(Integer.parseInt(sizeStrs[0]));
    dataSource.setMaxActive(Integer.parseInt(sizeStrs[1]));
    dataSource.setMaxIdle(Integer.parseInt(sizeStrs[2]));
    dataSource.setMinIdle(Integer.parseInt(sizeStrs[3]));

    dataSource.setValidationQuery("SELECT 1");
    dataSource.setTestOnBorrow(true);
    dataSource.setTestOnReturn(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setMinEvictableIdleTimeMillis(5 * 60 * 1000);
    dataSource.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000);
    // dataSource.setNumTestsPerEvictionRun(3);
    // max wait in milliseconds for a connection.
    dataSource.setMaxWait(maxWaitInMillis);

    // force connection pool initialization.
    Connection conn = null;
    try {
        // Here not getting the connection from ThreadLocal no need to worry about that.
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        LOG.error(String.format("Failed to get a db connection when creating DataSource, url = %s", url), e);
    } finally {
        DbUtils.closeQuietly(conn);
    }
    return dataSource;
}

From source file:fr.cnes.sitools.datasource.jdbc.business.SitoolsDataSourceFactory.java

/**
 * Setup a dataSource for "users". Usage is for all users for consultation functions.
 * //from w w  w  . j  a v  a2  s .  co  m
 * @param dataSource
 *          the DataSource to update
 * @return SitoolsDataSource the new DataSource
 */
public SitoolsDataSource setupDataSourceForUsers(JDBCDataSource dataSource) {
    String key = dataSource.getId();
    SitoolsDataSource foundDatasource = dataSources.get(key);
    if (foundDatasource == null) {

        BasicDataSource ds = new BasicDataSource();
        // OSGi
        ds.setDriverClassLoader(getClass().getClassLoader());
        ds.setDriverClassName(dataSource.getDriverClass());
        ds.setUsername(dataSource.getUserLogin());
        ds.setPassword(dataSource.getUserPassword());
        ds.setUrl(dataSource.getUrl());
        ds.setMaxActive(dataSource.getMaxActive());
        ds.setInitialSize(dataSource.getInitialSize());
        ds.setDefaultReadOnly(true);
        if ((dataSource.getSchemaOnConnection() != null) && !dataSource.getSchemaOnConnection().equals("")) {
            ds.setDefaultCatalog(dataSource.getSchemaOnConnection());
        }
        foundDatasource = new SitoolsDataSource(dataSource, ds, dataSource.getSchemaOnConnection());
        dataSources.put(key, foundDatasource);
    }
    return foundDatasource;
}

From source file:fr.cnes.sitools.datasource.jdbc.business.SitoolsSQLDataSourceFactory.java

/**
 * Setup a dataSource for "users". Usage is for all users for consultation functions.
 * //from www.  j  a v a  2s. com
 * @param dataSource
 *          the DataSource to update
 * @return SitoolsDataSource the new DataSource
 */
public SitoolsSQLDataSource setupDataSourceForUsers(JDBCDataSource dataSource) {
    String key = dataSource.getId();
    SitoolsSQLDataSource foundDatasource = dataSources.get(key);
    if (foundDatasource == null) {

        BasicDataSource ds = new BasicDataSource();
        // OSGi
        ds.setDriverClassLoader(getClass().getClassLoader());
        ds.setDriverClassName(dataSource.getDriverClass());
        ds.setUsername(dataSource.getUserLogin());
        ds.setPassword(dataSource.getUserPassword());
        ds.setUrl(dataSource.getUrl());
        ds.setMaxActive(dataSource.getMaxActive());
        ds.setInitialSize(dataSource.getInitialSize());
        ds.setDefaultReadOnly(true);
        // test that the connection is alive on each request. If not It will be dropped from the pool and another
        // connection will be created
        ds.setTestOnBorrow(true);
        ds.setValidationQuery("SELECT 1");
        if ((dataSource.getSchemaOnConnection() != null) && !dataSource.getSchemaOnConnection().equals("")) {
            ds.setDefaultCatalog(dataSource.getSchemaOnConnection());
        }
        foundDatasource = new SitoolsSQLDataSource(dataSource, ds, dataSource.getSchemaOnConnection());
        dataSources.put(key, foundDatasource);
    }
    return foundDatasource;
}

From source file:com.bstek.dorado.core.store.SqlBaseStoreSupport.java

protected synchronized DataSource getDataSource() throws Exception {
    if (dataSource != null) {
        return dataSource;
    }/*from   ww  w .  j a  va  2s . co m*/

    if (StringUtils.isBlank(namespace)) {
        throw new IllegalArgumentException("The namespace of store cannot be empty. ");
    }

    prepareNamespace();

    BasicDataSource pds = new BasicDataSource();
    dataSource = pds;

    pds.setDriverClassName(driverClassName);
    pds.setUrl(getConnectionUrl());
    pds.setUsername(username);
    pds.setPassword(password);
    pds.setDefaultCatalog(defaultCatalog);

    if (defaultAutoCommit != null) {
        pds.setDefaultAutoCommit(defaultAutoCommit.booleanValue());
    }
    if (defaultReadOnly != null) {
        pds.setDefaultReadOnly(defaultReadOnly.booleanValue());
    }
    if (defaultTransactionIsolation != null) {
        pds.setDefaultTransactionIsolation(defaultTransactionIsolation.intValue());
    }
    if (maxActive != null) {
        pds.setMaxActive(maxActive.intValue());
    }
    if (maxIdle != null) {
        pds.setMaxIdle(maxIdle.intValue());
    }
    if (minIdle != null) {
        pds.setMinIdle(minIdle.intValue());
    }
    if (initialSize != null) {
        pds.setInitialSize(initialSize.intValue());
    }
    if (maxWait != null) {
        pds.setMaxWait(maxWait.longValue());
    }
    if (timeBetweenEvictionRunsMillis != null) {
        pds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis.longValue());
    }
    if (minEvictableIdleTimeMillis != null) {
        pds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis.longValue());
    }
    return dataSource;
}

From source file:binky.reportrunner.service.impl.DatasourceServiceImpl.java

private DataSource getDs(RunnerDataSource runnerDs)
        throws SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException,
        PropertyVetoException, NamingException, EncryptionException {

    final String jndiDataSource = runnerDs.getJndiName();

    if (StringUtils.isBlank(jndiDataSource)) {
        EncryptionUtil enc = new EncryptionUtil();
        logger.info("using dbcp pooled connection for: " + runnerDs.getDataSourceName());

        String jdbcUser = runnerDs.getUsername();
        if (StringUtils.isBlank(runnerDs.getPassword()))
            throw new SecurityException("password is empty");
        String jdbcPassword = enc.decrpyt(secureKey, runnerDs.getPassword());

        String jdbcUrl = runnerDs.getJdbcUrl();
        String databaseDriver = runnerDs.getJdbcClass();

        Class.forName(databaseDriver).newInstance();

        BasicDataSource ds1 = new BasicDataSource();
        ds1.setDriverClassName(databaseDriver);
        ds1.setUrl(jdbcUrl);/*from  w w  w . ja  v a  2s  .  c o m*/
        ds1.setUsername(jdbcUser);
        ds1.setPassword(jdbcPassword);
        ds1.setInitialSize(runnerDs.getInitialPoolSize());
        ds1.setMaxActive(runnerDs.getMaxPoolSize());

        ds1.setRemoveAbandoned(true);
        ds1.setRemoveAbandonedTimeout(600);

        // do not want anything updating anything
        ds1.setDefaultReadOnly(true);

        ds1.setLogAbandoned(true);
        ds1.setTestOnBorrow(true);
        ds1.setTestOnReturn(true);
        ds1.setTestWhileIdle(true);

        // does this work across all RBMS? - no it doesn't
        //ds1.setValidationQuery("select 1");
        //ds1.setValidationQueryTimeout(300);

        return ds1;
    } else {
        logger.info(
                "getting datasource from JNDI url: " + jndiDataSource + " for " + runnerDs.getDataSourceName());
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup("java:/comp/env/" + jndiDataSource);
        return ds;
    }
}

From source file:jetsennet.orm.datasource.DbcpDataSourceCreator.java

@Override
public DataSource createDatasource(ConnectionInfo conn, DbPoolInfo props) throws SQLException {
    org.apache.commons.dbcp.BasicDataSource dataSource = new org.apache.commons.dbcp.BasicDataSource();
    dataSource.setDriverClassName(conn.driver);
    dataSource.setUrl(conn.url);/*w ww  .  j a  va  2s . co m*/
    dataSource.setUsername(conn.user);
    dataSource.setPassword(conn.pwd);

    String connectionProperties = props.get("connectionProperties");
    if (connectionProperties != null && connectionProperties.trim().length() > 0) {
        dataSource.setConnectionProperties(connectionProperties);
    }
    Boolean defaultAutoCommit = Utils.str2Boolean(props.get("defaultAutoCommit"));
    if (defaultAutoCommit != null) {
        dataSource.setDefaultAutoCommit(defaultAutoCommit);
    }
    Boolean defaultReadOnly = Utils.str2Boolean(props.get("defaultReadOnly"));
    if (defaultReadOnly != null) {
        dataSource.setDefaultReadOnly(defaultReadOnly);
    }
    Integer defaultTransactionIsolation = Utils.strToInteger(props.get("defaultTransactionIsolation"));
    if (defaultTransactionIsolation != null) {
        dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
    }
    String defaultCatalog = props.get("defaultCatalog");
    if (defaultCatalog != null && defaultCatalog.trim().length() > 0) {
        dataSource.setDefaultCatalog(defaultCatalog);
    }

    int initialSize = Utils.strToInt(props.get("initialSize"));
    if (initialSize > 0) {
        dataSource.setInitialSize(initialSize);
    }
    int maxActive = Utils.strToInt(props.get("maxActive"));
    if (maxActive > 0) {
        dataSource.setMaxActive(maxActive);
    }
    int maxIdle = Utils.strToInt(props.get("maxIdle"));
    if (maxIdle > 0) {
        dataSource.setMaxIdle(maxIdle);
    }
    int minIdle = Utils.strToInt(props.get("minIdle"));
    if (minIdle > 0) {
        dataSource.setMinIdle(minIdle);
    }
    int maxWait = Utils.strToInt(props.get("maxWait"));
    if (maxWait > 0) {
        dataSource.setMaxWait(maxWait);
    }

    String validationQuery = props.get("validationQuery");
    if (validationQuery != null && validationQuery.trim().length() > 0) {
        dataSource.setValidationQuery(validationQuery);
    }
    Integer validationQueryTimeout = Utils.strToInteger(props.get("validationQueryTimeout"));
    if (validationQueryTimeout != null) {
        dataSource.setValidationQueryTimeout(validationQueryTimeout);
    }
    Boolean testOnBorrow = Utils.str2Boolean(props.get("testOnBorrow"));
    if (testOnBorrow != null) {
        dataSource.setTestOnBorrow(testOnBorrow);
    }
    Boolean testOnReturn = Utils.str2Boolean(props.get("testOnReturn"));
    if (testOnReturn != null) {
        dataSource.setTestOnReturn(testOnReturn);
    }
    Boolean testWhileIdle = Utils.str2Boolean(props.get("testWhileIdle"));
    if (testWhileIdle != null) {
        dataSource.setTestWhileIdle(testWhileIdle);
    }
    Integer timeBetweenEvictionRunsMillis = Utils.strToInteger(props.get("timeBetweenEvictionRunsMillis"));
    if (timeBetweenEvictionRunsMillis != null) {
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    }
    Integer numTestsPerEvictionRun = Utils.strToInteger(props.get("numTestsPerEvictionRun"));
    if (numTestsPerEvictionRun != null) {
        dataSource.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    }
    int minEvictableIdleTimeMillis = Utils.strToInt(props.get("minEvictableIdleTimeMillis"));
    if (minEvictableIdleTimeMillis > 0) {
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    }

    Boolean removeAbandoned = Utils.str2Boolean(props.get("removeAbandoned"));
    if (removeAbandoned != null) {
        dataSource.setRemoveAbandoned(removeAbandoned);
    }
    int removeAbandonedTimeout = Utils.strToInt(props.get("removeAbandonedTimeout"));
    if (removeAbandonedTimeout > 0) {
        dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
    }
    Boolean logAbandoned = Utils.str2Boolean(props.get("logAbandoned"));
    if (logAbandoned != null) {
        dataSource.setLogAbandoned(logAbandoned);
    }
    return dataSource;
}

From source file:com.googlecode.wmbutil.jdbc.DataSourceLocator.java

/**
 * Looks up a named data source// ww w.ja  v  a2 s .co  m
 * 
 * @param dataSourceName
 *            The name of the data source to look for
 * @return The data source
 * @throws RuntimeException
 *             If the configuration can not be loaded or the data source
 *             definition is missing
 */
public synchronized DataSource lookup(String dataSourceName) {
    BasicDataSource ds;
    if (dataSources.containsKey(dataSourceName)) {
        ds = (BasicDataSource) dataSources.get(dataSourceName);

        if (ds == null) {
            // we failed to create it earlier
            throw new RuntimeException("Failed to create data source");
        }
    } else {
        ds = new BasicDataSource();

        try {
            String driver = config.getProperty("jdbc." + dataSourceName + ".class");
            if (driver == null || driver.trim().length() == 0) {
                throw new RuntimeException("Lookup connections configuration file must contain a jdbc."
                        + dataSourceName + ".class value");
            } else {
                ds.setDriverClassName(driver);
            }

            String url = config.getProperty("jdbc." + dataSourceName + ".url");
            if (url == null || url.trim().length() == 0) {
                throw new RuntimeException("Lookup connections configuration file must contain a jdbc."
                        + dataSourceName + ".url value");
            } else {
                ds.setUrl(url);
            }

            String username = config.getProperty("jdbc." + dataSourceName + ".username");
            if (username == null || username.trim().length() == 0) {
                throw new RuntimeException("Lookup connections configuration file must contain a jdbc."
                        + dataSourceName + ".username value");
            } else {
                ds.setUsername(username);
            }

            ds.setPassword(config.getProperty("jdbc." + dataSourceName + ".password"));
            ds.setDefaultReadOnly(true);

            dataSources.put(dataSourceName, ds);
        } catch (RuntimeException e) {
            // mark failed to create
            dataSources.put(dataSourceName, null);
            throw e;
        }
    }

    return ds;

}

From source file:org.apache.synapse.commons.datasource.factory.DataSourceFactory.java

/**
 * Factory method to create a DataSource based on provided information
 * which is encapsulated in the DataSourceInformation object.
 *
 * @param dataSourceInformation Information about DataSource
 * @return DataSource Instance if one can be created ,
 *         otherwise null or exception if provided details are not valid or enough to create
 *         a DataSource/*from  www  .  ja va 2 s  . co  m*/
 */
public static DataSource createDataSource(DataSourceInformation dataSourceInformation) {

    String dsType = dataSourceInformation.getType();
    String driver = dataSourceInformation.getDriver();

    if (driver == null || "".equals(driver)) {
        handleException("Database driver class name cannot be found.");
    }

    String url = dataSourceInformation.getUrl();

    if (url == null || "".equals(url)) {
        handleException("Database connection URL cannot be found.");
    }

    String user = dataSourceInformation.getSecretInformation().getUser();
    String password = dataSourceInformation.getSecretInformation().getResolvedSecret();

    int defaultTransactionIsolation = dataSourceInformation.getDefaultTransactionIsolation();

    if (DataSourceInformation.BASIC_DATA_SOURCE.equals(dsType)) {

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(driver);
        basicDataSource.setUrl(url);

        if (user != null && !"".equals(user)) {
            basicDataSource.setUsername(user);
        }

        if (password != null && !"".equals(password)) {
            basicDataSource.setPassword(password);
        }

        basicDataSource.setMaxActive(dataSourceInformation.getMaxActive());
        basicDataSource.setMaxIdle(dataSourceInformation.getMaxIdle());
        basicDataSource.setMaxWait(dataSourceInformation.getMaxWait());
        basicDataSource.setMinIdle(dataSourceInformation.getMinIdle());
        basicDataSource.setDefaultAutoCommit(dataSourceInformation.isDefaultAutoCommit());
        basicDataSource.setDefaultReadOnly(dataSourceInformation.isDefaultReadOnly());
        basicDataSource.setTestOnBorrow(dataSourceInformation.isTestOnBorrow());
        basicDataSource.setTestOnReturn(dataSourceInformation.isTestOnReturn());
        basicDataSource.setTestWhileIdle(dataSourceInformation.isTestWhileIdle());
        basicDataSource.setMinEvictableIdleTimeMillis(dataSourceInformation.getMinEvictableIdleTimeMillis());
        basicDataSource
                .setTimeBetweenEvictionRunsMillis(dataSourceInformation.getTimeBetweenEvictionRunsMillis());
        basicDataSource.setNumTestsPerEvictionRun(dataSourceInformation.getNumTestsPerEvictionRun());
        basicDataSource.setMaxOpenPreparedStatements(dataSourceInformation.getMaxOpenPreparedStatements());
        basicDataSource.setAccessToUnderlyingConnectionAllowed(
                dataSourceInformation.isAccessToUnderlyingConnectionAllowed());
        basicDataSource.setInitialSize(dataSourceInformation.getInitialSize());
        basicDataSource.setPoolPreparedStatements(dataSourceInformation.isPoolPreparedStatements());

        if (defaultTransactionIsolation != -1) {
            basicDataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
        }

        String defaultCatalog = dataSourceInformation.getDefaultCatalog();
        if (defaultCatalog != null && !"".equals(defaultCatalog)) {
            basicDataSource.setDefaultCatalog(defaultCatalog);
        }

        String validationQuery = dataSourceInformation.getValidationQuery();

        if (validationQuery != null && !"".equals(validationQuery)) {
            basicDataSource.setValidationQuery(validationQuery);
        }

        return basicDataSource;

    } else if (DataSourceInformation.PER_USER_POOL_DATA_SOURCE.equals(dsType)) {

        DriverAdapterCPDS adapterCPDS = new DriverAdapterCPDS();

        try {
            adapterCPDS.setDriver(driver);
        } catch (ClassNotFoundException e) {
            handleException("Error setting driver : " + driver + " in DriverAdapterCPDS", e);
        }

        adapterCPDS.setUrl(url);

        if (user != null && !"".equals(user)) {
            adapterCPDS.setUser(user);
        }

        if (password != null && !"".equals(password)) {
            adapterCPDS.setPassword(password);
        }

        adapterCPDS.setPoolPreparedStatements(dataSourceInformation.isPoolPreparedStatements());
        adapterCPDS.setMaxIdle(dataSourceInformation.getMaxIdle());

        PerUserPoolDataSource perUserPoolDataSource = new PerUserPoolDataSource();
        perUserPoolDataSource.setConnectionPoolDataSource(adapterCPDS);

        perUserPoolDataSource.setDefaultMaxActive(dataSourceInformation.getMaxActive());
        perUserPoolDataSource.setDefaultMaxIdle(dataSourceInformation.getMaxIdle());
        perUserPoolDataSource.setDefaultMaxWait((int) dataSourceInformation.getMaxWait());
        perUserPoolDataSource.setDefaultAutoCommit(dataSourceInformation.isDefaultAutoCommit());
        perUserPoolDataSource.setDefaultReadOnly(dataSourceInformation.isDefaultReadOnly());
        perUserPoolDataSource.setTestOnBorrow(dataSourceInformation.isTestOnBorrow());
        perUserPoolDataSource.setTestOnReturn(dataSourceInformation.isTestOnReturn());
        perUserPoolDataSource.setTestWhileIdle(dataSourceInformation.isTestWhileIdle());
        perUserPoolDataSource
                .setMinEvictableIdleTimeMillis((int) dataSourceInformation.getMinEvictableIdleTimeMillis());
        perUserPoolDataSource.setTimeBetweenEvictionRunsMillis(
                (int) dataSourceInformation.getTimeBetweenEvictionRunsMillis());
        perUserPoolDataSource.setNumTestsPerEvictionRun(dataSourceInformation.getNumTestsPerEvictionRun());

        if (defaultTransactionIsolation != -1) {
            perUserPoolDataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
        }

        String validationQuery = dataSourceInformation.getValidationQuery();

        if (validationQuery != null && !"".equals(validationQuery)) {
            perUserPoolDataSource.setValidationQuery(validationQuery);
        }

        return perUserPoolDataSource;

    } else {
        handleException("Unsupported DataSource : " + dsType);
    }
    return null;
}