You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@openjpa.apache.org by pc...@apache.org on 2008/02/15 10:20:40 UTC
svn commit: r627979 [29/39] - in /openjpa/trunk:
openjpa-lib/src/test/java/org/apache/openjpa/lib/test/
openjpa-persistence-jdbc/ openjpa-persistence-jdbc/src/test/java/
openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/
openjpa-per...
Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManager.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManager.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManager.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManager.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,431 @@
+/*
+ * TestOpenJPAEntityManager.java
+ *
+ * Created on October 12, 2006, 4:40 PM
+ *
+ * To change this template, choose Tools | Template Manager
+ * and open the template in the editor.
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence.kernel;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityNotFoundException;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest1;
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest2;
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest4;
+import org.apache.openjpa.kernel.BrokerFactory;
+import org.apache.openjpa.kernel.DelegatingBrokerFactory;
+import org.apache.openjpa.kernel.PCState;
+import org.apache.openjpa.persistence.Extent;
+import org.apache.openjpa.persistence.JPAFacadeHelper;
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+import org.apache.openjpa.persistence.OpenJPAEntityManagerFactory;
+import org.apache.openjpa.util.Id;
+
+public class TestPersistenceManager extends BaseKernelTest {
+
+ private int _id = 0;
+ private int _id2 = 0;
+
+ public TestPersistenceManager(String name) {
+ super(name);
+ }
+
+ /**
+ * Creates a new instance of TestOpenJPAEntityManager
+ */
+ public TestPersistenceManager() {
+ }
+
+ public void setUp() throws Exception {
+ deleteAll(RuntimeTest1.class);
+ deleteAll(RuntimeTest2.class);
+
+ OpenJPAEntityManager pm = getPM();
+ startTx(pm);
+
+ RuntimeTest1 a = new RuntimeTest1("STRING", 10);
+ RuntimeTest2 b = new RuntimeTest2("STRING2", 11);
+ pm.persist(a);
+ pm.persist(b);
+ _id = a.getIntField();
+ _id2 = b.getIntField();
+
+ endTx(pm);
+ endEm(pm);
+ }
+
+ /**
+ * No-op test that can be run in name to see if the setup is working
+ * properly.
+ */
+ public void testSetup() {
+ }
+
+ /**
+ * Tests that the PM throws Exceptions on usage attempts after it has been
+ * closed.
+ */
+ public void testClosed() {
+ OpenJPAEntityManager pm = getPM();
+ endEm(pm);
+
+ try {
+ // this is the only method that should succeed
+ pm.isOpen();
+ } catch (RuntimeException re) {
+ fail("isClosed");
+ }
+ try {
+ pm.find(RuntimeTest1.class, _id);
+ fail("find");
+ } catch (RuntimeException re) {
+ }
+ try {
+ pm.persist(new RuntimeTest1(20));
+ fail("setUserObject");
+ } catch (RuntimeException re) {
+ }
+ try {
+ pm.setNontransactionalRead(true);
+ fail("setNontransactionalRead");
+ } catch (RuntimeException re) {
+ }
+ try {
+ // this method should fail
+ endEm(pm);
+ bug(65, null, "multiple close should not be allowed");
+ fail("multiple close should not be allowed");
+ } catch (Exception jdoe) {
+ // good: we should get an exception
+ }
+ }
+
+ public void testMultipleCloseThreaded()
+ throws Throwable {
+ final OpenJPAEntityManager pm = getPM();
+ final List result = new ArrayList();
+ startTx(pm);
+
+ endEm(pm);
+
+ new Thread() {
+ public void run() {
+ try {
+ endEm(pm);
+ result.add(new Integer(0));
+ } catch (Exception jdoe) {
+ result.add(jdoe);
+ } catch (Throwable t) {
+ result.add(t);
+ }
+ }
+ }.start();
+
+ while (result.size() == 0)
+ Thread.currentThread().yield(); // wait for results
+ Object ret = result.get(0);
+
+ if (ret instanceof Exception)
+ return; // good
+
+ if (ret instanceof Throwable)
+ throw (Throwable) ret;
+
+ bug(65, null,
+ "multiple close in different threads should not be allowed");
+ }
+
+ /**
+ * This method tries to perform operations that should lead to
+ * illegal states, such as persisting instances outside of transactions,
+ * etc.
+ */
+ public void testIllegalState() {
+ OpenJPAEntityManager pm = getPM();
+
+ RuntimeTest1 a = new RuntimeTest1("foo", 14);
+ RuntimeTest1 a2 = (RuntimeTest1) pm.find(RuntimeTest1.class, _id);
+
+ try {
+ pm.persist(a);
+ fail("persist");
+ }
+ catch (Exception ise) {
+ }
+ try {
+ pm.isTransactional(a2);
+ fail("makeTransactional");
+ }
+ catch (Exception ise) {
+ }
+ try {
+ pm.remove(a2);
+ fail("deletePersistent");
+ }
+ catch (Exception ise) {
+ }
+
+ endEm(pm);
+ }
+
+ public void testOpenJPAEntityManagerFactorySerializable()
+ throws Exception {
+ OpenJPAEntityManagerFactory pmf =
+ (OpenJPAEntityManagerFactory) getEmf();
+ assertNotNull("OpenJPAEntityManagerFactory is null.", pmf);
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(pmf);
+
+ OpenJPAEntityManagerFactory pmf2 = (OpenJPAEntityManagerFactory)
+ new ObjectInputStream(
+ new ByteArrayInputStream(baos.toByteArray())).readObject();
+ assertNotNull("Deserialized OpenJPAEntityManagerFactory is null.",
+ pmf2);
+
+ OpenJPAEntityManager pm = pmf2.createEntityManager();
+ startTx(pm);
+ // go through some objects to make sure our PM is OK
+ for (Iterator i = pm.createExtent(RuntimeTest1.class, true).iterator();
+ i.hasNext(); i.next())
+ ;
+ endTx(pm);
+ endEm(pm);
+ }
+
+ private static BrokerFactory toBrokerFactory(EntityManagerFactory emf) {
+ BrokerFactory bf = JPAFacadeHelper.toBrokerFactory(emf);
+ if (bf instanceof DelegatingBrokerFactory)
+ bf = ((DelegatingBrokerFactory) bf).getInnermostDelegate();
+ return bf;
+ }
+
+ /**
+ * Test that a getObjectById() returns the correct instance.
+ */
+ public void testGetObjectById() {
+ // test with valid id
+ OpenJPAEntityManager pm = getPM();
+ RuntimeTest1 b = (RuntimeTest1) pm.find(RuntimeTest1.class, _id);
+ assertEquals("STRING", b.getStringField());
+
+ // invalid with possible subclasses should throw immediate exception
+ Object invalidId = new Id(RuntimeTest1.class, -1L);
+ try {
+ pm.find(RuntimeTest1.class, invalidId);
+ fail("Invalid Object");
+ } catch (Exception e) {
+ }
+
+ // invalid without subclasses and without validating should return
+ // hollow
+ invalidId = new Id(RuntimeTest4.class, -1L);
+ try {
+ RuntimeTest4 a = (RuntimeTest4) pm.getReference(RuntimeTest4.class,
+ invalidId);
+ assertNotNull("invalid without subclasses and without validating "
+ + "should return hollow or throw exception", a);
+ a.getName();
+ fail("Allowed access of invalid hollow instance.");
+ }
+ catch (EntityNotFoundException enfe) {
+ // expected
+ }
+
+ invalidId = new Id(RuntimeTest4.class, -3L);
+ assertNull(pm.find(RuntimeTest4.class, invalidId));
+
+ endEm(pm);
+ }
+
+ public void testGetObjectsById() {
+ OpenJPAEntityManager pm = getPM();
+ ArrayList idlist = new ArrayList();
+ idlist.add(_id);
+ idlist.add(_id2);
+ Collection pcs = pm.findAll(RuntimeTest1.class, idlist);
+ assertEquals(2, pcs.size());
+ Iterator iter = pcs.iterator();
+ assertEquals("STRING", ((RuntimeTest1) iter.next()).getStringField());
+ assertEquals("STRING2", ((RuntimeTest2) iter.next()).getStringField());
+ endEm(pm);
+
+ pm = getPM();
+ idlist = new ArrayList();
+ idlist.add(_id);
+ idlist.add(_id);
+ pcs = pm.findAll(RuntimeTest1.class, idlist);
+ iter = pcs.iterator();
+ assertEquals(2, pcs.size());
+ assertEquals("STRING", ((RuntimeTest1) iter.next()).getStringField());
+ iter = pcs.iterator();
+ assertTrue(iter.next() == iter.next());
+ endEm(pm);
+
+ // invalid id causes exception
+ Object invalidId = new Id(RuntimeTest4.class, -1L);
+ pm = getPM();
+ idlist = new ArrayList();
+ idlist.add(_id);
+ idlist.add(invalidId);
+ try {
+ pcs = (ArrayList) pm.findAll(RuntimeTest1.class, idlist);
+ iter = pcs.iterator();
+ assertEquals(2, pcs.size());
+ assertEquals("STRING",
+ ((RuntimeTest1) iter.next()).getStringField());
+ assertNotNull(iter.next());
+ fail("invalid id didnt cause exception");
+ }
+ catch (Exception onfe) {
+ //expected exception. invalid id causes exception
+ }
+
+ try {
+ ((RuntimeTest4) iter.next()).getName();
+ fail("Accessed invalid object.");
+ }
+ catch (Exception onfe) {
+ bug(1138, onfe, "Wrong exception type");
+ }
+
+ pm = getPM();
+ try {
+ pm.findAll(RuntimeTest1.class, idlist);
+ fail("Found invalid object.");
+ } catch (Exception e) {
+ }
+ endEm(pm);
+ }
+
+ public void testEvictAll() {
+ OpenJPAEntityManager pm = getPM();
+
+ List l = ((Extent) pm.createExtent(RuntimeTest1.class, true)).list();
+ pm.retrieveAll(l);
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ assertEquals(PCState.PNONTRANS, s);
+ }
+ pm.evictAll();
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ assertEquals(PCState.HOLLOW, s);
+ }
+ }
+
+ public void testEvictAllCollection() {
+ OpenJPAEntityManager pm = getPM();
+
+ List l = ((Extent) pm.createExtent(RuntimeTest1.class, true)).list();
+ pm.retrieveAll(l);
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ assertEquals(PCState.PNONTRANS, s);
+ }
+ pm.evictAll(l);
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ assertEquals(PCState.HOLLOW, s);
+ }
+ }
+
+ public void testEvictAllClass() {
+ OpenJPAEntityManager pm = getPM();
+
+ List l = ((Extent) pm.createExtent(RuntimeTest1.class, true)).list();
+ pm.retrieveAll(l);
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ assertEquals(PCState.PNONTRANS, s);
+ }
+ pm.evictAll(RuntimeTest1.class);
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ assertEquals(PCState.HOLLOW, s);
+ }
+ }
+
+ public void testEvictAllClassFailure() {
+ OpenJPAEntityManager pm = getPM();
+
+ List l = ((Extent) pm.createExtent(RuntimeTest1.class, true)).list();
+ pm.retrieveAll(l);
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ assertEquals(PCState.PNONTRANS, s);
+ }
+ pm.evictAll(RuntimeTest2.class);
+ boolean foundPNONTRANS = false;
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ if (s == PCState.PNONTRANS) {
+ foundPNONTRANS = true;
+ break;
+ }
+ }
+ assertTrue("should have found some RuntimeTest1s that were not "
+ + "evicted", foundPNONTRANS);
+ }
+
+ public void testEvictAllExtent() {
+ OpenJPAEntityManager pm = getPM();
+
+ List l = ((Extent) pm.createExtent(RuntimeTest1.class, true)).list();
+ pm.retrieveAll(l);
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ assertEquals(PCState.PNONTRANS, s);
+ }
+ pm.evictAll(pm.createExtent(RuntimeTest1.class, true));
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ assertEquals(PCState.HOLLOW, s);
+ }
+
+ pm.retrieveAll(l);
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ PCState s = getStateManager(iter.next(), pm).getPCState();
+ assertEquals(PCState.PNONTRANS, s);
+ }
+ pm.evictAll(pm.createExtent(RuntimeTest1.class, false));
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ Object o = iter.next();
+ if (o.getClass() == RuntimeTest1.class) {
+ PCState s = getStateManager(o, pm).getPCState();
+ assertEquals(PCState.HOLLOW, s);
+ }
+ }
+ }
+}
Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManagerFactoryImpl.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManagerFactoryImpl.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManagerFactoryImpl.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistenceManagerFactoryImpl.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,229 @@
+/*
+ * TestOpenJPAEntityManagerFactoryImpl.java
+ *
+ * Created on October 13, 2006, 10:54 AM
+ *
+ * To change this template, choose Tools | Template Manager
+ * and open the template in the editor.
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence.kernel;
+
+import java.util.Map;
+
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest1;
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest4;
+import org.apache.openjpa.conf.OpenJPAConfiguration;
+import org.apache.openjpa.conf.OpenJPAConfigurationImpl;
+import org.apache.openjpa.event.LifecycleEvent;
+import org.apache.openjpa.event.LoadListener;
+import org.apache.openjpa.kernel.AbstractBrokerFactory;
+import org.apache.openjpa.kernel.BrokerImpl;
+import org.apache.openjpa.kernel.StoreManager;
+import org.apache.openjpa.lib.conf.ConfigurationProvider;
+import org.apache.openjpa.meta.MetaDataRepository;
+import org.apache.openjpa.persistence.JPAFacadeHelper;
+import org.apache.openjpa.persistence.OpenJPAEntityManagerFactory;
+import org.apache.openjpa.persistence.OpenJPAEntityManagerFactorySPI;
+import org.apache.openjpa.persistence.OpenJPAPersistence;
+
+public class TestPersistenceManagerFactoryImpl extends BaseKernelTest {
+
+ private OpenJPAConfiguration _conf = null;
+
+ /**
+ * Creates a new instance of TestOpenJPAEntityManagerFactoryImpl
+ */
+ public TestPersistenceManagerFactoryImpl() {
+ }
+
+ public TestPersistenceManagerFactoryImpl(String test) {
+ super(test);
+ }
+
+ public void setUp() {
+ _conf = new OpenJPAConfigurationImpl();
+ _conf.setConnection2UserName("user");
+ _conf.setConnection2Password("pass");
+ _conf.setConnection2URL("url");
+ }
+
+ /**
+ * Test that configuration is frozen after retrieving a factory.
+ *
+ * This test case is for kodo persistencemanagerfactories and not openjpaentitymanagers.
+ * therefore its been commented out.
+ * FIX ME: aokeke
+ */
+/* public void testConfigurationFreeze()
+ {
+ OpenJPAEntityManagerFactory pmf = getOpenJPAEntityManagerFactory(_conf.toProperties(false));
+ assertEquals("user", pmf.getConfiguration().getConnection2UserName());
+ assertEquals("url", pmf.getConfiguration().getConnection2URL());
+ try
+ {
+ pmf.getConfiguration().setConnection2URL("url2");
+ fail("Allowed configuration change.");
+ }
+ catch (Exception e)
+ {
+ }
+ }*/
+
+ /**
+ * Test that persistence manager factories are being pooled.
+ *
+ * This test case is for kodo persistencemanagerfactories. It doesnt apply to
+ * openjpaentitymanagerfactories therefore it will be commented out.
+ * FIX ME: aokeke
+ */
+ /*public void testFactoryPooling() {
+ Properties props = new Properties();
+ props.putAll(_conf.toProperties(false));
+ OpenJPAEntityManagerFactory pmf1 = getOpenJPAEntityManagerFactory(props);
+
+ props = new Properties();
+ props.putAll(_conf.toProperties(false));
+ OpenJPAEntityManagerFactory pmf2 = getOpenJPAEntityManagerFactory(props);
+
+ props = new Properties();
+ props.putAll(_conf.toProperties(false));
+ OpenJPAEntityManagerFactory pmf3 = getOpenJPAEntityManagerFactory(props);
+
+ _conf.setConnectionURL("url2");
+ props = new Properties();
+ props.putAll(_conf.toProperties(false));
+ OpenJPAEntityManagerFactory pmf4 = getOpenJPAEntityManagerFactory
+ (_conf.toProperties(false));
+
+ props = new Properties();
+ props.putAll(_conf.toProperties(false));
+ OpenJPAEntityManagerFactory pmf5 = getOpenJPAEntityManagerFactory(_conf.toProperties(false));
+
+ assertTrue(JPAFacadeHelper.toBrokerFactory(pmf1) == JPAFacadeHelper.toBrokerFactory(pmf2));
+ assertTrue(JPAFacadeHelper.toBrokerFactory(pmf1) == JPAFacadeHelper.toBrokerFactory(pmf3));
+ assertTrue(JPAFacadeHelper.toBrokerFactory(pmf1) != JPAFacadeHelper.toBrokerFactory(pmf4));
+ assertTrue(JPAFacadeHelper.toBrokerFactory(pmf4) == JPAFacadeHelper.toBrokerFactory(pmf5));
+ }*/
+
+ /**
+ * Tests that lifecycle listeners are transferred from factory to
+ * persistence managers.
+ */
+ public void testFactoryLifecycleListeners() {
+ OpenJPAEntityManagerFactory pmf =
+ (OpenJPAEntityManagerFactory) getEmf();
+ OpenJPAEntityManagerFactorySPI pmfSPI =
+ ((OpenJPAEntityManagerFactorySPI) OpenJPAPersistence.cast(pmf));
+
+ //FIXME jthomas
+ LoadListener listener = new LoadListener() {
+ public void afterLoad(LifecycleEvent ev) {
+ }
+
+ public void afterRefresh(LifecycleEvent ev) {
+ }
+ };
+
+ pmfSPI
+ .addLifecycleListener(listener, new Class[]{ RuntimeTest4.class });
+
+ try {
+ BrokerImpl broker = (BrokerImpl) JPAFacadeHelper.toBroker
+ (pmf.createEntityManager());
+ MetaDataRepository repos = broker.getConfiguration().
+ getMetaDataRepositoryInstance();
+ assertTrue("no listeners defined added to Runtimetest4",
+ broker.getLifecycleEventManager().hasLoadListeners(
+ new RuntimeTest4("foo"),
+ repos.getMetaData(RuntimeTest4.class, null, true)));
+ assertFalse("there should be listeners def for runtimetest1",
+ broker.getLifecycleEventManager().hasLoadListeners
+ (new RuntimeTest1(), repos.getMetaData
+ (RuntimeTest1.class, null, true)));
+ broker.close();
+ } finally {
+ pmfSPI.removeLifecycleListener(listener);
+ }
+ }
+
+ /**
+ * Tests that pooling is maintained on deserialization.
+ * This test case is for kodo persistencemanagerfactories. It doesnt apply to
+ * openjpaentitymanagerfactories therefore it will be commented out.
+ */
+ /*
+ public void testFactorySerialization()
+ throws Exception {
+ OpenJPAEntityManagerFactory pmf1 = getOpenJPAEntityManagerFactory(_conf.toProperties(false));
+ Object pmf2 = roundtrip(pmf1, true);
+ assertEquals(pmf1, pmf2);
+ assertTrue(JPAFacadeHelper.toBrokerFactory(pmf1) ==
+ JPAFacadeHelper.toBrokerFactory((OpenJPAEntityManagerFactory) pmf2));
+ }
+ */
+
+ /**
+ * Tests that the <code>Platform</code> property is set by the
+ * concrete PMF implementation.
+ */
+ public void testPlatform() {
+ OpenJPAEntityManagerFactory pmf =
+ (OpenJPAEntityManagerFactory) getEmf();
+ assertNotNull(pmf.getProperties().getProperty("Platform"));
+ }
+
+ protected OpenJPAEntityManagerFactory getEmf(Map props) {
+ props.put("openjpa.BrokerFactory", BrokerFactoryTest.class.getName());
+ return (OpenJPAEntityManagerFactory) getEmf(props);
+ }
+
+ public static class BrokerFactoryTest extends AbstractBrokerFactory {
+
+ // standard brokerfactory getter implemented by subclasses
+ public static synchronized BrokerFactoryTest getInstance(
+ ConfigurationProvider cp) {
+ Object key = toPoolKey(cp.getProperties());
+ BrokerFactoryTest factory =
+ (BrokerFactoryTest) getPooledFactoryForKey(key);
+ if (factory != null)
+ return factory;
+
+ factory = newInstance(cp);
+ pool(key, factory);
+ return factory;
+ }
+
+ // standard brokerfactory getter implemented by subclasses
+ public static BrokerFactoryTest newInstance(ConfigurationProvider cp) {
+ OpenJPAConfigurationImpl conf = new OpenJPAConfigurationImpl();
+ cp.setInto(conf);
+ return new BrokerFactoryTest(conf);
+ }
+
+ protected BrokerFactoryTest(OpenJPAConfiguration conf) {
+ super(conf);
+ }
+
+ protected StoreManager newStoreManager() {
+ return null;
+ }
+ }
+}
Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistentMaps.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistentMaps.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistentMaps.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPersistentMaps.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,352 @@
+/*
+ * TestPersistentMaps.java
+ *
+ * Created on October 13, 2006, 1:54 PM
+ *
+ * To change this template, choose Tools | Template Manager
+ * and open the template in the editor.
+ */
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence.kernel;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.MapElementPC;
+import org.apache.openjpa.persistence.kernel.common.apps.MapElementPCChild;
+import org.apache.openjpa.persistence.kernel.common.apps.PersistentMapHolder;
+
+import org.apache.openjpa.persistence.Extent;
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+import org.apache.openjpa.persistence.OpenJPAQuery;
+
+public class TestPersistentMaps extends BaseKernelTest {
+
+ private static final String JDOQL = "javax.jdo.query.JDOQL";
+
+ /**
+ * Creates a new instance of TestPersistentMaps
+ */
+ public TestPersistentMaps() {
+ }
+
+ public TestPersistentMaps(String name) {
+ super(name);
+ }
+
+ public void setUp() {
+ deleteAll(PersistentMapHolder.class);
+ OpenJPAEntityManager pm = getPM();
+ startTx(pm);
+
+ pm.persist(new PersistentMapHolder());
+
+ endTx(pm);
+ endEm(pm);
+ }
+
+ private PersistentMapHolder getHolder(OpenJPAEntityManager pm) {
+ Extent e = pm.createExtent(PersistentMapHolder.class, true);
+ assertSize(1, ((Collection) e.list()));
+ return (PersistentMapHolder) e.iterator().next();
+ }
+
+ private Object keyInstance(Class type) throws Exception {
+ if (type.getName().equals(String.class.getName()))
+ return randomString();
+ else
+ return type.newInstance();
+ }
+
+ private void testMap(int num, String name, Class keyClass, Class valueClass)
+ throws Exception {
+ OpenJPAEntityManager srcpm = getPM(true, true);
+ startTx(srcpm);
+
+ PersistentMapHolder holder = getHolder(srcpm);
+ Map map = holder.getNamedMap(name);
+ Map internalMap = new HashMap();
+
+ for (int i = 0; i < num; i++) {
+ Object key = keyInstance(keyClass);
+ Object value = keyInstance(valueClass);
+ map.put(key, value);
+ internalMap.put(key, value);
+
+ assertEquals(map.get(key), internalMap.get(key));
+ }
+ endTx(srcpm);
+
+ OpenJPAEntityManager pm = getPM();
+ startTx(pm);
+// holder = getHolder(pm);
+ map = holder.getNamedMap(name);
+ for (Iterator i = internalMap.keySet().iterator(); i.hasNext();) {
+ Object k = i.next();
+ assertEquals(map.get(k), internalMap.get(k));
+ }
+ endTx(pm);
+ endEm(pm);
+
+ String selectWhere =
+ "select from " + PersistentMapHolder.class.getName() + " where ";
+
+ pm = getPM();
+ startTx(pm);
+ for (Iterator i = internalMap.keySet().iterator(); i.hasNext();) {
+
+ Object param = i.next();
+ if (pm.isPersistent(param))
+ param = pm.find(param.getClass(), pm.getObjectId(param));
+
+ Object val = internalMap.get(param);
+ if (pm.isPersistent(val))
+ val = pm.find(val.getClass(), pm.getObjectId(val));
+
+ OpenJPAQuery q;
+
+ q = pm.createQuery(JDOQL,
+ selectWhere + name + ".containsKey(:param)");
+ q.setParameter("param", param);
+ assertSize(1, q.getResultList());
+
+ q = pm.createQuery(JDOQL,
+ selectWhere + name + ".containsValue(:value)");
+ q.setParameter("value", val);
+ assertSize(1, q.getResultList());
+
+ q = pm.createQuery(JDOQL, selectWhere + name + ".containsValue(" +
+ name + ".get(:param))");
+ q.setParameter("param", param);
+ assertSize(1, q.getResultList());
+
+ q = pm.createQuery(JDOQL,
+ selectWhere + name + ".get(:param) != null");
+ q.setParameter("param", param);
+ assertSize(1, q.getResultList());
+
+ q = pm.createQuery(JDOQL,
+ selectWhere + name + ".get(:param) == :value");
+ q.setParameter("param", param);
+ q.setParameter("value", val);
+ assertSize(1, q.getResultList());
+
+ q = pm.createQuery(JDOQL,
+ selectWhere + name + ".get(:param) != :value");
+ q.setParameter("param", param);
+ q.setParameter("value", val);
+ assertSize(0, q.getResultList());
+ }
+ endTx(pm);
+ endEm(pm);
+
+ pm = getPM();
+ startTx(pm);
+ for (Iterator i = internalMap.keySet().iterator(); i.hasNext();) {
+ Object param = i.next();
+ if (pm.isPersistent(param))
+ param = pm.find(param.getClass(), pm.getObjectId(param));
+
+ List getQueries = new ArrayList(Arrays.asList(new String[]{
+ selectWhere + name + ".get(:param) != null",
+ selectWhere + name + ".get(:param) == " + name + ".get(:param)",
+ selectWhere + "!(" + name + ".get(:param) == null)",
+ selectWhere + "!(" + name + ".get(:param) != " + name +
+ ".get(:param))",
+ }));
+
+ for (Iterator qi = getQueries.iterator(); qi.hasNext();) {
+ String query = (String) qi.next();
+ if (valueClass == String.class)
+ query += " order by " + name + ".get(:param) desc";
+ OpenJPAQuery q = pm.createQuery(JDOQL, query);
+ q.setParameter("param", param);
+ assertSize(1, q.getResultList());
+ }
+ }
+ endTx(pm);
+ endEm(pm);
+
+ endEm(srcpm);
+ }
+
+ public void testPCKeyStringValue()
+ throws Exception {
+ testMap(5, "testPCKeyStringValue",
+ MapElementPC.class, String.class);
+ }
+
+ public void testStringKeyPCValue()
+ throws Exception {
+ testMap(6, "testStringKeyPCValue",
+ String.class, MapElementPC.class);
+ }
+
+ public void testPCKeyPCValue()
+ throws Exception {
+ testMap(7, "testPCKeyPCValue",
+ MapElementPC.class, MapElementPC.class);
+ }
+
+ public void testPCSubKeyStringValue()
+ throws Exception {
+ testMap(8, "testPCSubKeyStringValue",
+ MapElementPCChild.class, String.class);
+ }
+
+ public void testStringKeyPCSubValue()
+ throws Exception {
+ testMap(9, "testStringKeyPCSubValue",
+ String.class, MapElementPCChild.class);
+ }
+
+ public void testPCSubKeyPCValue()
+ throws Exception {
+ testMap(10, "testPCSubKeyPCValue",
+ MapElementPCChild.class, MapElementPC.class);
+ }
+
+ public void testPCSubKeyPCSubValue()
+ throws Exception {
+ testMap(11, "testPCSubKeyPCSubValue",
+ MapElementPCChild.class, MapElementPCChild.class);
+ }
+
+ public void testPCKeyPCSubValue()
+ throws Exception {
+ testMap(12, "testPCKeyPCSubValue",
+ MapElementPC.class, MapElementPCChild.class);
+ }
+
+ public void testPCIntfKeyStringValue()
+ throws Exception {
+ testMap(13, "testPCIntfKeyStringValue",
+ MapElementPC.class, String.class);
+ }
+
+ public void testStringKeyPCIntfValue()
+ throws Exception {
+ testMap(14, "testStringKeyPCIntfValue",
+ String.class, MapElementPC.class);
+ }
+
+ public void testPCIntfKeyPCValue()
+ throws Exception {
+ testMap(15, "testPCIntfKeyPCValue",
+ MapElementPC.class, MapElementPC.class);
+ }
+
+ /**
+ * Test querying maps when there are multiple holder instances that
+ * have maps with the same key.
+ */
+ public void testQueryMultipleMaps() throws Exception {
+ deleteAll(PersistentMapHolder.class);
+
+ String mapName = "testStringKeyPCValue";
+
+ String[] mapNames = new String[]{
+ "testPCKeyStringValue",
+ // "testStringKeyPCValue",
+ "testPCKeyPCValue",
+ "testPCSubKeyStringValue",
+ "testStringKeyPCSubValue",
+ "testPCSubKeyPCValue",
+ "testPCSubKeyPCSubValue",
+ "testPCKeyPCSubValue",
+ "testPCIntfKeyStringValue",
+ "testStringKeyPCIntfValue",
+ "testPCIntfKeyPCValue",
+ };
+
+ OpenJPAEntityManager pm;
+
+ pm = getPM();
+ startTx(pm);
+
+ MapElementPC pc = new MapElementPC();
+ pc.setElementData("foo");
+
+ int max = 5;
+
+ for (int i = 0; i < max; i++) {
+ PersistentMapHolder holder = new PersistentMapHolder();
+ for (int j = 0; j < i; j++) {
+ holder.getNamedMap(mapName).put("key" + j, pc);
+ }
+ pm.persist(holder);
+ }
+
+ endTx(pm);
+ endEm(pm);
+
+ pm = getPM();
+ pc = (MapElementPC) pm.find(MapElementPC.class, pm.getObjectId(pc));
+ for (int i = 0; i < max; i++) {
+ OpenJPAQuery q;
+
+ String key = "key" + i;
+ String selectWhere = "select from " +
+ PersistentMapHolder.class.getName() + " where ";
+ q = pm.createQuery(JDOQL,
+ selectWhere + mapName + ".containsKey(:key)");
+ q.setParameter("key", key);
+ assertSize(max - i - 1, q.getResultList());
+
+ q = pm.createQuery(JDOQL,
+ selectWhere + mapName + ".get(:key) == :val");
+ q.setParameter("key", key);
+ q.setParameter("val", pc);
+ assertSize(max - i - 1, q.getResultList());
+
+ q = pm.createQuery(JDOQL,
+ selectWhere + "testPCKeyStringValue.isEmpty() && "
+ + mapName + ".get(:key) == :val");
+ q.setParameter("key", key);
+ q.setParameter("val", pc);
+ assertSize(max - i - 1, q.getResultList());
+
+ // now try to execute queries against multiple other
+ // map instances, so we can make sure the joins are robust
+ for (int j = 0; j < mapNames.length; j++) {
+ StringBuffer query = new StringBuffer(selectWhere);
+
+ for (int k = 0; k < j; k++) {
+ query.append(mapNames[k] + ".isEmpty() && ");
+ }
+
+ q = pm.createQuery(JDOQL,
+ query + mapName + ".get(:key) == :val");
+ q.setParameter("key", key);
+ q.setParameter("val", pc);
+ assertSize(max - i - 1, q.getResultList());
+ }
+ }
+ endEm(pm);
+ }
+}
Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPessimisticLocking.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPessimisticLocking.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPessimisticLocking.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPessimisticLocking.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,274 @@
+/*
+ * TestPessimisticLocking.java
+ *
+ * Created on October 13, 2006, 3:17 PM
+ *
+ * To change this template, choose Tools | Template Manager
+ * and open the template in the editor.
+ */
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence.kernel;
+
+import java.util.HashMap;
+import java.util.Map;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest1;
+import org.apache.openjpa.persistence.common.utils.AbstractTestCase;
+
+import org.apache.openjpa.jdbc.conf.JDBCConfiguration;
+import org.apache.openjpa.lib.util.concurrent.ReentrantLock;
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+import org.apache.openjpa.persistence.OpenJPAEntityManagerFactory;
+import org.apache.openjpa.persistence.jdbc.FetchMode;
+import org.apache.openjpa.persistence.jdbc.JDBCFetchPlan;
+
+public class TestPessimisticLocking extends BaseKernelTest {
+
+ private Object _id = null;
+ private int _bugCount = 0;
+ private OpenJPAEntityManagerFactory _factory = null;
+
+ public TestPessimisticLocking(String name) {
+ super(name);
+ }
+
+ /**
+ * Creates a new instance of TestPessimisticLocking
+ */
+ public TestPessimisticLocking() {
+ }
+
+ protected boolean skipTest() {
+ // pointbase doesn't really lock
+ if (getCurrentPlatform() == AbstractTestCase.Platform.POINTBASE)
+ return true;
+
+ if (getConfiguration() instanceof JDBCConfiguration) {
+ JDBCConfiguration conf = (JDBCConfiguration) getConfiguration();
+ return !conf.getDBDictionaryInstance().supportsSelectForUpdate;
+ }
+ return false;
+ }
+
+ /**
+ * Use a locking persistence manager with subclass fetch mode to set to
+ * "none" to avoid subclass joins.
+ */
+ protected OpenJPAEntityManager getLockingPM() {
+ OpenJPAEntityManager pm = _factory.createEntityManager();
+ ((JDBCFetchPlan) pm.getFetchPlan())
+ .setSubclassFetchMode(FetchMode.NONE);
+ return pm;
+ }
+
+ public void setUp() throws Exception {
+ deleteAll(RuntimeTest1.class);
+
+ Map propsMap = new HashMap();
+ propsMap.put("openjpa.LockManager", "pessimistic");
+ _factory = (OpenJPAEntityManagerFactory) getEmf(propsMap);
+
+ OpenJPAEntityManager pm = getLockingPM();
+ startTx(pm);
+
+ RuntimeTest1 a = new RuntimeTest1("name", 0);
+ pm.persist(a);
+ _id = pm.getObjectId(a);
+
+ endTx(pm);
+ endEm(pm);
+ }
+
+ public void tearDown() {
+ try {
+ if (_factory != null)
+ _factory.close();
+ } catch (Exception e) {
+ }
+ }
+
+ /**
+ * Test that pessimistic locking is working in the data store.
+ */
+ public void testPessimisticLocking() throws Throwable {
+ pessimisticLockingTest(false);
+ }
+
+ /**
+ * Test that the test case itself is working be using a ReentrantLock. This
+ * test will validate that the test case itself is working correctly, not
+ * that the datastore's pessimistic locking is working.
+ */
+ public void testPessimisticLockingInternal() throws Throwable {
+ pessimisticLockingTest(true);
+ }
+
+ /**
+ * Test that pessimistic locking is working by attempting to update the same
+ * object in the data store.
+ *
+ * @param useReentrantLock true if we want to synchronize on a lock instead of relying on
+ * the data store (used for validating the test case).
+ */
+ public void pessimisticLockingTest(boolean useReentrantLock)
+ throws Throwable {
+ long timeout = System.currentTimeMillis() + (60 * 5 * 1000);
+
+ ReentrantLock lock = null;
+ if (useReentrantLock)
+ lock = new ReentrantLock();
+
+ TestThread t1 = new TestThread(lock);
+ TestThread t2 = new TestThread(lock);
+ t1.start();
+ t2.start();
+
+ getLog().trace("started thread");
+
+ // wait for threads to die or timeout
+ while ((t1.isAlive() || t2.isAlive())
+ && System.currentTimeMillis() < timeout) {
+ Thread.sleep(1000);
+ getLog().trace(
+ "thread waiting for completion ("
+ + (timeout - System.currentTimeMillis())
+ + " ms left)");
+ }
+
+ getLog().trace("checking if thread is alive");
+ System.out.flush();
+
+ if (t1.isAlive() || t2.isAlive()) {
+ getLog().trace("thread is still alive");
+ System.out.flush();
+
+ // do out best to clean them up
+ try {
+ t1.interrupt();
+ }
+ catch (Exception e) {
+ }
+ try {
+ t2.interrupt();
+ }
+ catch (Exception e) {
+ }
+
+ throw new Exception("Thread did not complete after timeout ("
+ + timeout + "): possible deadlock");
+ }
+
+ getLog().trace("checking exception for t1");
+ if (t1.exception != null)
+ throw t1.exception;
+
+ getLog().trace("checking exception for t2");
+ if (t2.exception != null)
+ throw t2.exception;
+
+ getLog().trace("verifying pessimistic locking worked...");
+ OpenJPAEntityManager pm = getLockingPM();
+ RuntimeTest1 a = (RuntimeTest1) pm.find(RuntimeTest1.class, _id);
+ assertEquals(20 - _bugCount, a.getIntField1());
+ getLog().trace("closing pm");
+ endEm(pm);
+ getLog().trace("done");
+ }
+
+ /**
+ * Update thread that tries to increment an int field.
+ *
+ * @author <a href="mailto:marc@solarmetric.com">Marc Prud'hommeaux</a>
+ */
+ private class TestThread extends Thread {
+
+ private OpenJPAEntityManager _pm = getLockingPM();
+
+ public Exception exception = null;
+
+ private final ReentrantLock _lock;
+
+ /**
+ * Constructor
+ *
+ * @param lock the ReentrantLock we should use, or null to rely on
+ * pessimistic locking in the data store.
+ */
+ public TestThread(ReentrantLock lock) {
+ this._lock = lock;
+ }
+
+ public synchronized void run() {
+ getLog().trace(
+ Thread.currentThread().getName()
+ + ": starting update thread");
+ try {
+ for (int i = 0; i < 10; i++) {
+ if (_lock != null)
+ _lock.lock();
+
+ try {
+ _pm.setOptimistic(false);
+ startTx(_pm);
+ RuntimeTest1 a = (RuntimeTest1) _pm.find(
+ RuntimeTest1.class, _id);
+ getLog().trace(
+ Thread.currentThread().getName()
+ + ": obtained and locked: " + a);
+ yield();
+ super.wait(50);
+ getLog().trace(
+ Thread.currentThread().getName()
+ + ": updating age from "
+ + a.getIntField1());
+ a.setIntField1(a.getIntField1() + 1);
+ getLog().trace(
+ Thread.currentThread().getName()
+ + ": committed update");
+ try {
+ _pm.flush();
+ endTx(_pm);
+ }
+ catch (Exception ex) {
+ throw new org.apache.openjpa.util.UserException(
+ "Optimistic lock probably failed after "
+ + i + " iterations ("
+ + Thread.currentThread().getName()
+ + ")", ex);
+ }
+ yield();
+ }
+ finally {
+ if (_lock != null)
+ _lock.unlock();
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ exception = e;
+ }
+ }
+ }
+
+}
Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPojoWithoutAnnotationsCannotBePersisted.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPojoWithoutAnnotationsCannotBePersisted.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPojoWithoutAnnotationsCannotBePersisted.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestPojoWithoutAnnotationsCannotBePersisted.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence.kernel;
+
+import javax.persistence.EntityManager;
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.UnAnnotPojo;
+import org.apache.openjpa.persistence.common.utils.AbstractTestCase;
+/*
+ * @author Afam Okeke
+ * Ensures that pojo that is not persistent capable cannot be persisted.
+ */
+
+public class TestPojoWithoutAnnotationsCannotBePersisted
+ extends AbstractTestCase {
+
+ UnAnnotPojo pojo = null;
+
+ public TestPojoWithoutAnnotationsCannotBePersisted(String name) {
+ super(name, "kernelcactusapp");
+ }
+
+ public void setUp() {
+ System.out.println("Running test " + this.getName() + " of " +
+ this.getClass().getSimpleName());
+ pojo = new UnAnnotPojo();
+ pojo.setName("failure");
+ pojo.setNum(0);
+ }
+
+ /*
+ * Try to persist pojo with no metadata
+ */
+ public void testPersistingUnAnnotatedObject() {
+ EntityManager em = currentEntityManager();
+ startTx(em);
+
+ try {
+ em.persist(pojo);
+ fail("...Should not persist object without proper metadata...");
+ }
+ catch (Exception e) {
+ //expected
+ }
+
+ endTx(em);
+ endEm(em);
+ }
+}
Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestProxies2.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestProxies2.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestProxies2.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestProxies2.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,526 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence.kernel;
+
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.ProxiesPC;
+import org.apache.commons.collections.comparators.ComparableComparator;
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+import org.apache.openjpa.util.Proxy;
+
+public class TestProxies2 extends BaseKernelTest {
+
+ private int _oid = 0;
+ private Date _date = null;
+ private java.sql.Date _sqlDate = null;
+ private java.sql.Timestamp _timestamp = null;
+
+ public TestProxies2(String casename) {
+ super(casename);
+ }
+
+ public void setUp() {
+ deleteAll(ProxiesPC.class);
+
+ OpenJPAEntityManager pm = getPM(false, false);
+ startTx(pm);
+
+ long now = System.currentTimeMillis();
+ _date = new Date(now);
+ _sqlDate = new java.sql.Date(now);
+ _timestamp = new java.sql.Timestamp(now);
+
+ ProxiesPC pc = new ProxiesPC("main");
+ pc.setDate(_date);
+ pc.setSQLDate(_sqlDate);
+ pc.setTimestamp(_timestamp);
+
+ pc.getStringSet().add("val1");
+ pc.getStringSet().add("val2");
+ pc.getStringSet().add("val3");
+ pc.getStringSet().add(null);
+
+ pc.getProxySet().add(new ProxiesPC("set1"));
+ pc.getProxySet().add(new ProxiesPC("set2"));
+ pc.getProxySet().add(new ProxiesPC("set3"));
+
+ pc.getStringMap().put("key1", "1");
+ pc.getStringMap().put("key2", "2");
+ pc.getStringMap().put("key3", "3");
+ pc.getStringMap().put(null, "null");
+ pc.getStringMap().put("null", null);
+
+ pc.getProxyMap().put("key1", new ProxiesPC("map1"));
+ pc.getProxyMap().put("key2", new ProxiesPC("map2"));
+ pc.getProxyMap().put("key3", new ProxiesPC("map3"));
+
+ pc.getList().add("val1");
+ pc.getList().add("val1");
+ pc.getList().add("val2");
+ pc.getList().add("val3");
+ pc.getList().add("val3");
+
+ pm.persist(pc);
+
+ _oid = pc.getId();
+
+ endTx(pm);
+ endEm(pm);
+ }
+
+ public void testStringSet() {
+ OpenJPAEntityManager pm = getPM(false, false);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+
+ // check that orig values are correct
+ Set set = pc.getStringSet();
+ assertEquals(4, set.size());
+ assertTrue(set.contains("val1"));
+ assertTrue(set.contains("val2"));
+ assertTrue(set.contains("val3"));
+ assertTrue(set.contains(null));
+
+ // do some mods to try to confuse the proxy
+ set.remove("val1");
+ set.remove("val1");
+ set.add("val4");
+ set.remove("val4");
+ set.add("val5");
+ set.add("val5");
+ endTx(pm);
+ endEm(pm);
+
+ // re-retrieve and check set
+ pm = getPM(false, false);
+ pc = pm.find(ProxiesPC.class, _oid);
+
+ set = pc.getStringSet();
+ assertEquals(4, set.size());
+ assertTrue(!set.contains("val1"));
+ assertTrue(set.contains("val2"));
+ assertTrue(set.contains("val3"));
+ assertTrue(!set.contains("val4"));
+ assertTrue(set.contains("val5"));
+ assertTrue(set.contains(null));
+ endEm(pm);
+ }
+
+ public void testStringMap() {
+ OpenJPAEntityManager pm = getPM(false, false);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+
+ // check that orig values are correct
+ Map map = pc.getStringMap();
+ assertEquals(5, map.size());
+ assertEquals("1", map.get("key1"));
+ assertEquals("2", map.get("key2"));
+ assertEquals("3", map.get("key3"));
+ assertNull(map.get("null"));
+ assertEquals("null", map.get(null));
+
+ // do some mods to try to confuse the proxy
+ map.put("key1", "1a");
+ map.put("key1", "1b");
+ map.put("key4", "4");
+ map.remove("key4");
+ map.remove("foo");
+ map.put("key5", "5");
+ endTx(pm);
+ endEm(pm);
+
+ // re-retrieve and check map
+ pm = getPM(false, false);
+ pc = pm.find(ProxiesPC.class, _oid);
+
+ map = pc.getStringMap();
+ assertEquals(6, map.size());
+ assertEquals("1b", map.get("key1"));
+ assertEquals("5", map.get("key5"));
+ endEm(pm);
+ }
+
+ public void testProxySet() {
+ OpenJPAEntityManager pm = getPM(false, false);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+
+ // check that orig values are correct
+ Set set = pc.getProxySet();
+ assertEquals(3, set.size());
+ Iterator itr = set.iterator();
+ ProxiesPC set1 = (ProxiesPC) itr.next();
+ ProxiesPC set2 = (ProxiesPC) itr.next();
+ ProxiesPC set3 = (ProxiesPC) itr.next();
+ assertEquals("set1", set1.getName());
+ assertEquals("set2", set2.getName());
+ assertEquals("set3", set3.getName());
+
+ // do some mods to try to confuse the proxy
+ set.remove(set1);
+ set.remove(set1);
+ ProxiesPC set4 = new ProxiesPC("set4");
+ set.add(set4);
+ set.remove(set4);
+ ProxiesPC set5 = new ProxiesPC("set5");
+ set.add(set5);
+ set.add(set5);
+ endTx(pm);
+ endEm(pm);
+
+ // re-retrieve and check set
+ pm = getPM(true, false);
+ startTx(pm);
+ pc = pm.find(ProxiesPC.class, _oid);
+ pm.refresh(pc);
+
+ set = pc.getProxySet();
+ assertEquals(3, set.size());
+ itr = set.iterator();
+ set1 = (ProxiesPC) itr.next();
+ set2 = (ProxiesPC) itr.next();
+ set3 = (ProxiesPC) itr.next();
+ assertEquals("set2", set1.getName());
+ assertEquals("set3", set2.getName());
+ assertEquals("set5", set3.getName());
+ endTx(pm);
+ endEm(pm);
+ }
+
+ public void testProxyMap() {
+ OpenJPAEntityManager pm = getPM(false, false);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+
+ // check that orig values are correct
+ Map map = pc.getProxyMap();
+ assertEquals("original map size is correct: 3", 3, map.size());
+ ProxiesPC map1 = (ProxiesPC) map.get("key1");
+ ProxiesPC map2 = (ProxiesPC) map.get("key2");
+ ProxiesPC map3 = (ProxiesPC) map.get("key3");
+ assertEquals("map1", map1.getName());
+ assertEquals("map2", map2.getName());
+ assertEquals("map3", map3.getName());
+
+ // do some mods to try to confuse the proxy
+ ProxiesPC map1a = new ProxiesPC("map1a");
+ map.put("key1", map1a);
+ ProxiesPC map1b = new ProxiesPC("map1b");
+ map.put("key1", map1b);
+ map.put("key4", new ProxiesPC("map4"));
+ map.remove("key4");
+ map.remove("foo");
+ map.put("key5", new ProxiesPC("map5"));
+ endTx(pm);
+ endEm(pm);
+
+ // re-retrieve and check map
+ pm = getPM(false, false);
+ pc = pm.find(ProxiesPC.class, _oid);
+ startTx(pm);
+ pm.refresh(pc);
+
+ map = pc.getProxyMap();
+
+ assertEquals(4, map.size());
+ assertEquals("map1b", ((ProxiesPC) map.get("key1")).getName());
+ assertEquals("map5", ((ProxiesPC) map.get("key5")).getName());
+
+ endTx(pm);
+ endEm(pm);
+ }
+
+ public void testReplace() {
+ OpenJPAEntityManager pm = getPM(false, false);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+
+ // totally replace set
+ Set set = new HashSet();
+ set.add("new");
+ pc.setStringSet(set);
+
+ endTx(pm);
+ endEm(pm);
+
+ // re-retrieve and check set
+ pm = getPM(false, false);
+ pc = pm.find(ProxiesPC.class, _oid);
+
+ set = pc.getStringSet();
+ assertEquals(1, set.size());
+ assertTrue(set.contains("new"));
+ endEm(pm);
+ }
+
+ public void testComparators() {
+ // make sure the system uses the initial field value to find
+ // comparators
+ OpenJPAEntityManager pm = getPM(false, false);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+ assertNotNull("pc is null", pc);
+ assertTrue("pc.getComp() is not instanceof Proxy",
+ pc.getComp() instanceof Proxy);
+ assertTrue(
+ "(TreeSet) is not pc.getComp()).comparator() instanceof ComparableComparator",
+ ((TreeSet) pc.getComp())
+ .comparator() instanceof ComparableComparator);
+ pm.evict(pc);
+ endTx(pm);
+
+ // see if it still saves comparator after transition to hollow
+ // and back
+ assertTrue("pc.getComp() is not instanceof ProxyTreeSet",
+ pc.getComp() instanceof Proxy);
+ Comparator compart = ((TreeSet) pc.getComp()).comparator();
+ assertNotNull("compart is null", compart);
+ assertTrue(
+ "((TreeSet) is not pc.getComp()).comparator()instanceof ComparableComparator",
+ ((TreeSet) pc.getComp())
+ .comparator() instanceof ComparableComparator);
+
+ endEm(pm);
+ }
+
+ // FIX ME: Moving fix to essex
+ /*public void testList() {
+ OpenJPAEntityManager pm = getPM(false, false);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+
+ // check that orig values are correct
+ List list = pc.getList();
+ assertEquals(5, list.size());
+ assertEquals("val1", list.get(0));
+ assertEquals("val1", list.get(1));
+ assertEquals("val2", list.get(2));
+ assertEquals("val3", list.get(3));
+ assertEquals("val3", list.get(4));
+
+ // do some mods to try to confuse the proxy
+ list.remove("val2");
+ list.add("val4");
+ list.remove("val4");
+ list.add("val5");
+ list.add("val6");
+ list.add("val6");
+ endTx(pm);
+ endEm(pm);
+
+ // re-retrieve and modify again to check holes in ordering
+ pm = getPM(false, false);
+ startTx(pm);
+ pc = (ProxiesPC) pm.find(ProxiesPC.class, _oid);
+
+ list = pc.getList();
+ assertEquals(7, list.size());
+ assertEquals("val1", list.get(0));
+ assertEquals("val1", list.get(1));
+ assertEquals("val3", list.get(2));
+ assertEquals("val3", list.get(3));
+ assertEquals("val5", list.get(4));
+ assertEquals("val6", list.get(5));
+ assertEquals("val6", list.get(6));
+
+ list.remove("val5");
+ list.add("val7");
+ endTx(pm);
+ endEm(pm);
+
+ // re-retrieve and check final contents
+ pm = getPM(false, false);
+ pc = pm.find(ProxiesPC.class, _oid);
+
+ list = pc.getList();
+ assertEquals(7, list.size());
+ assertEquals("val1", list.get(0));
+ assertEquals("val1", list.get(1));
+ assertEquals("val3", list.get(2));
+ assertEquals("val3", list.get(3));
+ assertEquals("val6", list.get(4));
+ assertEquals("val6", list.get(5));
+ assertEquals("val7", list.get(6));
+ endEm(pm);
+ }
+
+ public void testListDisablesChangeTracking() {
+ OpenJPAEntityManager pm = getPM(false, false);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+
+ // check that orig values are correct
+ List list = pc.getList();
+ assertEquals(5, list.size());
+ assertEquals("val1", list.get(0));
+ assertEquals("val1", list.get(1));
+ assertEquals("val2", list.get(2));
+ assertEquals("val3", list.get(3));
+ assertEquals("val3", list.get(4));
+
+ // removing a copy of val3 should disable tracking
+ list.remove("val2");
+ list.remove("val3");
+ list.add("val5");
+ list.add("val5");
+ endTx(pm);
+ endEm(pm);
+
+ // re-retrieve and change again to check ordering
+ pm = getPM(false, false);
+ startTx(pm);
+ pc = pm.find(ProxiesPC.class, _oid);
+
+ list = pc.getList();
+ assertEquals(5, list.size());
+ assertEquals("val1", list.get(0));
+ assertEquals("val1", list.get(1));
+ assertEquals("val3", list.get(2));
+ assertEquals("val5", list.get(3));
+ assertEquals("val5", list.get(4));
+
+ list.remove("val3");
+ list.add("val6");
+ endTx(pm);
+ endEm(pm);
+
+ // check final contents
+ pm = getPM(false, false);
+ pc = pm.find(ProxiesPC.class, _oid);
+
+ list = pc.getList();
+ assertEquals(5, list.size());
+ assertEquals("val1", list.get(0));
+ assertEquals("val1", list.get(1));
+ assertEquals("val6", list.get(2));
+ assertEquals("val5", list.get(3));
+ assertEquals("val5", list.get(4));
+ endEm(pm);
+ }
+*/
+ public void testChangeListOrder() {
+ OpenJPAEntityManager pm = getPM(false, false);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+
+ // check that orig values are correct
+ List list = pc.getList();
+ assertEquals(5, list.size());
+ assertEquals("val1", list.get(0));
+ assertEquals("val1", list.get(1));
+ assertEquals("val2", list.get(2));
+ assertEquals("val3", list.get(3));
+ assertEquals("val3", list.get(4));
+
+ // reorder val2
+ list.remove("val2");
+ list.add("val2");
+ endTx(pm);
+ endEm(pm);
+
+ // re-retrieve to check ordering
+ pm = getPM(false, false);
+ pc = pm.find(ProxiesPC.class, _oid);
+
+ list = pc.getList();
+ assertEquals(5, list.size());
+ assertEquals("val1", list.get(0));
+ assertEquals("val1", list.get(1));
+ assertEquals("val3", list.get(2));
+ assertEquals("val3", list.get(3));
+ assertEquals("val2", list.get(4));
+ endEm(pm);
+ }
+
+ public void testDate() {
+ OpenJPAEntityManager pm = getPM(true, true);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+ Date date = pc.getDate();
+ assertNotNull(date);
+
+ // dates can lose precision, but make sure same day
+ assertEquals(_date.getYear(), date.getYear());
+ assertEquals(_date.getMonth(), date.getMonth());
+ assertEquals(_date.getDate(), date.getDate());
+
+ // make sure proxied
+ assertTrue(!pm.isDirty(pc));
+ date.setTime(System.currentTimeMillis() + 1000 * 60 * 60 * 24);
+ assertTrue(pm.isDirty(pc));
+
+ endTx(pm);
+ assertEquals(date, pc.getDate());
+ endEm(pm);
+ }
+
+ public void testSQLDate() {
+ OpenJPAEntityManager pm = getPM(true, true);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+ java.sql.Date date = pc.getSQLDate();
+ assertNotNull(date);
+
+ // dates can lose precision, but make sure same day
+ assertEquals(_sqlDate.getYear(), date.getYear());
+ assertEquals(_sqlDate.getMonth(), date.getMonth());
+ assertEquals(_sqlDate.getDate(), date.getDate());
+
+ // make sure proxied
+ assertTrue(!pm.isDirty(pc));
+ date.setTime(System.currentTimeMillis() + 1000 * 60 * 60 * 24);
+ assertTrue(pm.isDirty(pc));
+
+ endTx(pm);
+ assertEquals(date, pc.getSQLDate());
+ endEm(pm);
+ }
+
+ public void testTimestamp() {
+ OpenJPAEntityManager pm = getPM(true, true);
+ startTx(pm);
+ ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
+ java.sql.Timestamp tstamp = pc.getTimestamp();
+ assertNotNull(tstamp);
+
+ // dates can lose precision, but make sure same day
+ assertEquals(_timestamp.getYear(), tstamp.getYear());
+ assertEquals(_timestamp.getMonth(), tstamp.getMonth());
+ assertEquals(_timestamp.getDate(), tstamp.getDate());
+
+ // make sure proxied
+ assertTrue(!pm.isDirty(pc));
+ tstamp.setNanos(100);
+ assertTrue(pm.isDirty(pc));
+
+ endTx(pm);
+ assertEquals(tstamp, pc.getTimestamp());
+ endEm(pm);
+ }
+}
Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestQueries.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestQueries.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestQueries.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestQueries.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,224 @@
+/*
+ * TestQueries.java
+ *
+ * Created on October 13, 2006, 4:27 PM
+ *
+ * To change this template, choose Tools | Template Manager
+ * and open the template in the editor.
+ */
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence.kernel;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest1;
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest2;
+
+import org.apache.openjpa.persistence.Extent;
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+import org.apache.openjpa.persistence.OpenJPAQuery;
+
+public class TestQueries extends BaseKernelTest {
+
+ private static final int CHILD_COUNT = 3;
+ private int id = 10000;
+
+ public TestQueries(String name) {
+ super(name);
+ }
+
+ public TestQueries() {
+ }
+
+ public void setUp()
+ throws Exception {
+ super.setUp();
+ deleteAll(RuntimeTest1.class);
+ }
+
+ public void testSimpleQuery() {
+ OpenJPAEntityManager pm = getPM();
+
+ persist(newRuntimeTest1("SimpleQueryA", 50), pm);
+ persist(newRuntimeTest2("SimpleQueryB", 50), pm);
+
+ Collection results = runQuery(RuntimeTest1.class, false,
+ "stringField = \'SimpleQueryA\'", pm);
+ assertEquals(1, results.size());
+
+ results = runQuery(RuntimeTest1.class, true, "intField1 = 50", pm);
+ assertEquals(2, results.size());
+
+ results = runQuery(RuntimeTest2.class, true, "intField1 = 50", pm);
+ assertEquals(1, results.size());
+
+ results = runQuery(RuntimeTest2.class, false, "intField1 = 50", pm);
+ assertEquals(1, results.size());
+
+ endEm(pm);
+ }
+
+ public void testAndQuery() {
+ String query = "intField1 > 10 AND o.intField1 < 50";
+
+ for (int currentCount = 1; currentCount < 15; currentCount++) {
+ OpenJPAEntityManager pm = getPM();
+
+ // make sure that none exist
+ deleteByQuery(RuntimeTest1.class, false, query, pm);
+
+ startTx(pm);
+ for (int i = 1; i <= currentCount; i++)
+ pm.persist(newRuntimeTest1("AndQueryTest", 30 + i));
+ endTx(pm);
+
+ // verify that the query works.
+ Collection results = runQuery(RuntimeTest1.class, false,
+ query, pm);
+ assertEquals(currentCount, results.size());
+ endEm(pm);
+ }
+ }
+
+ public void testRelationQuery() {
+ relationQuery(10, "JOE", 20);
+ relationQuery(99, "BOB", 2);
+ relationQuery(3, "MARTHA", 1);
+ relationQuery(5, "brenda", 43);
+ relationQuery(43, "SarA", 55);
+ }
+
+ public void relationQuery(int intField, String stringField, int count) {
+ OpenJPAEntityManager pm = getPM();
+
+ String query = "selfOneOne.intField1 = " + intField
+ + " AND o.selfOneOne.stringField = '" + stringField + "'";
+ deleteByQuery(RuntimeTest1.class, true, query, pm);
+
+ // we go up the to max count, adding to the people, and validate
+ // with a query each time.
+ for (int currentcount = 0; currentcount <= count; currentcount++) {
+ if (currentcount != 0)
+ persist(newRuntimeTest2(stringField, intField), pm);
+
+ Collection results = runQuery(RuntimeTest1.class, true, query, pm);
+ assertEquals("query (" + query + ") failed to yield "
+ + currentcount + " instances",
+ currentcount * CHILD_COUNT, results.size());
+ }
+
+ endEm(pm);
+ }
+
+ public void testQueryExecuteThrowsExceptionWhenNoNTR() {
+ OpenJPAEntityManager pm = getPM();
+ startTx(pm);
+ pm.persist(newRuntimeTest1("Query", 10));
+ endTx(pm);
+
+ pm.setNontransactionalRead(false);
+// OpenJPAQuery q = pm.createNativeQuery("",RuntimeTest1.class);
+ OpenJPAQuery q = pm.createQuery("SELECT o FROM RuntimeTest1 o");
+ try {
+ Collection c = (Collection) q.getResultList();
+ fail("Query.execute() should have thrown a JDOException when "
+ + "PM is outside a Transaction and NTR==false");
+ } catch (Exception jdoe) {
+ // good
+ startTx(pm);
+ q.getResultList();
+ rollbackTx(pm);
+ }
+ }
+
+ /**
+ * Delete the results of a query, so we can reinsert and test.
+ */
+ private void deleteByQuery(Class type, boolean subs, String filter,
+ OpenJPAEntityManager pm) {
+ startTx(pm);
+ Extent extent = pm.createExtent(type, subs);
+ //FIXME jthomas
+// OpenJPAQuery query = pm.newQuery(extent, filter);
+// Collection items = (Collection) query.execute();
+ String cstrng = type.getSimpleName();
+
+ OpenJPAQuery query =
+ pm.createQuery("SELECT o FROM " + cstrng + " o WHERE o." + filter);
+ query.setSubclasses(subs);
+ Collection items = (Collection) query.getResultList();
+ for (Iterator i = items.iterator(); i.hasNext();)
+ pm.remove(i.next());
+
+ //FIXME jthomas
+ //query = pm.newQuery(extent, filter);
+
+ query =
+ pm.createQuery("SELECT o FROM " + cstrng + " o WHERE o." + filter);
+ query.setSubclasses(subs);
+ items = query.getResultList();
+ endTx(pm);
+ assertEquals("after deleting from query (" + query
+ + "), there should have been zero items",
+ 0, items.size());
+ }
+
+ private Collection runQuery(Class type, boolean subs, String filter,
+ OpenJPAEntityManager pm) {
+ Extent extent = pm.createExtent(type, subs);
+ //FIXME jthomas
+ //Query query = pm.newQuery(extent, filter);
+ String cstrng = type.getName();
+ OpenJPAQuery query =
+ pm.createQuery("SELECT o FROM " + cstrng + " o WHERE o." + filter);
+ query.setSubclasses(subs);
+ Collection results = (Collection) query.getResultList();
+ return results;
+ }
+
+ private void persist(RuntimeTest1 parent, OpenJPAEntityManager pm) {
+ RuntimeTest1 child;
+ for (int i = 0; i < CHILD_COUNT; i++) {
+ child = newRuntimeTest1("CHILD" + i, i * 10);
+ child.setSelfOneOne(parent);
+ parent.getSelfOneMany().add(child);
+ }
+
+ startTx(pm);
+ pm.persist(parent);
+ endTx(pm);
+ }
+
+ private RuntimeTest1 newRuntimeTest1(String stringField, int intField) {
+ RuntimeTest1 pc = new RuntimeTest1(stringField, intField);
+ pc.setIntField(id++);
+ return pc;
+ }
+
+ private RuntimeTest2 newRuntimeTest2(String stringField, int intField) {
+ RuntimeTest2 pc = new RuntimeTest2(stringField, intField);
+ pc.setIntField(id++);
+ return pc;
+ }
+}
Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestRestoreValues.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestRestoreValues.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestRestoreValues.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestRestoreValues.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,142 @@
+/*
+ * TestRestoreValues.java
+ *
+ * Created on October 13, 2006, 4:48 PM
+ *
+ * To change this template, choose Tools | Template Manager
+ * and open the template in the editor.
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.persistence.kernel;
+
+import java.math.BigInteger;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.FetchGroupTestObject;
+
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+import org.apache.openjpa.persistence.RestoreStateType;
+
+public class TestRestoreValues extends BaseKernelTest {
+
+ private Object _oid = null;
+
+ /**
+ * Creates a new instance of TestRestoreValues
+ */
+ public TestRestoreValues(String name) {
+ super(name);
+ }
+
+ public void setUp() {
+ deleteAll(FetchGroupTestObject.class);
+
+ FetchGroupTestObject pc = new FetchGroupTestObject();
+ pc.setA(1);
+ pc.setB("2");
+ pc.setC(new BigInteger("100"));
+
+ OpenJPAEntityManager pm = getPM();
+ //pm.getTransaction().begin();
+ startTx(pm);
+ pm.persist(pc);
+ //pm.getTransaction().commit();
+ endTx(pm);
+ _oid = pm.getObjectId(pc);
+ endEm(pm);
+ }
+
+ public OpenJPAEntityManager getPM() {
+ OpenJPAEntityManager pm = super.getPM();
+ pm.setOptimistic(true);
+ //pm.setRestoreValues(true);
+ //pm.setRetainValues(true);
+ pm.setRestoreState(RestoreStateType.ALL);
+ pm.setRetainState(true);
+
+ return pm;
+ }
+
+ public void testUnloadedFieldDirtiedBeforeLoadedField() {
+ OpenJPAEntityManager pm = getPM();
+ FetchGroupTestObject pc = (FetchGroupTestObject) pm.find
+ (FetchGroupTestObject.class, _oid);
+
+ assertNotNull("fetch object is null", pc);
+
+ startTx(pm);
+ pc.setB("3");
+ pc.setA(2);
+ rollbackTx(pm);
+
+ assertEquals(1, pc.getA());
+ assertEquals("2", pc.getB());
+ assertEquals(new BigInteger("100"), pc.getC());
+ endEm(pm);
+ }
+
+ public void testUnloadedFieldDirtiedAfterLoadedField() {
+ OpenJPAEntityManager pm = getPM();
+ FetchGroupTestObject pc = (FetchGroupTestObject) pm.find
+ (FetchGroupTestObject.class, _oid);
+
+ startTx(pm);
+ pc.setA(2);
+ pc.setB("3");
+ rollbackTx(pm);
+
+ assertEquals(1, pc.getA());
+ assertEquals("2", pc.getB());
+ assertEquals(new BigInteger("100"), pc.getC());
+ endEm(pm);
+ }
+
+ public void testLoadedFieldDirtiedAfterLoadedField() {
+ OpenJPAEntityManager pm = getPM();
+ FetchGroupTestObject pc = (FetchGroupTestObject) pm.find
+ (FetchGroupTestObject.class, _oid);
+
+ startTx(pm);
+ pc.setA(2);
+ pc.getB();
+ pc.setB("3");
+ rollbackTx(pm);
+
+ assertEquals(1, pc.getA());
+ assertEquals("2", pc.getB());
+ assertEquals(new BigInteger("100"), pc.getC());
+ endEm(pm);
+ }
+
+ public void testNewInstanceUnmodifiedInTransaction() {
+ FetchGroupTestObject pc = new FetchGroupTestObject();
+ pc.setA(2);
+ pc.setB("3");
+
+ OpenJPAEntityManager pm = getPM();
+ startTx(pm);
+ pm.persist(pc);
+ rollbackTx(pm);
+ assertEquals(2, pc.getA());
+ assertEquals("3", pc.getB());
+ endEm(pm);
+ }
+}