Java Code Examples for java.sql.Connection.isReadOnly()

The following are Jave code examples for showing how to use isReadOnly() of the java.sql.Connection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: DBus   File: OracleManager.java   View Source Code Vote up 6 votes
/**
 * @return a Connection instance that can be used to connect to the
 * given database, if a previously-opened connection is available in
 * the cache. Returns null if none is available in the map.
 */
public synchronized Connection getConnection(String connectStr,
    String username) throws SQLException {
  CacheKey key = new CacheKey(connectStr, username);
  Connection cached = connectionMap.get(key);
  if (null != cached) {
    connectionMap.remove(key);
    if (cached.isReadOnly()) {
      // Read-only mode? Don't want it.
      cached.close();
    }

    if (cached.isClosed()) {
      // This connection isn't usable.
      return null;
    }

    cached.rollback(); // Reset any transaction state.
    cached.clearWarnings();

    LOG.debug("Got cached connection for " + key);
  }

  return cached;
}
 
Example 2
Project: aceql-http   File: ConnectionUtil.java   View Source Code Vote up 6 votes
/**
    * Put the Connection in auto-commit mode and in read only false
    * @param connection	the JDBC Connection to init
    * @throws SQLException	if any SQL Exception occurs
    */
   public static void connectionInit(Connection connection) throws SQLException {
	
// Make sure Connection extracted from the pool is always on autocommit mode
// This avoid for client side to send a connection.getAutoCommit() before 
// starting working.
// This is anyway mandatory for C# as all Connections are per default
// auto commit mode.
if (!connection.getAutoCommit()) {
    connection.rollback();
    connection.setAutoCommit(true);
}

// Make sure we are not in read only. Don't trap Exception because of
// Drivers not supporting this call
if (connection.isReadOnly()) {
    try {
	connection.setReadOnly(false);
    } catch (Exception e) {
	// Ignore
	System.err.println(e.toString());
    }
}
   }
 
Example 3
Project: lams   File: DataSourceUtils.java   View Source Code Vote up 6 votes
/**
 * Reset the given Connection after a transaction,
 * regarding read-only flag and isolation level.
 * @param con the Connection to reset
 * @param previousIsolationLevel the isolation level to restore, if any
 * @see #prepareConnectionForTransaction
 */
public static void resetConnectionAfterTransaction(Connection con, Integer previousIsolationLevel) {
	Assert.notNull(con, "No Connection specified");
	try {
		// Reset transaction isolation to previous value, if changed for the transaction.
		if (previousIsolationLevel != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Resetting isolation level of JDBC Connection [" +
						con + "] to " + previousIsolationLevel);
			}
			con.setTransactionIsolation(previousIsolationLevel);
		}

		// Reset read-only flag.
		if (con.isReadOnly()) {
			if (logger.isDebugEnabled()) {
				logger.debug("Resetting read-only flag of JDBC Connection [" + con + "]");
			}
			con.setReadOnly(false);
		}
	}
	catch (Throwable ex) {
		logger.debug("Could not reset JDBC Connection after transaction", ex);
	}
}
 
Example 4
Project: aliyun-maxcompute-data-collectors   File: OracleManager.java   View Source Code Vote up 6 votes
/**
 * @return a Connection instance that can be used to connect to the
 * given database, if a previously-opened connection is available in
 * the cache. Returns null if none is available in the map.
 */
public synchronized Connection getConnection(String connectStr,
    String username) throws SQLException {
  CacheKey key = new CacheKey(connectStr, username);
  Connection cached = connectionMap.get(key);
  if (null != cached) {
    connectionMap.remove(key);
    if (cached.isReadOnly()) {
      // Read-only mode? Don't want it.
      cached.close();
    }

    if (cached.isClosed()) {
      // This connection isn't usable.
      return null;
    }

    cached.rollback(); // Reset any transaction state.
    cached.clearWarnings();

    LOG.debug("Got cached connection for " + key);
  }

  return cached;
}
 
Example 5
Project: uroborosql   File: DataSourceConnectionSupplierImpl.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 *
 * @param datasourceName 取得するコネクションのデータソース名
 *
 * @see jp.co.future.uroborosql.connection.ConnectionSupplier#getConnection(java.lang.String)
 */
