@Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return new SQLExceptionConversionDelegate() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException ); if ( "40P01".equals( sqlState ) ) { // DEADLOCK DETECTED return new LockAcquisitionException( message, sqlException, sql ); } if ( "55P03".equals( sqlState ) ) { // LOCK NOT AVAILABLE return new PessimisticLockException( message, sqlException, sql ); } // returning null allows other delegates to operate return null; } }; }
@Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return new SQLExceptionConversionDelegate() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException); if (errorCode == SQLITE_TOOBIG || errorCode == SQLITE_MISMATCH) { return new DataException(message, sqlException, sql); } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) { return new LockAcquisitionException(message, sqlException, sql); } else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOTADB) { return new JDBCConnectionException(message, sqlException, sql); } // returning null allows other delegates to operate return null; } }; }
@Override public SQLExceptionConverter buildSQLExceptionConverter() { return new SQLExceptionConverter() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JdbcExceptionHelper .extractSqlState(sqlException); if (sqlState != null) { if (SQL_GRAMMAR_CATEGORIES.contains(sqlState)) { return new SQLGrammarException(message, sqlException, sql); } else if (DATA_CATEGORIES.contains(sqlState)) { return new DataException(message, sqlException, sql); } else if (LOCK_ACQUISITION_CATEGORIES.contains(sqlState)) { return new LockAcquisitionException(message, sqlException, sql); } } return null; } }; }
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return new SQLExceptionConversionDelegate() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JdbcExceptionHelper .extractSqlState(sqlException); if (sqlState != null) { if (SQL_GRAMMAR_CATEGORIES.contains(sqlState)) { return new SQLGrammarException(message, sqlException, sql); } else if (DATA_CATEGORIES.contains(sqlState)) { return new DataException(message, sqlException, sql); } else if (LOCK_ACQUISITION_CATEGORIES.contains(sqlState)) { return new LockAcquisitionException(message, sqlException, sql); } } return null; } }; }
@Override public SQLExceptionConverter buildSQLExceptionConverter() { return new SQLExceptionConverter() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JDBCExceptionHelper .extractSqlState(sqlException); if (sqlState != null) { if (SQL_GRAMMAR_CATEGORIES.contains(sqlState)) { return new SQLGrammarException(message, sqlException, sql); } else if (DATA_CATEGORIES.contains(sqlState)) { return new DataException(message, sqlException, sql); } else if (LOCK_ACQUISITION_CATEGORIES.contains(sqlState)) { return new LockAcquisitionException(message, sqlException, sql); } } return null; } }; }
@Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return new SQLExceptionConversionDelegate() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException); if (errorCode == SQLITE_TOOBIG || errorCode == SQLITE_MISMATCH) { return new DataException(message, sqlException, sql); } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) { return new LockAcquisitionException(message, sqlException, sql); } else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOTADB) { return new JDBCConnectionException(message, sqlException, sql); } return null; } }; }
@Override public SQLExceptionConverter buildSQLExceptionConverter() { return new SQLExceptionConverter() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final int errorCode = sqlException.getErrorCode(); if (errorCode == SQLITE_CONSTRAINT) { final String constraintName = EXTRACTER.extractConstraintName(sqlException); return new ConstraintViolationException(message, sqlException, sql, constraintName); } else if (errorCode == SQLITE_TOOBIG || errorCode == SQLITE_MISMATCH) { return new DataException(message, sqlException, sql); } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) { return new LockAcquisitionException(message, sqlException, sql); } else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOTADB) { return new JDBCConnectionException(message, sqlException, sql); } return new GenericJDBCException(message, sqlException, sql); } }; }
private static boolean isLockingException(final Throwable t, final boolean recurse) { if (t instanceof LockingException || t instanceof LockAcquisitionException || t instanceof PessimisticLockException) { return true; } if (t instanceof SQLException) { final SQLException e = (SQLException) t; return e.getErrorCode() == ER_LOCK_WAIT_TIMEOUT || ST_LOCK.equals(e.getSQLState()); } if (recurse) { for (final Throwable thr : ExceptionUtils.getThrowables(t)) { if (isLockingException(thr, false)) { return true; } } } return false; }
@Override public JDBCException convert(SQLException sqlException, String message, String sql) { final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException); if (errorCode == SQLITE_CONSTRAINT) { final String constraintName = EXTRACTER.extractConstraintName(sqlException); return new ConstraintViolationException(message, sqlException, sql, constraintName); } else if (errorCode == SQLITE_TOO_BIG || errorCode == SQLITE_MISMATCH) { return new DataException(message, sqlException, sql); } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) { return new LockAcquisitionException(message, sqlException, sql); } else if ((errorCode >= SQLITE_IO_ERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOT_ADB) { return new JDBCConnectionException(message, sqlException, sql); } return new GenericJDBCException(message, sqlException, sql); }
@Test public void returnsLockAcquisitionExceptionForSqliteBusy() { when(JdbcExceptionHelper.extractErrorCode(sqlException)).thenReturn(5); JDBCException exception = conversionDelegate.convert(sqlException, "message", "sql"); assertTrue(exception instanceof LockAcquisitionException); assertEquals("message", exception.getMessage()); assertEquals("sql", exception.getSQL()); }
@Test public void returnsLockAcquisitionExceptionForSqliteLocked() { when(JdbcExceptionHelper.extractErrorCode(sqlException)).thenReturn(6); JDBCException exception = conversionDelegate.convert(sqlException, "message", "sql"); assertTrue(exception instanceof LockAcquisitionException); assertEquals("message", exception.getMessage()); assertEquals("sql", exception.getSQL()); }
@Override public JDBCException convert(SQLException sqlException, String message, String sql) { if ( SQLClientInfoException.class.isInstance( sqlException ) || SQLInvalidAuthorizationSpecException.class.isInstance( sqlException ) || SQLNonTransientConnectionException.class.isInstance( sqlException ) || SQLTransientConnectionException.class.isInstance( sqlException ) ) { return new JDBCConnectionException( message, sqlException, sql ); } else if ( DataTruncation.class.isInstance( sqlException ) || SQLDataException.class.isInstance( sqlException ) ) { throw new DataException( message, sqlException, sql ); } else if ( SQLIntegrityConstraintViolationException.class.isInstance( sqlException ) ) { return new ConstraintViolationException( message, sqlException, sql, getConversionContext().getViolatedConstraintNameExtracter().extractConstraintName( sqlException ) ); } else if ( SQLSyntaxErrorException.class.isInstance( sqlException ) ) { return new SQLGrammarException( message, sqlException, sql ); } else if ( SQLTimeoutException.class.isInstance( sqlException ) ) { return new QueryTimeoutException( message, sqlException, sql ); } else if ( SQLTransactionRollbackException.class.isInstance( sqlException ) ) { // Not 100% sure this is completely accurate. The JavaDocs for SQLTransactionRollbackException state that // it indicates sql states starting with '40' and that those usually indicate that: // <quote> // the current statement was automatically rolled back by the database because of deadlock or // other transaction serialization failures. // </quote> return new LockAcquisitionException( message, sqlException, sql ); } return null; // allow other delegates the chance to look }
private static boolean isLockingException(Throwable throwable) { for (Throwable t = throwable; t != null; t = t.getCause()) { if (t instanceof StaleStateException || t instanceof LockAcquisitionException) { return true; } } return false; }
/** * API to get a batch by applying Hibernate level optimistic locking and to set lock owner ino db. * * @param identifier long * @param lockOwner {@link ServerRegistry} * @throws LockAcquisitionException in case of error */ @Transactional @Override public void lockBatch(long batchId, ServerRegistry lockOwner) throws LockAcquisitionException { BatchInstance batchInstance = batchInstanceDao.getBatch(batchId, LockMode.UPGRADE_NOWAIT); if (batchInstance.getLockOwner() == null) { batchInstance.setLockOwner(lockOwner); batchInstanceDao.saveOrUpdate(batchInstance); } else { throw new LockAcquisitionException(DataAccessConstant.BATCH_ALREADY_LOCKED, null); } }
/** * API to acquire lock on a batch instance. * * @param batchId long * @throws LockAcquisitionException in case of error */ @Transactional(propagation = Propagation.REQUIRES_NEW) @Override public void lockBatch(long batchId) throws LockAcquisitionException { BatchInstance batchInstance = batchInstanceDao.getBatch(batchId, LockMode.UPGRADE_NOWAIT); if (batchInstance.getStatus() == BatchInstanceStatus.NEW) { batchInstance.setStatus(BatchInstanceStatus.LOCKED); batchInstanceDao.saveOrUpdate(batchInstance); } else { throw new LockAcquisitionException(DataAccessConstant.BATCH_ALREADY_LOCKED, null); } }
@Override public void pickupBatchInstance() { List<BatchInstance> newBatches = batchInstanceService.getBatchInstByStatus(BatchInstanceStatus.NEW); for (BatchInstance newBatchInstance : newBatches) { try { batchInstanceService.lockBatch(newBatchInstance.getId()); workFlowService.startWorkflow(newBatchInstance.getBatchInstanceID()); } catch (LockAcquisitionException e) { log.trace("Batch instance -" + newBatchInstance.getIdentifier() + " is already locked."); } } }
public static void rethrowAsDatastoreLogAll( final HibernateException he, final Log log, final String message ) throws DatastoreException { final String internalMess = concMess( message, he ); if (he instanceof JDBCConnectionException || he instanceof GenericJDBCException || he instanceof SQLGrammarException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else if (he instanceof ConstraintViolationException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else if (he instanceof LockAcquisitionException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else if (he instanceof QuerySyntaxException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else if (he instanceof QueryException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } }
public static void rethrowJdbcAsDatastore( final HibernateException he, final Log log, final String message, final int logErrorMask ) // NOPMD by dan on 01/02/15 07:21 throws DatastoreException { final String internalMess = concMess( message, he ); if (he instanceof JDBCConnectionException || he instanceof GenericJDBCException || he instanceof SQLGrammarException) { if ((logErrorMask & JDBC_IS_ERROR) != 0) { log.error( internalMess, he ); } throw new DatastoreException( internalMess, he ); } else if (he instanceof ConstraintViolationException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else if (he instanceof LockAcquisitionException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else if (he instanceof QuerySyntaxException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } }
@Test public void testExecuteReadWriteTransactionRetry() { PASchedulerProperties.SCHEDULER_DB_TRANSACTION_MAXIMUM_RETRIES.updateProperty("5"); when(sessionWork.doInTransaction(session)).thenThrow(LockAcquisitionException.class) .thenThrow(Throwable.class) .thenReturn(null); transactionHelper.executeReadWriteTransaction(sessionWork); verify(session, times(3)).beginTransaction(); verify(sessionWork, times(3)).doInTransaction(session); verify(transaction, times(2)).rollback(); verify(transaction).commit(); }
public Boolean hasTCI(Booking_AppointmentRefVo appointment) { if (appointment == null) return Boolean.FALSE; long count = 0; String query = "SELECT COUNT (tci.id) FROM TCIForPatientElectiveList AS tci LEFT JOIN tci.appointment AS appt WHERE appt.id = :APPT_ID and tci.isRIE is null"; //WDEV-23321 try { count = getDomainFactory().countWithHQL(query, new String[] {"APPT_ID"}, new Object[] {appointment.getID_Booking_Appointment()}); } catch (RuntimeException e) { if (e instanceof LockAcquisitionException) { try { count = getDomainFactory().countWithHQL(query, new String[] {"APPT_ID"}, new Object[] {appointment.getID_Booking_Appointment()}); } catch (RuntimeException e1) { if (e1 instanceof LockAcquisitionException) { throw new StaleStateException(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()); } } } } //WDEV-23321 ends here if (count > 0) return Boolean.TRUE; return Boolean.FALSE; }
@Override public boolean isTransient(Exception e) { if (e instanceof LockAcquisitionException || e instanceof PessimisticLockException || e instanceof JDBCConnectionException) { return true; } if (e instanceof GenericJDBCException) { JDBCException se = (JDBCException) e; return super.isTransient(se.getSQLException()); } return false; }
@Override public boolean synchronize () throws InterruptedException { int retrieved = 0, updated = 0, deleted = 0; LOGGER.info("Synchronizer#{} started", getId()); try { if (this.copyProduct) { if (checkDownloadTasks()) { retrieved = getAndCopyNewProduct(); } } else { retrieved = getNewProducts(); } if (Thread.interrupted ()) { throw new InterruptedException (); } updated = getUpdatedProducts (); if (Thread.interrupted ()) { throw new InterruptedException (); } deleted = getDeletedProducts (); } catch (LockAcquisitionException | CannotAcquireLockException e) { throw new InterruptedException (e.getMessage ()); } finally { // Writes the database only if there is a modification if (this.dateChanged) { this.syncConf.setConfig("last_created", String.valueOf(this.lastCreated.getTime())); SYNC_SERVICE.saveSynchronizer(this); this.dateChanged = false; } } return retrieved < pageSize && updated < pageSize && deleted < pageSize; }
@Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException ); final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException ); if ( sqlState != null ) { String sqlStateClassCode = JdbcExceptionHelper.determineSqlStateClassCode( sqlState ); if ( sqlStateClassCode != null ) { if ( SQL_GRAMMAR_CATEGORIES.contains( sqlStateClassCode ) ) { return new SQLGrammarException( message, sqlException, sql ); } else if ( INTEGRITY_VIOLATION_CATEGORIES.contains( sqlStateClassCode ) ) { final String constraintName = getConversionContext() .getViolatedConstraintNameExtracter() .extractConstraintName( sqlException ); return new ConstraintViolationException( message, sqlException, sql, constraintName ); } else if ( CONNECTION_CATEGORIES.contains( sqlStateClassCode ) ) { return new JDBCConnectionException( message, sqlException, sql ); } else if ( DATA_CATEGORIES.contains( sqlStateClassCode ) ) { return new DataException( message, sqlException, sql ); } } if ( "40001".equals( sqlState ) ) { return new LockAcquisitionException( message, sqlException, sql ); } if ( "40XL1".equals( sqlState ) || "40XL2".equals( sqlState )) { // Derby "A lock could not be obtained within the time requested." return new PessimisticLockException( message, sqlException, sql ); } // MySQL Query execution was interrupted if ( "70100".equals( sqlState ) || // Oracle user requested cancel of current operation ( "72000".equals( sqlState ) && errorCode == 1013 ) ) { throw new QueryTimeoutException( message, sqlException, sql ); } } return null; }
@Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return new SQLExceptionConversionDelegate() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException ); if ( "41000".equals( sqlState ) ) { return new LockTimeoutException( message, sqlException, sql ); } if ( "40001".equals( sqlState ) ) { return new LockAcquisitionException( message, sqlException, sql ); } return null; } }; }
@Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return new SQLExceptionConversionDelegate() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { // interpreting Oracle exceptions is much much more precise based on their specific vendor codes. final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException ); // lock timeouts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( errorCode == 30006 ) { // ORA-30006: resource busy; acquire with WAIT timeout expired throw new LockTimeoutException( message, sqlException, sql ); } else if ( errorCode == 54 ) { // ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired throw new LockTimeoutException( message, sqlException, sql ); } else if ( 4021 == errorCode ) { // ORA-04021 timeout occurred while waiting to lock object throw new LockTimeoutException( message, sqlException, sql ); } // deadlocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( 60 == errorCode ) { // ORA-00060: deadlock detected while waiting for resource return new LockAcquisitionException( message, sqlException, sql ); } else if ( 4020 == errorCode ) { // ORA-04020 deadlock detected while trying to lock object return new LockAcquisitionException( message, sqlException, sql ); } // query cancelled ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( 1013 == errorCode ) { // ORA-01013: user requested cancel of current operation throw new QueryTimeoutException( message, sqlException, sql ); } // data integrity violation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( 1407 == errorCode ) { // ORA-01407: cannot update column to NULL final String constraintName = getViolatedConstraintNameExtracter().extractConstraintName( sqlException ); return new ConstraintViolationException( message, sqlException, sql, constraintName ); } return null; } }; }
@Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return new SQLExceptionConversionDelegate() { @Override public JDBCException convert(final SQLException sqlException, final String message, final String sql) { final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException ); if ( errorCode == 131 ) { // 131 - Transaction rolled back by lock wait timeout return new LockTimeoutException( message, sqlException, sql ); } if ( errorCode == 146 ) { // 146 - Resource busy and acquire with NOWAIT specified return new LockTimeoutException( message, sqlException, sql ); } if ( errorCode == 132 ) { // 132 - Transaction rolled back due to unavailable resource return new LockAcquisitionException( message, sqlException, sql ); } if ( errorCode == 133 ) { // 133 - Transaction rolled back by detected deadlock return new LockAcquisitionException( message, sqlException, sql ); } // 259 - Invalid table name // 260 - Invalid column name // 261 - Invalid index name // 262 - Invalid query name // 263 - Invalid alias name if ( errorCode == 257 || ( errorCode >= 259 && errorCode <= 263 ) ) { throw new SQLGrammarException( message, sqlException, sql ); } // 257 - Cannot insert NULL or update to NULL // 301 - Unique constraint violated // 461 - foreign key constraint violation // 462 - failed on update or delete by foreign key constraint violation if ( errorCode == 287 || errorCode == 301 || errorCode == 461 || errorCode == 462 ) { final String constraintName = getViolatedConstraintNameExtracter().extractConstraintName( sqlException ); return new ConstraintViolationException( message, sqlException, sql, constraintName ); } return null; } }; }
private boolean isExceptionRelatedToSerializationInternal(Exception ex) { if (ex instanceof SerializationRelatedException || ex instanceof PessimisticLockException || ex instanceof LockAcquisitionException || ex instanceof HibernateOptimisticLockingFailureException || ex instanceof StaleObjectStateException) { // todo the last one is questionable return true; } // it's not locking exception (optimistic, pesimistic lock or simple lock acquisition) understood by hibernate // however, it still could be such exception... wrapped in e.g. TransactionException // so we have a look inside - we try to find SQLException there SQLException sqlException = findSqlException(ex); if (sqlException == null) { return false; } // these error codes / SQL states we consider related to locking: // code 50200 [table timeout lock in H2, 50200 is LOCK_TIMEOUT_1 error code] // code 40001 [DEADLOCK_1 in H2] // state 40001 [serialization failure in PostgreSQL - http://www.postgresql.org/docs/9.1/static/transaction-iso.html - and probably also in other systems] // state 40P01 [deadlock in PostgreSQL] // code ORA-08177: can't serialize access for this transaction in Oracle // code ORA-01466 ["unable to read data - table definition has changed"] in Oracle // code ORA-01555: snapshot too old: rollback segment number with name "" too small // code ORA-22924: snapshot too old // // sql states should be somewhat standardized; sql error codes are vendor-specific // todo: so it is probably not very safe to test for codes without testing for specific database (h2, oracle) // but the risk of problem is quite low here, so let it be... // strange exception occurring in MySQL when doing multithreaded org closure maintenance // alternatively we might check for error code = 1030, sql state = HY000 // but that would cover all cases of "Got error XYZ from storage engine" if ((getConfiguration().isUsingMySQL() || getConfiguration().isUsingMariaDB()) && sqlException.getMessage() != null && sqlException.getMessage().contains("Got error -1 from storage engine")) { return true; } // this is some recent H2 weirdness (MID-3969) if (getConfiguration().isUsingH2() && sqlException.getMessage() != null && sqlException.getMessage().contains("Referential integrity constraint violation: \"FK_AUDIT_ITEM: PUBLIC.M_AUDIT_ITEM FOREIGN KEY(RECORD_ID) REFERENCES PUBLIC.M_AUDIT_EVENT(ID)")) { return true; } return sqlException.getErrorCode() == 50200 || sqlException.getErrorCode() == 40001 || "40001".equals(sqlException.getSQLState()) || "40P01".equals(sqlException.getSQLState()) || sqlException.getErrorCode() == 8177 || sqlException.getErrorCode() == 1466 || sqlException.getErrorCode() == 1555 || sqlException.getErrorCode() == 22924 || sqlException.getErrorCode() == 3960; // Snapshot isolation transaction aborted due to update conflict. }
@Override @Transactional(propagation = Propagation.REQUIRES_NEW) public void lockJobToResume(long jobId) throws LockAcquisitionException { throw new UnsupportedOperationException("Operation not supported."); }
public static void rethrowJdbcAsDatastoreAndConstraintAsItself( final HibernateException he, final Log log, final String message, final int logErrorMask ) throws DatastoreException, MAConstraintViolationException { final String internalMess = concMess( message, he ); if (he instanceof JDBCConnectionException || he instanceof GenericJDBCException || he instanceof SQLGrammarException) { if ((logErrorMask & JDBC_IS_ERROR) != 0) { log.error( internalMess, he ); } throw new DatastoreException( internalMess, he ); } else if (he instanceof ConstraintViolationException) { if ((logErrorMask & CONSTRAINT_IS_ERROR) != 0) { log.error( internalMess, he ); } throw new MAConstraintViolationException( internalMess, he ); } else if (he instanceof LockAcquisitionException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else if (he instanceof QuerySyntaxException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else if (he instanceof IdentifierGenerationException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else if (he instanceof PropertyValueException) { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } else { log.error( internalMess, he ); throw new DatastoreException( internalMess, he ); } }
@Override public boolean synchronize () throws InterruptedException { int retrieved = 0, updated = 0, deleted = 0; LOGGER.info("Synchronizer#" + getId () + " started"); try { if (this.copyProduct) { retrieved = getAndCopyNewProduct(); } else { retrieved = getNewProducts(); } if (Thread.interrupted ()) { throw new InterruptedException (); } updated = getUpdatedProducts (); if (Thread.interrupted ()) { throw new InterruptedException (); } deleted = getDeletedProducts (); } catch (LockAcquisitionException | CannotAcquireLockException e) { throw new InterruptedException (e.getMessage ()); } finally { // Logs a summary of what it has done this session StringBuilder sb = new StringBuilder ("Synchronizer#"); sb.append (getId ()).append (" done: "); sb.append (retrieved).append (" new Products, "); sb.append (updated).append (" updated Products, "); sb.append (deleted).append (" deleted Products"); sb.append (" from ").append (this.client.getServiceRoot ()); LOGGER.info(sb.toString()); // Writes the database only if there is a modification if (this.dateChanged) { SYNC_SERVICE.saveSynchronizer (this); this.dateChanged = false; } } return retrieved < pageSize && updated < pageSize && deleted < pageSize; }
private boolean isExceptionRelatedToSerializationInternal(Exception ex) { if (ex instanceof SerializationRelatedException || ex instanceof PessimisticLockException || ex instanceof LockAcquisitionException || ex instanceof HibernateOptimisticLockingFailureException || ex instanceof StaleObjectStateException) { // todo the last one is questionable return true; } // it's not locking exception (optimistic, pesimistic lock or simple lock acquisition) understood by hibernate // however, it still could be such exception... wrapped in e.g. TransactionException // so we have a look inside - we try to find SQLException there SQLException sqlException = findSqlException(ex); if (sqlException == null) { return false; } // these error codes / SQL states we consider related to locking: // code 50200 [table timeout lock in H2, 50200 is LOCK_TIMEOUT_1 error code] // code 40001 [DEADLOCK_1 in H2] // state 40001 [serialization failure in PostgreSQL - http://www.postgresql.org/docs/9.1/static/transaction-iso.html - and probably also in other systems] // state 40P01 [deadlock in PostgreSQL] // code ORA-08177: can't serialize access for this transaction in Oracle // code ORA-01466 ["unable to read data - table definition has changed"] in Oracle // code ORA-01555: snapshot too old: rollback segment number with name "" too small // code ORA-22924: snapshot too old // // sql states should be somewhat standardized; sql error codes are vendor-specific // todo: so it is probably not very safe to test for codes without testing for specific database (h2, oracle) // but the risk of problem is quite low here, so let it be... // strange exception occurring in MySQL when doing multithreaded org closure maintenance // alternatively we might check for error code = 1030, sql state = HY000 // but that would cover all cases of "Got error XYZ from storage engine" if (getConfiguration().isUsingMySqlCompatible() && sqlException.getMessage() != null && sqlException.getMessage().contains("Got error -1 from storage engine")) { return true; } // this is some recent H2 weirdness (MID-3969) if (getConfiguration().isUsingH2() && sqlException.getMessage() != null && sqlException.getMessage().contains("Referential integrity constraint violation: \"FK_AUDIT_ITEM: PUBLIC.M_AUDIT_ITEM FOREIGN KEY(RECORD_ID) REFERENCES PUBLIC.M_AUDIT_EVENT(ID)")) { return true; } return sqlException.getErrorCode() == 50200 || sqlException.getErrorCode() == 40001 || "40001".equals(sqlException.getSQLState()) || "40P01".equals(sqlException.getSQLState()) || sqlException.getErrorCode() == 8177 || sqlException.getErrorCode() == 1466 || sqlException.getErrorCode() == 1555 || sqlException.getErrorCode() == 22924 || sqlException.getErrorCode() == 3960; // Snapshot isolation transaction aborted due to update conflict. }
public BedSpaceStateLiteVo getBedSpaceState(BedSpaceRefVo bed) { if(bed == null ) throw new DomainRuntimeException("Invalid BedRefVo"); String hql = "select bs,(select adm.healthyLodger from AdmissionDetail as adm where adm.pasEvent.id = bs.inpatientEpisode.pasEvent.id) from BedSpaceState as bs left join bs.bedSpace as bed where bed.id = " + bed.getID_BedSpace(); List<?> bedState = null; //WDEV-23014 - Catch the Lock error and retry the entire transaction. After two retries, throw a SOE message. try { bedState = getDomainFactory().find(hql); } catch (RuntimeException e) { if (e instanceof LockAcquisitionException) { try { bedState = getDomainFactory().find(hql); } catch (RuntimeException e1) { if (e1 instanceof LockAcquisitionException) { throw new StaleStateException(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()); } } } } //WDEV-23014 ends here //WDEV-11039 boolean hasAlerts = false; BedSpaceStateLiteVoCollection voColl = new BedSpaceStateLiteVoCollection(); if (bedState != null && bedState.size() > 0 && bedState.get(0) instanceof Object[]) { Object[] recordDO = (Object[]) bedState.get(0); BedSpaceStateLiteVo bs = null; for (int i =0;i<recordDO.length;i++) { if (recordDO[0] instanceof BedSpaceState) { BedSpaceState doBed = (BedSpaceState)recordDO[0]; if(doBed.getInpatientEpisode() != null && doBed.getInpatientEpisode().getPasEvent() != null && doBed.getInpatientEpisode().getPasEvent().getPatient() != null && doBed.getInpatientEpisode().getPasEvent().getPatient().getPatientAlerts() != null) if(doBed.getInpatientEpisode().getPasEvent().getPatient().getPatientAlerts().size() > 0 && isOneActive(doBed.getInpatientEpisode().getPasEvent().getPatient().getPatientAlerts(), true)) hasAlerts = true; bs = BedSpaceStateLiteVoAssembler.create((BedSpaceState)recordDO[0]); } if (bs.getInpatientEpisodeIsNotNull() && recordDO[1] != null && recordDO[1] instanceof HealthyLodger) bs.getInpatientEpisode().setHealthyLodgerDetails(HealthyLodgerVoAssembler.create((HealthyLodger)recordDO[1])); } if (bs != null) voColl.add(bs); } //BedSpaceStateLiteVoCollection voColl = BedSpaceStateLiteVoAssembler.createBedSpaceStateLiteVoCollectionFromBedSpaceState(bedState); if (voColl != null && voColl.size() > 0) { if(voColl.get(0).getInpatientEpisodeIsNotNull() && voColl.get(0).getInpatientEpisode().getPasEventIsNotNull() && voColl.get(0).getInpatientEpisode().getPasEvent().getPatientIsNotNull()) voColl.get(0).getInpatientEpisode().getPasEvent().getPatient().setHasAlerts(hasAlerts); return voColl.get(0); } return null; }
/** * Special-case for SQL Server deadlock errors, that look like: * <pre>2017-12-01 07:49:48,504 ERROR Transaction (Process ID 55) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction. * 2017-12-01 07:49:48,539 ERROR z9ti8f0eai POST /automation/work-orders threw exception: * javax.persistence.PersistenceException: org.hibernate.exception.LockAcquisitionException: could not execute query * at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149) * at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157) * at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1423) * at org.hibernate.query.Query.getResultList(Query.java:146) * at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:72) * at com.peterphi.std.guice.hibernate.webquery.impl.jpa.JPAQueryBuilder.selectEntity(JPAQueryBuilder.java:512) * at com.peterphi.std.guice.hibernate.webquery.impl.jpa.JPASearchExecutor.find(JPASearchExecutor.java:118) * at com.peterphi.std.guice.hibernate.dao.HibernateDao.find(HibernateDao.java:552) * at com.peterphi.std.guice.hibernate.module.TransactionMethodInterceptor.invoke(TransactionMethodInterceptor.java:84) * at com.peterphi.std.guice.hibernate.dao.HibernateDao.find(HibernateDao.java:532) * at com.peterphi.std.guice.hibernate.dao.HibernateDao.find(HibernateDao.java:525) * at com.peterphi.std.guice.hibernate.dao.HibernateDao.findByUriQuery(HibernateDao.java:518) * ... * at com.peterphi.std.guice.hibernate.module.TransactionMethodInterceptor.createTransactionAndExecuteMethod(TransactionMethodInterceptor.java:164) * at com.peterphi.std.guice.hibernate.module.TransactionMethodInterceptor.invoke(TransactionMethodInterceptor.java:105) * ... * Caused by: org.hibernate.exception.LockAcquisitionException: could not execute query * at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123) * at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) * at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111) * at org.hibernate.loader.Loader.doList(Loader.java:2705) * at org.hibernate.loader.Loader.doList(Loader.java:2685) * at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2517) * at org.hibernate.loader.Loader.list(Loader.java:2512) * at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502) * at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:384) * at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) * at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1490) * at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1445) * at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1414) * ... 44 more * Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Transaction (Process ID 55) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction. * at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217) * at com.microsoft.sqlserver.jdbc.SQLServerResultSet$FetchBuffer.nextRow(SQLServerResultSet.java:6357) * at com.microsoft.sqlserver.jdbc.SQLServerResultSet.fetchBufferNext(SQLServerResultSet.java:1798) * at com.microsoft.sqlserver.jdbc.SQLServerResultSet.next(SQLServerResultSet.java:1049) * at org.hibernate.loader.Loader.processResultSet(Loader.java:997) * at org.hibernate.loader.Loader.doQuery(Loader.java:959) * at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:351) * at org.hibernate.loader.Loader.doList(Loader.java:2702) * ... 53 more</pre> * * @param t * * @return */ private boolean isDeadlockError(Throwable e) { // Looking for PersistenceException, wrapping a LockAcquisitionException if (e != null && e instanceof PersistenceException) { e = e.getCause(); if (e != null && e instanceof LockAcquisitionException) { return true; } } // Does not match return false; }