Search in sources :

Example 1 with Login

use of org.jpox.samples.one_one.unidir.Login 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 Login

use of org.jpox.samples.one_one.unidir.Login 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 Login

use of org.jpox.samples.one_one.unidir.Login 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 4 with Login

use of org.jpox.samples.one_one.unidir.Login 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)

Example 5 with Login

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

the class CacheTest method testRelationshipCachingWhenNontransactional.

public void testRelationshipCachingWhenNontransactional() throws Exception {
    try {
        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        // Create sample data
        Object acctId = null;
        try {
            tx.begin();
            LoginAccount acct = new LoginAccount("Barney", "Rubble", "brubble", "bambam");
            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();
        }
        // Make sure the object isn't in the cache following persistence
        pmf.getDataStoreCache().evictAll();
        pmf.getDataStoreCache().pinAll(true, LoginAccount.class);
        pmf.getDataStoreCache().pinAll(true, Login.class);
        // Retrieve the record and check the data
        pm = pmf.getPersistenceManager();
        try {
            LOG.info(">> CacheTest fetching LoginAccount(1)");
            LoginAccount acct = (LoginAccount) pm.getObjectById(acctId);
            assertTrue("LoginAccount \"firstName\" is incorrect", acct.getFirstName().equals("Barney"));
            assertTrue("LoginAccount \"lastName\" is incorrect", acct.getLastName().equals("Rubble"));
            LOG.info(">> CacheTest fetching Login(1)");
            // Access the login field to make sure it is read. Should get L2 cached now
            Login login = acct.getLogin();
            assertEquals("Login \"login\" is incorrect", login.getUserName(), "brubble");
            assertEquals("Login \"password\" is incorrect", login.getPassword(), "bambam");
        } catch (Exception e) {
            LOG.error(e);
            fail("Exception thrown while interrogating 1-1 unidirectional relationship data : " + e.getMessage());
        } finally {
            pm.close();
        }
        // login account is in the cache now after the last getObjectById
        LOG.info(">> CacheTest fetching LoginAccount(non-tx)");
        CachedPC cpc = ((JDOPersistenceManagerFactory) pmf).getNucleusContext().getLevel2Cache().get(acctId);
        assertTrue("LoginAccount is not cached", cpc != null);
        assertTrue("LoginAccount \"login\" is not cached", cpc.getFieldValue(2) != null);
        // Retrieve the record and check the data
        pm = pmf.getPersistenceManager();
        try {
            LoginAccount acct = (LoginAccount) pm.getObjectById(acctId);
            String[] loadedFields = NucleusJDOHelper.getLoadedFields(acct, pm);
            LOG.info(">> loadedFields=" + StringUtils.objectArrayToString(loadedFields));
            LOG.info(">> Accessing field login");
            Login login = acct.getLogin();
            LOG.info(">> login=" + login);
        } finally {
            pm.close();
        }
    } finally {
        clean(LoginAccount.class);
    }
}
Also used : Transaction(javax.jdo.Transaction) PersistenceManager(javax.jdo.PersistenceManager) LoginAccount(org.jpox.samples.one_one.unidir.LoginAccount) CachedPC(org.datanucleus.cache.CachedPC) Login(org.jpox.samples.one_one.unidir.Login) JDOPersistenceManagerFactory(org.datanucleus.api.jdo.JDOPersistenceManagerFactory) JDOObjectNotFoundException(javax.jdo.JDOObjectNotFoundException)

Aggregations

Login (org.jpox.samples.one_one.unidir.Login)8 LoginAccount (org.jpox.samples.one_one.unidir.LoginAccount)8 PersistenceManager (javax.jdo.PersistenceManager)7 Transaction (javax.jdo.Transaction)7 JDOObjectNotFoundException (javax.jdo.JDOObjectNotFoundException)4 JDOException (javax.jdo.JDOException)2 SQLException (java.sql.SQLException)1 JDODetachedFieldAccessException (javax.jdo.JDODetachedFieldAccessException)1 JDOUserException (javax.jdo.JDOUserException)1 NamingException (javax.naming.NamingException)1 HeuristicMixedException (javax.transaction.HeuristicMixedException)1 HeuristicRollbackException (javax.transaction.HeuristicRollbackException)1 NotSupportedException (javax.transaction.NotSupportedException)1 RollbackException (javax.transaction.RollbackException)1 SystemException (javax.transaction.SystemException)1 UserTransaction (javax.transaction.UserTransaction)1 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)1 NucleusContext (org.datanucleus.NucleusContext)1 PersistenceNucleusContextImpl (org.datanucleus.PersistenceNucleusContextImpl)1 JDOPersistenceManager (org.datanucleus.api.jdo.JDOPersistenceManager)1