Search in sources :

Example 16 with PersistenceManager

use of javax.jdo.PersistenceManager in project motech by motech.

the class SchemaChangeLockManager method releaseLock.

@Transactional(propagation = Propagation.MANDATORY)
public void releaseLock(String comment) {
    LOGGER.info("Releasing lock for: {}", comment);
    final PersistenceManager pm = getPersistenceManager();
    final Boolean originalSerializedRead = pm.currentTransaction().getSerializeRead();
    try {
        pm.currentTransaction().setSerializeRead(true);
        SchemaChangeLock lock = getLock(pm);
        lock.setComment(null);
        lock.setTimestamp(null);
        LOGGER.info("Lock released for: {}", comment);
    } finally {
        pm.currentTransaction().setSerializeRead(originalSerializedRead);
    }
}
Also used : PersistenceManager(javax.jdo.PersistenceManager) SchemaChangeLock(org.motechproject.mds.domain.SchemaChangeLock) Transactional(org.springframework.transaction.annotation.Transactional)

Example 17 with PersistenceManager

use of javax.jdo.PersistenceManager in project tests by datanucleus.

the class StorageTester method validateObjects.

protected void validateObjects(Class c) throws Exception {
    // Read them back and verify that they contain what they should
    TestHelper.LOG.info("Validating " + TEST_OBJECT_COUNT + " " + c.getName() + " objects:");
    TestHelper.LOG.info("  Normal read");
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        TestObject[] loaded = new TestObject[TEST_OBJECT_COUNT];
        for (int i = 0; i < TEST_OBJECT_COUNT; ++i) {
            tx.begin();
            TestObject obj = (TestObject) pm.getObjectById(ids[i], true);
            assertFieldsEqual(objs[i], obj);
            loaded[i] = obj;
            tx.commit();
        }
    } catch (Exception e) {
        TestHelper.LOG.error("StorageTester.validateObjects exception thrown", e);
        throw e;
    } finally {
        if (tx.isActive())
            tx.rollback();
        pm.close();
    }
    /*
         * Read some of them back and verify them using non-transactional reads.
         * Only some are done because non-transactional reads are much slower
         * unless connection pooling is used (eventually we should use pooling
         * when testing).
         */
    TestHelper.LOG.info("  Non-transactional read");
    pm = pmf.getPersistenceManager();
    tx = pm.currentTransaction();
    try {
        tx.setNontransactionalRead(true);
        for (int i = 0; i < TEST_OBJECT_COUNT; i += 10) {
            TestObject obj = (TestObject) pm.getObjectById(ids[i], false);
            assertFieldsEqual(objs[i], obj);
        }
    } catch (Exception e) {
        TestHelper.LOG.error("StorageTester.validateObjects exception thrown", e);
        throw e;
    } finally {
        pm.close();
    }
    // Read some of them back, verify them, then verify values get retained after commit when retainValues mode is on
    TestHelper.LOG.info("  Retain values mode");
    pm = pmf.getPersistenceManager();
    tx = pm.currentTransaction();
    try {
        tx.setRetainValues(true);
        tx.begin();
        TestObject[] loaded = new TestObject[TEST_OBJECT_COUNT];
        for (int i = 0; i < TEST_OBJECT_COUNT; i += 10) {
            TestObject obj = (TestObject) pm.getObjectById(ids[i], true);
            assertFieldsEqual(objs[i], obj);
            loaded[i] = obj;
        }
        tx.commit();
        for (int i = 0; i < TEST_OBJECT_COUNT; i += 10) assertFieldsEqual(objs[i], loaded[i]);
    } catch (Exception e) {
        TestHelper.LOG.error("StorageTester.validateObjects exception thrown", e);
        throw e;
    } finally {
        if (tx.isActive())
            tx.rollback();
        pm.close();
    }
}
Also used : Transaction(javax.jdo.Transaction) PersistenceManager(javax.jdo.PersistenceManager)

Example 18 with PersistenceManager

use of javax.jdo.PersistenceManager in project tests by datanucleus.

the class StorageTester method validateTransactionalRefresh.

