Search in sources :

Example 1 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class CustomRunner method convertSkipToIgnore.

protected Ignore convertSkipToIgnore(FrameworkMethod frameworkMethod) {
    // @Skip
    Skip skip = Helper.locateAnnotation(Skip.class, frameworkMethod, getTestClass());
    if (skip != null) {
        if (isMatch(skip.condition())) {
            return buildIgnore(skip);
        }
    }
    // @SkipForDialects & @SkipForDialect
    for (SkipForDialect skipForDialectAnn : Helper.collectAnnotations(SkipForDialect.class, SkipForDialects.class, frameworkMethod, getTestClass())) {
        for (Class<? extends Dialect> dialectClass : skipForDialectAnn.value()) {
            if (skipForDialectAnn.strictMatching()) {
                if (dialectClass.equals(dialect.getClass())) {
                    return buildIgnore(skipForDialectAnn);
                }
            } else {
                if (dialectClass.isInstance(dialect)) {
                    return buildIgnore(skipForDialectAnn);
                }
            }
        }
    }
    // @RequiresDialects & @RequiresDialect
    final List<RequiresDialect> requiresDialects = Helper.collectAnnotations(RequiresDialect.class, RequiresDialects.class, frameworkMethod, getTestClass());
    if (!requiresDialects.isEmpty() && !isDialectMatchingRequired(requiresDialects)) {
        return buildIgnore(requiresDialects);
    }
    // @RequiresDialectFeature
    RequiresDialectFeature requiresDialectFeatureAnn = Helper.locateAnnotation(RequiresDialectFeature.class, frameworkMethod, getTestClass());
    if (requiresDialectFeatureAnn != null) {
        try {
            for (Class<? extends DialectCheck> checkClass : requiresDialectFeatureAnn.value()) {
                if (!checkClass.newInstance().isMatch(dialect)) {
                    return buildIgnore(requiresDialectFeatureAnn);
                }
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("Unable to instantiate DialectCheck", e);
        }
    }
    return null;
}
Also used : SkipForDialect(org.hibernate.testing.SkipForDialect) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) Skip(org.hibernate.testing.Skip) RequiresDialect(org.hibernate.testing.RequiresDialect) NoTestsRemainException(org.junit.runner.manipulation.NoTestsRemainException)

Example 2 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class CMTTest method testConcurrentCachedDirtyQueries.

