Search in sources :

Example 6 with OptimisticLockException

use of javax.persistence.OptimisticLockException in project nhin-d by DirectProject.

the class AggregationDAOImpl method getAggregationCompleted.

/**
	 * {@inheritDoc}
	 */
@Override
@Transactional(readOnly = false, rollbackFor = { AggregationDAOException.class })
public AggregationCompleted getAggregationCompleted(String id, boolean lock) throws AggregationDAOException {
    validateState();
    try {
        if (!lock) {
            // it's not locked, so just find the completed aggregation and return it
            return entityManager.find(AggregationCompleted.class, id);
        } else {
            /* this is essentially a recovery of a failed completed exchange
				* camel runs this on start up and incremental intervals... it is
				* essential that two application or route instances do not try to play
				* back the same exchange at the same time, or else duplicate exchanges may be
				* routed.... the recovery needs to be locked
				*/
            // first check to see if the recovery is available for locking
            final AggregationCompleted entity = entityManager.find(AggregationCompleted.class, id);
            if (entity == null)
                return null;
            // if the recovery lock time has not passed, then we can't recover
            if (entity.getRecoveryLockedUntilDtTm() != null && entity.getRecoveryLockedUntilDtTm().after(Calendar.getInstance(Locale.getDefault())))
                return null;
            // now lock the row and update lock time and the count
            entityManager.lock(entity, LockModeType.WRITE);
            final Calendar newRecoveryLockTime = Calendar.getInstance(Locale.getDefault());
            newRecoveryLockTime.add(Calendar.SECOND, recoveredEntityLockInterval);
            entity.setRecoveryLockedUntilDtTm(newRecoveryLockTime);
            // persist the time new lock time and increment the update count
            entityManager.persist(entity);
            entityManager.flush();
            return entity;
        }
    } catch (OptimisticLockException ol) {
        // someone else locked the row... return null
        return null;
    } catch (Exception e) {
        throw new AggregationDAOException(e);
    }
}
Also used : Calendar(java.util.Calendar) AggregationCompleted(org.nhindirect.monitor.dao.entity.AggregationCompleted) OptimisticLockException(javax.persistence.OptimisticLockException) AggregationDAOException(org.nhindirect.monitor.dao.AggregationDAOException) OptimisticLockException(javax.persistence.OptimisticLockException) AggregationDAOException(org.nhindirect.monitor.dao.AggregationDAOException) AggregationVersionException(org.nhindirect.monitor.dao.AggregationVersionException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 7 with OptimisticLockException

use of javax.persistence.OptimisticLockException in project nhin-d by DirectProject.

the class AggregationDAOImpl method removeAggregation.

/**
	 * {@inheritDoc}
	 */
@Override
@Transactional(readOnly = false, rollbackFor = { AggregationDAOException.class })
public void removeAggregation(Aggregation agg, String exchangeId) throws AggregationDAOException {
    try {
        // find the aggregation
        final Aggregation existingAgg = this.getAggregation(agg.getId());
        if (existingAgg != null) {
            // check the version number for consistency
            if (existingAgg.getVersion() != agg.getVersion())
                throw new AggregationVersionException("Version number of aggreation does not match what is in the store.");
            // lock for removal
            entityManager.lock(existingAgg, LockModeType.WRITE);
            entityManager.remove(existingAgg);
        } else
            throw new AggregationDAOException("Aggregation does not exist is store.");
        // add to the completed repository
        final AggregationCompleted completed = new AggregationCompleted();
        completed.setExchangeBlob(existingAgg.getExchangeBlob());
        completed.setId(exchangeId);
        completed.setVersion(1);
        entityManager.persist(completed);
        // commit
        entityManager.flush();
    } catch (AggregationDAOException ae) {
        throw ae;
    }///CLOVER:OFF
     catch (OptimisticLockException ol) {
        throw new AggregationVersionException("Aggregation was removed by another thread or process before it could be committed.");
    } catch (Exception e) {
        throw new AggregationDAOException("Failed to remove aggregation.", e);
    }
///CLOVER:ON
}
Also used : Aggregation(org.nhindirect.monitor.dao.entity.Aggregation) AggregationVersionException(org.nhindirect.monitor.dao.AggregationVersionException) AggregationCompleted(org.nhindirect.monitor.dao.entity.AggregationCompleted) OptimisticLockException(javax.persistence.OptimisticLockException) AggregationDAOException(org.nhindirect.monitor.dao.AggregationDAOException) OptimisticLockException(javax.persistence.OptimisticLockException) AggregationDAOException(org.nhindirect.monitor.dao.AggregationDAOException) AggregationVersionException(org.nhindirect.monitor.dao.AggregationVersionException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 8 with OptimisticLockException

use of javax.persistence.OptimisticLockException in project hibernate-orm by hibernate.

the class SybaseTimestampVersioningTest method testLocking.

@Test
public void testLocking() throws Throwable {
    // First, create the needed row...
    Session s = openSession();
    Transaction t = s.beginTransaction();
    User steve = new User("steve");
    s.persist(steve);
    t.commit();
    s.close();
    // next open two sessions, and try to update from each "simultaneously"...
    Session s1 = null;
    Session s2 = null;
    Transaction t1 = null;
    Transaction t2 = null;
    try {
        s1 = sessionFactory().openSession();
        t1 = s1.beginTransaction();
        s2 = sessionFactory().openSession();
        t2 = s2.beginTransaction();
        User user1 = (User) s1.get(User.class, steve.getId());
        User user2 = (User) s2.get(User.class, steve.getId());
        user1.setUsername("se");
        t1.commit();
        t1 = null;
        user2.setUsername("steve-e");
        try {
            t2.commit();
            fail("optimistic lock check did not fail");
        } catch (OptimisticLockException e) {
            // expected...
            try {
                t2.rollback();
            } catch (Throwable ignore) {
            }
        }
    } catch (Throwable error) {
        if (t1 != null) {
            try {
                t1.rollback();
            } catch (Throwable ignore) {
            }
        }
        if (t2 != null) {
            try {
                t2.rollback();
            } catch (Throwable ignore) {
            }
        }
        throw error;
    } finally {
        if (s1 != null) {
            try {
                s1.close();
            } catch (Throwable ignore) {
            }
        }
        if (s2 != null) {
            try {
                s2.close();
            } catch (Throwable ignore) {
            }
        }
    }
    // lastly, clean up...
    s = openSession();
    t = s.beginTransaction();
    s.delete(s.load(User.class, steve.getId()));
    t.commit();
    s.close();
}
Also used : Transaction(org.hibernate.Transaction) OptimisticLockException(javax.persistence.OptimisticLockException) Session(org.hibernate.Session) Test(org.junit.Test)

Example 9 with OptimisticLockException

use of javax.persistence.OptimisticLockException in project hibernate-orm by hibernate.

the class ExceptionTest method testOptimisticLockingException.

@Test
public void testOptimisticLockingException() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    EntityManager em2 = entityManagerFactory().createEntityManager();
    em.getTransaction().begin();
    Music music = new Music();
    music.setName("Old Country");
    em.persist(music);
    em.getTransaction().commit();
    try {
        em2.getTransaction().begin();
        Music music2 = em2.find(Music.class, music.getId());
        music2.setName("HouseMusic");
        em2.getTransaction().commit();
    } catch (Exception e) {
        em2.getTransaction().rollback();
        throw e;
    } finally {
        em2.close();
    }
    em.getTransaction().begin();
    music.setName("Rock");
    try {
        em.flush();
        fail("Should raise an optimistic lock exception");
    } catch (OptimisticLockException e) {
        //success
        assertEquals(music, e.getEntity());
    } catch (Exception e) {
        fail("Should raise an optimistic lock exception");
    } finally {
        em.getTransaction().rollback();
        em.close();
    }
}
Also used : EntityManager(javax.persistence.EntityManager) OptimisticLockException(javax.persistence.OptimisticLockException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) OptimisticLockException(javax.persistence.OptimisticLockException) PersistenceException(javax.persistence.PersistenceException) EntityNotFoundException(javax.persistence.EntityNotFoundException) Test(org.junit.Test)

Example 10 with OptimisticLockException

use of javax.persistence.OptimisticLockException in project hibernate-orm by hibernate.

the class ExceptionConverterImpl method wrapStaleStateException.

protected PersistenceException wrapStaleStateException(StaleStateException e) {
    PersistenceException pe;
    if (e instanceof StaleObjectStateException) {
        final StaleObjectStateException sose = (StaleObjectStateException) e;
        final Serializable identifier = sose.getIdentifier();
        if (identifier != null) {
            try {
                final Object entity = sharedSessionContract.internalLoad(sose.getEntityName(), identifier, false, true);
                if (entity instanceof Serializable) {
                    //avoid some user errors regarding boundary crossing
                    pe = new OptimisticLockException(e.getMessage(), e, entity);
                } else {
                    pe = new OptimisticLockException(e.getMessage(), e);
                }
            } catch (EntityNotFoundException enfe) {
                pe = new OptimisticLockException(e.getMessage(), e);
            }
        } else {
            pe = new OptimisticLockException(e.getMessage(), e);
        }
    } else {
        pe = new OptimisticLockException(e.getMessage(), e);
    }
    return pe;
}
Also used : Serializable(java.io.Serializable) PersistenceException(javax.persistence.PersistenceException) OptimisticLockException(javax.persistence.OptimisticLockException) EntityNotFoundException(javax.persistence.EntityNotFoundException) StaleObjectStateException(org.hibernate.StaleObjectStateException)

Aggregations

OptimisticLockException (javax.persistence.OptimisticLockException)18 Test (org.junit.Test)11 EntityManager (javax.persistence.EntityManager)9 PersistenceException (javax.persistence.PersistenceException)4 AggregationVersionException (org.nhindirect.monitor.dao.AggregationVersionException)4 EntityNotFoundException (javax.persistence.EntityNotFoundException)3 Session (org.hibernate.Session)3 AggregationDAOException (org.nhindirect.monitor.dao.AggregationDAOException)3 Aggregation (org.nhindirect.monitor.dao.entity.Aggregation)3 AggregationCompleted (org.nhindirect.monitor.dao.entity.AggregationCompleted)3 TransactionStatus (org.springframework.transaction.TransactionStatus)3 Transactional (org.springframework.transaction.annotation.Transactional)3 Transaction (org.hibernate.Transaction)2 AggregationDAOImpl (org.nhindirect.monitor.dao.impl.AggregationDAOImpl)2 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)2 Serializable (java.io.Serializable)1 Calendar (java.util.Calendar)1 EntityExistsException (javax.persistence.EntityExistsException)1 EntityManagerFactory (javax.persistence.EntityManagerFactory)1 EntityTransaction (javax.persistence.EntityTransaction)1