protected void validateTransactionalRefresh(Class c) throws Exception {
    // Validate that persistent non-transactional objects transition to persistent,
    // and refresh themselves, when accessed from within a transaction
    TestHelper.LOG.info("Validating transactional refresh on " + TEST_OBJECT_COUNT + " " + c.getName() + " objects");
    PersistenceManager pm1 = pmf.getPersistenceManager();
    Transaction tx1 = pm1.currentTransaction();
    tx1.setRetainValues(true);
    try {
        PersistenceManager pm2 = pmf.getPersistenceManager();
        Transaction tx2 = pm2.currentTransaction();
        Random rnd = new Random(0);
        TestObject[] pobjs = new TestObject[TEST_OBJECT_COUNT];
        try {
            // Load all of the objects using pm1
            tx1.begin();
            for (int i = 0; i < TEST_OBJECT_COUNT; ++i) {
                // Half will be Hollow and half PersistentClean
                boolean validate = rnd.nextBoolean();
                pobjs[i] = (TestObject) pm1.getObjectById(ids[i], validate);
                // Half of the PersistentClean will be fully loaded
                if (validate && rnd.nextBoolean())
                    assertFieldsEqual(objs[i], pobjs[i]);
            }
            tx1.commit();
            for (int i = 0; i < TEST_OBJECT_COUNT; ++i) {
                Assert.assertTrue("Object is not persistent: " + ids[i], JDOHelper.isPersistent(pobjs[i]));
                Assert.assertTrue("Object is transactional: " + ids[i], !JDOHelper.isTransactional(pobjs[i]));
            }
            // Modify them all using pm2
            tx2.begin();
            for (int i = 0; i < TEST_OBJECT_COUNT; ++i) {
                TestObject obj = (TestObject) pm2.getObjectById(ids[i], false);
                obj.fillUpdateRandom();
                objs[i] = (TestObject) obj.clone();
                assertFieldsEqual(obj, objs[i]);
            }
            tx2.commit();
            if (!tx1.getOptimistic()) {
                // Access them all inside a transaction using pm1
                tx1.begin();
                for (int i = 0; i < TEST_OBJECT_COUNT; ++i) {
                    Assert.assertTrue("Object is not persistent: " + ids[i], JDOHelper.isPersistent(pobjs[i]));
                    Assert.assertTrue("Object is transactional: " + ids[i], !JDOHelper.isTransactional(pobjs[i]));
                    assertFieldsEqual(objs[i], pobjs[i]);
                    Assert.assertTrue("Object is not persistent: " + ids[i], JDOHelper.isPersistent(pobjs[i]));
                    Assert.assertTrue("Object is not transactional: " + ids[i], JDOHelper.isTransactional(pobjs[i]));
                }
                tx1.commit();
            }
        } finally {
            if (tx2.isActive())
                tx2.rollback();
            pm2.close();
        }
    } catch (Exception e) {
        TestHelper.LOG.error("StorageTester.validateTransactionalRefresh exception thrown", e);
        throw e;
    } finally {
        if (tx1.isActive())
            tx1.rollback();
        pm1.close();
    }
}
Also used : Transaction(javax.jdo.Transaction) Random(java.util.Random) PersistenceManager(javax.jdo.PersistenceManager)

Example 19 with PersistenceManager

use of javax.jdo.PersistenceManager in project tests by datanucleus.

the class StorageTester method insertObjects.

/**
 * Method to insert a series of test objects of the specified type
 * @param c The class whose objects we create
 * @throws Exception
 */
public void insertObjects(Class c) throws Exception {
    // Insert TEST_OBJECT_COUNT random objects
    TestHelper.LOG.info("Inserting " + TEST_OBJECT_COUNT + " " + c.getName() + " objects");
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        for (int i = 0; i < TEST_OBJECT_COUNT; ++i) {
            tx.setRetainValues(true);
            tx.begin();
            TestObject obj = (TestObject) c.newInstance();
            obj.fillRandom();
            objs[i] = (TestObject) obj.clone();
            assertFieldsEqual(obj, objs[i]);
            pm.makePersistent(obj);
            ids[i] = JDOHelper.getObjectId(obj);
            tx.commit();
        }
    } catch (Exception e) {
        TestHelper.LOG.error("StorageTester.insertObjects exception thrown", e);
        throw e;
    } finally {
        if (tx.isActive())
            tx.rollback();
        pm.close();
    }
}
Also used : Transaction(javax.jdo.Transaction) PersistenceManager(javax.jdo.PersistenceManager)

