Example usage for java.sql Connection TRANSACTION_READ_COMMITTED

List of usage examples for java.sql Connection TRANSACTION_READ_COMMITTED

Introduction

In this page you can find the example usage for java.sql Connection TRANSACTION_READ_COMMITTED.

Prototype

int TRANSACTION_READ_COMMITTED

To view the source code for java.sql Connection TRANSACTION_READ_COMMITTED.

Click Source Link

Document

A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.

Usage

From source file:org.apache.sqoop.mapreduce.db.DBInputFormat.java

private void setTxIsolation(Connection conn) {
    try {//from   ww  w .j a  va  2  s  . co  m

        if (getConf().getBoolean(DBConfiguration.PROP_RELAXED_ISOLATION, false)) {
            if (dbProductName.startsWith("ORACLE")) {
                LOG.info("Using read committed transaction isolation for Oracle"
                        + " as read uncommitted is not supported");
                this.connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            } else {
                LOG.info("Using read uncommited transaction isolation");
                this.connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            }
        } else {
            LOG.info("Using read commited transaction isolation");
            this.connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.amazon.carbonado.repo.jdbc.LoggingConnection.java

public void setTransactionIsolation(int level) throws SQLException {
    String levelStr;// www  .j  a v a 2 s  .  c o  m
    switch (level) {
    default:
        levelStr = String.valueOf(level);
        break;
    case Connection.TRANSACTION_NONE:
        levelStr = "TRANSACTION_NONE";
        break;
    case Connection.TRANSACTION_READ_UNCOMMITTED:
        levelStr = "TRANSACTION_READ_UNCOMMITTED";
        break;
    case Connection.TRANSACTION_READ_COMMITTED:
        levelStr = "TRANSACTION_READ_COMMITTED";
        break;
    case Connection.TRANSACTION_REPEATABLE_READ:
        levelStr = "TRANSACTION_REPEATABLE_READ";
        break;
    case Connection.TRANSACTION_SERIALIZABLE:
        levelStr = "TRANSACTION_SERIALIZABLE";
        break;
    }

    mLog.debug("Connection.setTransactionIsolation(" + levelStr + ')');
    mCon.setTransactionIsolation(level);
}

From source file:org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.java

/**
 * Constructor.//www .j  a v a 2 s.  c o m
 *
 * @param derivations whether to apply product derivations
 * @param loadGlobals whether to attempt to load the global properties
 */
public JDBCConfigurationImpl(boolean derivations, boolean loadGlobals) {
    super(false, false);
    String[] aliases;

    schema = addString("jdbc.Schema");
    schemas = addStringList("jdbc.Schemas");

    transactionIsolation = addInt("jdbc.TransactionIsolation");
    aliases = new String[] { "default", String.valueOf(-1), "none", String.valueOf(Connection.TRANSACTION_NONE),
            "read-committed", String.valueOf(Connection.TRANSACTION_READ_COMMITTED), "read-uncommitted",
            String.valueOf(Connection.TRANSACTION_READ_UNCOMMITTED), "repeatable-read",
            String.valueOf(Connection.TRANSACTION_REPEATABLE_READ), "serializable",
            String.valueOf(Connection.TRANSACTION_SERIALIZABLE) };
    transactionIsolation.setAliases(aliases);
    transactionIsolation.setDefault(aliases[0]);
    transactionIsolation.set(-1);
    transactionIsolation.setAliasListComprehensive(true);

    resultSetType = addInt("jdbc.ResultSetType");
    aliases = new String[] { "forward-only", String.valueOf(ResultSet.TYPE_FORWARD_ONLY), "scroll-sensitive",
            String.valueOf(ResultSet.TYPE_SCROLL_SENSITIVE), "scroll-insensitive",
            String.valueOf(ResultSet.TYPE_SCROLL_INSENSITIVE), };
    resultSetType.setAliases(aliases);
    resultSetType.setDefault(aliases[0]);
    resultSetType.set(ResultSet.TYPE_FORWARD_ONLY);
    resultSetType.setAliasListComprehensive(true);

    fetchDirection = addInt("jdbc.FetchDirection");
    aliases = new String[] { "forward", String.valueOf(ResultSet.FETCH_FORWARD), "reverse",
            String.valueOf(ResultSet.FETCH_REVERSE), "unknown", String.valueOf(ResultSet.FETCH_UNKNOWN), };
    fetchDirection.setAliases(aliases);
    fetchDirection.setDefault(aliases[0]);
    fetchDirection.set(ResultSet.FETCH_FORWARD);
    fetchDirection.setAliasListComprehensive(true);

    eagerFetchMode = new FetchModeValue("jdbc.EagerFetchMode");
    eagerFetchMode.setDefault(FetchModeValue.EAGER_PARALLEL);
    eagerFetchMode.set(EagerFetchModes.EAGER_PARALLEL);
    addValue(eagerFetchMode);

    subclassFetchMode = new FetchModeValue("jdbc.SubclassFetchMode");
    subclassFetchMode.setDefault(FetchModeValue.EAGER_JOIN);
    subclassFetchMode.set(EagerFetchModes.EAGER_JOIN);
    addValue(subclassFetchMode);

    lrsSize = addInt("jdbc.LRSSize");
    aliases = new String[] { "query", String.valueOf(LRSSizes.SIZE_QUERY), "unknown",
            String.valueOf(LRSSizes.SIZE_UNKNOWN), "last", String.valueOf(LRSSizes.SIZE_LAST), };
    lrsSize.setAliases(aliases);
    lrsSize.setDefault(aliases[0]);
    lrsSize.set(LRSSizes.SIZE_QUERY);
    lrsSize.setAliasListComprehensive(true);

    synchronizeMappings = addString("jdbc.SynchronizeMappings");
    aliases = new String[] { "false", null };
    synchronizeMappings.setAliases(aliases);
    synchronizeMappings.setDefault(aliases[0]);

    jdbcListenerPlugins = addPluginList("jdbc.JDBCListeners");
    jdbcListenerPlugins.setInstantiatingGetter("getJDBCListenerInstances");

    connectionDecoratorPlugins = addPluginList("jdbc.ConnectionDecorators");
    connectionDecoratorPlugins.setInstantiatingGetter("getConnectionDecoratorInstances");

    dbdictionaryPlugin = addPlugin("jdbc.DBDictionary", true);
    aliases = new String[] { "access", "org.apache.openjpa.jdbc.sql.AccessDictionary", "db2",
            "org.apache.openjpa.jdbc.sql.DB2Dictionary", "derby", "org.apache.openjpa.jdbc.sql.DerbyDictionary",
            "empress", "org.apache.openjpa.jdbc.sql.EmpressDictionary", "foxpro",
            "org.apache.openjpa.jdbc.sql.FoxProDictionary", "h2", "org.apache.openjpa.jdbc.sql.H2Dictionary",
            "hsql", "org.apache.openjpa.jdbc.sql.HSQLDictionary", "informix",
            "org.apache.openjpa.jdbc.sql.InformixDictionary", "ingres",
            "org.apache.openjpa.jdbc.sql.IngresDictionary", "jdatastore",
            "org.apache.openjpa.jdbc.sql.JDataStoreDictionary", "mysql",
            "org.apache.openjpa.jdbc.sql.MySQLDictionary", "oracle",
            "org.apache.openjpa.jdbc.sql.OracleDictionary", "pointbase",
            "org.apache.openjpa.jdbc.sql.PointbaseDictionary", "postgres",
            "org.apache.openjpa.jdbc.sql.PostgresDictionary", "soliddb",
            "org.apache.openjpa.jdbc.sql.SolidDBDictionary", "sqlserver",
            "org.apache.openjpa.jdbc.sql.SQLServerDictionary", "sybase",
            "org.apache.openjpa.jdbc.sql.SybaseDictionary", "maxdb",
            MaxDBDictionary.class.getCanonicalName(), };
    dbdictionaryPlugin.setAliases(aliases);
    dbdictionaryPlugin.setInstantiatingGetter("getDBDictionaryInstance");

    updateManagerPlugin = addPlugin("jdbc.UpdateManager", true);
    aliases = new String[] { "default", BatchingConstraintUpdateManager.class.getName(), "operation-order",
            "org.apache.openjpa.jdbc.kernel.OperationOrderUpdateManager", "constraint",
            "org.apache.openjpa.jdbc.kernel.ConstraintUpdateManager", "batching-constraint",
            BatchingConstraintUpdateManager.class.getName(), "batching-operation-order",
            BatchingOperationOrderUpdateManager.class.getName(), };
    updateManagerPlugin.setAliases(aliases);
    updateManagerPlugin.setDefault(aliases[0]);
    updateManagerPlugin.setString(aliases[0]);
    updateManagerPlugin.setInstantiatingGetter("getUpdateManagerInstance");

    driverDataSourcePlugin = addPlugin("jdbc.DriverDataSource", false);
    aliases = new String[] { "auto", "org.apache.openjpa.jdbc.schema.AutoDriverDataSource", "simple",
            "org.apache.openjpa.jdbc.schema.SimpleDriverDataSource", "dbcp",
            "org.apache.openjpa.jdbc.schema.DBCPDriverDataSource", };
    driverDataSourcePlugin.setAliases(aliases);
    driverDataSourcePlugin.setDefault(aliases[0]);
    driverDataSourcePlugin.setString(aliases[0]);

    schemaFactoryPlugin = addPlugin("jdbc.SchemaFactory", true);
    aliases = new String[] { "dynamic", "org.apache.openjpa.jdbc.schema.DynamicSchemaFactory", "native",
            "org.apache.openjpa.jdbc.schema.LazySchemaFactory", "file",
            "org.apache.openjpa.jdbc.schema.FileSchemaFactory", "table",
            "org.apache.openjpa.jdbc.schema.TableSchemaFactory",
            // deprecated alias
            "db", "org.apache.openjpa.jdbc.schema.TableSchemaFactory", };
    schemaFactoryPlugin.setAliases(aliases);
    schemaFactoryPlugin.setDefault(aliases[0]);
    schemaFactoryPlugin.setString(aliases[0]);
    schemaFactoryPlugin.setInstantiatingGetter("getSchemaFactoryInstance");

    sqlFactoryPlugin = addPlugin("jdbc.SQLFactory", true);
    aliases = new String[] { "default", "org.apache.openjpa.jdbc.sql.SQLFactoryImpl", };
    sqlFactoryPlugin.setAliases(aliases);
    sqlFactoryPlugin.setDefault(aliases[0]);
    sqlFactoryPlugin.setString(aliases[0]);
    sqlFactoryPlugin.setInstantiatingGetter("getSQLFactoryInstance");

    mappingFactoryPlugin = new MappingFactoryValue("jdbc.MappingFactory");
    addValue(mappingFactoryPlugin);

    mappingDefaultsPlugin = addPlugin("jdbc.MappingDefaults", true);
    aliases = new String[] { "default", "org.apache.openjpa.jdbc.meta.MappingDefaultsImpl", };
    mappingDefaultsPlugin.setAliases(aliases);
    mappingDefaultsPlugin.setDefault(aliases[0]);
    mappingDefaultsPlugin.setString(aliases[0]);
    mappingDefaultsPlugin.setInstantiatingGetter("getMappingDefaultsInstance");

    // set up broker factory defaults
    brokerFactoryPlugin.setAlias("jdbc", JDBCBrokerFactory.class.getName());
    brokerFactoryPlugin.setDefault("jdbc");
    brokerFactoryPlugin.setString("jdbc");

    // set new default for mapping repos
    metaRepositoryPlugin.setAlias("default", "org.apache.openjpa.jdbc.meta.MappingRepository");
    metaRepositoryPlugin.setDefault("default");
    metaRepositoryPlugin.setString("default");

    // set new default for lock manager
    lockManagerPlugin.setAlias("pessimistic", PessimisticLockManager.class.getName());
    lockManagerPlugin.setDefault("pessimistic");
    lockManagerPlugin.setString("pessimistic");

    // native savepoint manager options
    savepointManagerPlugin.setAlias("jdbc", "org.apache.openjpa.jdbc.kernel.JDBC3SavepointManager");

    // set new aliases and defaults for sequence
    seqPlugin.setAliases(JDBCSeqValue.ALIASES);
    seqPlugin.setDefault(JDBCSeqValue.ALIASES[0]);
    seqPlugin.setString(JDBCSeqValue.ALIASES[0]);

    // This plug-in is declared in superclass but defined here
    // because PreparedQueryCache is currently available for JDBC
    // backend only
    preparedQueryCachePlugin = addPlugin("jdbc.QuerySQLCache", true);
    aliases = new String[] { "true", "org.apache.openjpa.jdbc.kernel.PreparedQueryCacheImpl", "false", null };
    preparedQueryCachePlugin.setAliases(aliases);
    preparedQueryCachePlugin.setAliasListComprehensive(true);
    preparedQueryCachePlugin.setDefault(aliases[0]);
    preparedQueryCachePlugin.setClassName(aliases[1]);
    preparedQueryCachePlugin.setDynamic(true);
    preparedQueryCachePlugin.setInstantiatingGetter("getQuerySQLCacheInstance");

    finderCachePlugin = addPlugin("jdbc.FinderCache", true);
    aliases = new String[] { "true", "org.apache.openjpa.jdbc.kernel.FinderCacheImpl", "false", null };
    finderCachePlugin.setAliases(aliases);
    finderCachePlugin.setAliasListComprehensive(true);
    finderCachePlugin.setDefault(aliases[0]);
    finderCachePlugin.setClassName(aliases[1]);
    finderCachePlugin.setDynamic(true);
    finderCachePlugin.setInstantiatingGetter("getFinderCacheInstance");

    identifierUtilPlugin = addPlugin("jdbc.IdentifierUtil", true);
    aliases = new String[] { "default", "org.apache.openjpa.jdbc.identifier.DBIdentifierUtilImpl" };
    identifierUtilPlugin.setAliases(aliases);
    identifierUtilPlugin.setDefault(aliases[0]);
    identifierUtilPlugin.setString(aliases[0]);
    identifierUtilPlugin.setInstantiatingGetter("getIdentifierUtilInstance");

    // this static initializer is to get past a weird
    // ClassCircularityError that happens only under IBM's
    // JDK 1.3.1 on Linux from within the JRun ClassLoader;
    // while exact causes are unknown, it is almost certainly
    // a bug in JRun, and we can get around it by forcing
    // Instruction.class to be loaded and initialized
    // before TypedInstruction.class
    try {
        serp.bytecode.lowlevel.Entry.class.getName();
    } catch (Throwable t) {
    }
    try {
        serp.bytecode.Instruction.class.getName();
    } catch (Throwable t) {
    }

    supportedOptions().add(OPTION_QUERY_SQL);
    supportedOptions().add(OPTION_JDBC_CONNECTION);
    supportedOptions().remove(OPTION_VALUE_INCREMENT);
    supportedOptions().remove(OPTION_NULL_CONTAINER);

    if (derivations)
        ProductDerivations.beforeConfigurationLoad(this);
    if (loadGlobals)
        loadGlobals();
}

From source file:org.everit.osgi.jdbc.commons.dbcp.internal.Util.java

public static void applyPropertiesOnBasicDataSource(final BasicDataSource basicDataSource,
        final Map<String, Object> componentProperties) {

    setPropertyIfNotNull(basicDataSource, componentProperties,
            DSFConstants.PROP_ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED, boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_DEFAULT_AUTO_COMMIT,
            Boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_DEFAULT_CATALOG, String.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_DEFAULT_READ_ONLY,
            Boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_DEFAULT_QUERY_TIMEOUT,
            Integer.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_INITIAL_SIZE, int.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_LOG_ABANDONED, boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_MAX_TOTAL, int.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_MAX_IDLE, int.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_MAX_OPEN_PREPARED_STATEMENTS,
            int.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_MAX_WAIT_MILLIS, long.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_MIN_EVICTABLE_IDLE_TIME_MILLIS,
            long.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_MIN_IDLE, int.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_NUM_TESTS_PER_EVICTION_RUN,
            int.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_POOL_PREPARED_STATEMENTS,
            boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_REMOVE_ABANDONED_ON_BORROW,
            boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties,
            DSFConstants.PROP_REMOVE_ABANDONED_ON_MAINTENANCE, boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_REMOVE_ABANDONED_TIMEOUT,
            int.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_TEST_ON_BORROW, boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_TEST_ON_RETURN, boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_TEST_WHILE_IDLE,
            boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties,
            DSFConstants.PROP_TIME_BETWEEN_EVICTION_RUNS_MILLIS, long.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_VALIDATION_QUERY,
            String.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_VALIDATION_QUERY_TIMEOUT,
            int.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_LIFO, boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_CACHE_STATE, boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_TEST_ON_CREATE, boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties,
            DSFConstants.PROP_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS, long.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_MAX_CONN_LIFETIME_MILLIS,
            long.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_JMX_NAME, String.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_ENABLE_AUTO_COMMIT_ON_RETURN,
            boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_ROLLBACK_ON_RETURN,
            boolean.class);

    setPropertyIfNotNull(basicDataSource, componentProperties, DSFConstants.PROP_ABANDONED_USAGE_TRACKING,
            boolean.class);

    Object connectionInitSqlsObject = componentProperties.get(DSFConstants.PROP_CONNECTION_INIT_SQLS);
    if (connectionInitSqlsObject != null) {
        if (!(connectionInitSqlsObject instanceof Collection)) {
            throw new RuntimeException("Expected type of " + DSFConstants.PROP_CONNECTION_INIT_SQLS
                    + "' is Collection but " + connectionInitSqlsObject.getClass() + " provided");
        }//from   w  w w  .j a  va  2  s  .  co m

        @SuppressWarnings("unchecked")
        Collection<String> connectionInitSqls = (Collection<String>) connectionInitSqlsObject;
        basicDataSource.setConnectionInitSqls(connectionInitSqls);
    }

    Object transactionIsolationObject = componentProperties
            .get(DSFConstants.PROP_DEFAULT_TRANSACTION_ISOLATION);
    if (transactionIsolationObject != null) {
        if (DSFConstants.VALUE_READ_COMMITED.equals(transactionIsolationObject)) {
            basicDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if (DSFConstants.VALUE_READ_UNCOMMITTED.equals(transactionIsolationObject)) {
            basicDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if (DSFConstants.VALUE_REPEATABLE_READ.equals(transactionIsolationObject)) {
            basicDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if (DSFConstants.VALUE_SERIALIZABLE.equals(transactionIsolationObject)) {
            basicDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if (DSFConstants.VALUE_TRANSACTION_NONE.equals(transactionIsolationObject)) {
            basicDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        } else {
            throw new RuntimeException("Unknown value '" + transactionIsolationObject
                    + "' for the property key '" + DSFConstants.PROP_DEFAULT_TRANSACTION_ISOLATION
                    + " during datasource configuration.");
        }

    }
}

From source file:org.apache.ofbiz.entity.connection.DBCPConnectionFactory.java

public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc)
        throws SQLException, GenericEntityException {
    String cacheKey = helperInfo.getHelperFullName();
    DebugManagedDataSource mds = dsCache.get(cacheKey);
    if (mds != null) {
        return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
    }/*  ww w.jav a2s  .  c o  m*/
    if (!(abstractJdbc instanceof InlineJdbc)) {
        throw new GenericEntityConfException(
                "DBCP requires an <inline-jdbc> child element in the <datasource> element");
    }
    InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
    // connection properties
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    String driverName = jdbcElement.getJdbcDriver();

    String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
    String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
    String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));

    // pool settings
    int maxSize = jdbcElement.getPoolMaxsize();
    int minSize = jdbcElement.getPoolMinsize();
    int maxIdle = jdbcElement.getIdleMaxsize();
    // maxIdle must be greater than pool-minsize
    maxIdle = maxIdle > minSize ? maxIdle : minSize;
    // load the driver
    Driver jdbcDriver;
    synchronized (DBCPConnectionFactory.class) {
        // Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
        try {
            jdbcDriver = (Driver) Class
                    .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            Debug.logError(e, module);
            throw new GenericEntityException(e.getMessage(), e);
        }
    }

    // connection factory properties
    Properties cfProps = new Properties();
    cfProps.put("user", jdbcUsername);
    cfProps.put("password", jdbcPassword);

    // create the connection factory
    org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);

    // wrap it with a LocalXAConnectionFactory
    XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);

    // create the pool object factory
    PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
    factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
    factory.setDefaultReadOnly(false);
    factory.setRollbackOnReturn(false);
    factory.setEnableAutoCommitOnReturn(false);
    String transIso = jdbcElement.getIsolationLevel();
    if (!transIso.isEmpty()) {
        if ("Serializable".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if ("RepeatableRead".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("ReadUncommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("ReadCommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("None".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        }
    }

    // configure the pool settings
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(maxSize);
    // settings for idle connections
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minSize);
    poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
    poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
    // settings for when the pool is exhausted
    poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    // settings for the execution of the validation query
    poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
    poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
    poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
    poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());

    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(factory, poolConfig);
    factory.setPool(pool);

    mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry());
    mds.setAccessToUnderlyingConnectionAllowed(true);

    // cache the pool
    dsCache.putIfAbsent(cacheKey, mds);
    mds = dsCache.get(cacheKey);

    return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}

From source file:org.everit.persistence.jdbc.commons.dbcp.ecm.internal.Util.java

private static void applyTransactionIsolationPropertyOnBasicDataSource(final BasicDataSource basicDataSource,
        final Object transactionIsolationObject) {
    if (transactionIsolationObject != null) {
        if (DSFConstants.VALUE_READ_COMMITED.equals(transactionIsolationObject)) {
            basicDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if (DSFConstants.VALUE_READ_UNCOMMITTED.equals(transactionIsolationObject)) {
            basicDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if (DSFConstants.VALUE_REPEATABLE_READ.equals(transactionIsolationObject)) {
            basicDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if (DSFConstants.VALUE_SERIALIZABLE.equals(transactionIsolationObject)) {
            basicDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if (DSFConstants.VALUE_TRANSACTION_NONE.equals(transactionIsolationObject)) {
            basicDataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        } else {//from ww  w  .jav a 2s. c  om
            throw new RuntimeException("Unknown value '" + transactionIsolationObject
                    + "' for the property key '" + DSFConstants.ATTR_DEFAULT_TRANSACTION_ISOLATION
                    + " during datasource configuration.");
        }
    }
}

From source file:com.oltpbenchmark.WorkloadConfiguration.java

public void setIsolationMode(String mode) {
    if (mode.equals("TRANSACTION_SERIALIZABLE"))
        this.isolationMode = Connection.TRANSACTION_SERIALIZABLE;
    else if (mode.equals("TRANSACTION_READ_COMMITTED"))
        this.isolationMode = Connection.TRANSACTION_READ_COMMITTED;
    else if (mode.equals("TRANSACTION_REPEATABLE_READ"))
        this.isolationMode = Connection.TRANSACTION_REPEATABLE_READ;
    else if (mode.equals("TRANSACTION_READ_UNCOMMITTED"))
        this.isolationMode = Connection.TRANSACTION_READ_UNCOMMITTED;
    else if (!mode.isEmpty())
        System.out.println("Indefined isolation mode, set to default [TRANSACTION_SERIALIZABLE]");
}

From source file:org.kawanfw.test.api.client.DatabaseMetaDataTest.java

public void test(Connection connection) throws Exception {
    MessageDisplayer.initClassDisplay(this.getClass().getSimpleName());

    DatabaseMetaData databaseMetaData = connection.getMetaData();

    // Test that getMetaData() will return value from cache
    databaseMetaData = connection.getMetaData();

    if (connection instanceof RemoteConnection) {
        MessageDisplayer.display("Java Version : " + System.getProperty("java.version"));
        MessageDisplayer.display("AceQL Version: " + ((RemoteConnection) connection).getVersion());
        MessageDisplayer.display("AceQL Url    : " + ((RemoteConnection) connection).getUrl());
        MessageDisplayer.display("");
    }/*from   w w w. j a  v  a  2 s.co m*/

    if (connection instanceof RemoteConnection) {
        MessageDisplayer.display("((RemoteConnection)connection).clone();");
        Connection connection2 = ((RemoteConnection) connection).clone();
        @SuppressWarnings("unused")
        DatabaseMetaData databaseMetaData2 = connection2.getMetaData();
        connection2.close();
    }

    MessageDisplayer.display("General info (no Assert done):");

    MessageDisplayer.display("connection.getCatalog()                     : " + connection.getCatalog());

    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductName()   : " + databaseMetaData.getDatabaseProductName());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductVersion(): " + databaseMetaData.getDatabaseProductVersion());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseMajorVersion()  : " + databaseMetaData.getDatabaseMajorVersion());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseMinorVersion()  : " + databaseMetaData.getDatabaseMinorVersion());
    MessageDisplayer.display(
            "databaseMetaData.allProceduresAreCallable() : " + databaseMetaData.allProceduresAreCallable());
    // SystemOutHandle.display(DatabaseMetaData.bestRowSession);
    MessageDisplayer.display("");

    // SystemOutHandle.display(databaseMetaData.autoCommitFailureClosesAllResultSets());

    MessageDisplayer.display("databaseMetaData.getCatalogTerm(): " + databaseMetaData.getCatalogTerm());

    try {

        MessageDisplayer.display(
                "databaseMetaData.supportsStoredProcedures(): " + databaseMetaData.supportsStoredProcedures());

        MessageDisplayer.display("databaseMetaData.supportsStoredFunctionsUsingCallSyntax(): "
                + databaseMetaData.supportsStoredFunctionsUsingCallSyntax());

    } catch (Throwable e) {
        MessageDisplayer.display(e.toString());
    }

    MessageDisplayer.display("connection.getAutoCommit(): " + connection.getAutoCommit());

    MessageDisplayer.display("databaseMetaData.getDefaultTransactionIsolation()    : "
            + databaseMetaData.getDefaultTransactionIsolation());

    MessageDisplayer
            .display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_READ_UNCOMMITTED): "
                    + databaseMetaData
                            .supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_READ_COMMITTED): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_REPEATABLE_READ): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_SERIALIZABLE): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE));

    MessageDisplayer
            .display("databaseMetaData.supportsBatchUpdates()    : " + databaseMetaData.supportsBatchUpdates());
    MessageDisplayer
            .display("databaseMetaData.supportsSavepoints()      : " + databaseMetaData.supportsSavepoints());
    MessageDisplayer.display(
            "databaseMetaData.supportsGetGeneratedKeys(): " + databaseMetaData.supportsGetGeneratedKeys());

    if (!new SqlUtil(connection).isTeradata() && !new SqlUtil(connection).isInformix()) {
        Assert.assertEquals(true,
                databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));
    }

    Assert.assertEquals("databaseMetaData.supportsBatchUpdates()", true,
            databaseMetaData.supportsBatchUpdates());

    if (!new SqlUtil(connection).isSQLAnywhere() && !new SqlUtil(connection).isAccess()) {
        Assert.assertEquals("databaseMetaData.supportsGetGeneratedKeys()", true,
                databaseMetaData.supportsGetGeneratedKeys());
    }
    // Informix does not support savepoints
    SqlUtil sqlUtil = new SqlUtil(connection);
    if (!sqlUtil.isInformix() && !sqlUtil.isTeradata() && !new SqlUtil(connection).isAccess()) {
        Assert.assertEquals(true, databaseMetaData.supportsSavepoints());
    }

    MessageDisplayer.display("");

    String catalog = null;
    String schema = null;
    String table = "customer";

    // Table name must be uppercase for Oracle & DB2, lowercase for MySQL
    // and PostgreSQL
    if (new SqlUtil(connection).isOracle() || new SqlUtil(connection).isHSQLDB()
            || new SqlUtil(connection).isDB2()) {
        table = table.toUpperCase();
    }

    ResultSet rs = null;

    if (!new SqlUtil(connection).isAccess()) {

        rs = databaseMetaData.getPrimaryKeys(catalog, schema, table);

        printResultSet(rs);

        boolean rsNext = false;

        while (rs.next()) {
            rsNext = true;
            String keyColumnName = rs.getString("COLUMN_NAME");
            MessageDisplayer.display("Primary Key is: " + keyColumnName + " for Table: " + table);
            Assert.assertEquals("customer_id", keyColumnName.toLowerCase());
        }

        if (!new SqlUtil(connection).isH2()) {
            Assert.assertEquals(true, rsNext);
        }

        rs.close();
    }

    // boolean returnNow = true;
    // if (returnNow) return;

    String[] types = { "TABLE", "VIEW" };
    rs = databaseMetaData.getTables(null, null, null, types);

    Set<String> tablesSet = new HashSet<String>();

    Set<String> ourTables = new HashSet<String>();
    ourTables.add("banned_usernames");
    ourTables.add("customer");
    ourTables.add("customer_auto");
    ourTables.add("orderlog");
    ourTables.add("user_login");

    MessageDisplayer.display("");
    while (rs.next()) {
        table = rs.getString("TABLE_NAME");

        if (ourTables.contains(table.toLowerCase())) {
            MessageDisplayer.display("Table: " + table);
        }

        tablesSet.add(table.toLowerCase());
    }

    // printResultSet(rs);

    testTable("banned_usernames", tablesSet);
    testTable("customer", tablesSet);
    testTable("orderlog", tablesSet);
    testTable("user_login", tablesSet);

    rs.close();
}

