Search in sources :

Example 26 with BasicDataSource

use of org.apache.commons.dbcp.BasicDataSource in project opentheso by miledrousset.

the class BaseHelper method buildDataSource.

/**
 * @param user
 * @param passwd
 * @param url
 * @param maxActive
 * @param maxIdle
 * @param maxWait
 * @return
 */
public static BasicDataSource buildDataSource(String user, String passwd, String url, int maxActive, int maxIdle, long maxWait) {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.postgresql.Driver");
    ds.setUsername(user);
    ds.setPassword(passwd);
    ds.setUrl(url);
    // Tweaking pool
    ds.setMaxActive(maxActive);
    ds.setMaxIdle(maxIdle);
    ds.setMaxWait(maxWait);
    return ds;
}
Also used : BasicDataSource(org.apache.commons.dbcp.BasicDataSource)

Example 27 with BasicDataSource

use of org.apache.commons.dbcp.BasicDataSource in project wso2-synapse by wso2.

the class AbstractDBMediator method getPreparedStatement.

/**
 * Return a Prepared statement for the given Statement object, which is ready to be executed
 *
 * @param stmnt  SQL stataement to be executed
 * @param con    The connection to be used
 * @param msgCtx Current message context
 * @return a PreparedStatement
 * @throws SQLException on error
 */
protected PreparedStatement getPreparedStatement(Statement stmnt, Connection con, MessageContext msgCtx) throws SQLException {
    SynapseLog synLog = getLog(msgCtx);
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Getting a connection from DataSource " + getDSName() + " and preparing statement : " + stmnt.getRawStatement());
    }
    if (con == null) {
        String msg = "Connection from DataSource " + getDSName() + " is null.";
        log.error(msg);
        throw new SynapseException(msg);
    }
    if (dataSource instanceof BasicDataSource) {
        BasicDataSource basicDataSource = (BasicDataSource) dataSource;
        int numActive = basicDataSource.getNumActive();
        int numIdle = basicDataSource.getNumIdle();
        String connectionId = Integer.toHexString(con.hashCode());
        DBPoolView dbPoolView = getDbPoolView();
        if (dbPoolView != null) {
            dbPoolView.setNumActive(numActive);
            dbPoolView.setNumIdle(numIdle);
            dbPoolView.updateConnectionUsage(connectionId);
        }
        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("[ DB Connection : " + con + " ]");
            synLog.traceOrDebug("[ DB Connection instance identifier : " + connectionId + " ]");
            synLog.traceOrDebug("[ Number of Active Connection : " + numActive + " ]");
            synLog.traceOrDebug("[ Number of Idle Connection : " + numIdle + " ]");
        }
    }
    PreparedStatement ps = con.prepareStatement(stmnt.getRawStatement());
    // set parameters if any
    List<Statement.Parameter> params = stmnt.getParameters();
    int column = 1;
    for (Statement.Parameter param : params) {
        if (param == null) {
            continue;
        }
        String value = (param.getPropertyName() != null ? param.getPropertyName() : param.getXpath().stringValueOf(msgCtx));
        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Setting as parameter : " + column + " value : " + value + " as JDBC Type : " + param.getType() + "(see java.sql.Types for valid " + "types)");
        }
        switch(param.getType()) {
            // according to J2SE 1.5 /docs/guide/jdbc/getstart/mapping.html
            case Types.CHAR:
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                {
                    if (value != null && value.length() != 0) {
                        ps.setString(column++, value);
                    } else {
                        ps.setString(column++, null);
                    }
                    break;
                }
            case Types.NUMERIC:
            case Types.DECIMAL:
                {
                    if (value != null && value.length() != 0) {
                        ps.setBigDecimal(column++, new BigDecimal(value));
                    } else {
                        ps.setBigDecimal(column++, null);
                    }
                    break;
                }
            case Types.BIT:
                {
                    if (value != null && value.length() != 0) {
                        ps.setBoolean(column++, Boolean.parseBoolean(value));
                    } else {
                        ps.setNull(column++, Types.BIT);
                    }
                    break;
                }
            case Types.TINYINT:
                {
                    if (value != null && value.length() != 0) {
                        ps.setByte(column++, Byte.parseByte(value));
                    } else {
                        ps.setNull(column++, Types.TINYINT);
                    }
                    break;
                }
            case Types.SMALLINT:
                {
                    if (value != null && value.length() != 0) {
                        ps.setShort(column++, Short.parseShort(value));
                    } else {
                        ps.setNull(column++, Types.SMALLINT);
                    }
                    break;
                }
            case Types.INTEGER:
                {
                    if (value != null && value.length() != 0) {
                        ps.setInt(column++, Integer.parseInt(value));
                    } else {
                        ps.setNull(column++, Types.INTEGER);
                    }
                    break;
                }
            case Types.BIGINT:
                {
                    if (value != null && value.length() != 0) {
                        ps.setLong(column++, Long.parseLong(value));
                    } else {
                        ps.setNull(column++, Types.BIGINT);
                    }
                    break;
                }
            case Types.REAL:
                {
                    if (value != null && value.length() != 0) {
                        ps.setFloat(column++, Float.parseFloat(value));
                    } else {
                        ps.setNull(column++, Types.REAL);
                    }
                    break;
                }
            case Types.FLOAT:
                {
                    if (value != null && value.length() != 0) {
                        ps.setDouble(column++, Double.parseDouble(value));
                    } else {
                        ps.setNull(column++, Types.FLOAT);
                    }
                    break;
                }
            case Types.DOUBLE:
                {
                    if (value != null && value.length() != 0) {
                        ps.setDouble(column++, Double.parseDouble(value));
                    } else {
                        ps.setNull(column++, Types.DOUBLE);
                    }
                    break;
                }
            // skip BINARY, VARBINARY and LONGVARBINARY
            case Types.DATE:
                {
                    if (value != null && value.length() != 0) {
                        ps.setDate(column++, Date.valueOf(value));
                    } else {
                        ps.setNull(column++, Types.DATE);
                    }
                    break;
                }
            case Types.TIME:
                {
                    if (value != null && value.length() != 0) {
                        ps.setTime(column++, Time.valueOf(value));
                    } else {
                        ps.setNull(column++, Types.TIME);
                    }
                    break;
                }
            case Types.TIMESTAMP:
                {
                    if (value != null && value.length() != 0) {
                        ps.setTimestamp(column++, Timestamp.valueOf(value));
                    } else {
                        ps.setNull(column++, Types.TIMESTAMP);
                    }
                    break;
                }
            // skip CLOB, BLOB, ARRAY, DISTINCT, STRUCT, REF, JAVA_OBJECT
            default:
                {
                    String msg = "Trying to set an un-supported JDBC Type : " + param.getType() + " against column : " + column + " and statement : " + stmnt.getRawStatement() + " used by a DB mediator against DataSource : " + getDSName() + " (see java.sql.Types for valid type values)";
                    handleException(msg, msgCtx);
                }
        }
    }
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Successfully prepared statement : " + stmnt.getRawStatement() + " against DataSource : " + getDSName());
    }
    return ps;
}
Also used : SynapseLog(org.apache.synapse.SynapseLog) DBPoolView(org.apache.synapse.commons.datasource.DBPoolView) SynapseException(org.apache.synapse.SynapseException) PreparedStatement(java.sql.PreparedStatement) PreparedStatement(java.sql.PreparedStatement) BasicDataSource(org.apache.commons.dbcp.BasicDataSource) BigDecimal(java.math.BigDecimal)