@Test
@RequiresDialectFeature(value = DialectChecks.DoesReadCommittedNotCauseWritersToBlockReadersCheck.class, comment = "write locks block readers")
public void testConcurrentCachedDirtyQueries() throws Exception {
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s = openSession();
    Map foo = new HashMap();
    foo.put("name", "Foo");
    foo.put("description", "a big foo");
    s.persist("Item", foo);
    Map bar = new HashMap();
    bar.put("name", "Bar");
    bar.put("description", "a small bar");
    s.persist("Item", bar);
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    synchronized (this) {
        wait(1000);
    }
    sessionFactory().getStatistics().clear();
    // we need a clean 2L cache here.
    cleanupCache();
    // open a TX and suspend it
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s4 = openSession();
    Transaction tx4 = TestingJtaPlatformImpl.INSTANCE.getTransactionManager().suspend();
    // open a new TX and execute a query, this would fill the query cache.
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s1 = openSession();
    List r1 = s1.createCriteria("Item").addOrder(Order.asc("description")).setCacheable(true).list();
    assertEquals(r1.size(), 2);
    foo = (Map) r1.get(0);
    // update data and make query cache stale, but TX is suspended
    foo.put("description", "a big red foo");
    s1.flush();
    Transaction tx1 = TestingJtaPlatformImpl.INSTANCE.getTransactionManager().suspend();
    // open a new TX and run query again
    // this TX is committed afterQuery query
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s2 = openSession();
    List r2 = s2.createCriteria("Item").addOrder(Order.asc("description")).setCacheable(true).list();
    assertEquals(r2.size(), 2);
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    assertEquals(0, sessionFactory().getStatistics().getSecondLevelCacheHitCount());
    assertEquals(0, sessionFactory().getStatistics().getSecondLevelCacheMissCount());
    assertEquals(4, sessionFactory().getStatistics().getEntityLoadCount());
    assertEquals(0, sessionFactory().getStatistics().getEntityFetchCount());
    assertEquals(2, sessionFactory().getStatistics().getQueryExecutionCount());
    assertEquals(2, sessionFactory().getStatistics().getQueryCachePutCount());
    assertEquals(0, sessionFactory().getStatistics().getQueryCacheHitCount());
    assertEquals(2, sessionFactory().getStatistics().getQueryCacheMissCount());
    // updateTimestampsCache put happens at two places
    // 1. {@link org.hibernate.engine.spi.ActionQueue#registerCleanupActions} calls preinvalidate
    // 2. {@link org.hibernate.engine.spi.ActionQueue.AfterTransactionCompletionProcessQueue#afterTransactionCompletion} calls invalidate
    // but since the TX which the update action happened is not committed yet, so there should be only 1 updateTimestamps put.
    assertEquals(1, sessionFactory().getStatistics().getUpdateTimestampsCachePutCount());
    // updateTimestampsCache hit only happens when the query cache data's timestamp is newer
    // than the timestamp of when update happens
    // since there is only 1 update action
    assertEquals(1, sessionFactory().getStatistics().getUpdateTimestampsCacheHitCount());
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().resume(tx1);
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    // update action's TX committed, so, invalidate is called, put new timestamp into UpdateTimestampsCache
    assertEquals(2, sessionFactory().getStatistics().getUpdateTimestampsCachePutCount());
    // but no more query cache lookup here, so it should still 1
    assertEquals(1, sessionFactory().getStatistics().getUpdateTimestampsCacheHitCount());
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s3 = openSession();
    s3.createCriteria("Item").addOrder(Order.asc("description")).setCacheable(true).list();
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    assertEquals(0, sessionFactory().getStatistics().getSecondLevelCacheHitCount());
    assertEquals(0, sessionFactory().getStatistics().getSecondLevelCacheMissCount());
    assertEquals(6, sessionFactory().getStatistics().getEntityLoadCount());
    assertEquals(0, sessionFactory().getStatistics().getEntityFetchCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryExecutionCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryCachePutCount());
    assertEquals(0, sessionFactory().getStatistics().getQueryCacheHitCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryCacheMissCount());
    // a new query cache hit and one more update timestamps cache hit, so should be 2
    assertEquals(2, sessionFactory().getStatistics().getUpdateTimestampsCacheHitCount());
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().resume(tx4);
    List r4 = s4.createCriteria("Item").addOrder(Order.asc("description")).setCacheable(true).list();
    assertEquals(r4.size(), 2);
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    assertEquals(2, sessionFactory().getStatistics().getSecondLevelCacheHitCount());
    assertEquals(0, sessionFactory().getStatistics().getSecondLevelCacheMissCount());
    assertEquals(6, sessionFactory().getStatistics().getEntityLoadCount());
    assertEquals(0, sessionFactory().getStatistics().getEntityFetchCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryExecutionCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryCachePutCount());
    assertEquals(1, sessionFactory().getStatistics().getQueryCacheHitCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryCacheMissCount());
    assertEquals(3, sessionFactory().getStatistics().getUpdateTimestampsCacheHitCount());
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    s = openSession();
    s.createQuery("delete from Item").executeUpdate();
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
}
Also used : Transaction(javax.transaction.Transaction) HashMap(java.util.HashMap) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Session(org.hibernate.Session) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature)

Example 3 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class LockTest method testFindWithPessimisticWriteLockTimeoutException.