From source file:org.spring.data.gemfire.app.dao.provider.JdbcUserDao.java

@Override
public int count() {
    try {//  w ww.ja  va  2s  . c  o  m
        Connection connection = createConnectionBuilder()
                .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED).build();

        Statement statement = connection.createStatement();

        ResultSet resultSet = statement.executeQuery(COUNT_USER_SQL);

        int count = 0;

        if (resultSet != null && resultSet.next()) {
            count = resultSet.getInt(1);
        }

        return count;
    } catch (SQLException e) {
        throw createDataAccessException("Failed to count the number of users!", e);
    }
}

From source file:org.lib4j.dbcp.DataSources.java

/**
 * Create a <code>BasicDataSource</code> given a dbcp JAXB binding.
 *
 * @param dbcp JAXB dbcp binding.//from   www .  j ava  2 s.c  o m
 * @param driverClassLoader Class loader to be used to load the JDBC driver.
 * @return the <code>BasicDataSource</code> instance.
 * @throws SQLException If a database access error occurs.
 */
public static BasicDataSource createDataSource(final Dbcp dbcp, final ClassLoader driverClassLoader)
        throws SQLException {
    final BasicDataSource dataSource = new BasicDataSource();

    final Dbcp.Jdbc jdbc = dbcp.getJdbc();
    dataSource.setDriverClassName(jdbc.getDriverClassName());
    dataSource.setDriverClassLoader(driverClassLoader);

    dataSource.setUrl(jdbc.getUrl());

    dataSource.setUsername(jdbc.getUsername());
    dataSource.setPassword(jdbc.getPassword());

    final Dbcp.Default _default = dbcp.getDefault();
    if (_default != null && _default.getCatalog() != null)
        dataSource.setDefaultCatalog(_default.getCatalog());

    dataSource.setDefaultAutoCommit(
            _default == null || _default.getAutoCommit() == null || _default.getAutoCommit());
    dataSource.setDefaultReadOnly(_default != null && _default.getReadOnly() != null && _default.getReadOnly());
    if (_default != null && _default.getQueryTimeout() != null)
        dataSource.setDefaultQueryTimeout(_default.getQueryTimeout());

    if (_default != null && _default.getTransactionIsolation() != null) {
        if ("NONE".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        else if ("READ_COMMITTED".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        else if ("READ_UNCOMMITTED".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        else if ("REPEATABLE_READ".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        else if ("SERIALIZABLE".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        else
            throw new UnsupportedOperationException(
                    "Unsupported transaction isolation: " + _default.getTransactionIsolation());
    }

    final Dbcp.Connection connection = dbcp.getConnection();
    if (connection != null) {
        if (connection.getProperties() != null)
            for (final Dbcp.Connection.Properties.Property property : connection.getProperties().getProperty())
                if (property.getName() != null && property.getValue() != null)
                    dataSource.addConnectionProperty(property.getName(), property.getValue());

        if (connection.getInitSqls() != null) {
            final List<String> initSqls = new ArrayList<>();
            for (final String initSql : connection.getInitSqls().getInitSql())
                initSqls.add(initSql);

            dataSource.setConnectionInitSqls(initSqls);
        }
    }

    final Dbcp.Size size = dbcp.getSize();
    dataSource.setInitialSize(size == null || size.getInitialSize() == null ? 0 : size.getInitialSize());
    dataSource.setMaxTotal(size == null || size.getMaxTotal() == null ? 8
            : INDEFINITE.equals(size.getMaxTotal()) ? -1 : Integer.parseInt(size.getMaxTotal()));
    dataSource.setMaxIdle(size == null || size.getMaxIdle() == null ? 8
            : INDEFINITE.equals(size.getMaxIdle()) ? -1 : Integer.parseInt(size.getMaxIdle()));
    dataSource.setMinIdle(size == null || size.getMinIdle() == null ? 9 : size.getMinIdle());
    if (size == null || size.getMaxOpenPreparedStatements() == null
            || INDEFINITE.equals(size.getMaxOpenPreparedStatements())) {
        dataSource.setPoolPreparedStatements(false);
    } else {
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxOpenPreparedStatements(Integer.parseInt(size.getMaxOpenPreparedStatements()));
    }

    final Dbcp.Pool pool = dbcp.getPool();
    if (pool == null || pool.getQueue() == null || "lifo".equals(pool.getQueue()))
        dataSource.setLifo(true);
    else if ("fifo".equals(pool.getQueue()))
        dataSource.setLifo(false);
    else
        throw new UnsupportedOperationException("Unsupported queue spec: " + pool.getQueue());

    dataSource.setCacheState(pool != null && pool.getCacheState() != null && pool.getCacheState());
    dataSource.setMaxWaitMillis(
            pool == null || pool.getMaxWait() != null || INDEFINITE.equals(pool.getMaxWait()) ? -1
                    : Long.parseLong(pool.getMaxWait()));
    dataSource.setMaxConnLifetimeMillis(pool == null || pool.getMaxConnectionLifetime() == null
            || INDEFINITE.equals(pool.getMaxConnectionLifetime()) ? 0
                    : Long.parseLong(pool.getMaxConnectionLifetime()));
    dataSource.setEnableAutoCommitOnReturn(_default == null || pool.getEnableAutoCommitOnReturn() == null
            || pool.getEnableAutoCommitOnReturn());
    dataSource.setRollbackOnReturn(
            pool == null || pool.getRollbackOnReturn() == null || pool.getRollbackOnReturn());
    if (pool != null && pool.getRemoveAbandoned() != null) {
        if ("borrow".equals(pool.getRemoveAbandoned().getOn()))
            dataSource.setRemoveAbandonedOnBorrow(true);
        else if ("maintenance".equals(pool.getRemoveAbandoned().getOn()))
            dataSource.setRemoveAbandonedOnMaintenance(true);
        else
            throw new UnsupportedOperationException(
                    "Unsupported remove abandoned spec: " + pool.getRemoveAbandoned().getOn());

        dataSource.setRemoveAbandonedTimeout(pool.getRemoveAbandoned().getTimeout());
    }

    dataSource.setAbandonedUsageTracking(
            pool != null && pool.getAbandonedUsageTracking() != null && pool.getAbandonedUsageTracking());
    dataSource.setAccessToUnderlyingConnectionAllowed(
            pool != null && pool.getAllowAccessToUnderlyingConnection() != null
                    && pool.getAllowAccessToUnderlyingConnection());

    final Dbcp.Pool.Eviction evictor = pool != null && pool.getEviction() != null ? pool.getEviction() : null;
    if (evictor != null) {
        dataSource.setTimeBetweenEvictionRunsMillis(evictor.getTimeBetweenRuns());
        dataSource.setNumTestsPerEvictionRun(evictor.getNumTestsPerRun());
        dataSource.setMinEvictableIdleTimeMillis(
                evictor.getMinIdleTime() == null ? 1800000 : evictor.getMinIdleTime());
        dataSource.setSoftMinEvictableIdleTimeMillis(
                evictor.getSoftMinIdleTime() == null || INDEFINITE.equals(evictor.getSoftMinIdleTime()) ? -1
                        : Long.parseLong(evictor.getSoftMinIdleTime()));
        if (evictor.getPolicyClassName() != null)
            dataSource.setEvictionPolicyClassName(evictor.getPolicyClassName());
    }

    final Dbcp.Validation validation = dbcp.getValidation();
    if (validation != null && validation.getQuery() != null)
        dataSource.setValidationQuery(validation.getQuery());

    dataSource.setTestOnBorrow(
            validation == null || validation.getTestOnBorrow() == null || validation.getTestOnBorrow());
    dataSource.setTestOnReturn(
            validation != null && validation.getTestOnReturn() != null && validation.getTestOnReturn());
    dataSource.setTestWhileIdle(
            validation != null && validation.getTestWhileIdle() != null && validation.getTestWhileIdle());
    if (validation != null && validation.getFastFail() != null) {
        dataSource.setFastFailValidation(true);
        if (validation.getFastFail().getDisconnectionSqlCodes() != null)
            dataSource.setDisconnectionSqlCodes(
                    Arrays.asList(validation.getFastFail().getDisconnectionSqlCodes().split(" ")));
    }

    final Dbcp.Logging logging = dbcp.getLogging();
    if (logging != null) {
        final Logger logger = LoggerFactory.getLogger(DataSources.class);
        final LoggerPrintWriter loggerPrintWriter = new LoggerPrintWriter(logger,
                Level.valueOf(logging.getLevel().toString()));
        dataSource.setLogWriter(loggerPrintWriter);
        dataSource.setLogExpiredConnections(logging.isLogExpiredConnections());
        if (logging.isLogAbandoned()) {
            dataSource.setAbandonedLogWriter(loggerPrintWriter);
            dataSource.setLogAbandoned(true);
        }
    }

    return dataSource;
}