Search in sources :

Example 1 with LoginAccount

use of org.jpox.samples.one_one.unidir.LoginAccount in project tests by datanucleus.

the class XMLTest method testSqlResultSetMapping.

/**
 * Test of JPA <sql-result-set-mapping>
 */
public void testSqlResultSetMapping() {
    NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null);
    ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null);
    MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx);
    PersistenceUnitMetaData pumd = getMetaDataForPersistenceUnit(nucleusCtx, "JPATest");
    metaDataMgr.loadPersistenceUnit(pumd, null);
    ClassMetaData cmd = (ClassMetaData) metaDataMgr.getMetaDataForClass(LoginAccount.class.getName(), clr);
    QueryResultMetaData[] queryResultMappings = cmd.getQueryResultMetaData();
    assertNotNull("LoginAccount has no QueryResultMetaData!", queryResultMappings);
    assertEquals("LoginAccount has incorrect number of query result mappings", 2, queryResultMappings.length);
    // Example 1 : Returning 2 entities
    QueryResultMetaData qrmd = null;
    for (int i = 0; i < queryResultMappings.length; i++) {
        QueryResultMetaData md = queryResultMappings[i];
        if (md.getName().equals("MD_LOGIN_PLUS_ACCOUNT")) {
            qrmd = md;
            break;
        }
    }
    if (qrmd == null) {
        fail("SQL ResultSet mapping MD_LOGIN_PLUS_ACCOUNT is not present!");
    }
    String[] scalarCols = qrmd.getScalarColumns();
    assertNull("LoginAccount sql mapping has incorrect scalar cols", scalarCols);
    PersistentTypeMapping[] sqlMappingEntities = qrmd.getPersistentTypeMappings();
    assertNotNull("LoginAccount sql mapping has incorrect entities", sqlMappingEntities);
    assertEquals("LoginAccount sql mapping has incorrect number of entities", 2, sqlMappingEntities.length);
    // LoginAccount
    assertEquals("LoginAccount sql mapping entity 0 has incorrect class", LoginAccount.class.getName(), sqlMappingEntities[0].getClassName());
    assertNull("LoginAccount sql mapping entity 0 has incorrect discriminator", sqlMappingEntities[0].getDiscriminatorColumn());
    // Login
    assertEquals("LoginAccount sql mapping entity 1 has incorrect class", Login.class.getName(), sqlMappingEntities[1].getClassName());
    assertNull("LoginAccount sql mapping entity 1 has incorrect discriminator", sqlMappingEntities[1].getDiscriminatorColumn());
    // Example 2 : Returning 2 scalars
    qrmd = null;
    for (int i = 0; i < queryResultMappings.length; i++) {
        QueryResultMetaData md = queryResultMappings[i];
        if (md.getName().equals("MD_ACCOUNT_NAMES")) {
            qrmd = md;
            break;
        }
    }
    if (qrmd == null) {
        fail("SQL ResultSet mapping MD_ACCOUNT_NAMES is not present!");
    }
    scalarCols = qrmd.getScalarColumns();
    assertNotNull("LoginAccount sql mapping has incorrect scalar cols", scalarCols);
    assertEquals("LoginAccount sql mapping has incorrect column name", "FIRSTNAME", scalarCols[0]);
    assertEquals("LoginAccount sql mapping has incorrect column name", "LASTNAME", scalarCols[1]);
    sqlMappingEntities = qrmd.getPersistentTypeMappings();
    assertNull("LoginAccount sql mapping has incorrect entities", sqlMappingEntities);
}
Also used : JPAMetaDataManager(org.datanucleus.api.jpa.metadata.JPAMetaDataManager) NucleusContext(org.datanucleus.NucleusContext) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) JPAMetaDataManager(org.datanucleus.api.jpa.metadata.JPAMetaDataManager) MetaDataManager(org.datanucleus.metadata.MetaDataManager) PersistenceNucleusContextImpl(org.datanucleus.PersistenceNucleusContextImpl) Login(org.jpox.samples.one_one.unidir.Login) PersistenceUnitMetaData(org.datanucleus.metadata.PersistenceUnitMetaData) LoginAccount(org.jpox.samples.one_one.unidir.LoginAccount) PersistentTypeMapping(org.datanucleus.metadata.QueryResultMetaData.PersistentTypeMapping) ClassMetaData(org.datanucleus.metadata.ClassMetaData) QueryResultMetaData(org.datanucleus.metadata.QueryResultMetaData)

Example 2 with LoginAccount

use of org.jpox.samples.one_one.unidir.LoginAccount in project tests by datanucleus.

