List of usage examples for java.sql Connection getAutoCommit
boolean getAutoCommit() throws SQLException;
Connection
object. From source file:org.apache.torque.util.ExceptionMapperTest.java
/** * Check that a deadlockExcetion is thrown if two transaction want to access * a resource locked by the other thread. * * @throws Exception if an error occurs. *//*from ww w.j a va 2 s. com*/ public void testTransactionDeadlock() throws Exception { Adapter adapter = Torque.getDatabase(Torque.getDefaultDB()).getAdapter(); if (adapter instanceof HsqldbAdapter) { log.warn( "hsqldb (2.2.6) fails to detect the deadlock in this test" + " therefore this test is skipped"); return; } // prepare cleanBookstore(); List<Author> bookstoreContent = insertBookstoreData(); Connection transaction1 = null; Connection transaction2 = null; try { // lock author 1 in transaction 1 transaction1 = Transaction.begin(); if (transaction1.getAutoCommit()) { fail("autocommit must be set to false for this test"); } Author author1 = bookstoreContent.get(0); author1.setName("new Author1"); author1.save(transaction1); // lock author 2 in transaction 2 transaction2 = Transaction.begin(); if (transaction2.getAutoCommit()) { fail("autocommit must be set to false for this test(2)"); } Author author2 = bookstoreContent.get(1); author2.setName("new Author2"); author2.save(transaction2); // lock author 2 in transaction 1 (must wait for lock) author2.setName("newer Author2"); SaveAndRollbackThread saveThreadTransaction1 = new SaveAndRollbackThread(author2, transaction1, "saveThreadAuthor2Con1"); saveThreadTransaction1.start(); long startTime = System.currentTimeMillis(); while (!author2.isSaving() && author2.isModified() && saveThreadTransaction1.isAlive()) { Thread.sleep(SLEEP_TIME); if (System.currentTimeMillis() > startTime + TIMEOUT) { fail("Waited too long for saving to start"); } } // Try to lock author1 in transaction 2 (deadlock) author1.setName("newer Author1"); SaveAndRollbackThread saveThreadTransaction2 = new SaveAndRollbackThread(author1, transaction2, "saveThreadAuthor1Con2"); saveThreadTransaction2.start(); startTime = System.currentTimeMillis(); while (!author1.isSaving() && author1.isModified() && saveThreadTransaction2.isAlive()) { Thread.sleep(SLEEP_TIME); if (System.currentTimeMillis() > startTime + TIMEOUT) { fail("Waited too long for saving to start (2)"); } } // wait till save on transaction 1 has finished startTime = System.currentTimeMillis(); while (saveThreadTransaction1.isAlive()) { Thread.sleep(10); if (System.currentTimeMillis() > startTime + TIMEOUT) { fail("Waited too long for saving to finish"); } } // wait till save on transaction 2 has finished startTime = System.currentTimeMillis(); while (saveThreadTransaction2.isAlive()) { Thread.sleep(10); if (System.currentTimeMillis() > startTime + TIMEOUT) { fail("Waited too long for saving to finish (2)"); } } // verify. Either in transaction 1 or in transaction 2 // a deadlock exception must have occurred if (saveThreadTransaction1.getCaughtException() != null) { if (!(saveThreadTransaction1.getCaughtException() instanceof DeadlockException)) { throw saveThreadTransaction1.getCaughtException(); } } else if (saveThreadTransaction2.getCaughtException() == null) { fail("No Deadlock occured"); if (!(saveThreadTransaction2.getCaughtException() instanceof DeadlockException)) { throw saveThreadTransaction2.getCaughtException(); } } } finally { Transaction.safeRollback(transaction1); Transaction.safeRollback(transaction2); } }
From source file:org.flowable.dmn.engine.impl.db.DmnDbSchemaManager.java
public Liquibase createLiquibaseInstance(DmnEngineConfiguration dmnEngineConfiguration) throws SQLException, DatabaseException, LiquibaseException { Connection jdbcConnection = null; CommandContext commandContext = CommandContextUtil.getCommandContext(); if (commandContext == null) { jdbcConnection = dmnEngineConfiguration.getDataSource().getConnection(); } else {// ww w. java 2s .c om jdbcConnection = CommandContextUtil.getDbSqlSession(commandContext).getSqlSession().getConnection(); } if (!jdbcConnection.getAutoCommit()) { jdbcConnection.commit(); } DatabaseConnection connection = new JdbcConnection(jdbcConnection); Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection); database.setDatabaseChangeLogTableName( DmnEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogTableName()); database.setDatabaseChangeLogLockTableName( DmnEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogLockTableName()); String databaseSchema = dmnEngineConfiguration.getDatabaseSchema(); if (StringUtils.isNotEmpty(databaseSchema)) { database.setDefaultSchemaName(databaseSchema); database.setLiquibaseSchemaName(databaseSchema); } String databaseCatalog = dmnEngineConfiguration.getDatabaseCatalog(); if (StringUtils.isNotEmpty(databaseCatalog)) { database.setDefaultCatalogName(databaseCatalog); database.setLiquibaseCatalogName(databaseCatalog); } Liquibase liquibase = new Liquibase(LIQUIBASE_CHANGELOG, new ClassLoaderResourceAccessor(), database); return liquibase; }
From source file:net.ageto.gyrex.persistence.carbonado.storage.internal.SchemaSupportJob.java
private IStatus processSchemas(final Collection<RepositoryContentType> contentTypes, final JDBCConnectionCapability jdbcConnectionCapability, final IProgressMonitor monitor) throws Exception { // spin the migration loop Connection connection = null; boolean wasAutoCommit = true; // default to auto-commit try {//from www . j a v a 2 s . c om // get connection connection = jdbcConnectionCapability.getConnection(); // remember auto-commit state wasAutoCommit = connection.getAutoCommit(); // collect result final MultiStatus result = new MultiStatus(CarbonadoActivator.SYMBOLIC_NAME, 0, String.format( "Database schema verification result for database %s.", repository.getDescription()), null); // verify schemas final SubMonitor subMonitor = SubMonitor.convert(monitor, contentTypes.size()); for (final RepositoryContentType contentType : contentTypes) { result.add(processSchema(contentType, connection, subMonitor.newChild(1))); } // commit any pending changes if migration was allowed if (commitWhenDone) { connection.commit(); } else { connection.rollback(); } return result; } finally { if (null != connection) { try { // verify that auto-commit state was not modified if (wasAutoCommit != connection.getAutoCommit()) { // Carbonado uses auto-commit to detect if a transaction // was in progress whan the connection was acquired previously // in this case it does not close the connection, which is fine; // however, if any schema-support implementation removed the auto-commit flag // Carbonado will no longer close the connection because it thinks a // transaction is in progress; // thus we need to reset the auto-commit flag in this case! LOG.debug( "Resetting auto-commit flag on connection {} due to modifications during schema migration", connection); connection.setAutoCommit(wasAutoCommit); } jdbcConnectionCapability.yieldConnection(connection); } catch (final Exception e) { throw new IllegalStateException( "Unable to properly return a database connection to the pool. This will lead to resource leaks! " + e.getMessage(), e); } } } }
From source file:net.sourceforge.squirrel_sql.fw.sql.SQLConnection.java
/** * @see net.sourceforge.squirrel_sql.fw.sql.ISQLConnection#setAutoCommit(boolean) *//*w w w . ja va2s . co m*/ public void setAutoCommit(boolean value) throws SQLException { validateConnection(); final Connection conn = getConnection(); final boolean oldValue = conn.getAutoCommit(); if (oldValue != value) { _conn.setAutoCommit(value); getPropertyChangeReporter().firePropertyChange(IPropertyNames.AUTO_COMMIT, oldValue, value); } }
From source file:org.geoserver.security.jdbc.AbstractJDBCService.java
/** * Get a new connection from the datasource, * check/set autocommit == false and isolation level * according to {@link #DEFAULT_ISOLATION_LEVEL} * /*from w w w .ja va 2s . com*/ * @return * @throws SQLException */ protected Connection getConnection() throws SQLException { Connection con = getDataSource().getConnection(); if (con.getAutoCommit()) con.setAutoCommit(false); if (con.getTransactionIsolation() != DEFAULT_ISOLATION_LEVEL) con.setTransactionIsolation(DEFAULT_ISOLATION_LEVEL); return con; }
From source file:com.wabacus.system.dataset.update.action.rationaldb.AbsRationalDBUpdateAction.java
public void commitTransaction(ReportRequest rrequest) { Connection conn = rrequest.getConnection(this.datasource); try {/* www . ja va 2s .c o m*/ if (conn.getAutoCommit()) return; conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { throw new WabacusRuntimeException( "??" + this.ownerUpdateBean.getOwner().getReportBean().getPath() + "??" + this.datasource + "", e); } }
From source file:com.wabacus.system.dataset.update.action.rationaldb.AbsRationalDBUpdateAction.java
public void rollbackTransaction(ReportRequest rrequest) { Connection conn = rrequest.getConnection(this.datasource); try {/*from w w w .java 2 s . c o m*/ if (conn.getAutoCommit()) return; conn.rollback(); conn.setAutoCommit(true); } catch (SQLException e) { throw new WabacusRuntimeException( "" + this.ownerUpdateBean.getOwner().getReportBean().getPath() + "??" + this.datasource + "", e); } }
From source file:org.jtester.module.database.support.DefaultSQLHandler.java
public int executeUpdateAndCommit(String sql) { JTesterLogger.debug(sql);//from w w w. ja v a2 s.c o m if (!doExecuteUpdates) { // skip update return 0; } Connection connection = null; Statement statement = null; try { connection = dataSource.getConnection(); statement = connection.createStatement(); int nbChanges = statement.executeUpdate(sql); if (!connection.getAutoCommit()) { connection.commit(); } return nbChanges; } catch (Throwable e) { throw new JTesterException("Error while performing database update: " + sql, e); } finally { closeQuietly(connection, statement, null); } }
From source file:org.squale.jraf.provider.persistence.hibernate.SessionImpl.java
public void closeSession() throws JrafPersistenceException { if (session != null) { try {/*from www. java 2 s . c o m*/ if (tx == null) { session.flush(); // on effectue le commit seulement si les transactions // ne sont pas gerees par le conteneur if (!isContainerManagedTransaction() && session.isOpen()) { // FB depuis Hibernate 3 le session.connection() ouvre // une nouvelle connection jdbc avec la base et l'utilisateur // doit la refermer explicitement Connection connection = session.connection(); if (connection.getAutoCommit()) { connection.close(); } else { connection.commit(); } } session.close(); } } catch (HibernateException e) { log.error("Probleme lors de la fermeture la session", e); throw new JrafPersistenceException("Probleme lors de la fermeture la session", e); } catch (SQLException e) { log.error("Probleme lors de la fermeture la session", e); throw new JrafPersistenceException("Probleme lors de la fermeture la session", e); } finally { } } else { throw new JrafPersistenceException("Pas de session ouverte"); } }
From source file:org.opencms.db.oracle.CmsProjectDriver.java
/** * Writes data for a publish job.<p> * // w w w. ja va2s . c o m * @param dbc the database context * @param publishJobHistoryId the publish job id * @param queryKey the query to use * @param fieldName the fiueld to use * @param data the data to write * @throws CmsDataAccessException if something goes wrong */ private void internalWritePublishJobData(CmsDbContext dbc, CmsUUID publishJobHistoryId, String queryKey, String fieldName, byte[] data) throws CmsDataAccessException { Connection conn = null; PreparedStatement stmt = null; PreparedStatement commit = null; ResultSet res = null; boolean wasInTransaction = false; try { conn = m_sqlManager.getConnection(dbc); stmt = m_sqlManager.getPreparedStatement(conn, queryKey); wasInTransaction = !conn.getAutoCommit(); if (!wasInTransaction) { conn.setAutoCommit(false); } // update the file content in the contents table stmt.setString(1, publishJobHistoryId.toString()); res = ((DelegatingResultSet) stmt.executeQuery()).getInnermostDelegate(); if (!res.next()) { throw new CmsDbEntryNotFoundException( Messages.get().container(Messages.ERR_READ_PUBLISH_JOB_1, publishJobHistoryId)); } // write file content OutputStream output = CmsUserDriver.getOutputStreamFromBlob(res, fieldName); output.write(data); output.close(); if (!wasInTransaction) { commit = m_sqlManager.getPreparedStatement(conn, "C_COMMIT"); commit.execute(); m_sqlManager.closeAll(dbc, null, commit, null); } m_sqlManager.closeAll(dbc, null, stmt, res); // this is needed so the finally block works correctly commit = null; stmt = null; res = null; if (!wasInTransaction) { conn.setAutoCommit(true); } } catch (IOException e) { throw new CmsDbIoException( Messages.get().container(Messages.ERR_WRITING_TO_OUTPUT_STREAM_1, publishJobHistoryId), e); } catch (SQLException e) { throw new CmsDbSqlException(org.opencms.db.generic.Messages.get().container( org.opencms.db.generic.Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e); } finally { org.opencms.db.oracle.CmsSqlManager.closeAllInTransaction(m_sqlManager, dbc, conn, stmt, res, commit, wasInTransaction); } }