List of usage examples for java.sql Connection TRANSACTION_SERIALIZABLE
int TRANSACTION_SERIALIZABLE
To view the source code for java.sql Connection TRANSACTION_SERIALIZABLE.
Click Source Link
From source file:org.noerp.entity.connection.DBCPConnectionFactory.java
public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc) throws SQLException, GenericEntityException { String cacheKey = helperInfo.getHelperFullName(); ManagedDataSource mds = dsCache.get(cacheKey); if (mds != null) { return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection()); }// w w w . ja va 2 s .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); 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 pool = new GenericObjectPool(factory, poolConfig); factory.setPool(pool); mds = new ManagedDataSource(pool, xacf.getTransactionRegistry()); //mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry()); // Useful to debug the usage of connections in the pool mds.setAccessToUnderlyingConnectionAllowed(true); // cache the pool dsCache.putIfAbsent(cacheKey, mds); mds = dsCache.get(cacheKey); return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection()); }
From source file:org.nuxeo.runtime.datasource.BasicManagedDataSourceFactory.java
/** * Creates and configures a {@link BasicManagedDataSource} instance based on * the given properties./*from w w w .j a v a 2 s . c o m*/ * * @param properties the datasource configuration properties * @throws Exception if an error occurs creating the data source */ public static DataSource createDataSource(Properties properties) throws Exception { BasicManagedDataSource dataSource = new BasicManagedDataSource(); String value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT); if (value != null) { dataSource.setDefaultAutoCommit(Boolean.valueOf(value).booleanValue()); } value = properties.getProperty(PROP_DEFAULTREADONLY); if (value != null) { dataSource.setDefaultReadOnly(Boolean.valueOf(value).booleanValue()); } value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION); if (value != null) { int level = UNKNOWN_TRANSACTIONISOLATION; if ("NONE".equalsIgnoreCase(value)) { level = Connection.TRANSACTION_NONE; } else if ("READ_COMMITTED".equalsIgnoreCase(value)) { level = Connection.TRANSACTION_READ_COMMITTED; } else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) { level = Connection.TRANSACTION_READ_UNCOMMITTED; } else if ("REPEATABLE_READ".equalsIgnoreCase(value)) { level = Connection.TRANSACTION_REPEATABLE_READ; } else if ("SERIALIZABLE".equalsIgnoreCase(value)) { level = Connection.TRANSACTION_SERIALIZABLE; } else { try { level = Integer.parseInt(value); } catch (NumberFormatException e) { System.err.println("Could not parse defaultTransactionIsolation: " + value); System.err.println("WARNING: defaultTransactionIsolation not set"); System.err.println("using default value of database driver"); level = UNKNOWN_TRANSACTIONISOLATION; } } dataSource.setDefaultTransactionIsolation(level); } value = properties.getProperty(PROP_DEFAULTCATALOG); if (value != null) { dataSource.setDefaultCatalog(value); } value = properties.getProperty(PROP_DRIVERCLASSNAME); if (value != null) { dataSource.setDriverClassName(value); } value = properties.getProperty(PROP_MAXACTIVE); if (value != null) { dataSource.setMaxActive(Integer.parseInt(value)); } value = properties.getProperty(PROP_MAXIDLE); if (value != null) { dataSource.setMaxIdle(Integer.parseInt(value)); } value = properties.getProperty(PROP_MINIDLE); if (value != null) { dataSource.setMinIdle(Integer.parseInt(value)); } value = properties.getProperty(PROP_INITIALSIZE); if (value != null) { dataSource.setInitialSize(Integer.parseInt(value)); } value = properties.getProperty(PROP_MAXWAIT); if (value != null) { dataSource.setMaxWait(Long.parseLong(value)); } value = properties.getProperty(PROP_TESTONBORROW); if (value != null) { dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue()); } value = properties.getProperty(PROP_TESTONRETURN); if (value != null) { dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue()); } value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS); if (value != null) { dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value)); } value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN); if (value != null) { dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value)); } value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS); if (value != null) { dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value)); } value = properties.getProperty(PROP_TESTWHILEIDLE); if (value != null) { dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue()); } value = properties.getProperty(PROP_PASSWORD); if (value != null) { dataSource.setPassword(value); } value = properties.getProperty(PROP_URL); if (value != null) { dataSource.setUrl(value); } value = properties.getProperty(PROP_USERNAME); if (value != null) { dataSource.setUsername(value); } value = properties.getProperty(PROP_VALIDATIONQUERY); if (value != null) { dataSource.setValidationQuery(value); } value = properties.getProperty(PROP_VALIDATIONQUERY_TIMEOUT); if (value != null) { dataSource.setValidationQueryTimeout(Integer.parseInt(value)); } value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED); if (value != null) { dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue()); } value = properties.getProperty(PROP_REMOVEABANDONED); if (value != null) { dataSource.setRemoveAbandoned(Boolean.valueOf(value).booleanValue()); } value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT); if (value != null) { dataSource.setRemoveAbandonedTimeout(Integer.parseInt(value)); } value = properties.getProperty(PROP_LOGABANDONED); if (value != null) { dataSource.setLogAbandoned(Boolean.valueOf(value).booleanValue()); } value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS); if (value != null) { dataSource.setPoolPreparedStatements(Boolean.valueOf(value).booleanValue()); } value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS); if (value != null) { dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value)); } value = properties.getProperty(PROP_INITCONNECTIONSQLS); if (value != null) { StringTokenizer tokenizer = new StringTokenizer(value, ";"); dataSource.setConnectionInitSqls(Collections.list(tokenizer)); } value = properties.getProperty(PROP_CONNECTIONPROPERTIES); if (value != null) { Properties p = getProperties(value); Enumeration<?> e = p.propertyNames(); while (e.hasMoreElements()) { String propertyName = (String) e.nextElement(); dataSource.addConnectionProperty(propertyName, p.getProperty(propertyName)); } } // Managed: initialize XADataSource value = properties.getProperty(PROP_XADATASOURCE); if (value != null) { Class<?> xaDataSourceClass; try { xaDataSourceClass = Class.forName(value); } catch (Throwable t) { throw (SQLException) new SQLException("Cannot load XA data source class '" + value + "'") .initCause(t); } XADataSource xaDataSource; try { xaDataSource = (XADataSource) xaDataSourceClass.newInstance(); } catch (Throwable t) { throw (SQLException) new SQLException("Cannot create XA data source of class '" + value + "'") .initCause(t); } dataSource.setXaDataSourceInstance(xaDataSource); } // DBCP-215 // Trick to make sure that initialSize connections are created if (dataSource.getInitialSize() > 0) { dataSource.getLogWriter(); } // Return the configured DataSource instance return dataSource; }
From source file:org.openconcerto.sql.model.SQLDataSource.java
public final void setInitialTransactionIsolation(int level) { if (level != Connection.TRANSACTION_READ_UNCOMMITTED && level != Connection.TRANSACTION_READ_COMMITTED && level != Connection.TRANSACTION_REPEATABLE_READ && level != Connection.TRANSACTION_SERIALIZABLE) throw new IllegalArgumentException("Invalid value :" + level); synchronized (this) { if (this.txIsolation != level) { this.txIsolation = level; // perhaps do like setInitialSchema() : i.e. call setTransactionIsolation() on // existing connections this.invalidateAllConnections(false); }//www. ja v a 2s. c o m } }
From source file:org.opendatakit.common.persistence.engine.mysql.TaskLockImpl.java
private TaskLockTable doTransaction(TaskLockTable entity, long l) throws ODKEntityNotFoundException, ODKTaskLockException { boolean first; final List<String> stmts = new ArrayList<String>(); final String uri = entity.getUri(); StringBuilder b = new StringBuilder(); String tableName = K_BQ + datastore.getDefaultSchemaName() + K_BQ + "." + K_BQ + TaskLockTable.TABLE_NAME + K_BQ;// w ww . jav a 2 s .c o m // String tableName= TaskLockTable.TABLE_NAME; b.append("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE"); stmts.add(b.toString()); b.setLength(0); b.append("START TRANSACTION WITH CONSISTENT SNAPSHOT"); stmts.add(b.toString()); b.setLength(0); b.append("SET @present := NOW(),"); b.append(" @uriUser := '"); b.append(user.getUriUser().replaceAll("'", "''")); b.append("',"); b.append(" @uriLock := '"); b.append(uri.replaceAll("'", "''")); b.append("',"); b.append(" @formId := '"); b.append(entity.getFormId().replaceAll("'", "''")); b.append("',"); b.append(" @taskType := '"); b.append(entity.getTaskType().replaceAll("'", "''")); b.append("',"); b.append(" @lifetimeMicroseconds := "); b.append(1000L * l); stmts.add(b.toString()); b.setLength(0); b.append("LOCK TABLES "); b.append(tableName); b.append(" WRITE "); stmts.add(b.toString()); b.setLength(0); dam.recordPutUsage(TaskLockTable.TABLE_NAME); if (!entity.isFromDatabase()) { // insert a new record b.append("REPLACE INTO "); b.append(tableName); b.append(" ("); first = true; for (DataField f : entity.getFieldList()) { if (!first) { b.append(","); } first = false; b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); } first = true; b.append(") VALUES ( "); for (DataField f : entity.getFieldList()) { if (!first) { b.append(","); } first = false; if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) { b.append("@present"); } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) { b.append("@uriUser"); } else if (f.equals(entity.formId)) { b.append("@formId"); } else if (f.equals(entity.taskType)) { b.append("@taskType"); } else if (f.equals(entity.primaryKey)) { b.append("@uriLock"); } else if (f.equals(entity.expirationDateTime)) { b.append(" DATE_ADD(CAST(@present AS DATETIME), INTERVAL @lifetimeMicroseconds MICROSECOND)"); } else { throw new IllegalStateException("unexpected case " + f.getName()); } } b.append(")"); stmts.add(b.toString()); b.setLength(0); } else { // update existing record b.append("UPDATE "); b.append(tableName); b.append(" SET "); first = true; for (DataField f : entity.getFieldList()) { if (f == entity.primaryKey) continue; if (!first) { b.append(","); } first = false; b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); b.append(" = "); if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) { b.append("@present"); } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) { b.append("@uriUser"); } else if (f.equals(entity.formId)) { b.append("@formId"); } else if (f.equals(entity.taskType)) { b.append("@taskType"); } else if (f.equals(entity.primaryKey)) { b.append("@uriLock"); } else if (f.equals(entity.expirationDateTime)) { b.append(" DATE_ADD(CAST(@present AS DATETIME), INTERVAL @lifetimeMicroseconds MICROSECOND)"); } else { throw new IllegalStateException("unexpected case " + f.getName()); } } b.append(" WHERE "); b.append(K_BQ); b.append(entity.primaryKey.getName()); b.append(K_BQ); b.append(" = "); b.append("@uriLock"); stmts.add(b.toString()); b.setLength(0); } // delete stale locks (don't care who's) dam.recordDeleteUsage(TaskLockTable.TABLE_NAME); b.append("DELETE FROM "); b.append(tableName); b.append(" WHERE "); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(" <= CAST(@present AS DATETIME)"); stmts.add(b.toString()); b.setLength(0); // determine the time of the oldest lock for this resource and task type... // do this by querying for the minimum expiration time // BUT, first, set the minimum time to the present time in case there are no locks. b.append("SET @minExpiration = @present"); stmts.add(b.toString()); b.setLength(0); dam.recordQueryUsage(TaskLockTable.TABLE_NAME, 1); b.append("SELECT @minExpiration := MIN("); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(") FROM "); b.append(tableName); b.append(" WHERE "); b.append(K_BQ); b.append(entity.formId.getName()); b.append(K_BQ); b.append(" = @formId AND "); b.append(K_BQ); b.append(entity.taskType.getName()); b.append(K_BQ); b.append(" = @taskType"); stmts.add(b.toString()); b.setLength(0); // determine if there are two or more records matching // the minimum expiration time. If there are, we must // release the locks and retry, as we cannot determine // which one is first. b.append("SET @uriCount = 0"); stmts.add(b.toString()); b.setLength(0); b.append("SELECT @uriCount := COUNT("); b.append(K_BQ); b.append(entity.primaryKey.getName()); b.append(K_BQ); b.append(") FROM "); b.append(tableName); b.append(" WHERE "); b.append(K_BQ); b.append(entity.formId.getName()); b.append(K_BQ); b.append(" = @formId AND "); b.append(K_BQ); b.append(entity.taskType.getName()); b.append(K_BQ); b.append(" = @taskType AND "); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(" = CAST(@minExpiration AS DATETIME)"); stmts.add(b.toString()); b.setLength(0); // delete all locks except the oldest one for this resource and task type... // or, if we have two or more old locks, release ours // whatever lock exists identifies the owner of the resource. dam.recordDeleteUsage(TaskLockTable.TABLE_NAME); b.append("DELETE FROM "); b.append(tableName); b.append(" WHERE "); b.append(K_BQ); b.append(entity.formId.getName()); b.append(K_BQ); b.append(" = @formId AND "); b.append(K_BQ); b.append(entity.taskType.getName()); b.append(K_BQ); b.append(" = @taskType AND ( "); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(" > CAST(@minExpiration AS DATETIME)"); b.append(" OR ( @uriCount > 1 AND "); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(" = CAST(@minExpiration AS DATETIME)"); b.append(" AND "); b.append(K_BQ); b.append(entity.primaryKey.getName()); b.append(K_BQ); b.append(" = @uriLock ) )"); stmts.add(b.toString()); b.setLength(0); // and within the transaction, see if the primary key of the winning lock is ours... b.append("SELECT "); b.append(K_BQ); b.append(entity.primaryKey.getName()); b.append(K_BQ); b.append(" FROM "); b.append(tableName); b.append(" WHERE "); b.append(K_BQ); b.append(entity.formId.getName()); b.append(K_BQ); b.append(" = @formId AND "); b.append(K_BQ); b.append(entity.taskType.getName()); b.append(K_BQ); b.append(" = @taskType AND "); b.append(K_BQ); b.append(entity.expirationDateTime.getName()); b.append(K_BQ); b.append(" = CAST(@minExpiration AS DATETIME)"); stmts.add(b.toString()); b.setLength(0); b.append("UNLOCK TABLES"); stmts.add(b.toString()); b.setLength(0); b.append("COMMIT"); stmts.add(b.toString()); b.setLength(0); TaskLockTable relation; try { relation = TaskLockTable.assertRelation(datastore, user); } catch (ODKDatastoreException e) { throw new ODKTaskLockException(PERSISTENCE_LAYER_PROBLEM, e); } boolean success = false; try { JdbcTemplate jdbc = datastore.getJdbcConnection(); Object o = jdbc.execute(new ConnectionCallback<Object>() { @Override public Object doInConnection(Connection conn) throws SQLException, DataAccessException { boolean success = false; boolean oldValue = conn.getAutoCommit(); try { conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); String lastResult = null; for (String s : stmts) { Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT); if (s.startsWith("SELECT")) { ResultSet rs = stmt.executeQuery(s); if (rs.first()) { lastResult = rs.getString(1); } rs.close(); } else { stmt.executeUpdate(s); } stmt.close(); } conn.commit(); success = uri.equals(lastResult); } catch (Exception e) { e.printStackTrace(); conn.rollback(); } finally { if (!success) { Statement stmt = conn.createStatement(); LogFactory.getLog(TaskLockImpl.class).info("UNLOCK TABLES"); stmt.execute("UNLOCK TABLES"); conn.commit(); } } conn.setAutoCommit(oldValue); return success ? uri : null; } }); success = o != null && uri.equals((String) o); } catch (Exception e) { throw new ODKTaskLockException(PERSISTENCE_LAYER_PROBLEM, e); } if (success) { return (TaskLockTable) datastore.getEntity(relation, uri, user); } else { throw new ODKEntityNotFoundException(); } }
From source file:org.opendatakit.common.persistence.engine.pgres.TaskLockImpl.java
private TaskLockTable doTransaction(TaskLockTable entity, long l) throws ODKEntityNotFoundException, ODKTaskLockException { boolean first; final List<String> stmts = new ArrayList<String>(); String uri = entity.getUri(); StringBuilder b = new StringBuilder(); String tableName = K_BQ + datastore.getDefaultSchemaName() + K_BQ + "." + K_BQ + TaskLockTable.TABLE_NAME + K_BQ;//w ww .j a v a2s. c o m b.append("'").append(user.getUriUser().replaceAll("'", "''")).append("'"); String uriUserInline = b.toString(); b.setLength(0); b.append("'").append(uri.replaceAll("'", "''")).append("'"); String uriLockInline = b.toString(); b.setLength(0); b.append("'").append(entity.getFormId().replaceAll("'", "''")).append("'"); String formIdInline = b.toString(); b.setLength(0); b.append("'").append(entity.getTaskType().replaceAll("'", "''")).append("'"); String taskTypeInline = b.toString(); b.setLength(0); b.append("interval '").append(l).append(" milliseconds'"); String lifetimeIntervalMilliseconds = b.toString(); b.setLength(0); b.append("LOCK TABLE ").append(tableName).append(" IN ACCESS EXCLUSIVE MODE"); stmts.add(b.toString()); b.setLength(0); dam.recordPutUsage(TaskLockTable.TABLE_NAME); if (!entity.isFromDatabase()) { // insert a new record (prospective lock) b.append("INSERT INTO "); b.append(tableName); b.append(" ("); first = true; for (DataField f : entity.getFieldList()) { if (!first) { b.append(","); } first = false; b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); } first = true; b.append(") VALUES ( "); for (DataField f : entity.getFieldList()) { if (!first) { b.append(","); } first = false; if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) { b.append("NOW()"); } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) { b.append(uriUserInline); } else if (f.equals(entity.formId)) { b.append(formIdInline); } else if (f.equals(entity.taskType)) { b.append(taskTypeInline); } else if (f.equals(entity.primaryKey)) { b.append(uriLockInline); } else if (f.equals(entity.expirationDateTime)) { b.append(" NOW() + "); b.append(lifetimeIntervalMilliseconds); } else { throw new IllegalStateException("unexpected case " + f.getName()); } } b.append(")"); stmts.add(b.toString()); b.setLength(0); } else { // update existing record (prospective lock) b.append("UPDATE "); b.append(tableName); b.append(" SET "); first = true; for (DataField f : entity.getFieldList()) { if (f == entity.primaryKey) continue; if (!first) { b.append(","); } first = false; b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); b.append(" = "); if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) { b.append("NOW()"); } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) { b.append(uriUserInline); } else if (f.equals(entity.formId)) { b.append(formIdInline); } else if (f.equals(entity.taskType)) { b.append(taskTypeInline); } else if (f.equals(entity.primaryKey)) { b.append(uriLockInline); } else if (f.equals(entity.expirationDateTime)) { b.append(" NOW() + "); b.append(lifetimeIntervalMilliseconds); } else { throw new IllegalStateException("unexpected case " + f.getName()); } } b.append(" WHERE "); b.append(K_BQ); b.append(entity.primaryKey.getName()); b.append(K_BQ); b.append(" = "); b.append(uriLockInline); stmts.add(b.toString()); b.setLength(0); } // delete stale locks (don't care who's) dam.recordDeleteUsage(TaskLockTable.TABLE_NAME); b.append("DELETE FROM ").append(tableName).append(" WHERE "); b.append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ).append(" <= NOW()"); stmts.add(b.toString()); b.setLength(0); // delete prospective locks which are not the oldest for that resource and // task type dam.recordDeleteUsage(TaskLockTable.TABLE_NAME); b.append("DELETE FROM ").append(tableName).append(" WHERE "); b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND "); b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline) .append(" AND "); b.append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ); b.append(" > (SELECT MIN(t3.").append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ); b.append(") FROM ").append(tableName).append(" AS t3 WHERE t3."); b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND t3."); b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline) .append(")"); stmts.add(b.toString()); b.setLength(0); // delete our entry if it collides with another entry with exactly // this time. b.append("DELETE FROM ").append(tableName).append(" WHERE "); b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND "); b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline) .append(" AND "); b.append(K_BQ).append(entity.primaryKey.getName()).append(K_BQ).append(" = ").append(uriLockInline) .append(" AND "); b.append("1 < (SELECT COUNT(t3.").append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ); b.append(") FROM ").append(tableName).append(" AS t3 WHERE t3."); b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND t3."); b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline) .append(")"); stmts.add(b.toString()); b.setLength(0); // assert: only the lock that holds the resource for that task type appears // in the task lock table TaskLockTable relation; try { JdbcTemplate jdbc = datastore.getJdbcConnection(); jdbc.execute(new ConnectionCallback<Object>() { @Override public Object doInConnection(Connection conn) throws SQLException, DataAccessException { boolean oldAutoCommitValue = conn.getAutoCommit(); int oldTransactionValue = conn.getTransactionIsolation(); try { conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); Statement stmt = conn.createStatement(); for (String s : stmts) { // for debugging: LogFactory.getLog(TaskLockImpl.class).info(s); stmt.execute(s); } conn.commit(); } catch (Exception e) { e.printStackTrace(); conn.rollback(); } conn.setTransactionIsolation(oldTransactionValue); conn.setAutoCommit(oldAutoCommitValue); return null; } }); relation = TaskLockTable.assertRelation(datastore, user); } catch (Exception e) { throw new ODKTaskLockException(PERSISTENCE_LAYER_PROBLEM, e); } return (TaskLockTable) datastore.getEntity(relation, entity.getUri(), user); }
From source file:org.opendatakit.common.persistence.engine.sqlserver.TaskLockImpl.java
private TaskLockTable doTransaction(TaskLockTable entity, long l) throws ODKEntityNotFoundException, ODKTaskLockException { boolean first; final List<String> stmts = new ArrayList<String>(); String uri = entity.getUri(); StringBuilder b = new StringBuilder(); String tableName = K_BQ + datastore.getDefaultSchemaName() + K_BQ + "." + K_BQ + TaskLockTable.TABLE_NAME + K_BQ;/*ww w. ja v a 2 s .c o m*/ b.append("'").append(user.getUriUser().replaceAll("'", "''")).append("'"); String uriUserInline = b.toString(); b.setLength(0); b.append("'").append(uri.replaceAll("'", "''")).append("'"); String uriLockInline = b.toString(); b.setLength(0); b.append("'").append(entity.getFormId().replaceAll("'", "''")).append("'"); String formIdInline = b.toString(); b.setLength(0); b.append("'").append(entity.getTaskType().replaceAll("'", "''")).append("'"); String taskTypeInline = b.toString(); b.setLength(0); b.append("DATEADD(ms,").append(l).append(",SYSUTCDATETIME())"); String nowPlusLifetimeIntervalMilliseconds = b.toString(); b.setLength(0); b.append("SELECT COUNT(1) FROM ").append(tableName).append(" WITH (TABLOCKX, HOLDLOCK)"); stmts.add(b.toString()); b.setLength(0); dam.recordPutUsage(TaskLockTable.TABLE_NAME); if (!entity.isFromDatabase()) { // insert a new record (prospective lock) b.append("INSERT INTO "); b.append(tableName); b.append(" ("); first = true; for (DataField f : entity.getFieldList()) { if (!first) { b.append(","); } first = false; b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); } first = true; b.append(") VALUES ( "); for (DataField f : entity.getFieldList()) { if (!first) { b.append(","); } first = false; if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) { b.append("SYSUTCDATETIME()"); } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) { b.append(uriUserInline); } else if (f.equals(entity.formId)) { b.append(formIdInline); } else if (f.equals(entity.taskType)) { b.append(taskTypeInline); } else if (f.equals(entity.primaryKey)) { b.append(uriLockInline); } else if (f.equals(entity.expirationDateTime)) { b.append(nowPlusLifetimeIntervalMilliseconds); } else { throw new IllegalStateException("unexpected case " + f.getName()); } } b.append(")"); stmts.add(b.toString()); b.setLength(0); } else { // update existing record (prospective lock) b.append("UPDATE "); b.append(tableName); b.append(" SET "); first = true; for (DataField f : entity.getFieldList()) { if (f == entity.primaryKey) continue; if (!first) { b.append(","); } first = false; b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); b.append(" = "); if (f.equals(entity.creationDate) || f.equals(entity.lastUpdateDate)) { b.append("SYSUTCDATETIME()"); } else if (f.equals(entity.creatorUriUser) || f.equals(entity.lastUpdateUriUser)) { b.append(uriUserInline); } else if (f.equals(entity.formId)) { b.append(formIdInline); } else if (f.equals(entity.taskType)) { b.append(taskTypeInline); } else if (f.equals(entity.primaryKey)) { b.append(uriLockInline); } else if (f.equals(entity.expirationDateTime)) { b.append(nowPlusLifetimeIntervalMilliseconds); } else { throw new IllegalStateException("unexpected case " + f.getName()); } } b.append(" WHERE "); b.append(K_BQ); b.append(entity.primaryKey.getName()); b.append(K_BQ); b.append(" = "); b.append(uriLockInline); stmts.add(b.toString()); b.setLength(0); } // delete stale locks (don't care who's) dam.recordDeleteUsage(TaskLockTable.TABLE_NAME); b.append("DELETE FROM ").append(tableName).append(" WHERE "); b.append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ).append(" <= SYSUTCDATETIME()"); stmts.add(b.toString()); b.setLength(0); // delete prospective locks which are not the oldest for that resource and // task type dam.recordDeleteUsage(TaskLockTable.TABLE_NAME); b.append("DELETE FROM ").append(tableName).append(" WHERE "); b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND "); b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline) .append(" AND "); b.append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ); b.append(" > (SELECT MIN(t3.").append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ); b.append(") FROM ").append(tableName).append(" AS t3 WHERE t3."); b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND t3."); b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline) .append(")"); stmts.add(b.toString()); b.setLength(0); // delete our entry if it collides with another entry with exactly // this time. b.append("DELETE FROM ").append(tableName).append(" WHERE "); b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND "); b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline) .append(" AND "); b.append(K_BQ).append(entity.primaryKey.getName()).append(K_BQ).append(" = ").append(uriLockInline) .append(" AND "); b.append("1 < (SELECT COUNT(t3.").append(K_BQ).append(entity.expirationDateTime.getName()).append(K_BQ); b.append(") FROM ").append(tableName).append(" AS t3 WHERE t3."); b.append(K_BQ).append(entity.formId.getName()).append(K_BQ).append(" = ").append(formIdInline) .append(" AND t3."); b.append(K_BQ).append(entity.taskType.getName()).append(K_BQ).append(" = ").append(taskTypeInline) .append(")"); stmts.add(b.toString()); b.setLength(0); // assert: only the lock that holds the resource for that task type appears // in the task lock table TaskLockTable relation; try { JdbcTemplate jdbc = datastore.getJdbcConnection(); jdbc.execute(new ConnectionCallback<Object>() { @Override public Object doInConnection(Connection conn) throws SQLException, DataAccessException { boolean oldAutoCommitValue = conn.getAutoCommit(); int oldTransactionValue = conn.getTransactionIsolation(); try { conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); Statement stmt = conn.createStatement(); for (String s : stmts) { // for debugging: LogFactory.getLog(TaskLockImpl.class).info(s); stmt.execute(s); } conn.commit(); } catch (Exception e) { e.printStackTrace(); conn.rollback(); } conn.setTransactionIsolation(oldTransactionValue); conn.setAutoCommit(oldAutoCommitValue); return null; } }); relation = TaskLockTable.assertRelation(datastore, user); } catch (Exception e) { throw new ODKTaskLockException(PERSISTENCE_LAYER_PROBLEM, e); } return (TaskLockTable) datastore.getEntity(relation, entity.getUri(), user); }
From source file:org.quartz.impl.jdbcjobstore.JobStoreSupport.java
protected Connection getConnection() throws JobPersistenceException { Connection conn = null;//from w ww.j av a2 s . com try { conn = DBConnectionManager.getInstance().getConnection(getDataSource()); } catch (SQLException sqle) { throw new JobPersistenceException( "Failed to obtain DB connection from data source '" + getDataSource() + "': " + sqle.toString(), sqle); } catch (Throwable e) { throw new JobPersistenceException( "Failed to obtain DB connection from data source '" + getDataSource() + "': " + e.toString(), e, JobPersistenceException.ERR_PERSISTENCE_CRITICAL_FAILURE); } if (conn == null) { throw new JobPersistenceException("Could not get connection from DataSource '" + getDataSource() + "'"); } // Protect connection attributes we might change. conn = getAttributeRestoringConnection(conn); // Set any connection connection attributes we are to override. try { if (!isDontSetAutoCommitFalse()) { conn.setAutoCommit(false); } if (isTxIsolationLevelSerializable()) { conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); } } catch (SQLException sqle) { getLog().warn("Failed to override connection auto commit/transaction isolation.", sqle); } catch (Throwable e) { try { conn.close(); } catch (Throwable tt) { } throw new JobPersistenceException("Failure setting up connection.", e); } return conn; }
From source file:org.rimudb.C3P0PoolTests.java
@Test public void testConnectionAttributes() throws Exception { // Connect to the database CompoundDatabase cdb = new CompoundDatabase("/testconfig/pooltests-c3p0-2-jdbcconfig.xml", true); cdb.connect("dbid-1"); Database db = cdb.getDatabase("dbid-1"); Connection conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_COMMITTED, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", false, conn.getAutoCommit()); db.disconnect();// w ww. j ava 2s. co m cdb.connect("dbid-2"); db = cdb.getDatabase("dbid-2"); conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_UNCOMMITTED, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", true, conn.getAutoCommit()); db.disconnect(); cdb.connect("dbid-3"); db = cdb.getDatabase("dbid-3"); conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_REPEATABLE_READ, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", false, conn.getAutoCommit()); db.disconnect(); cdb.connect("dbid-4"); db = cdb.getDatabase("dbid-4"); conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_SERIALIZABLE, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", true, conn.getAutoCommit()); db.disconnect(); cdb.disconnectAllNoException(); }
From source file:org.rimudb.DBCPPoolTests.java
@Test public void testConnectionAttributes() throws Exception { // Connect to the database CompoundDatabase cdb = new CompoundDatabase("/testconfig/pooltests-dbcp-2-jdbcconfig.xml", true); cdb.connect("dbid-1"); Database db = cdb.getDatabase("dbid-1"); Connection conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_COMMITTED, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", false, conn.getAutoCommit()); db.disconnect();// w w w .j a v a2 s . c om cdb.connect("dbid-2"); db = cdb.getDatabase("dbid-2"); conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_UNCOMMITTED, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", true, conn.getAutoCommit()); db.disconnect(); cdb.connect("dbid-3"); db = cdb.getDatabase("dbid-3"); conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_REPEATABLE_READ, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", false, conn.getAutoCommit()); db.disconnect(); cdb.connect("dbid-4"); db = cdb.getDatabase("dbid-4"); conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_SERIALIZABLE, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", true, conn.getAutoCommit()); db.disconnect(); cdb.disconnectAllNoException(); }
From source file:org.sakaiproject.tomcat.jdbc.pool.SakaiBasicDataSource.java
/** * Set the default transaction isolation level from a string value, based on the settings and values in java.sql.Connection * // www . ja va2 s . c om * @param defaultTransactionIsolation */ public void setDefaultTransactionIsolationString(String defaultTransactionIsolation) { if ((defaultTransactionIsolation == null) || (defaultTransactionIsolation.trim().length() == 0)) { setDefaultTransactionIsolation(DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION); } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_NONE")) { setDefaultTransactionIsolation(Connection.TRANSACTION_NONE); } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_READ_UNCOMMITTED")) { setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_READ_COMMITTED")) { setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_REPEATABLE_READ")) { setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); } else if (defaultTransactionIsolation.trim().equalsIgnoreCase("TRANSACTION_SERIALIZABLE")) { setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); } else { setDefaultTransactionIsolation(DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION); M_log.warn("invalid transaction isolation level: " + defaultTransactionIsolation); } }