Example usage for java.sql Connection TRANSACTION_REPEATABLE_READ

List of usage examples for java.sql Connection TRANSACTION_REPEATABLE_READ

Introduction

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

Prototype

int TRANSACTION_REPEATABLE_READ

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

Click Source Link

Document

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

Usage

From source file:org.apache.synapse.config.xml.AbstractDBMediatorFactory.java

/**
 * Create a custom DataSource using the specified properties and Apache DBCP
 * @param pool the toplevel 'pool' element that holds DataSource information
 * @param mediator the mediator to store properties for serialization
 * @return a DataSource created using specified properties
 *//*from ww  w . j ava  2  s  .c  om*/
private DataSource createCustomDataSource(OMElement pool, AbstractDBMediator mediator) {

    BasicDataSource ds = new BasicDataSource();

    // load the minimum required properties
    ds.setDriverClassName(getValue(pool, DRIVER_Q));
    ds.setUsername(getValue(pool, USER_Q));
    ds.setPassword(getValue(pool, PASS_Q));
    ds.setUrl(getValue(pool, URL_Q));

    //save loaded properties for later
    mediator.addDataSourceProperty(DRIVER_Q, getValue(pool, DRIVER_Q));
    mediator.addDataSourceProperty(URL_Q, getValue(pool, URL_Q));
    mediator.addDataSourceProperty(USER_Q, getValue(pool, USER_Q));
    mediator.addDataSourceProperty(PASS_Q, getValue(pool, PASS_Q));

    Iterator props = pool.getChildrenWithName(PROP_Q);
    while (props.hasNext()) {

        OMElement prop = (OMElement) props.next();
        String name = prop.getAttribute(ATT_NAME).getAttributeValue();
        String value = prop.getAttribute(ATT_VALUE).getAttributeValue();
        // save property for later
        mediator.addDataSourceProperty(name, value);

        if ("autocommit".equals(name)) {
            if ("true".equals(value)) {
                ds.setDefaultAutoCommit(true);
            } else if ("false".equals(value)) {
                ds.setDefaultAutoCommit(false);
            }
        } else if ("isolation".equals(name)) {
            try {
                if ("Connection.TRANSACTION_NONE".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
                } else if ("Connection.TRANSACTION_READ_COMMITTED".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                } else if ("Connection.TRANSACTION_READ_UNCOMMITTED".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
                } else if ("Connection.TRANSACTION_REPEATABLE_READ".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
                } else if ("Connection.TRANSACTION_SERIALIZABLE".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                }
            } catch (NumberFormatException ignore) {
            }
        } else if ("initialsize".equals(name)) {
            try {
                ds.setInitialSize(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxactive".equals(name)) {
            try {
                ds.setMaxActive(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxidle".equals(name)) {
            try {
                ds.setMaxIdle(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxopenstatements".equals(name)) {
            try {
                ds.setMaxOpenPreparedStatements(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxwait".equals(name)) {
            try {
                ds.setMaxWait(Long.parseLong(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("minidle".equals(name)) {
            try {
                ds.setMinIdle(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("poolstatements".equals(name)) {
            if ("true".equals(value)) {
                ds.setPoolPreparedStatements(true);
            } else if ("false".equals(value)) {
                ds.setPoolPreparedStatements(false);
            }
        } else if ("testonborrow".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestOnBorrow(true);
            } else if ("false".equals(value)) {
                ds.setTestOnBorrow(false);
            }
        } else if ("testonreturn".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestOnReturn(true);
            } else if ("false".equals(value)) {
                ds.setTestOnReturn(false);
            }
        } else if ("testwhileidle".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestWhileIdle(true);
            } else if ("false".equals(value)) {
                ds.setTestWhileIdle(false);
            }
        } else if ("validationquery".equals(name)) {
            ds.setValidationQuery(value);
        }
    }
    return ds;
}

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");
        }// w  ww  . j a va2 s . c o  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.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 w  w  w  .j  a  va  2  s.com
            throw new RuntimeException("Unknown value '" + transactionIsolationObject
                    + "' for the property key '" + DSFConstants.ATTR_DEFAULT_TRANSACTION_ISOLATION
                    + " during datasource configuration.");
        }
    }
}

From source file:org.executequery.gui.browser.ConnectionPanel.java

private int isolationLevelFromSelection(int index) {
    int isolationLevel = -1;
    switch (index) {
    case 1:// w w w  .  ja  v  a  2  s.c o  m
        isolationLevel = Connection.TRANSACTION_NONE;
        break;
    case 2:
        isolationLevel = Connection.TRANSACTION_READ_UNCOMMITTED;
        break;
    case 3:
        isolationLevel = Connection.TRANSACTION_READ_COMMITTED;
        break;
    case 4:
        isolationLevel = Connection.TRANSACTION_REPEATABLE_READ;
        break;
    case 5:
        isolationLevel = Connection.TRANSACTION_SERIALIZABLE;
        break;
    }
    return isolationLevel;
}

From source file:org.executequery.gui.browser.ConnectionPanel.java

/**
 * Sets the values for the tx level on the tx combo
 * based on the tx level in the connection object.
 *//*from   w  ww  .  ja  va2  s.c o m*/
private void setTransactionIsolationLevel() {
    int index = 0;
    int isolationLevel = databaseConnection.getTransactionIsolation();
    switch (isolationLevel) {
    case Connection.TRANSACTION_NONE:
        index = 1;
        break;
    case Connection.TRANSACTION_READ_UNCOMMITTED:
        index = 2;
        break;
    case Connection.TRANSACTION_READ_COMMITTED:
        index = 3;
        break;
    case Connection.TRANSACTION_REPEATABLE_READ:
        index = 4;
        break;
    case Connection.TRANSACTION_SERIALIZABLE:
        index = 5;
        break;
    }
    txCombo.setSelectedIndex(index);
}

From source file:org.jxstar.dao.pool.PooledConnection.java

/**
 * ???JDBC/*from w  ww .  j  a v a 2s  .  c o m*/
 * Connection.TRANSACTION_NONE
 *       ????
 * Connection.TRANSACTION_READ_UNCOMMITTED
 *       ?????????
 * Connection.TRANSACTION_READ_COMMITTED(?)
 *       ????????? 
 * Connection.TRANSACTION_REPEATABLE_READ
 *       ?????????
 * Connection.TRANSACTION_SERIALIZABLE
 *       ????????
 * 
 * @param sTranLevel
 * @return
 */
private int getTranLevelConstant(String sTranLevel) {
    if (sTranLevel == null || sTranLevel.length() == 0) {
        return Connection.TRANSACTION_READ_COMMITTED;
    }

    String sTmpLevel = sTranLevel.toUpperCase();
    if (sTmpLevel.equals("TRANSACTION_NONE")) {
        return Connection.TRANSACTION_NONE;
    } else if (sTmpLevel.equals("TRANSACTION_READ_UNCOMMITTED")) {
        return Connection.TRANSACTION_READ_UNCOMMITTED;
    } else if (sTmpLevel.equals("TRANSACTION_READ_COMMITTED")) {
        return Connection.TRANSACTION_READ_COMMITTED;
    } else if (sTmpLevel.equals("TRANSACTION_REPEATABLE_READ")) {
        return Connection.TRANSACTION_REPEATABLE_READ;
    } else if (sTmpLevel.equals("TRANSACTION_SERIALIZABLE")) {
        return Connection.TRANSACTION_SERIALIZABLE;
    }

    return Connection.TRANSACTION_READ_COMMITTED;
}

From source file:org.kawanfw.sql.jdbc.ConnectionHttp.java

/**
 * Attempts to change the transaction isolation level for this
 * <code>Connection</code> object to the one given. The constants defined in
 * the interface <code>Connection</code> are the possible transaction
 * isolation levels.//from w w w  .j a  v  a2 s.com
 * <P>
 * <B>Note:</B> If this method is called during a transaction, the result is
 * implementation-defined.
 * 
 * @param level
 *            one of the following <code>Connection</code> constants:
 *            <code>Connection.TRANSACTION_READ_UNCOMMITTED</code>,
 *            <code>Connection.TRANSACTION_READ_COMMITTED</code>,
 *            <code>Connection.TRANSACTION_REPEATABLE_READ</code>, or
 *            <code>Connection.TRANSACTION_SERIALIZABLE</code>. (Note that
 *            <code>Connection.TRANSACTION_NONE</code> cannot be used
 *            because it specifies that transactions are not supported.)
 * @exception SQLException
 *                if a database access error occurs, this method is called
 *                on a closed connection or the given parameter is not one
 *                of the <code>Connection</code> constants
 * @see DatabaseMetaData#supportsTransactionIsolationLevel
 * @see #getTransactionIsolation
 */
@Override
public void setTransactionIsolation(int level) throws SQLException {
    testIfClosed();

    if (level != Connection.TRANSACTION_READ_UNCOMMITTED && level != Connection.TRANSACTION_READ_COMMITTED
            && level != Connection.TRANSACTION_REPEATABLE_READ
            && level != Connection.TRANSACTION_SERIALIZABLE) {
        throw new SQLException("Illegal transaction isolation level: " + level);
    }

    if (!statelessMode) {
        JdbcHttpTransactionTransfer jdbcHttpTransactionTransfer = new JdbcHttpTransactionTransfer(this,
                authenticationToken);
        jdbcHttpTransactionTransfer.setTransactionIsolation(level);
    }

    this.transactionIsolation = level;
}

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  www. jav a  2s . c om

    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.lib4j.dbcp.DataSources.java

/**
 * Create a <code>BasicDataSource</code> given a dbcp JAXB binding.
 *
 * @param dbcp JAXB dbcp binding./*from  w  w w .  j a va  2s.  c om*/
 * @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;
}

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

public static BasicDataSource createDataSource(final $dbcp_dbcp dbcp) throws SQLException {
    if (dbcp.isNull())
        throw new BindingRuntimeException("/dbcp:jdbc is missing");

    final dbcp_dbcp._jdbc jdbc = dbcp._jdbc(0);
    final BasicDataSource dataSource = new BasicDataSource() {
        @Override/*from www  . j a va 2s . c  om*/
        public Connection getConnection() throws SQLException {
            //        try {
            return super.getConnection();
            //        }
            //        catch (final SQLException e) {
            //          // TODO: Finish this!
            //          if ("Cannot get a connection, pool error Timeout waiting for idle object".equals(e.getMessage()))
            //            Throwables.set(e, "XX" + e.getMessage());
            //
            //          throw e;
            //        }
        }
    };

    if (jdbc._driverClassName(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:driverClassName is missing");

    dataSource.setDriverClassName(jdbc._driverClassName(0).text());

    //    if (jdbc._loginTimeout() != null && jdbc._loginTimeout().size() != 0 && jdbc._loginTimeout(0).text() != null) {
    // FIXME: This causes a ClassNotFoundException: com.sybase.jdbc3.jdbc.SybDriver
    //      try {
    //        dataSource.setLoginTimeout(jdbc._loginTimeout(0).text());
    //      }
    //      catch(final SQLException e) {
    //        throw new SQLException(e);
    //      }
    //  }

    if (jdbc._url(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:url is missing");

    dataSource.setUrl(jdbc._url(0).text());

    if (jdbc._username(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:username is missing");

    dataSource.setUsername(jdbc._username(0).text());

    if (jdbc._password(0).isNull())
        throw new BindingRuntimeException("/dbcp:jdbc/dbcp:password is missing");

    dataSource.setPassword(jdbc._password(0).text());
    final dbcp_dbcp._default defaults = dbcp._default(0);
    if (!defaults._connectionProperties(0).isNull())
        for (final dbcp_dbcp._default._connectionProperties._property property : defaults
                ._connectionProperties(0)._property())
            if (property._name$() != null && property._name$().text() != null && property._value$() != null
                    && property._value$().text() != null)
                dataSource.addConnectionProperty(property._name$().text(), property._value$().text());

    if (!defaults._autoCommit(0).isNull())
        dataSource.setDefaultAutoCommit(defaults._autoCommit(0).text());

    if (!defaults._readOnly(0).isNull())
        dataSource.setDefaultReadOnly(defaults._readOnly(0).text());

    if (!defaults._transactionIsolation(0).isNull()) {
        if (dbcp_dbcp._default._transactionIsolation.NONE.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        else if (dbcp_dbcp._default._transactionIsolation.READ_5FCOMMITTED.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        else if (dbcp_dbcp._default._transactionIsolation.READ_5FUNCOMMITTED.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        else if (dbcp_dbcp._default._transactionIsolation.REPEATABLE_5FREAD.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        else if (dbcp_dbcp._default._transactionIsolation.SERIALIZABLE.text()
                .equals(defaults._transactionIsolation(0).text()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        else
            throw new UnsupportedOperationException(
                    "Unsupported transaction isolation: " + defaults._transactionIsolation(0).text());
    }

    final dbcp_dbcp._size size = dbcp._size(0);
    if (!size.isNull()) {
        if (!size._initialSize(0).isNull())
            dataSource.setInitialSize(size._initialSize(0).text().intValue());

        if (!size._maxActive(0).isNull())
            dataSource.setMaxTotal(size._maxActive(0).text().intValue());

        if (!size._maxIdle(0).isNull())
            dataSource.setMaxIdle(size._maxIdle(0).text().intValue());

        if (!size._minIdle(0).isNull())
            dataSource.setMinIdle(size._minIdle(0).text().intValue());

        if (!size._maxWait(0).isNull())
            dataSource.setMaxWaitMillis(size._maxWait(0).text().intValue());
    }

    final dbcp_dbcp._management management = dbcp._management(0);
    if (!management.isNull()) {
        if (!management._validationQuery(0).isNull())
            dataSource.setValidationQuery(management._validationQuery(0).text());

        if (!management._testOnBorrow(0).isNull())
            dataSource.setTestOnBorrow(management._testOnBorrow(0).text());

        if (!management._testOnReturn(0).isNull())
            dataSource.setTestOnReturn(management._testOnReturn(0).text());

        if (!management._testWhileIdle(0).isNull())
            dataSource.setTestWhileIdle(management._testWhileIdle(0).text());

        if (!management._timeBetweenEvictionRuns(0).isNull())
            dataSource
                    .setTimeBetweenEvictionRunsMillis(management._timeBetweenEvictionRuns(0).text().intValue());

        if (!management._numTestsPerEvictionRun(0).isNull())
            dataSource.setNumTestsPerEvictionRun(management._numTestsPerEvictionRun(0).text().intValue());

        if (!management._minEvictableIdleTime(0).isNull())
            dataSource.setMinEvictableIdleTimeMillis(management._minEvictableIdleTime(0).text().intValue());
    }

    final dbcp_dbcp._preparedStatements preparedStatements = dbcp._preparedStatements(0);
    if (!preparedStatements.isNull()) {
        if (!preparedStatements._poolPreparedStatements(0).isNull())
            dataSource.setPoolPreparedStatements(preparedStatements._poolPreparedStatements(0).text());

        if (!preparedStatements._maxOpenPreparedStatements(0).isNull())
            dataSource.setMaxOpenPreparedStatements(
                    preparedStatements._maxOpenPreparedStatements(0).text().intValue());
    }

    final dbcp_dbcp._removal removal = dbcp._removal(0);
    if (!removal.isNull()) {
        if (!removal._removeAbandoned(0).isNull())
            dataSource.setRemoveAbandonedOnBorrow(removal._removeAbandoned(0).text());

        if (!removal._removeAbandonedTimeout(0).isNull())
            dataSource.setRemoveAbandonedTimeout(removal._removeAbandonedTimeout(0).text().intValue());

        if (!removal._logAbandoned(0).isNull())
            dataSource.setLogAbandoned(removal._logAbandoned(0).text());
    }

    final dbcp_dbcp._logging logging = dbcp._logging(0);
    if (!logging.isNull()) {
        final Logger logger = LoggerFactory.getLogger(DataSources.class);
        final LoggerPrintWriter loggerPrintWriter = new LoggerPrintWriter(logger,
                Level.valueOf(logging._level(0).text()));
        dataSource.setLogWriter(loggerPrintWriter);
        dataSource.setLogExpiredConnections(
                !logging._logExpiredConnections(0).isNull() && logging._logExpiredConnections(0).text());
        if (!logging._logAbandoned(0).isNull() && logging._logAbandoned(0).text()) {
            dataSource.setAbandonedLogWriter(loggerPrintWriter);
            dataSource.setLogAbandoned(true);
        }
    }

    return dataSource;
}