@Override
public Connection getConnection(final String datasourceName) {
	try {
		DataSource ds = dsMap.computeIfAbsent(datasourceName, DataSourceConnectionSupplierImpl::getNewDataSource);
		final Connection connection;
		synchronized (ds) {
			connection = ds.getConnection();
		}
		boolean autoCommit = getAutoCommit(datasourceName);
		if (connection.getAutoCommit() != autoCommit) {
			connection.setAutoCommit(autoCommit);
		}
		boolean readOnly = getReadOnly(datasourceName);
		if (connection.isReadOnly() != readOnly) {
			connection.setReadOnly(readOnly);
		}
		int transactionIsolation = getTransactionIsolation(datasourceName);
		if (transactionIsolation > 0 && connection.getTransactionIsolation() != transactionIsolation) {
			connection.setTransactionIsolation(transactionIsolation);
		}
		return connection;
	} catch (SQLException ex) {
		throw new UroborosqlRuntimeException("Connection[" + datasourceName + "] can not be acquired.", ex);
	}
}
 
Example 6
Project: sstore-soft   File: ConnectionDefaults.java   View Source Code Vote up 5 votes
public ConnectionDefaults(Connection connection) throws SQLException {

        this.holdability          = connection.getHoldability();
        this.transactionIsolation = connection.getTransactionIsolation();
        this.isAutoCommit         = connection.getAutoCommit();
        this.isReadOnly           = connection.isReadOnly();
        this.catalog              = connection.getCatalog();
    }
 
Example 7
Project: dubbo-transaction   File: DBTransaction.java   View Source Code Vote up 5 votes
public boolean prepare(){
    try {
        if (status.getTransaction() instanceof JdbcTransactionObjectSupport) {
            JdbcTransactionObjectSupport support = (JdbcTransactionObjectSupport) status.getTransaction();
            ConnectionHolder holder = support.getConnectionHolder();
            Connection con = holder.getConnection();
            return !con.isClosed() && !con.isReadOnly();
        }
    }catch (Exception e){
    }
    return false;
}
 
Example 8
Project: s-store   File: ConnectionDefaults.java   View Source Code Vote up 5 votes
public ConnectionDefaults(Connection connection) throws SQLException {

        this.holdability          = connection.getHoldability();
        this.transactionIsolation = connection.getTransactionIsolation();
        this.isAutoCommit         = connection.getAutoCommit();
        this.isReadOnly           = connection.isReadOnly();
        this.catalog              = connection.getCatalog();
    }
 
Example 9
Project: calcite-avatica   File: RemoteMetaTest.java   View Source Code Vote up 5 votes
@Test public void testRemoteConnectionProperties() throws Exception {
  ConnectionSpec.getDatabaseLock().lock();
  try (AvaticaConnection conn = (AvaticaConnection) DriverManager.getConnection(url)) {
    String id = conn.id;
    final Map<String, ConnectionPropertiesImpl> m = ((RemoteMeta) getMeta(conn)).propsMap;
    assertFalse("remote connection map should start ignorant", m.containsKey(id));
    // force creating a connection object on the remote side.
    try (final Statement stmt = conn.createStatement()) {
      assertTrue("creating a statement starts a local object.", m.containsKey(id));
      assertTrue(stmt.execute("select count(1) from EMP"));
    }
    Connection remoteConn = getConnection(FullyRemoteJdbcMetaFactory.getInstance(), id);
    final boolean defaultRO = remoteConn.isReadOnly();
    final boolean defaultAutoCommit = remoteConn.getAutoCommit();
    final String defaultCatalog = remoteConn.getCatalog();
    final String defaultSchema = remoteConn.getSchema();
    conn.setReadOnly(!defaultRO);
    assertTrue("local changes dirty local state", m.get(id).isDirty());
    assertEquals("remote connection has not been touched", defaultRO, remoteConn.isReadOnly());
    conn.setAutoCommit(!defaultAutoCommit);
    assertEquals("remote connection has not been touched",
        defaultAutoCommit, remoteConn.getAutoCommit());

    // further interaction with the connection will force a sync
    try (final Statement stmt = conn.createStatement()) {
      assertEquals(!defaultAutoCommit, remoteConn.getAutoCommit());
      assertFalse("local values should be clean", m.get(id).isDirty());
    }
  } finally {
    ConnectionSpec.getDatabaseLock().unlock();
  }
}
 