//5 minutes
@Test(timeout = 5 * 60 * 1000)
@TestForIssue(jiraKey = "HHH-7252")
@RequiresDialectFeature(value = DialectChecks.SupportsLockTimeouts.class, comment = "Test verifies proper exception throwing when a lock timeout is specified.", jiraKey = "HHH-7252")
public void testFindWithPessimisticWriteLockTimeoutException() {
    Lock lock = new Lock();
    lock.setName("name");
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    em.persist(lock);
    em.getTransaction().commit();
    em.close();
    EntityManager em2 = createIsolatedEntityManager();
    em2.getTransaction().begin();
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(AvailableSettings.LOCK_TIMEOUT, 0L);
    Lock lock2 = em2.find(Lock.class, lock.getId(), LockModeType.PESSIMISTIC_WRITE, properties);
    assertEquals("lock mode should be PESSIMISTIC_WRITE ", LockModeType.PESSIMISTIC_WRITE, em2.getLockMode(lock2));
    EntityManager em3 = createIsolatedEntityManager();
    em3.getTransaction().begin();
    try {
        em3.find(Lock.class, lock.getId(), LockModeType.PESSIMISTIC_WRITE, properties);
        fail("Exception should be thrown");
    } catch (LockTimeoutException lte) {
    // Proper exception thrown for dialect supporting lock timeouts when an immediate timeout is set.
    } catch (PessimisticLockException pe) {
        fail("Find with immediate timeout should have thrown LockTimeoutException.");
    } catch (PersistenceException pe) {
        log.info("EntityManager.find() for PESSIMISTIC_WRITE with timeout of 0 threw a PersistenceException.\n" + "This is likely a consequence of " + getDialect().getClass().getName() + " not properly mapping SQL errors into the correct HibernateException subtypes.\n" + "See HHH-7251 for an example of one such situation.", pe);
        fail("EntityManager should be throwing LockTimeoutException.");
    } finally {
        if (em3.getTransaction().getRollbackOnly()) {
            em3.getTransaction().rollback();
        } else {
            em3.getTransaction().commit();
        }
        em3.close();
    }
    em2.getTransaction().commit();
    em2.getTransaction().begin();
    em2.remove(lock2);
    em2.getTransaction().commit();
    em2.close();
}
Also used : EntityManager(javax.persistence.EntityManager) HashMap(java.util.HashMap) PersistenceException(javax.persistence.PersistenceException) LockTimeoutException(javax.persistence.LockTimeoutException) PessimisticLockException(javax.persistence.PessimisticLockException) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) TestForIssue(org.hibernate.testing.TestForIssue)

Example 4 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class LockTest method testContendedPessimisticReadLockTimeout.

@Test
@RequiresDialect(Oracle10gDialect.class)
@RequiresDialectFeature(DialectChecks.SupportsLockTimeouts.class)
public void testContendedPessimisticReadLockTimeout() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    final EntityManager em2 = createIsolatedEntityManager();
    Lock lock = new Lock();
    Thread t = null;
    FutureTask<Boolean> bgTask = null;
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        lock.setName("testContendedPessimisticReadLockTimeout");
        em.getTransaction().begin();
        em.persist(lock);
        em.getTransaction().commit();
        em.clear();
        em.getTransaction().begin();
        lock = em.getReference(Lock.class, lock.getId());
        em.lock(lock, LockModeType.PESSIMISTIC_WRITE);
        final Integer id = lock.getId();
        // force entity to be read
        lock.getName();
        log.info("testContendedPessimisticReadLockTimeout: got write lock");
        bgTask = new FutureTask<Boolean>(new Callable<Boolean>() {

            public Boolean call() {
                try {
                    // true (success) if LockTimeoutException occurred
                    boolean timedOut = false;
                    em2.getTransaction().begin();
                    log.info("testContendedPessimisticReadLockTimeout: (BG) about to read write-locked entity");
                    // we should block on the following read
                    Lock lock2 = em2.getReference(Lock.class, id);
                    //  force entity to be read
                    lock2.getName();
                    log.info("testContendedPessimisticReadLockTimeout: (BG) read write-locked entity");
                    Map<String, Object> props = new HashMap<String, Object>();
                    // timeout is in milliseconds
                    props.put(AvailableSettings.LOCK_TIMEOUT, 1000);
                    try {
                        em2.lock(lock2, LockModeType.PESSIMISTIC_READ, props);
                    } catch (LockTimeoutException e) {
                        // success
                        log.info("testContendedPessimisticReadLockTimeout: (BG) got expected timeout exception");
                        timedOut = true;
                        em2.getTransaction().rollback();
                        return timedOut;
                    } catch (Throwable e) {
                        log.info("Expected LockTimeoutException but got unexpected exception", e);
                        throw new RuntimeException("Expected LockTimeoutException but got unexpected exception", e);
                    }
                    em2.getTransaction().commit();
                    return timedOut;
                } finally {
                    // signal that we finished
                    latch.countDown();
                }
            }
        });
        t = new Thread(bgTask);
        t.setDaemon(true);
        t.setName("Lock timeout Test (bg)");
        t.start();
        // should return quickly on success
        boolean latchSet = latch.await(10, TimeUnit.SECONDS);
        assertTrue("background test thread finished (lock timeout is broken)", latchSet);
        assertTrue("background test thread timed out on lock attempt", bgTask.get());
        em.getTransaction().commit();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (t != null) {
            // wait for background thread to finish beforeQuery deleting entity
            t.join();
        }
        em.getTransaction().begin();
        lock = em.getReference(Lock.class, lock.getId());
        em.remove(lock);
        em.getTransaction().commit();
        em.close();
        em2.close();
    }
}
Also used : HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) EntityManager(javax.persistence.EntityManager) LockTimeoutException(javax.persistence.LockTimeoutException) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) RequiresDialect(org.hibernate.testing.RequiresDialect)