Example 20 with PersistenceManager

use of javax.jdo.PersistenceManager in project tests by datanucleus.

the class JDOPersistenceTestCase method cleanup.

protected void cleanup(Set<Object> toCleanup) throws Exception {
    // Keep track of what is being deleted so we don't need to
    // delete what has already been deleted by the cascade.
    Set<Object> deleted = new HashSet<>();
    DeleteLifecycleListener listener = new DeleteLifecycleListener() {

        @Override
        public void preDelete(InstanceLifecycleEvent event) {
        // Nothing to do
        }

        @Override
        public void postDelete(InstanceLifecycleEvent event) {
            Object id = ((Persistable) event.getSource()).dnGetObjectId();
            deleted.add(id);
        }
    };
    try (PersistenceManager pm = pmf.getPersistenceManager()) {
        pm.addInstanceLifecycleListener(listener, Object.class);
        Set<Object> toDelete = toCleanup;
        Set<Object> retry = new HashSet<>();
        int attempts = 0;
        do {
            // Try to delete
            for (Object id : toDelete) {
                try {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Cleaning up: " + id);
                    }
                    if (deleted.contains(id)) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Already deleted: " + id);
                        }
                    } else {
                        Object object = pm.getObjectById(id, false);
                        boolean cleanerRun = false;
                        for (Entry<String, Consumer<PersistenceManager>> entry : cleanersByPrefix.entrySet()) {
                            if (object.getClass().getName().startsWith(entry.getKey())) {
                                entry.getValue().accept(pm);
                                cleanerRun = true;
                                break;
                            }
                        }
                        if (!cleanerRun) {
                            LOG.debug(">> calling deletePersistent on " + StringUtils.toJVMIDString(object) + " state=" + JDOHelper.getObjectState(object));
                            pm.deletePersistent(object);
                        }
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Cleaned " + id + " successfully");
                        }
                    }
                } catch (Exception e) {
                    LOG.warn("Exception in delete process", e);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Failed, retrying later: " + id);
                    }
                    retry.add(id);
                }
            }
            attempts++;
            if (!retry.isEmpty() && attempts > MAX_CLEANUP_ATTEMPTS) {
                // Give up
                retry.clear();
            // throw new Exception("Fail to cleanup the following object(s) after " + attempts + " attempts: " + retry);
            }
            // Try again
            toDelete.clear();
            toDelete.addAll(retry);
            retry.clear();
        } while (!toDelete.isEmpty());
    }
}
Also used : Persistable(org.datanucleus.enhancement.Persistable) PersistenceManager(javax.jdo.PersistenceManager) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) InstanceLifecycleEvent(javax.jdo.listener.InstanceLifecycleEvent) Consumer(java.util.function.Consumer) DeleteLifecycleListener(javax.jdo.listener.DeleteLifecycleListener) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

PersistenceManager (javax.jdo.PersistenceManager)1664 Transaction (javax.jdo.Transaction)1542 Query (javax.jdo.Query)671 List (java.util.List)397 JDOUserException (javax.jdo.JDOUserException)352 Collection (java.util.Collection)309 Iterator (java.util.Iterator)239 JDOObjectNotFoundException (javax.jdo.JDOObjectNotFoundException)185 JDOPersistenceManager (org.datanucleus.api.jdo.JDOPersistenceManager)170 Person (org.jpox.samples.models.company.Person)146 Employee (org.jpox.samples.models.company.Employee)128 Manager (org.jpox.samples.models.company.Manager)107 HashSet (java.util.HashSet)101 ArrayList (java.util.ArrayList)85 SQLException (java.sql.SQLException)82 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)77 JDOException (javax.jdo.JDOException)74 Extent (javax.jdo.Extent)72 JDOFatalUserException (javax.jdo.JDOFatalUserException)68 JDODataStoreException (javax.jdo.JDODataStoreException)65