Example 10
Project: calcite-avatica   File: AlternatingRemoteMetaTest.java   View Source Code Vote up 5 votes
@Test public void testRemoteConnectionProperties() throws Exception {
  ConnectionSpec.getDatabaseLock().lock();
  try (AvaticaConnection conn = (AvaticaConnection) DriverManager.getConnection(url)) {
    String id = conn.id;
    final Map<String, ConnectionPropertiesImpl> m = ((RemoteMeta) getMeta(conn)).propsMap;
    assertFalse("remote connection map should start ignorant", m.containsKey(id));
    // force creating a connection object on the remote side.
    try (final Statement stmt = conn.createStatement()) {
      assertTrue("creating a statement starts a local object.", m.containsKey(id));
      assertTrue(stmt.execute("select count(1) from EMP"));
    }
    Connection remoteConn = getConnection(FullyRemoteJdbcMetaFactory.getInstance(), id);
    final boolean defaultRO = remoteConn.isReadOnly();
    final boolean defaultAutoCommit = remoteConn.getAutoCommit();
    final String defaultCatalog = remoteConn.getCatalog();
    final String defaultSchema = remoteConn.getSchema();
    conn.setReadOnly(!defaultRO);
    assertTrue("local changes dirty local state", m.get(id).isDirty());
    assertEquals("remote connection has not been touched", defaultRO, remoteConn.isReadOnly());
    conn.setAutoCommit(!defaultAutoCommit);
    assertEquals("remote connection has not been touched",
        defaultAutoCommit, remoteConn.getAutoCommit());

    // further interaction with the connection will force a sync
    try (final Statement stmt = conn.createStatement()) {
      assertEquals(!defaultAutoCommit, remoteConn.getAutoCommit());
      assertFalse("local values should be clean", m.get(id).isDirty());
    }
  } finally {
    ConnectionSpec.getDatabaseLock().unlock();
  }
}
 
Example 11
Project: spwrap   File: ConnectionProps.java   View Source Code Vote up 5 votes
public static ConnectionProps from(Connection connection) {
    try {
        return new ConnectionProps(connection.isReadOnly(), Isolation.of(connection.getTransactionIsolation()));
    } catch (SQLException e) {
        throw new CallException(e);
    }
}
 
Example 12
Project: the-vigilantes   File: ConnectionTest.java   View Source Code Vote up 4 votes
public void testReadOnly56() throws Exception {
    if (versionMeetsMinimum(5, 6, 5)) {
        try {
            Connection notLocalState = getConnectionWithProps("profileSql=true");

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                notLocalState.setReadOnly(true);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") != -1);
                notLocalState.createStatement().execute("set session transaction read write");
                assertFalse(notLocalState.isReadOnly());
            }

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                notLocalState.setReadOnly(false);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read write") != -1);
                notLocalState.createStatement().execute("set session transaction read only");
                assertTrue(notLocalState.isReadOnly());
            }

            Connection localState = getConnectionWithProps("profileSql=true,useLocalSessionState=true");

            String txReadOnlyName = versionMeetsMinimum(8, 0, 3) ? "transaction_read_only" : "tx_read_only";

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                localState.setReadOnly(true);
                if (i == 0) {
                    assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") != -1);
                } else {
                    assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") == -1);
                }
                StandardLogger.startLoggingToBuffer();
                localState.isReadOnly();
                assertTrue(StandardLogger.getBuffer().toString().indexOf("select @@session." + txReadOnlyName) == -1);
            }

            Connection noOptimization = getConnectionWithProps("profileSql=true,readOnlyPropagatesToServer=false");

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                noOptimization.setReadOnly(true);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") == -1);
                StandardLogger.startLoggingToBuffer();
                noOptimization.isReadOnly();
                assertTrue(StandardLogger.getBuffer().toString().indexOf("select @@session." + txReadOnlyName) == -1);
            }
        } finally {
            StandardLogger.dropBuffer();
        }
    }
}
 
Example 13
Project: OpenVertretung   File: ConnectionTest.java   View Source Code Vote up 4 votes
public void testReadOnly56() throws Exception {
    if (versionMeetsMinimum(5, 6, 5)) {
        try {
            Connection notLocalState = getConnectionWithProps("profileSql=true");

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                notLocalState.setReadOnly(true);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") != -1);
                notLocalState.createStatement().execute("set session transaction read write");
                assertFalse(notLocalState.isReadOnly());
            }

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                notLocalState.setReadOnly(false);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read write") != -1);
                notLocalState.createStatement().execute("set session transaction read only");
                assertTrue(notLocalState.isReadOnly());
            }

            Connection localState = getConnectionWithProps("profileSql=true,useLocalSessionState=true");

            String txReadOnlyName = versionMeetsMinimum(8, 0, 3) ? "transaction_read_only" : "tx_read_only";

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                localState.setReadOnly(true);
                if (i == 0) {
                    assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") != -1);
                } else {
                    assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") == -1);
                }
                StandardLogger.startLoggingToBuffer();
                localState.isReadOnly();
                assertTrue(StandardLogger.getBuffer().toString().indexOf("select @@session." + txReadOnlyName) == -1);
            }

            Connection noOptimization = getConnectionWithProps("profileSql=true,readOnlyPropagatesToServer=false");

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                noOptimization.setReadOnly(true);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") == -1);
                StandardLogger.startLoggingToBuffer();
                noOptimization.isReadOnly();
                assertTrue(StandardLogger.getBuffer().toString().indexOf("select @@session." + txReadOnlyName) == -1);
            }
        } finally {
            StandardLogger.dropBuffer();
        }
    }
}
 