Example 5 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class LockTest method testContendedPessimisticWriteLockTimeout.

@Test
@RequiresDialect(Oracle10gDialect.class)
@RequiresDialectFeature(DialectChecks.SupportsLockTimeouts.class)
public void testContendedPessimisticWriteLockTimeout() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    final EntityManager em2 = createIsolatedEntityManager();
    Lock lock = new Lock();
    Thread t = null;
    FutureTask<Boolean> bgTask;
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        lock.setName("testContendedPessimisticWriteLockTimeout");
        em.getTransaction().begin();
        em.persist(lock);
        em.getTransaction().commit();
        em.clear();
        em.getTransaction().begin();
        lock = em.getReference(Lock.class, lock.getId());
        em.lock(lock, LockModeType.PESSIMISTIC_WRITE);
        final Integer id = lock.getId();
        // force entity to be read
        lock.getName();
        log.info("testContendedPessimisticWriteLockTimeout: got write lock");
        bgTask = new FutureTask<Boolean>(new Callable<Boolean>() {

            public Boolean call() {
                try {
                    // true (success) if LockTimeoutException occurred
                    boolean timedOut = false;
                    em2.getTransaction().begin();
                    log.info("testContendedPessimisticWriteLockTimeout: (BG) about to read write-locked entity");
                    // we should block on the following read
                    Lock lock2 = em2.getReference(Lock.class, id);
                    //  force entity to be read
                    lock2.getName();
                    log.info("testContendedPessimisticWriteLockTimeout: (BG) read write-locked entity");
                    Map<String, Object> props = new HashMap<String, Object>();
                    // timeout is in milliseconds
                    props.put(AvailableSettings.LOCK_TIMEOUT, 1000);
                    try {
                        em2.lock(lock2, LockModeType.PESSIMISTIC_WRITE, props);
                    } catch (LockTimeoutException e) {
                        // success
                        log.info("testContendedPessimisticWriteLockTimeout: (BG) got expected timeout exception");
                        timedOut = true;
                    } catch (Throwable e) {
                        log.info("Expected LockTimeoutException but got unexpected exception", e);
                    }
                    em2.getTransaction().commit();
                    return timedOut;
                } finally {
                    // signal that we finished
                    latch.countDown();
                }
            }
        });
        t = new Thread(bgTask);
        t.setDaemon(true);
        t.setName("Lock timeout Test (bg)");
        t.start();
        // should return quickly on success
        boolean latchSet = latch.await(10, TimeUnit.SECONDS);
        assertTrue("background test thread finished (lock timeout is broken)", latchSet);
        assertTrue("background test thread timed out on lock attempt", bgTask.get());
        em.getTransaction().commit();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (t != null) {
            // wait for background thread to finish beforeQuery deleting entity
            t.join();
        }
        em.getTransaction().begin();
        lock = em.getReference(Lock.class, lock.getId());
        em.remove(lock);
        em.getTransaction().commit();
        em.close();
        em2.close();
    }
}
Also used : HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) EntityManager(javax.persistence.EntityManager) LockTimeoutException(javax.persistence.LockTimeoutException) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) RequiresDialect(org.hibernate.testing.RequiresDialect)

Aggregations

RequiresDialectFeature (org.hibernate.testing.RequiresDialectFeature)46 Test (org.junit.Test)45 Session (org.hibernate.Session)34 Transaction (org.hibernate.Transaction)17 TestForIssue (org.hibernate.testing.TestForIssue)10 EntityManager (javax.persistence.EntityManager)8 HashMap (java.util.HashMap)7 RequiresDialect (org.hibernate.testing.RequiresDialect)7 List (java.util.List)6 Callable (java.util.concurrent.Callable)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 Query (org.hibernate.Query)6 LockTimeoutException (javax.persistence.LockTimeoutException)5 ArrayList (java.util.ArrayList)4 QuerySyntaxException (org.hibernate.hql.internal.ast.QuerySyntaxException)4 SkipForDialect (org.hibernate.testing.SkipForDialect)4 Query (javax.persistence.Query)3 BigDecimal (java.math.BigDecimal)2 Map (java.util.Map)2 QueryTimeoutException (javax.persistence.QueryTimeoutException)2