Example 28 with BasicDataSource

use of org.apache.commons.dbcp.BasicDataSource in project wso2-synapse by wso2.

the class DataSourceFactory method createDataSource.

/**
 * 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
 */
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;
}
Also used : DriverAdapterCPDS(org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS) PerUserPoolDataSource(org.apache.commons.dbcp.datasources.PerUserPoolDataSource) BasicDataSource(org.apache.commons.dbcp.BasicDataSource)

Example 29 with BasicDataSource

use of org.apache.commons.dbcp.BasicDataSource in project incubator-gobblin by apache.

the class MysqlDataSourceFactory method createResource.

@Override
public SharedResourceFactoryResponse<BasicDataSource> createResource(SharedResourcesBroker<S> broker, ScopedConfigView<S, MysqlDataSourceKey> config) throws NotConfiguredException {
    MysqlDataSourceKey key = config.getKey();
    Config configuration = key.getConfig();
    BasicDataSource dataSource = MysqlStateStore.newDataSource(configuration);
    return new ResourceInstance<>(dataSource);
}
Also used : Config(com.typesafe.config.Config) ResourceInstance(org.apache.gobblin.broker.ResourceInstance) BasicDataSource(org.apache.commons.dbcp.BasicDataSource)

Example 30 with BasicDataSource

use of org.apache.commons.dbcp.BasicDataSource in project incubator-gobblin by apache.

the class SqlBasedRetentionPoc method setup.

/**
 * <ul>
 * <li>Create the in-memory database and connect
 * <li>Create tables for snapshots and daily_paritions
 * <li>Attach all user defined functions from {@link SqlUdfs}
 * </ul>
 */
@BeforeClass
public void setup() throws SQLException {
    basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    basicDataSource.setUrl("jdbc:derby:memory:derbypoc;create=true");
    Connection connection = basicDataSource.getConnection();
    connection.setAutoCommit(false);
    this.connection = connection;
    execute("CREATE TABLE Snapshots (dataset_path VARCHAR(255), name VARCHAR(255), path VARCHAR(255), ts TIMESTAMP, row_count bigint)");
    execute("CREATE TABLE Daily_Partitions (dataset_path VARCHAR(255), path VARCHAR(255), ts TIMESTAMP)");
    // Register UDFs
    execute("CREATE FUNCTION TIMESTAMP_DIFF(timestamp1 TIMESTAMP, timestamp2 TIMESTAMP, unitString VARCHAR(50)) RETURNS BIGINT PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA EXTERNAL NAME 'org.apache.gobblin.data.management.retention.sql.SqlUdfs.timestamp_diff'");
}
Also used : Connection(java.sql.Connection) BasicDataSource(org.apache.commons.dbcp.BasicDataSource) BeforeClass(org.testng.annotations.BeforeClass)

Aggregations

BasicDataSource (org.apache.commons.dbcp.BasicDataSource)141 Connection (java.sql.Connection)25 Test (org.junit.Test)13 SQLException (java.sql.SQLException)12 Properties (java.util.Properties)12 DataSource (javax.sql.DataSource)10 Platform (org.apache.ddlutils.Platform)8 Database (org.apache.ddlutils.model.Database)8 DdlGenerator (siena.jdbc.ddl.DdlGenerator)8 Statement (java.sql.Statement)7 Bean (org.springframework.context.annotation.Bean)6 ResultSet (java.sql.ResultSet)5 Before (org.junit.Before)5 JdbcPersistenceManager (siena.jdbc.JdbcPersistenceManager)5 Config (com.typesafe.config.Config)4 File (java.io.File)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 Test (org.testng.annotations.Test)3 PostgresqlPersistenceManager (siena.jdbc.PostgresqlPersistenceManager)3