Example 14
Project: ProyectoPacientes   File: ConnectionTest.java   View Source Code Vote up 4 votes
public void testReadOnly56() throws Exception {
    if (versionMeetsMinimum(5, 6, 5)) {
        try {
            Connection notLocalState = getConnectionWithProps("profileSql=true");

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                notLocalState.setReadOnly(true);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") != -1);
                notLocalState.createStatement().execute("set session transaction read write");
                assertFalse(notLocalState.isReadOnly());
            }

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                notLocalState.setReadOnly(false);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read write") != -1);
                notLocalState.createStatement().execute("set session transaction read only");
                assertTrue(notLocalState.isReadOnly());
            }

            Connection localState = getConnectionWithProps("profileSql=true,useLocalSessionState=true");

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                localState.setReadOnly(true);
                if (i == 0) {
                    assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") != -1);
                } else {
                    assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") == -1);
                }
                StandardLogger.startLoggingToBuffer();
                localState.isReadOnly();
                assertTrue(StandardLogger.getBuffer().toString().indexOf("select @@session.tx_read_only") == -1);
            }

            Connection noOptimization = getConnectionWithProps("profileSql=true,readOnlyPropagatesToServer=false");

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                noOptimization.setReadOnly(true);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") == -1);
                StandardLogger.startLoggingToBuffer();
                noOptimization.isReadOnly();
                assertTrue(StandardLogger.getBuffer().toString().indexOf("select @@session.tx_read_only") == -1);
            }
        } finally {
            StandardLogger.dropBuffer();
        }
    }
}
 
Example 15
Project: BibliotecaPS   File: ConnectionTest.java   View Source Code Vote up 4 votes
public void testReadOnly56() throws Exception {
    if (versionMeetsMinimum(5, 6, 5)) {
        try {
            Connection notLocalState = getConnectionWithProps("profileSql=true");

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                notLocalState.setReadOnly(true);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") != -1);
                notLocalState.createStatement().execute("set session transaction read write");
                assertFalse(notLocalState.isReadOnly());
            }

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                notLocalState.setReadOnly(false);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read write") != -1);
                notLocalState.createStatement().execute("set session transaction read only");
                assertTrue(notLocalState.isReadOnly());
            }

            Connection localState = getConnectionWithProps("profileSql=true,useLocalSessionState=true");

            String txReadOnlyName = versionMeetsMinimum(8, 0, 3) ? "transaction_read_only" : "tx_read_only";

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                localState.setReadOnly(true);
                if (i == 0) {
                    assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") != -1);
                } else {
                    assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") == -1);
                }
                StandardLogger.startLoggingToBuffer();
                localState.isReadOnly();
                assertTrue(StandardLogger.getBuffer().toString().indexOf("select @@session." + txReadOnlyName) == -1);
            }

            Connection noOptimization = getConnectionWithProps("profileSql=true,readOnlyPropagatesToServer=false");

            for (int i = 0; i < 2; i++) {
                StandardLogger.startLoggingToBuffer();
                noOptimization.setReadOnly(true);
                assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") == -1);
                StandardLogger.startLoggingToBuffer();
                noOptimization.isReadOnly();
                assertTrue(StandardLogger.getBuffer().toString().indexOf("select @@session." + txReadOnlyName) == -1);
            }
        } finally {
            StandardLogger.dropBuffer();
        }
    }
}
 
Example 16
Project: calcite-avatica   File: ConnectionPropertiesImpl.java   View Source Code Vote up 4 votes
public ConnectionPropertiesImpl(Connection conn) throws SQLException {
  this(conn.getAutoCommit(), conn.isReadOnly(), conn.getTransactionIsolation(),
      conn.getCatalog(), conn.getSchema());
}