the class RelationshipTest method test1to1Unidir.

/**
 * Test case for 1-1 unidirectional relationships.
 */
public void test1to1Unidir() throws Exception {
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    // Create sample data
    Object acctId = null;
    try {
        tx.begin();
        LoginAccount acct = new LoginAccount("JPOX", "User", "jpox", "password");
        pm.makePersistent(acct);
        acctId = JDOHelper.getObjectId(acct);
        tx.commit();
    } catch (Exception e) {
        LOG.error(e);
        fail("Exception thrown while creating 1-1 unidirectional relationship data : " + e.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
    // Retrieve the record and check the data
    pm = pmf.getPersistenceManager();
    tx = pm.currentTransaction();
    try {
        tx.begin();
        LoginAccount acct = (LoginAccount) pm.getObjectById(acctId);
        assertTrue("LoginAccount \"firstName\" is incorrect", acct.getFirstName().equals("JPOX"));
        assertTrue("LoginAccount \"lastName\" is incorrect", acct.getLastName().equals("User"));
        Login login = acct.getLogin();
        assertEquals("Login \"login\" is incorrect", login.getUserName(), "jpox");
        assertEquals("Login \"password\" is incorrect", login.getPassword(), "password");
        tx.commit();
    } catch (Exception e) {
        LOG.error(e);
        fail("Exception thrown while interrogating 1-1 unidirectional relationship data : " + e.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
Also used : Transaction(javax.jdo.Transaction) PersistenceManager(javax.jdo.PersistenceManager) LoginAccount(org.jpox.samples.one_one.unidir.LoginAccount) Login(org.jpox.samples.one_one.unidir.Login) JDOObjectNotFoundException(javax.jdo.JDOObjectNotFoundException)

Example 3 with LoginAccount

use of org.jpox.samples.one_one.unidir.LoginAccount in project tests by datanucleus.

the class GeneralTest method testEmptyTxTimeout.

/**
 * Test that pm.currentTransaction.isActive() is correct when marked for rollback before
 * JTATransactionImpl had a chance to join
 */
public void testEmptyTxTimeout() throws NamingException, SystemException, NotSupportedException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
    try {
        PersistenceManager pm = pmf.getPersistenceManager();
        try {
            UserTransaction ut = getUserTransaction();
            ut.setTransactionTimeout(1);
            ut.begin();
            synchronized (this) {
                // provoke timeout
                try {
                    wait(1200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            // make sure we were marked for rollback (JOTM + JBoss 4.0.3SP1), or rolled back already (JBoss 4.2.3)
            assertTrue("Expected UserTransaction.getStatus() to be either STATUS_MARKED_ROLLBACK or STATUS_ROLLEDBACK, but was " + ut.getStatus(), ut.getStatus() == Status.STATUS_MARKED_ROLLBACK || ut.getStatus() == Status.STATUS_ROLLEDBACK);
            if (// JOTM + JBoss 4.0.3SP1
            ut.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
                // by definition should be active even if marked for rollback
                assertTrue(pm.currentTransaction().isActive());
                ut.rollback();
            } else if (// JBoss 4.2.3
            ut.getStatus() == Status.STATUS_ROLLEDBACK) {
                // by definition should be active (anything but NO_TRANSACTION means active)
                assertTrue(pm.currentTransaction().isActive());
                // workaround for JBoss 4.2.3 bug https://jira.jboss.org/jira/browse/JBAS-6663
                if (cargoContainerId.equals("jboss42x")) {
                    try {
                        ut.rollback();
                    } catch (IllegalStateException e) {
                        // expected, make sure transaction has been disassociated from thread
                        assertTrue("Workaround for https://jira.jboss.org/jira/browse/JBAS-6663 has failed?!", ut.getStatus() == Status.STATUS_NO_TRANSACTION);
                    }
                } else // whatever appserver this may be
                {
                    ut.rollback();
                }
            }
            assertFalse(pm.currentTransaction().isActive());
            // reset timeout to default
            ut.setTransactionTimeout(0);
            // now verify that we can still commit, i.e. tx was rolled back properly and is not active anymore
            ut.begin();
            LoginAccount acct2 = new LoginAccount("Wilma", "Flintstone", "wilma", "pebbles");
            pm.makePersistent(acct2);
            ut.commit();
            assertFalse(pm.currentTransaction().isActive());
        } finally {
            try {
                pm.close();
            } catch (Exception e) {
                // eat exception so test will fail with the underlying exception
                TestHelper.LOG.error("pm.close() failed", e);
            }
        }
    } finally {
        try {
            clean(LoginAccount.class);
        } catch (Exception e) {
            // eat exception so test will fail with the underlying exception
            TestHelper.LOG.error("clean(LoginAccount.class) failed", e);
        }
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) PersistenceManager(javax.jdo.PersistenceManager) LoginAccount(org.jpox.samples.one_one.unidir.LoginAccount) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) NamingException(javax.naming.NamingException) NotSupportedException(javax.transaction.NotSupportedException) SystemException(javax.transaction.SystemException) RollbackException(javax.transaction.RollbackException) HeuristicMixedException(javax.transaction.HeuristicMixedException)

Example 4 with LoginAccount

use of org.jpox.samples.one_one.unidir.LoginAccount in project tests by datanucleus.

the class GeneralTest method testFailedCommit.

/**
 * Test expected behaviour upon failed commit with JTA
 * (copied from test.jdo.general/org.datanucleus.tests.TransactionTest.java)
 * @throws NamingException
 * @throws SystemException
 * @throws NotSupportedException
 * @throws HeuristicRollbackException
 * @throws HeuristicMixedException
 * @throws RollbackException
 * @throws IllegalStateException
 * @throws SecurityException
 */
public void testFailedCommit() throws NamingException, NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
    try {
        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        tx.setOptimistic(true);
        UserTransaction ut = getUserTransaction();
        LoginAccount acct = new LoginAccount("Fred", "Flintstone", "fred", "yabbadabbadoo");
        Login login = acct.getLogin();
        try {
            ut.begin();
            pm.makePersistent(acct);
            ut.commit();
            // provoke FK violation
            ut.begin();
            pm.deletePersistent(login);
            boolean exceptionCaught = false;
            try {
                ut.commit();
                assertTrue("Should have caught exception during commit due to FK violation", false);
            }// e.g. JBoss wraps the NucleusDataStoreException
             catch (Exception e) {
                // Expected
                if (isRollbackDueToDatastoreException(e)) {
                    exceptionCaught = true;
                }
            }
            assertTrue("No exception was thrown during commit so couldnt test autoRollback", exceptionCaught);
            // receiving a RollbackException in commmit() by definition means the UT was rolled back
            if (ut.getStatus() == Status.STATUS_NO_TRANSACTION && pm.currentTransaction().isActive() && ut.getClass().getName().startsWith("org.objectweb.jotm")) {
                // see http://www.jpox.org/servlet/jira/browse/NUCCORE-224
                fail("JOTM bug: when an exception is thrown during Synchronization.beforeCompletion(), the UserTransaction's status is " + "STATUS_NO_TRANSCTION, but there was no callback to Synchronization.afterCompletion()");
            }
            assertFalse(pm.currentTransaction().isActive());
            // now verify that we can still commit, i.e. tx was rolled back properly and is not active anymore
            ut.begin();
            LoginAccount acct2 = new LoginAccount("Wilma", "Flintstone", "wilma", "pebbles");
            pm.makePersistent(acct2);
            ut.commit();
            assertFalse(pm.currentTransaction().isActive());
        } finally {
            try {
                if (ut.getStatus() != Status.STATUS_NO_TRANSACTION) {
                    ut.rollback();
                }
                pm.close();
            } catch (Exception e) {
                // eat exception so test will fail with the underlying exception
                TestHelper.LOG.error("failure during finally block", e);
            }
        }
    } finally {
        try {
            clean(LoginAccount.class);
        } catch (Exception e) {
            // eat exception so test will fail with the underlying exception
            TestHelper.LOG.error("clean(LoginAccount.class) failed", e);
        }
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) UserTransaction(javax.transaction.UserTransaction) Transaction(javax.jdo.Transaction) PersistenceManager(javax.jdo.PersistenceManager) LoginAccount(org.jpox.samples.one_one.unidir.LoginAccount) Login(org.jpox.samples.one_one.unidir.Login) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) NamingException(javax.naming.NamingException) NotSupportedException(javax.transaction.NotSupportedException) SystemException(javax.transaction.SystemException) RollbackException(javax.transaction.RollbackException) HeuristicMixedException(javax.transaction.HeuristicMixedException)

Example 5 with LoginAccount

use of org.jpox.samples.one_one.unidir.LoginAccount in project tests by datanucleus.

the class AttachDetachTest method testCopyOnAttachFalseOneToOne.

/**
 * Test for use of CopyOnAttach=false with a 1-1 unidir relation.
 */
public void testCopyOnAttachFalseOneToOne() {
    try {
        LoginAccount acct = null;
        Login login = null;
        Object acctId = null;
        Object loginId = null;
        // Persist the owner object
        PersistenceManager pm = newPM();
        pm.setDetachAllOnCommit(true);
        pm.setCopyOnAttach(false);
        pm.getFetchPlan().setGroup(FetchPlan.ALL).setMaxFetchDepth(2);
        Transaction tx = pm.currentTransaction();
        try {
            // Persist
            tx.begin();
            acct = new LoginAccount("George", "Bush", "bush", "iraq");
            login = acct.getLogin();
            pm.makePersistent(acct);
            tx.commit();
            acctId = pm.getObjectId(acct);
            loginId = pm.getObjectId(login);
        } catch (Exception e) {
            LOG.error("Exception in test", e);
            fail(e.toString());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            pm.close();
        }
        // Update the detached objects
        assertEquals("Owner object is in incorrect state", ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(acct));
        assertEquals("Owner object is in incorrect state", ObjectState.DETACHED_CLEAN, JDOHelper.getObjectState(login));
        acct.setFirstName("George W");
        login.setPassword("vietnam");
        // Attach the owner object
        pm = newPM();
        pm.setCopyOnAttach(false);
        pm.setDetachAllOnCommit(true);
        tx = pm.currentTransaction();
        try {
            tx.begin();
            LoginAccount acct2 = (LoginAccount) pm.makePersistent(acct);
            pm.flush();
            assertEquals("Attached LoginAccount is different object to detached, yet with CopyOnAttach=false should be same", acct, acct2);
            assertTrue("LoginAccount should be persistent but isnt", JDOHelper.isPersistent(acct));
            assertTrue("Login should be persistent but isnt", JDOHelper.isPersistent(login));
            tx.commit();
            assertTrue("LoginAccount should not be dirty but is", JDOHelper.isDetached(acct));
            assertFalse("LoginAccount should not be dirty but is", JDOHelper.isDirty(acct));
        } catch (Exception e) {
            LOG.error("Exception in test", e);
            fail(e.toString());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            pm.close();
        }
        // Retrieve and check the datastore state
        pm = newPM();
        pm.getFetchPlan().setGroup(FetchPlan.ALL);
        tx = pm.currentTransaction();
        try {
            tx.begin();
            LoginAccount acct2 = (LoginAccount) pm.getObjectById(acctId);
            Login login2 = (Login) pm.getObjectById(loginId);
            assertEquals("Account has incorrect first name", "George W", acct2.getFirstName());
            assertEquals("Account has incorrect last name", "Bush", acct2.getLastName());
            assertEquals("Login has incorrect username", "bush", login2.getUserName());
            assertEquals("Login has incorrect password", "vietnam", login2.getPassword());
            tx.commit();
        } catch (Exception e) {
            LOG.error("Exception in test", e);
            fail(e.toString());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            pm.close();
        }
    } finally {
        clean(LoginAccount.class);
        clean(Login.class);
    }
}
Also used : Transaction(javax.jdo.Transaction) JDOPersistenceManager(org.datanucleus.api.jdo.JDOPersistenceManager) PersistenceManager(javax.jdo.PersistenceManager) LoginAccount(org.jpox.samples.one_one.unidir.LoginAccount) Login(org.jpox.samples.one_one.unidir.Login) JDODetachedFieldAccessException(javax.jdo.JDODetachedFieldAccessException) JDOUserException(javax.jdo.JDOUserException) JDOObjectNotFoundException(javax.jdo.JDOObjectNotFoundException)

Aggregations

LoginAccount (org.jpox.samples.one_one.unidir.LoginAccount)12 PersistenceManager (javax.jdo.PersistenceManager)11 Transaction (javax.jdo.Transaction)10 Login (org.jpox.samples.one_one.unidir.Login)8 JDOObjectNotFoundException (javax.jdo.JDOObjectNotFoundException)5 JDOUserException (javax.jdo.JDOUserException)3 JDODetachedFieldAccessException (javax.jdo.JDODetachedFieldAccessException)2 JDOException (javax.jdo.JDOException)2 NamingException (javax.naming.NamingException)2 HeuristicMixedException (javax.transaction.HeuristicMixedException)2 HeuristicRollbackException (javax.transaction.HeuristicRollbackException)2 NotSupportedException (javax.transaction.NotSupportedException)2 RollbackException (javax.transaction.RollbackException)2 SystemException (javax.transaction.SystemException)2 UserTransaction (javax.transaction.UserTransaction)2 JDOPersistenceManager (org.datanucleus.api.jdo.JDOPersistenceManager)2 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)2 SQLException (java.sql.SQLException)1 Properties (java.util.Properties)1 PersistenceManagerFactory (javax.jdo.PersistenceManagerFactory)1