openjpa-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From p..@apache.org
Subject svn commit: r627979 [30/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...
Date Fri, 15 Feb 2008 09:20:40 GMT
Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestRetainValuesInOptimistic.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestRetainValuesInOptimistic.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestRetainValuesInOptimistic.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestRetainValuesInOptimistic.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,183 @@
+/*
+ * TestRetainValuesInOptimistic.java
+ *
+ * Created on October 16, 2006, 10:18 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.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest1;
+
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+import org.apache.openjpa.persistence.OpenJPAEntityManagerFactory;
+
+public class TestRetainValuesInOptimistic extends BaseKernelTest {
+
+    private Object _oid = null;
+
+    /**
+     * Creates a new instance of TestRetainValuesInOptimistic
+     */
+    public TestRetainValuesInOptimistic() {
+    }
+
+    public TestRetainValuesInOptimistic(String test) {
+        super(test);
+    }
+
+    public void setUp()
+        throws Exception {
+        super.setUp();
+
+        deleteAll(RuntimeTest1.class);
+
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        RuntimeTest1 pc = new RuntimeTest1("str1", 1);
+        pm.persist(pc);
+        endTx(pm);
+        _oid = pm.getObjectId(pc);
+        endEm(pm);
+    }
+
+    public void testRetain() {
+        clearTest(true);
+        optLockTest(true);
+    }
+
+    public void testNotRetain() {
+        clearTest(false);
+        optLockTest(false);
+    }
+
+    private void clearTest(boolean retain) {
+        OpenJPAEntityManager pm = getPM(retain);
+        OpenJPAEntityManagerFactory pmf = pm.getEntityManagerFactory();
+        RuntimeTest1 pc = (RuntimeTest1) pm.find(RuntimeTest1.class, _oid);
+
+        OpenJPAEntityManager pm2 = getPM();
+        RuntimeTest1 pc2 = (RuntimeTest1) pm2.find(RuntimeTest1.class, _oid);
+        startTx(pm2);
+        pc2.setStringField("str2");
+        pc2.setIntField1(2);
+        endTx(pm2);
+        endEm(pm2);
+
+        startTx(pm);
+        // tickle the object so that it enters the transaction
+        pc.setLocaleField(Locale.CHINA);
+        assertEquals((retain) ? "str1" : "str2", pc.getStringField());
+        assertEquals((retain) ? 1 : 2, pc.getIntField1());
+        try {
+            endTx(pm);
+            if (retain)
+                fail("Should have caused OL violation");
+        }
+        catch (RuntimeException re) {
+            if (!retain)
+                throw re;
+        }
+        catch (Exception e) {
+            //
+        }
+
+        endEm(pm);
+
+        // make sure everything stuck
+        if (!retain) {
+            pm = getPM();
+            pc = (RuntimeTest1) pm.find(RuntimeTest1.class, _oid);
+            assertEquals("str2", pc.getStringField());
+            assertEquals(2, pc.getIntField1());
+            endEm(pm);
+            try {
+                pmf.close();
+            } catch (Exception e) {
+                // consumme exceptions ... other PMs might be open and
+                // active on this PMF.
+            }
+        }
+    }
+
+    private void optLockTest(boolean retain) {
+        OpenJPAEntityManager pm1 = getPM(retain);
+        OpenJPAEntityManagerFactory pmf = pm1.getEntityManagerFactory();
+
+        startTx(pm1);
+        RuntimeTest1 pc1 = (RuntimeTest1) pm1.find(RuntimeTest1.class, _oid);
+        endTx(pm1);
+
+        OpenJPAEntityManager pm2 = getPM(retain);
+        startTx(pm2);
+        RuntimeTest1 pc2 = (RuntimeTest1) pm2.find(RuntimeTest1.class, _oid);
+        pc2.setStringField("str3");
+        pc2.setIntField1(3);
+        endTx(pm2);
+
+        startTx(pm1);
+        pc1.setStringField("str4");
+        pc1.setIntField1(4);
+        try {
+            endTx(pm1);
+            if (retain)
+                fail("Expected opt lock error.");
+        } catch (Exception jove) {
+            if (!retain)
+                fail("Caught opt lock error.");
+        }
+
+        pm1.close();
+        endEm(pm2);
+        if (retain) {
+            try {
+                pmf.close();
+            } catch (Exception e) {
+                // maybe other PMs are open...
+            }
+        }
+    }
+
+    private OpenJPAEntityManager getPM(boolean retain) {
+        OpenJPAEntityManager pm;
+        Map props = new HashMap();
+        props.put("openjpa.AutoClear", "all");
+
+        if (retain)
+            pm = getPM(true, true);
+        else {
+            OpenJPAEntityManagerFactory pmf = getEmf(props);
+
+            pm = (OpenJPAEntityManager) pmf.createEntityManager();
+            pm.setOptimistic(true);
+            pm.setRetainState(true);
+        }
+        return pm;
+    }
+}

Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointEmbedded.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointEmbedded.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointEmbedded.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointEmbedded.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,300 @@
+/*
+ * TestSavepointEmbedded.java
+ *
+ * Created on October 16, 2006, 10:29 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.Properties;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.EmbeddedOwnerPC;
+import org.apache.openjpa.persistence.kernel.common.apps.EmbeddedPC;
+
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+
+public class TestSavepointEmbedded extends BaseKernelTest {
+
+    private int id = 10000;
+
+    /**
+     * Creates a new instance of TestSavepointEmbedded
+     */
+    public TestSavepointEmbedded(String name) {
+        super(name);
+    }
+
+    protected String getSavepointPlugin() {
+        return "in-mem(PreFlush=false)";
+    }
+
+    protected boolean expectNewEmbeddedFailure() {
+        return true;
+    }
+
+    public Properties getProperties(String[] props) {
+        Properties properties = super.getProperties(props);
+        properties.put("openjpa.SavepointManager", getSavepointPlugin());
+        return properties;
+    }
+
+    public void setUp() {
+        deleteAll(EmbeddedOwnerPC.class);
+    }
+
+    private EmbeddedOwnerPC newEmbeddedOwnerPC() {
+        return new EmbeddedOwnerPC(id++, id++);
+    }
+
+    public void testClearNew()
+        throws Exception {
+        doClearNewTest(true, 0, 0);
+        doClearNewTest(true, 2, 0);
+        doClearNewTest(true, 0, 2);
+        doClearNewTest(true, 2, 2);
+        doClearNewTest(false, 0, 0);
+        doClearNewTest(false, 2, 0);
+        doClearNewTest(false, 0, 2);
+        doClearNewTest(false, 2, 2);
+    }
+
+    public void doClearNewTest(boolean newPC, int before, int after)
+        throws Exception {
+        deleteAll(EmbeddedOwnerPC.class);
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        EmbeddedOwnerPC pc = newEmbeddedOwnerPC();
+        pm.persist(pc);
+        pc.setStringField("orig");
+        Object oid = pm.getObjectId(pc);
+        if (!newPC) {
+            endTx(pm);
+            endEm(pm);
+            pm = getPM();
+            startTx(pm);
+            pc = (EmbeddedOwnerPC) pm.find(EmbeddedOwnerPC.class, oid);
+        }
+        for (int i = 0; i < before; i++) {
+            pc.setStringField("b" + i);
+            pm.setSavepoint("b" + i);
+        }
+
+        pc.setStringField("test");
+        pm.setSavepoint("test");
+        EmbeddedPC embed = new EmbeddedPC();
+        embed.setIntField(99);
+        pc.setEmbedded(embed);
+
+        for (int i = 0; i < after; i++) {
+            pc.setStringField("a" + i);
+            pm.setSavepoint("a" + i);
+        }
+
+        pm.rollbackToSavepoint("test");
+        if (newPC)
+            assertNull(pc.getEmbedded());
+        else
+            assertEquals(0, pc.getEmbedded().getIntField());
+        assertEquals("test", pc.getStringField());
+        endTx(pm);
+        endEm(pm);
+    }
+
+    public void testEmbeddedReassign() {
+        doEmbeddedReassignTest(true, 0, 0);
+        doEmbeddedReassignTest(true, 2, 0);
+        doEmbeddedReassignTest(true, 0, 2);
+        doEmbeddedReassignTest(true, 2, 2);
+        doEmbeddedReassignTest(false, 0, 0);
+        doEmbeddedReassignTest(false, 2, 0);
+        doEmbeddedReassignTest(false, 0, 2);
+        doEmbeddedReassignTest(false, 2, 2);
+    }
+
+    public void doEmbeddedReassignTest(boolean newPC, int before, int after) {
+        deleteAll(EmbeddedOwnerPC.class);
+        deleteAll(EmbeddedPC.class);
+
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        EmbeddedOwnerPC pc = newEmbeddedOwnerPC();
+        EmbeddedPC embed = new EmbeddedPC();
+        embed.setIntField1(1000);
+        pc.setStringField("orig");
+        pm.persist(pc);
+        pc.setEmbedded(embed);
+
+        Object oid = pm.getObjectId(pc);
+        if (!newPC) {
+            endTx(pm);
+            endEm(pm);
+            pm = getPM();
+            startTx(pm);
+            pc = (EmbeddedOwnerPC) pm.find(EmbeddedOwnerPC.class, oid);
+        }
+        for (int i = 0; i < before; i++) {
+            pc.setStringField("b" + i);
+            pm.setSavepoint("b" + i);
+        }
+
+        pm.setSavepoint("test");
+        embed = new EmbeddedPC();
+        embed.setIntField1(2000);
+        pc.setEmbedded(embed);
+
+        for (int i = 0; i < after; i++) {
+            pc.setStringField("b" + i);
+            pm.setSavepoint("a" + i);
+        }
+
+        pm.rollbackToSavepoint("test");
+        assertNotNull(pc.getEmbedded());
+        assertEquals(1000, pc.getEmbedded().getIntField1());
+        endTx(pm);
+        endEm(pm);
+    }
+
+    public void testEmbeddedChange()
+        throws Exception {
+        try {
+            doEmbeddedChangeTest(true, 0, 0);
+            doEmbeddedChangeTest(true, 2, 0);
+            doEmbeddedChangeTest(true, 0, 2);
+            doEmbeddedChangeTest(true, 2, 2);
+        } catch (Throwable t) {
+            if (expectNewEmbeddedFailure())
+                bug(1141, t, "changes to new embedded not detected");
+            else
+                throw (Exception) t;
+        }
+        doEmbeddedChangeTest(false, 0, 0);
+        doEmbeddedChangeTest(false, 2, 0);
+        doEmbeddedChangeTest(false, 0, 2);
+        doEmbeddedChangeTest(false, 2, 2);
+    }
+
+    public void doEmbeddedChangeTest(boolean newPC, int before, int after) {
+        deleteAll(EmbeddedOwnerPC.class);
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        EmbeddedOwnerPC pc = newEmbeddedOwnerPC();
+        EmbeddedPC embed = new EmbeddedPC();
+        embed.setIntField1(1000);
+        pc.setStringField("orig");
+        pm.persist(pc);
+        pc.setEmbedded(embed);
+
+        Object oid = pm.getObjectId(pc);
+        if (!newPC) {
+            endTx(pm);
+            endEm(pm);
+            pm = getPM();
+            startTx(pm);
+            pc = (EmbeddedOwnerPC) pm.find(EmbeddedOwnerPC.class, oid);
+        }
+        for (int i = 0; i < before; i++) {
+            pc.setStringField("b" + i);
+            pm.setSavepoint("b" + i);
+        }
+
+        pm.setSavepoint("test");
+        pc.getEmbedded().setIntField1(2000);
+
+        for (int i = 0; i < after; i++) {
+            pc.setStringField("a" + i);
+            pm.setSavepoint("a" + i);
+        }
+
+        pm.rollbackToSavepoint("test");
+        assertNotNull(pc.getEmbedded());
+        assertEquals(1000, pc.getEmbedded().getIntField1());
+        endTx(pm);
+        endEm(pm);
+    }
+
+    public void testEmbeddedChange2()
+        throws Exception {
+        try {
+            doEmbeddedChangeTest2(true, 0, 0);
+            doEmbeddedChangeTest2(true, 2, 0);
+            doEmbeddedChangeTest2(true, 0, 2);
+            doEmbeddedChangeTest2(true, 2, 2);
+        } catch (Throwable t) {
+            if (expectNewEmbeddedFailure())
+                bug(1141, t, "changes to new embedded not detected");
+            else
+                throw (Exception) t;
+        }
+        doEmbeddedChangeTest2(false, 0, 0);
+        doEmbeddedChangeTest2(false, 2, 0);
+        doEmbeddedChangeTest2(false, 0, 2);
+        doEmbeddedChangeTest2(false, 2, 2);
+    }
+
+    // variation with changing embedde fields vs owner field
+    public void doEmbeddedChangeTest2(boolean newPC, int before, int after) {
+        deleteAll(EmbeddedOwnerPC.class);
+        deleteAll(EmbeddedPC.class);
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        EmbeddedOwnerPC pc = newEmbeddedOwnerPC();
+        EmbeddedPC embed = new EmbeddedPC();
+        embed.setIntField1(1000);
+        pc.setStringField("orig");
+        pm.persist(pc);
+        pc.setEmbedded(embed);
+
+        Object oid = pm.getObjectId(pc);
+        if (!newPC) {
+            endTx(pm);
+            endEm(pm);
+            pm = getPM();
+            startTx(pm);
+            pc = (EmbeddedOwnerPC) pm.find(EmbeddedOwnerPC.class, oid);
+        }
+        for (int i = 0; i < before; i++) {
+            pc.getEmbedded().setIntField1(i);
+            pm.setSavepoint("b" + i);
+        }
+
+        pm.setSavepoint("test");
+        pc.getEmbedded().setIntField1(2000);
+
+        for (int i = 0; i < after; i++) {
+            pc.getEmbedded().setIntField1(i * -1);
+            pm.setSavepoint("a" + i);
+        }
+
+        pm.rollbackToSavepoint("test");
+        assertNotNull(pc.getEmbedded());
+        if (before == 0)
+            assertEquals(1000, pc.getEmbedded().getIntField1());
+        else
+            assertEquals(before - 1, pc.getEmbedded().getIntField1());
+        endTx(pm);
+        endEm(pm);
+    }
+}

Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointEmbeddedPreFlush.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointEmbeddedPreFlush.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointEmbeddedPreFlush.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointEmbeddedPreFlush.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,49 @@
+/*
+ * TestSavepointEmbeddedPreFlush.java
+ *
+ * Created on October 16, 2006, 10:43 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;
+
+
+
+
+
+public class TestSavepointEmbeddedPreFlush extends TestSavepointEmbedded {
+
+    /**
+     * Creates a new instance of TestSavepointEmbeddedPreFlush
+     */
+    public TestSavepointEmbeddedPreFlush(String name) {
+        super(name);
+    }
+
+    protected String getSavepointPlugin() {
+        return "in-mem(PreFlush=true)";
+    }
+
+    protected boolean expectNewEmbeddedFailure() {
+        return false;
+    }
+}

Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointOrdering.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointOrdering.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointOrdering.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepointOrdering.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,268 @@
+/*
+ * TestSavepointOrdering.java
+ *
+ * Created on October 16, 2006, 10:45 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.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest1;
+
+import org.apache.openjpa.kernel.Broker;
+import org.apache.openjpa.kernel.OpenJPASavepoint;
+import org.apache.openjpa.kernel.SavepointManager;
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+import org.apache.openjpa.persistence.OpenJPAEntityManagerFactory;
+
+public class TestSavepointOrdering extends BaseKernelTest {
+
+    private static final int USER = 1;
+    private static final int RELEASED = 2;
+    private static final int ROLLBACK = 4;
+
+    static Map _assigned = new HashMap();
+
+    /**
+     * Creates a new instance of TestSavepointOrdering
+     */
+    public TestSavepointOrdering(String name) {
+        super(name);
+    }
+
+    public void setUp() {
+        deleteAll(RuntimeTest1.class);
+        _assigned.clear();
+    }
+
+    public void testCleanUpCommit() {
+        doCleanUpTest(true);
+    }
+
+    public void testCleanUpRollback() {
+        doCleanUpTest(false);
+    }
+
+    public void doCleanUpTest(boolean commit) {
+        Map props = new HashMap();
+        props.put("openjpa.SavepointManager",
+            TrackingSavepointManager.class.getName());
+        OpenJPAEntityManagerFactory pmf = getEmf(props);
+        OpenJPAEntityManager pm = pmf.createEntityManager();
+        startTx(pm);
+        pm.setSavepoint("test");
+        pm.setSavepoint("test2");
+        if (commit)
+            endTx(pm);
+        else
+            rollbackTx(pm);
+        assertFlags("test", RELEASED, USER | ROLLBACK);
+        assertFlags("test2", RELEASED, USER | ROLLBACK);
+        endEm(pm);
+    }
+
+    public void testOrderingWithRollback() {
+        doOrderingTest(true);
+    }
+
+    public void testOrderingWithRelease() {
+        doOrderingTest(false);
+    }
+
+    private void doOrderingTest(boolean rollback) {
+        Map props = new HashMap();
+        props.put("openjpa.SavepointManager",
+            TrackingSavepointManager.class.getName());
+        OpenJPAEntityManagerFactory pmf = getEmf(props);
+        OpenJPAEntityManager pm = pmf.createEntityManager();
+        startTx(pm);
+        pm.setSavepoint("before");
+        pm.setSavepoint("before2");
+        pm.setSavepoint("test");
+        pm.setSavepoint("test2");
+        pm.setSavepoint("after");
+        pm.setSavepoint("after2");
+        if (rollback)
+            pm.rollbackToSavepoint("test2");
+        else
+            pm.releaseSavepoint("test2");
+
+        assertFlags("before", 0, RELEASED | ROLLBACK);
+        assertFlags("before2", 0, RELEASED | ROLLBACK);
+        assertFlags("test", 0, RELEASED | ROLLBACK);
+        assertFlags("after", RELEASED, USER);
+        assertFlags("after2", RELEASED, USER);
+
+        if (rollback)
+            assertFlags("test2", ROLLBACK, 0);
+        else
+            assertFlags("test2", RELEASED | USER, 0);
+
+        pm.setSavepoint("after3");
+        if (rollback)
+            pm.rollbackToSavepoint("test");
+        else
+            pm.releaseSavepoint("test");
+
+        assertFlags("before", 0, RELEASED | ROLLBACK);
+        assertFlags("before2", 0, RELEASED | ROLLBACK);
+        if (rollback)
+            assertFlags("test", ROLLBACK, 0);
+        else
+            assertFlags("test", RELEASED | USER, 0);
+        assertFlags("after3", RELEASED, USER);
+        rollbackTx(pm);
+        endEm(pm);
+    }
+
+    public void testDisallowFlush() {
+        Map props = new HashMap();
+        props.put("openjpa.SavepointManager",
+            TrackingSavepointManager.class.getName() + "(AllowFlush=false)");
+        OpenJPAEntityManagerFactory pmf = getEmf(props);
+        OpenJPAEntityManager pm = pmf.createEntityManager();
+        startTx(pm);
+        pm.persist(new RuntimeTest1());
+        pm.setSavepoint("a");
+        try {
+            pm.flush();
+            fail("should have failed.");
+        } catch (Exception e) {
+        }
+        rollbackTx(pm);
+        endEm(pm);
+    }
+
+    public void testDisallowFlush2() {
+        Map props = new HashMap();
+        props.put("openjpa.SavepointManager",
+            TrackingSavepointManager.class.getName() + "(AllowFlush=false)");
+        OpenJPAEntityManagerFactory pmf = getEmf(props);
+        OpenJPAEntityManager pm = pmf.createEntityManager();
+
+        startTx(pm);
+        pm.persist(new RuntimeTest1());
+        pm.flush();
+        try {
+            pm.setSavepoint("a");
+            fail("should have failed.");
+        } catch (Exception e) {
+        }
+        rollbackTx(pm);
+        endEm(pm);
+    }
+
+    public void testAllowFlush() {
+        Map props = new HashMap();
+        props.put("openjpa.SavepointManager",
+            TrackingSavepointManager.class.getName() + "(AllowFlush=true)");
+        OpenJPAEntityManagerFactory pmf = getEmf(props);
+        OpenJPAEntityManager pm = pmf.createEntityManager();
+
+        startTx(pm);
+        pm.persist(new RuntimeTest1());
+        pm.setSavepoint("a");
+        try {
+            pm.flush();
+        } catch (Exception e) {
+            fail("allows flush.");
+        }
+        rollbackTx(pm);
+        endEm(pm);
+    }
+
+    public void testAllowFlush2() {
+        Map props = new HashMap();
+        props.put("openjpa.SavepointManager",
+            TrackingSavepointManager.class.getName() + "(AllowFlush=true)");
+        OpenJPAEntityManagerFactory pmf = getEmf(props);
+        OpenJPAEntityManager pm = pmf.createEntityManager();
+
+        startTx(pm);
+        pm.persist(new RuntimeTest1());
+        pm.flush();
+        try {
+            pm.setSavepoint("a");
+        } catch (Exception e) {
+            fail("allows flush.");
+        }
+        rollbackTx(pm);
+        endEm(pm);
+    }
+
+    private void assertFlags(String name, int flag, int noflag) {
+        TrackingSavepoint sp = (TrackingSavepoint) _assigned.get(name);
+        assertNotNull(sp);
+        assertEquals(sp.flags & flag, flag);
+        assertTrue((sp.flags & noflag) == 0);
+    }
+
+    public static class TrackingSavepointManager implements SavepointManager {
+
+        public boolean allowFlush = false;
+
+        public boolean supportsIncrementalFlush() {
+            return allowFlush;
+        }
+
+        public OpenJPASavepoint newSavepoint(String name, Broker broker) {
+            TrackingSavepoint sp = new TrackingSavepoint(broker, name);
+            _assigned.put(sp.getName(), sp);
+            return sp;
+        }
+    }
+
+    private static class TrackingSavepoint extends OpenJPASavepoint {
+
+        int flags = 0;
+
+        public TrackingSavepoint(Broker broker, String name) {
+            super(broker, name, false);
+        }
+
+        public Collection rollback(Collection previous) {
+            if ((flags & (ROLLBACK | RELEASED)) != 0)
+                fail("already used");
+            flags |= ROLLBACK;
+            return super.rollback(previous);
+        }
+
+        public void release(boolean user) {
+            if ((flags & (ROLLBACK | RELEASED)) != 0)
+                fail("already used");
+            flags |= RELEASED;
+            if (user) {
+                if ((flags & USER) != 0)
+                    fail("already released");
+                flags |= USER;
+            }
+
+            super.release(user);
+        }
+    }
+}

Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepoints.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepoints.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepoints.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSavepoints.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,509 @@
+/*
+ * TestSavepoints.java
+ *
+ * Created on October 16, 2006, 11:16 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.Iterator;
+import java.util.Properties;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.ModRuntimeTest1;
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest4;
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest5;
+
+import org.apache.openjpa.kernel.PCState;
+import org.apache.openjpa.persistence.JPAFacadeHelper;
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+import org.apache.openjpa.persistence.OpenJPAPersistence;
+
+public class TestSavepoints extends BaseKernelTest {
+
+    /**
+     * Creates a new instance of TestSavepoints
+     */
+    public TestSavepoints(String name) {
+        super(name);
+    }
+
+    protected String getSavepointPlugin() {
+        return "in-mem";
+    }
+
+    public Properties getProperties(String[] props) {
+        Properties properties = super.getProperties(props);
+        properties.put("openjpa.SavepointManager", getSavepointPlugin());
+        return properties;
+    }
+
+    public void setUp() {
+        deleteAll(ModRuntimeTest1.class);
+        deleteAll(RuntimeTest4.class);
+        deleteAll(RuntimeTest5.class);
+    }
+
+    public void testSimple() {
+        doSimpleTest(true, 0, 0);
+        doSimpleTest(true, 2, 0);
+        doSimpleTest(true, 0, 2);
+        doSimpleTest(false, 0, 0);
+        doSimpleTest(false, 2, 0);
+        doSimpleTest(false, 0, 2);
+    }
+
+    private void doSimpleTest(boolean newPC, int before, int after) {
+        OpenJPAEntityManager pm = getPM();
+        ModRuntimeTest1 pc = new ModRuntimeTest1();
+        startTx(pm);
+        pc.setStringField("orig");
+        pc.setIntField(-11);
+        //FIXME jthomas - setDateField
+        //pc.setDateField(randomDate());
+        pm.persist(pc);
+        Object oid = pm.getObjectId(pc);
+
+        if (!newPC) {
+            endTx(pm);
+            pm = getPM();
+            startTx(pm);
+            pc = (ModRuntimeTest1) pm.find(ModRuntimeTest1.class, oid);
+        }
+        for (int i = 0; i < before; i++) {
+            pc.setStringField("before" + i);
+            pc.setIntField(i);
+            //FIXME jthomas - setDateField
+            //pc.setDateField(randomDate());
+            pm.setSavepoint("before" + i);
+        }
+
+        pc.setStringField("value");
+        pc.setIntField(333);
+        //FIXME jthomas - setDateField
+        //pc.setDateField(randomDate());
+        //Date date = (Date) pc.getDateField().clone();
+        pm.setSavepoint("test");
+
+        for (int i = 0; i < after; i++) {
+            pc.setStringField("after" + i);
+            pc.setIntField(i * 10);
+            //FIXME jthomas - setDateField
+            //pc.setDateField(randomDate());
+            pm.setSavepoint("after" + i);
+        }
+
+        pm.rollbackToSavepoint("test");
+        assertEquals("value", pc.getStringField());
+        assertEquals(333, pc.getIntField());
+        //FIXME jthomas - setDateField
+        //assertEquals(date, pc.getDateField());
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        pc = (ModRuntimeTest1) pm.find(ModRuntimeTest1.class, oid);
+        assertEquals("value", pc.getStringField());
+        assertEquals(333, pc.getIntField());
+        //FIXME jthomas - setDateField
+        //assertEquals(date, pc.getDateField());
+        endEm(pm);
+    }
+
+    public void testCleanOrdering() {
+        OpenJPAEntityManager pm = getPM();
+        ModRuntimeTest1 pc = new ModRuntimeTest1("orig", 1);
+        startTx(pm);
+        pm.persist(pc);
+        Object oid = pm.getObjectId(pc);
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        pm.setOptimistic(false);
+        startTx(pm);
+        ModRuntimeTest1 pc2 = new ModRuntimeTest1("foo", 2);
+        pm.persist(pc2);
+        pm.setSavepoint("s1");
+        pc = (ModRuntimeTest1) pm.find(ModRuntimeTest1.class, oid);
+        assertTrue(pm.isTransactional(pc));
+        pm.setSavepoint("s2");
+        pc.setStringField("bar");
+        pm.rollbackToSavepoint("s2");
+        assertEquals("orig", pc.getStringField());
+        assertTrue(pm.isTransactional(pc));
+
+        rollbackTx(pm);
+        endEm(pm);
+    }
+
+    public void testLastSavepoint() {
+        OpenJPAEntityManager pm = getPM();
+        ModRuntimeTest1 pc = new ModRuntimeTest1("orig", 1);
+        startTx(pm);
+        pm.persist(pc);
+        Object oid = pm.getObjectId(pc);
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        pm.setOptimistic(false);
+        startTx(pm);
+        pc = (ModRuntimeTest1) pm.find(ModRuntimeTest1.class, oid);
+        pc.setStringField("s1");
+        pm.setSavepoint("s1");
+        pc.setStringField("s2");
+        pm.setSavepoint("s2");
+        pc.setStringField("diff");
+        pm.rollbackToSavepoint();
+        assertEquals("s2", pc.getStringField());
+        pm.releaseSavepoint();
+        try {
+            pm.rollbackToSavepoint("s1");
+            fail("Exhausted.");
+        } catch (Exception e) {
+        }
+        rollbackTx(pm);
+        endEm(pm);
+    }
+
+    public void testNewRollback() {
+        doNewRollbackTest(false, 0, 0);
+        doNewRollbackTest(false, 2, 0);
+        doNewRollbackTest(false, 0, 2);
+        doNewRollbackTest(true, 0, 0);
+        doNewRollbackTest(true, 2, 0);
+        doNewRollbackTest(true, 0, 2);
+    }
+
+    public void doNewRollbackTest(boolean restore, int before, int after) {
+        OpenJPAEntityManager pm = getPM();
+        pm.setRetainState(restore);
+        startTx(pm);
+
+        for (int i = 0; i < before; i++) {
+            pm.persist(new ModRuntimeTest1("s" + i, i));
+            //pm.setSavepoint("before" + i);
+        }
+        pm.setSavepoint("test");
+
+        ModRuntimeTest1 pc = new ModRuntimeTest1();
+        pc.setStringField("orig");
+        pm.persist(pc);
+        Object oid = pm.getObjectId(pc);
+
+        for (int i = 0; i < after; i++) {
+            pm.persist(new ModRuntimeTest1());
+            pm.setSavepoint("after" + i);
+        }
+
+        pm.rollbackToSavepoint("test");
+        assertEquals("orig", pc.getStringField());
+        assertFalse(pm.isPersistent(pc));
+        assertEquals(before, pm.getTransactionalObjects().size());
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        assertNull(pm.find(ModRuntimeTest1.class, oid));
+        endEm(pm);
+    }
+
+    public void testNewRelation() {
+        doNewRelationTest(true, 0, 0);
+        doNewRelationTest(true, 2, 0);
+        doNewRelationTest(true, 0, 2);
+        doNewRelationTest(false, 0, 0);
+        doNewRelationTest(false, 2, 0);
+        doNewRelationTest(false, 0, 2);
+    }
+
+    public void doNewRelationTest(boolean nullRel, int before, int after) {
+        deleteAll(ModRuntimeTest1.class);
+
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        ModRuntimeTest1 pc = new ModRuntimeTest1();
+        pc.setStringField("orig");
+        if (!nullRel)
+            pc.setSelfOneOne(new ModRuntimeTest1("one", 1));
+        pm.persist(pc);
+        Object oid = pm.getObjectId(pc);
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        pm.setRetainState(true);
+        startTx(pm);
+        pc = (ModRuntimeTest1) pm.find(ModRuntimeTest1.class, oid);
+
+        for (int i = 0; i < before; i++) {
+            pc.setSelfOneOne(new ModRuntimeTest1("before" + i, i));
+            pm.setSavepoint("before" + i);
+        }
+
+        pm.setSavepoint("test");
+        pc.setSelfOneOne(new ModRuntimeTest1("new", 2));
+        ModRuntimeTest1 pc2 = pc.getSelfOneOne();
+
+        for (int i = 0; i < after; i++) {
+            pc.setSelfOneOne(new ModRuntimeTest1());
+            pm.setSavepoint("after" + i);
+        }
+
+        pm.rollbackToSavepoint("test");
+        assertEquals("orig", pc.getStringField());
+        assertFalse(pm.isPersistent(pc2));
+        if (before > 0)
+            assertEquals("before" + (before - 1),
+                pc.getSelfOneOne().getStringField());
+        else {
+            if (nullRel)
+                assertNull(pc.getSelfOneOne());
+            else
+                assertEquals("one", pc.getSelfOneOne().getStringField());
+        }
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        pc = (ModRuntimeTest1) pm.find(ModRuntimeTest1.class, oid);
+        assertEquals("orig", pc.getStringField());
+        if (before > 0)
+            assertEquals("before" + (before - 1),
+                pc.getSelfOneOne().getStringField());
+        else {
+            if (nullRel)
+                assertNull(pc.getSelfOneOne());
+            else
+                assertEquals("one", pc.getSelfOneOne().getStringField());
+        }
+        endEm(pm);
+    }
+
+    public void testNullRelation() {
+        doNullRelationTest(true, 0, 0);
+        doNullRelationTest(true, 2, 0);
+        doNullRelationTest(true, 0, 2);
+        doNullRelationTest(false, 0, 0);
+        doNullRelationTest(false, 2, 0);
+        doNullRelationTest(false, 0, 2);
+    }
+
+    public void doNullRelationTest(boolean retain, int before, int after) {
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        ModRuntimeTest1 pc = new ModRuntimeTest1();
+        pc.setStringField("orig");
+        pc.setSelfOneOne(new ModRuntimeTest1("one", 1));
+        pm.persist(pc);
+        Object oid = pm.getObjectId(pc);
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        pm.setRetainState(true);
+        startTx(pm);
+        pc = (ModRuntimeTest1) pm.find(ModRuntimeTest1.class, oid);
+
+        for (int i = 0; i < before; i++) {
+            pc.setSelfOneOne(new ModRuntimeTest1("before" + i, i));
+            pm.setSavepoint("before" + i);
+        }
+
+        pm.setSavepoint("test");
+        pc.setSelfOneOne(null);
+
+        for (int i = 0; i < after; i++) {
+            pc.setSelfOneOne(new ModRuntimeTest1());
+            pm.setSavepoint("after" + i);
+        }
+
+        pm.rollbackToSavepoint("test");
+        assertEquals("orig", pc.getStringField());
+        if (before > 0)
+            assertEquals("before" + (before - 1),
+                pc.getSelfOneOne().getStringField());
+        else
+            assertEquals("one", pc.getSelfOneOne().getStringField());
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        pc = (ModRuntimeTest1) pm.find(ModRuntimeTest1.class, oid);
+        assertEquals("orig", pc.getStringField());
+        if (before > 0)
+            assertEquals("before" + (before - 1),
+                pc.getSelfOneOne().getStringField());
+        else
+            assertEquals("one", pc.getSelfOneOne().getStringField());
+        endEm(pm);
+    }
+
+    public void testCollection() {
+        doCollectionTest(true, 0, 0);
+        doCollectionTest(true, 2, 0);
+        doCollectionTest(true, 0, 2);
+        doCollectionTest(false, 0, 0);
+        doCollectionTest(false, 2, 0);
+        doCollectionTest(false, 0, 2);
+    }
+
+    public void doCollectionTest(boolean newPC, int before, int after) {
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        ModRuntimeTest1 pc = new ModRuntimeTest1("orig", 1);
+        ModRuntimeTest1 pc2 = newElement(pc, "persist", 2);
+        ModRuntimeTest1 pc3 = newElement(pc, "delete", 3);
+        pm.persist(pc);
+        pm.persist(pc3);
+        Object oid = pm.getObjectId(pc);
+        ModRuntimeTest1 temp;
+        if (!newPC) {
+            endTx(pm);
+            endEm(pm);
+
+            pm = getPM();
+            startTx(pm);
+            pc = (ModRuntimeTest1) pm.find(ModRuntimeTest1.class, oid);
+            assertEquals(2, pc.getSelfOneMany().size());
+            for (Iterator it = pc.getSelfOneMany().iterator(); it.hasNext();) {
+                temp = (ModRuntimeTest1) it.next();
+                if (temp.getIntField() == 2)
+                    pc2 = temp;
+                else if (temp.getIntField() == 3)
+                    pc3 = temp;
+                else
+                    fail("unknown");
+            }
+        }
+
+        for (int i = 0; i < before; i++) {
+            newElement(pc, "before" + i, (i + 1) * 10);
+            pm.setSavepoint("before" + i);
+        }
+        pm.setSavepoint("test");
+        pm.remove(pc3);
+        pc.getSelfOneMany().remove(pc2);
+
+        // kodo 4 is more stringent on deleted relations.
+        pc.getSelfOneMany().remove(pc3);
+        pc2.setSelfOneMany(null);
+
+        for (int i = 0; i < after; i++) {
+            newElement(pc, "after" + i, (i + 1) * -10);
+            pm.setSavepoint("after" + i);
+        }
+
+        pm.rollbackToSavepoint("test");
+
+        assertEquals("orig", pc.getStringField());
+        assertFalse(pm.isRemoved(pc2));
+        for (Iterator it = pc.getSelfOneMany().iterator(); it.hasNext();) {
+            temp = (ModRuntimeTest1) it.next();
+            assertFalse(pm.isRemoved(temp));
+            assertEquals(pc, temp.getSelfOneOne());
+            if (temp.getIntField() < 0)
+                fail("shouldn't be here:" + temp.getStringField());
+        }
+        assertTrue(pc.getSelfOneMany().contains(pc2));
+        assertTrue(pc.getSelfOneMany().contains(pc3));
+        assertEquals(2 + before, pc.getSelfOneMany().size());
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        pc = (ModRuntimeTest1) pm.find(ModRuntimeTest1.class, oid);
+        assertEquals("orig", pc.getStringField());
+        assertEquals(2 + before, pc.getSelfOneMany().size());
+        boolean found2 = false;
+        boolean found3 = false;
+        for (Iterator it = pc.getSelfOneMany().iterator(); it.hasNext();) {
+            temp = (ModRuntimeTest1) it.next();
+            assertEquals(pc, temp.getSelfOneOne());
+            if (temp.getIntField() < 0)
+                fail("shouldn't be here:" + temp.getStringField());
+            else if (temp.getIntField() == 2)
+                found2 = true;
+            else if (temp.getIntField() == 3)
+                found3 = true;
+        }
+        assertTrue(found2 && found3);
+        endEm(pm);
+    }
+
+    public void testChangeTracker() {
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        RuntimeTest4 pc = new RuntimeTest4("orig");
+        for (int i = 0; i < 12; i++)
+            pc.getRuntimeTest5s().add(new RuntimeTest5("five" + i));
+        pm.persist(pc);
+        Object oid = pm.getObjectId(pc);
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        startTx(pm);
+        pc = (RuntimeTest4) pm.find(RuntimeTest4.class, oid);
+        assertEquals(12, pc.getRuntimeTest5s().size());
+        int count = 0;
+        for (Iterator i = pc.getRuntimeTest5s().iterator();
+            count < 2; count++) {
+            i.next();
+            i.remove();
+        }
+        assertEquals(10, pc.getRuntimeTest5s().size());
+        pm.setSavepoint("test");
+        count = 0;
+        for (Iterator i = pc.getRuntimeTest5s().iterator();
+            count < 2; count++) {
+            i.next();
+            i.remove();
+        }
+        assertEquals(8, pc.getRuntimeTest5s().size());
+        endTx(pm);
+        endEm(pm);
+
+        pm = getPM();
+        pc = (RuntimeTest4) pm.find(RuntimeTest4.class, oid);
+        assertEquals(8, pc.getRuntimeTest5s().size());
+        endEm(pm);
+    }
+
+    private ModRuntimeTest1 newElement(ModRuntimeTest1 one, String str, int i) {
+        ModRuntimeTest1 two = new ModRuntimeTest1(str, i);
+        two.setSelfOneOne(one);
+        one.getSelfOneMany().add(two);
+        return two;
+    }
+
+    public static PCState getState(Object o) {
+        OpenJPAEntityManager pm = OpenJPAPersistence.getEntityManager(o);
+
+        if (pm == null)
+            return null;
+        return JPAFacadeHelper.toBroker(pm).getStateManager(o).getPCState();
+    }
+}

Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSecondClassValues.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSecondClassValues.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSecondClassValues.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSecondClassValues.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,780 @@
+/*
+ * TestSecondClassValues.java
+ *
+ * Created on October 13, 2006, 5:29 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.BigDecimal;
+import java.math.BigInteger;
+import java.text.Collator;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.SCOTest;
+import org.apache.openjpa.persistence.common.utils.AbstractTestCase;
+import junit.framework.AssertionFailedError;
+
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+
+public class TestSecondClassValues extends BaseKernelTest {
+
+    public static double DOUBLE_PRECISION = 0.0001D;
+    public static float FLOAT_PRECISION = 0.0001F;
+    // mprudhom: use optimistic so we don't hang on some databases
+    private OpenJPAEntityManager pm;
+
+    private String newline = System.getProperty("line.separator");
+
+    /**
+     * Creates a new instance of TestSecondClassValues
+     */
+    public TestSecondClassValues() {
+    }
+
+    public TestSecondClassValues(String name) {
+        super(name);
+    }
+
+    public void setUp() {
+        pm = getPM(true, false);
+    }
+
+    private int rnd() {
+        return ((int) (Math.random() * 20)) + 5;
+    }
+
+    public void testMapDeletion() {
+        OpenJPAEntityManager pm;
+        pm = getPM();
+        startTx(pm);
+        SCOTest test = new SCOTest();
+        pm.persist(test);
+        Map map = new HashMap();
+        map.put("foo", new Integer(1));
+        map.put("bar", new Integer(2));
+        for (int i = 0; i < 10; i++)
+            map.put("baz#" + i, new Integer(i));
+
+        test.setStrIntMap(map);
+        Object id = pm.getObjectId(test);
+        endTx(pm);
+
+        startTx(pm);
+        test = (SCOTest) pm.find(SCOTest.class, id);
+        assertNotNull(test);
+        map = test.getStrIntMap();
+        assertEquals(12, map.size());
+        assertEquals(new Integer(1), map.get("foo"));
+        assertEquals(new Integer(2), map.get("bar"));
+        map.remove("bar");
+        endTx(pm);
+
+        startTx(pm);
+        test = (SCOTest) pm.find(SCOTest.class, id);
+        assertNotNull(test);
+        map = test.getStrIntMap();
+        assertEquals(11, map.size());
+        assertEquals(new Integer(1), map.get("foo"));
+        assertTrue(map.get("bar") == null);
+
+        map.clear();
+
+        endTx(pm);
+
+        startTx(pm);
+        test = (SCOTest) pm.find(SCOTest.class, id);
+        assertNotNull(test);
+        map = test.getStrIntMap();
+        assertEquals(0, map.size());
+        endTx(pm);
+    }
+
+    public void testStringCollection()
+        throws Exception {
+        ArrayList list = new ArrayList();
+        for (int i = 0; i < rnd(); i++)
+            list.add(randomString());
+
+        saveSecondClassCollection(list);
+    }
+
+    public void testLongCollection()
+        throws Exception {
+        ArrayList list = new ArrayList();
+        for (int i = 0; i < rnd(); i++)
+            list.add(randomLong());
+        try {
+            saveSecondClassCollection(list);
+        } catch (AssertionFailedError afe) {
+            bug(AbstractTestCase.Platform.EMPRESS, 889, afe,
+                "Empress cannot store large long values");
+        }
+    }
+
+    public void testShortCollection()
+        throws Exception {
+        ArrayList list = new ArrayList();
+        for (int i = 0; i < rnd(); i++)
+            list.add(randomShort());
+        saveSecondClassCollection(list);
+    }
+
+    public void testBigIntegerCollection()
+        throws Exception {
+        ArrayList list = new ArrayList();
+        for (int i = 0; i < rnd(); i++)
+            list.add(randomBigInteger());
+        saveSecondClassCollection(list);
+    }
+
+    public void testBigDecimalCollection()
+        throws Exception {
+        try {
+            ArrayList list = new ArrayList();
+            for (int i = 0; i < rnd(); i++)
+                list.add(randomBigDecimal());
+            saveSecondClassCollection(list);
+        } catch (AssertionFailedError e) {
+            bug(3, e, "Precision loss for BigDecimals");
+        }
+    }
+
+    public void testIntegerCollection()
+        throws Exception {
+        ArrayList list = new ArrayList();
+        for (int i = 0; i < rnd(); i++)
+            list.add(randomInt());
+        saveSecondClassCollection(list);
+    }
+
+    public void testByteCollection()
+        throws Exception {
+        ArrayList list = new ArrayList();
+        for (int i = 0; i < rnd(); i++)
+            list.add(randomByte());
+        saveSecondClassCollection(list);
+    }
+
+    public void testBooleanCollection()
+        throws Exception {
+        ArrayList list = new ArrayList();
+        for (int i = 0; i < rnd(); i++)
+            list.add(randomBoolean());
+        saveSecondClassCollection(list, true);
+    }
+
+    public void testFloatCollection()
+        throws Exception {
+        try {
+            ArrayList list = new ArrayList();
+            for (int i = 0; i < rnd(); i++)
+                list.add(randomFloat());
+            saveSecondClassCollection(list);
+        } catch (AssertionFailedError afe) {
+            bug(3, afe, "Loss of BigDecimal precision");
+        }
+    }
+
+    public void testDoubleCollection()
+        throws Exception {
+        try {
+            ArrayList list = new ArrayList();
+            for (int i = 0; i < rnd(); i++)
+                list.add(randomDouble());
+            saveSecondClassCollection(list);
+        } catch (AssertionFailedError afe) {
+            bug(3, afe, "Loss of BigDecimal precision");
+        }
+    }
+
+    public void testDateCollection()
+        throws Exception {
+        ArrayList list = new ArrayList();
+        for (int i = 0; i < rnd(); i++)
+            list.add(randomDate());
+
+        list.add(new Date(472246800000L));
+
+        saveSecondClassCollection(list);
+    }
+
+    public void testBigDecimalBigIntegerMap()
+        throws Exception {
+        try {
+            HashMap map = new HashMap();
+            for (int i = 0; i < rnd(); i++)
+                map.put(randomBigDecimal(), randomBigInteger());
+            saveSecondClassMap(map);
+        } catch (AssertionFailedError e) {
+            bug(3, e, "Precision loss for BigDecimals");
+        }
+    }
+
+    public void testStrIntMap()
+        throws Exception {
+        HashMap map = new HashMap();
+        for (int i = 0; i < rnd(); i++)
+            map.put(randomString(), randomInt());
+        saveSecondClassMap(map);
+    }
+
+    public void testIntLongMap() throws Exception {
+        HashMap map = new HashMap();
+        for (int i = 0; i < rnd(); i++)
+            map.put(randomInt(), randomLong());
+        try {
+            saveSecondClassMap(map);
+        }
+        catch (AssertionFailedError afe) {
+            bug(AbstractTestCase.Platform.EMPRESS, 889, afe,
+                "Empress cannot store large long values");
+        }
+    }
+
+    public void testFloatByteMap()
+        throws Exception {
+        try {
+            HashMap map = new HashMap();
+            for (int i = 0; i < rnd(); i++)
+                map.put(randomFloat(), randomByte());
+            saveSecondClassMap(map);
+        } catch (AssertionFailedError afe) {
+            bug(3, afe, "Loss of BigDecimal precision");
+        }
+    }
+
+    public void testByteDoubleMap()
+        throws Exception {
+        try {
+            HashMap map = new HashMap();
+            for (int i = 0; i < rnd(); i++)
+                map.put(randomByte(), randomDouble());
+            saveSecondClassMap(map);
+        } catch (AssertionFailedError afe) {
+            bug(3, afe, "Loss of BigDecimal precision");
+        }
+    }
+
+    public void testDoubleCharMap()
+        throws Exception {
+        try {
+            HashMap map = new HashMap();
+            for (int i = 0; i < rnd(); i++)
+                map.put(randomDouble(), randomChar());
+            saveSecondClassMap(map);
+        } catch (AssertionFailedError afe) {
+            bug(3, afe, "Loss of BigDecimal precision");
+        }
+    }
+
+    public void testCharBooleanMap()
+        throws Exception {
+        HashMap map = new HashMap();
+        for (int i = 0; i < rnd(); i++)
+            map.put(randomChar(), randomBoolean());
+        saveSecondClassMap(map);
+    }
+
+    public void testDateStrMap() throws Exception {
+        HashMap map = new HashMap();
+        for (int i = 0; i < rnd(); i++)
+            map.put(randomDate(), randomString());
+
+        map.put(new Date(472246800000L),
+            "PostgreSQL ain't gonna like this date");
+        assertNotNull("map is null testDateStrMap", map);
+        saveSecondClassMap(map);
+    }
+
+    private void saveSecondClassMap(HashMap map)
+        throws Exception {
+        try {
+            saveSecondClassMapInternal(map);
+        } finally {
+            commit();
+        }
+    }
+
+    private void commit() {
+        try {
+            assertNotNull(pm);
+
+//  		EntityTransaction trans = pm.getTransaction();
+//  		if (trans != null && trans.isActive()) {
+//  		trans.commit();
+            endTx(pm);
+        }
+        catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    private void begin() {
+        commit(); // make sure we are clean
+
+        // get a fresh PM
+        pm = getPM(true, false);
+        startTx(pm);
+    }
+
+    /**
+     * Save the specified map as a second-class object and validate
+     * its contents by reading back in the object and comparing
+     * all the values to the original. Furthermore, this method
+     * deletes each element of both maps in turn and re-validates
+     * each time to make sure updating of the map is working correctly.
+     */
+    private void saveSecondClassMapInternal(HashMap map) throws Exception {
+        begin();
+        SCOTest test = new SCOTest();
+        pm.persist(test);
+        int testID = test.getId();
+        assertNotNull("Passed Map is null", map);
+        Map smap = setGetMap(test, map, true);
+        assertNotNull("Map is null in setGetMap", smap);
+        commit();
+
+        for (Iterator mapKey = ((HashMap) map.clone()).keySet().iterator();
+            mapKey.hasNext();) {
+            Object keyToDelete = mapKey.next();
+
+            begin();
+            SCOTest retrievedObject =
+                (SCOTest) pm.find(SCOTest.class, testID);
+
+            assertNotNull(
+                "retrievedObject Obj is null - saveSecondClassMapInternal",
+                retrievedObject);
+
+            Map retrievedMap = setGetMap(retrievedObject, map, false);
+
+            assertNotNull(
+                "retrievedMap Obj is null - saveSecondClassMapInternal",
+                retrievedMap);
+
+            assertTrue(map.size() != 0);
+            assertEquals(map.size(), retrievedMap.size());
+
+            assertTrue("Incompatible types", map.keySet().iterator().next().
+                getClass().isAssignableFrom(retrievedMap.keySet().
+                iterator().next().getClass()));
+
+            // check to make sure all the keys match up to the appropriate
+            // values.
+            for (Iterator i = map.keySet().iterator(); i.hasNext();) {
+                Object key = i.next();
+                assertTrue(key != null);
+                assertTrue(map.get(key) != null);
+                if (key.getClass() == Date.class
+                    && retrievedMap.get(key) == null) {
+                    getLog().trace("Time: "
+                        + (((Date) key).getTime()));
+                    getLog().trace("List: "
+                        + dumpDates(retrievedMap.keySet()));
+
+                    /*
+                        bug (6, "Dates lose precision in some data stores "
+                            + "(" + (((Date)key).getTime ()) + ","
+                            + "[" + dumpDates (retrievedMap.keySet ()) + "])");
+                    */
+                }
+                if ((key.getClass() == Double.class ||
+                    key.getClass() == Float.class ||
+                    key.getClass() == BigDecimal.class)
+                    && retrievedMap.get(key) == null) {
+                    /*
+                         bug (3, "Doubles and Floats "
+                             + " lose precision in some data stores");
+                     */
+                }
+
+                assertTrue("The original map contained the object (class="
+                    + key.getClass().getName() + ", value="
+                    + key.toString() + "), but that object was null "
+                    + "in the map that was retrieved "
+                    + dump(retrievedMap.keySet()) + ".",
+                    retrievedMap.get(key) != null);
+                assertClassAndValueEquals(
+                    map.get(key), retrievedMap.get(key));
+            }
+
+            // now delete the first key in both maps, and make sure
+            // thinks are still OK.
+            map.remove(keyToDelete);
+            retrievedMap.remove(keyToDelete);
+        }
+    }
+
+    private void saveSecondClassCollection(ArrayList collection)
+        throws Exception {
+        saveSecondClassCollection(collection, false);
+    }
+
+    private void saveSecondClassCollection(ArrayList collection,
+        boolean useCustomCollator)
+        throws Exception {
+        try {
+            saveSecondClassCollectionInternal(collection, useCustomCollator);
+        } finally {
+            commit();
+        }
+    }
+
+    private void saveSecondClassCollectionInternal(ArrayList collection,
+        boolean useCustomCollator)
+        throws Exception {
+        Object elementToDelete = null;
+
+        if (useCustomCollator)
+            Collections.sort(collection,
+                new CollectionSorter());
+        else
+            Collections.sort(collection);
+
+        OpenJPAEntityManager pm1 = getPM();
+        startTx(pm1);
+
+        SCOTest test = new SCOTest();
+        pm1.persist(test);
+        int testID = test.getId();
+
+        Collection storedCollection = setGetCollection(test,
+            (Collection) ((ArrayList) collection).clone(), true);
+
+        assertNotNull("retrieved storedCollection is null", storedCollection);
+
+        // make sure the pre-commit collections are identical!
+        assertEquals("Pre-commit collections were not equal: " + newline
+            + dump(collection) + newline + "!=" + newline
+            + dump(storedCollection),
+            collection.size(), storedCollection.size());
+
+        endTx(pm1);
+
+        int deletionIndex = 0;
+
+        OpenJPAEntityManager pm2 = getPM();
+
+        while (collection.size() > 0) {
+            deletionIndex++;
+
+            startTx(pm2);
+            SCOTest retrievedObject =
+                (SCOTest) pm2.find(SCOTest.class, testID);
+
+            assertNotNull(
+                "retrieved obj is null saveSecondClassCollectionInternal",
+                retrievedObject);
+
+            Collection identityCollection = new LinkedList(collection);
+            assertNotNull(
+                "identityCollection is null saveSecondClassCollectionInternal",
+                identityCollection);
+            Collection retrievedCollection = setGetCollection(
+                retrievedObject, identityCollection, false);
+
+            assertNotNull(
+                "retrievedCollection is null saveSecondClassCollectionInternal",
+                retrievedCollection);
+
+            validateCollection(retrievedCollection);
+
+            assertNotNull(retrievedCollection);
+            assertTrue(collection.size() != 0);
+
+            assertEquals("Retreived collection does not match original "
+                + "after the " + deletionIndex + "th deletion ("
+                + elementToDelete + "): "
+                + newline
+                + dump(collection) + newline + "!=" + newline
+                + dump(retrievedCollection) + newline,
+                collection.size(), retrievedCollection.size());
+
+            /*
+            try
+            {
+                assertEquals (collection.size retrievedCollection.size ());
+            } catch (AssertionFailedError afe) {
+                bug (AbstractTestCase.Platform.SQLSERVER, 2, afe, "Second-class collections"
+                    + " are not being retrieved correctly");
+            }
+            */
+
+            // make sure the classes of the keys are the same.
+            Iterator ci = collection.iterator();
+            Object co = collection.iterator().next();
+
+            Iterator rci = retrievedCollection.iterator();
+            Object rco = retrievedCollection.iterator().next();
+
+            assertNotNull(co);
+            assertNotNull(rco);
+            assertEquals(co.getClass(), rco.getClass());
+
+            List sortedRetreivedCollection =
+                new ArrayList(retrievedCollection);
+
+            if (useCustomCollator)
+                Collections.sort(sortedRetreivedCollection,
+                    new CollectionSorter());
+            else
+                Collections.sort(sortedRetreivedCollection);
+
+            // make sure the collection is OK
+            for (Iterator i = collection.iterator(),
+                j = sortedRetreivedCollection.iterator();
+                i.hasNext() && j.hasNext();) {
+                assertClassAndValueEquals(i.next(), j.next());
+            }
+
+            elementToDelete = collection.iterator().next();
+            if (!(collection.remove(elementToDelete)))
+                fail("Could not delete element "
+                    + "(<" + elementToDelete.getClass().getName() + ">"
+                    + elementToDelete + ") "
+                    + "from " + dump(collection));
+
+            if (!(retrievedCollection.remove(elementToDelete)))
+                fail("Could not delete element (" + elementToDelete + ") "
+                    + "from " + dump(retrievedCollection));
+
+            endTx(pm2);
+        }
+    }
+
+    private void assertClassAndValueEquals(Object o1, Object o2) {
+        assertTrue("First object was null", o1 != null);
+        assertTrue("Second object was null", o2 != null);
+
+        assertTrue("Types did not match (class1="
+            + o1.getClass().getName() + ", class2="
+            + o2.getClass().getName() + ")",
+            o1.getClass().isAssignableFrom(o2.getClass()));
+
+        // floats and doubles are a little special: we only
+        // compare them to a certain precision, after which
+        // we give up.
+        /*
+          if (o1 instanceof Double)
+              assertEquals (((Double)o1).doubleValue (),
+                  ((Double)o2).doubleValue (),
+                  DOUBLE_PRECISION);
+          else if (o1 instanceof Float)
+              assertEquals (((Float)o1).floatValue (),
+                  ((Float)o2).floatValue (),
+                  FLOAT_PRECISION);
+          else if (o1 instanceof BigDecimal)
+              // BigDecimal equalist is a little special: see
+              // JDORuntimeTestCase.assertEquals(BigDecimal,BigDecimal)
+              assertEquals ("BigDecimal did not match",
+                  (BigDecimal)o1, (BigDecimal)o2);
+          else
+         */
+        assertEquals("Object did not match (class1="
+            + o1.getClass().getName() + ", class2="
+            + o2.getClass().getName() + ")",
+            o1, o2);
+    }
+
+    private String dump(Collection coll) {
+        List list = new LinkedList(coll);
+        try {
+            Collections.sort(list);
+        } catch (RuntimeException e) {
+
+        }
+
+        StringBuffer buf = new StringBuffer().append("[")
+            .append("(size=").append(list.size()).append(")");
+
+        Iterator it = list.iterator();
+        if (it.hasNext())
+            buf.append("<class=" + it.next().getClass().getName() + ">");
+
+        for (Iterator i = list.iterator(); i.hasNext();)
+            buf.append(i.next()).append(i.hasNext() ? "," : "");
+
+        return buf.append("]").toString();
+    }
+
+    private String dumpDates(Collection coll) {
+        StringBuffer buf = new StringBuffer();
+        for (Iterator i = coll.iterator(); i.hasNext();)
+            buf.append(((Date) i.next()).getTime()).append(
+                i.hasNext() ? "," : "");
+
+        return buf.toString();
+    }
+
+    /**
+     * Generic setter/getter for setting the maps purposes.
+     */
+    private Map setGetMap(SCOTest test, HashMap map, boolean doSet) {
+        if (map == null)
+            return null;
+
+        Object key = map.keySet().iterator().next();
+        Object val = map.get(key);
+
+        if (key instanceof Date && val instanceof String) {
+            if (doSet)
+                test.setDateStrMap(map);
+            return test.getDateStrMap();
+        } else if (key instanceof Character && val instanceof Boolean) {
+            if (doSet)
+                test.setCharBooleanMap(map);
+            return test.getCharBooleanMap();
+        } else if (key instanceof Double && val instanceof Character) {
+            if (doSet)
+                test.setDoubleCharMap(map);
+            return test.getDoubleCharMap();
+        } else if (key instanceof Byte && val instanceof Double) {
+            if (doSet)
+                test.setByteDoubleMap(map);
+            return test.getByteDoubleMap();
+        } else if (key instanceof Float && val instanceof Byte) {
+            if (doSet)
+                test.setFloatByteMap(map);
+            return test.getFloatByteMap();
+        } else if (key instanceof Long && val instanceof Float) {
+            if (doSet)
+                test.setLongFloatMap(map);
+            return test.getLongFloatMap();
+        } else if (key instanceof Integer && val instanceof Long) {
+            if (doSet)
+                test.setIntLongMap(map);
+            return test.getIntLongMap();
+        } else if (key instanceof String && val instanceof Integer) {
+            if (doSet)
+                test.setStrIntMap(map);
+            return test.getStrIntMap();
+        } else if (key instanceof BigDecimal && val instanceof BigInteger) {
+            if (doSet)
+                test.setBigDecimalBigIntegerMap(map);
+            return test.getBigDecimalBigIntegerMap();
+        }
+
+        fail("Unknown map type");
+        return null;
+    }
+
+    /**
+     * Generic setter/getter for setting the collections purposes.
+     */
+    private Collection setGetCollection(SCOTest test,
+        Collection collection, boolean doSet) {
+        if (collection == null)
+            return null;
+
+        Object first = collection.iterator().next();
+
+        if (first instanceof BigInteger) {
+            if (doSet)
+                test.setCBigInteger(collection);
+            return test.getCBigInteger();
+        } else if (first instanceof BigDecimal) {
+            if (doSet)
+                test.setCBigDecimal(collection);
+            return test.getCBigDecimal();
+        } else if (first instanceof Date) {
+            if (doSet)
+                test.setCDate(collection);
+            return test.getCDate();
+        } else if (first instanceof Character) {
+            if (doSet)
+                test.setCCharacter(collection);
+            return test.getCCharacter();
+        } else if (first instanceof Double) {
+            if (doSet)
+                test.setCDouble(collection);
+            return test.getCDouble();
+        } else if (first instanceof Byte) {
+            if (doSet)
+                test.setCByte(collection);
+            return test.getCByte();
+        } else if (first instanceof Float) {
+            if (doSet)
+                test.setCFloat(collection);
+            return test.getCFloat();
+        } else if (first instanceof Long) {
+            if (doSet)
+                test.setCLong(collection);
+            return test.getCLong();
+        } else if (first instanceof Integer) {
+            if (doSet)
+                test.setCInteger(collection);
+            return test.getCInteger();
+        } else if (first instanceof String) {
+            if (doSet)
+                test.setCString(collection);
+            return test.getCString();
+        } else if (first instanceof Short) {
+            if (doSet)
+                test.setCShort(collection);
+            return test.getCShort();
+        } else if (first instanceof Boolean) {
+            if (doSet)
+                test.setCBoolean(collection);
+            return test.getCBoolean();
+        }
+
+        fail("Unknown collection type");
+        return null;
+    }
+
+    /**
+     * A simple sorter that should always return the same sort order.
+     * The only reason we need ti use this, instead of relying on the
+     * natural order in Collections.sort is that there seems to be
+     * a bug somewhere that prevents sorting on collections of Boolean
+     * objects.
+     */
+    public static class CollectionSorter
+        implements Comparator {
+
+        private Collator collator = Collator.getInstance();
+
+        public CollectionSorter() {
+
+        }
+
+        public int compare(Object o1, Object o2) {
+            if (o1 != null && !(o1 instanceof Boolean))
+                return collator.compare(o1, o2);
+
+            return collator.compare(o1.toString(), o2.toString());
+        }
+    }
+}

Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSecurityContext.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSecurityContext.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSecurityContext.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSecurityContext.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,286 @@
+/*
+ * TestSecurityContext.java
+ *
+ * Created on October 13, 2006, 5:25 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.FileDescriptor;
+import java.net.InetAddress;
+import java.security.Permission;
+
+
+
+import org.apache.openjpa.persistence.kernel.common.apps.RuntimeTest1;
+
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+
+public class TestSecurityContext extends BaseKernelTest {
+
+    private SecurityManager oldManager;
+    private StrictSecurityManager ssm;
+
+    /**
+     * Creates a new instance of TestSecurityContext
+     */
+    public TestSecurityContext() {
+    }
+
+    public TestSecurityContext(String name) {
+        super(name);
+    }
+
+    public void setUp() {
+        oldManager = System.getSecurityManager();
+        // System.setSecurityManager (ssm = new StrictSecurityManager ());
+    }
+
+    public void tearDown()
+        throws Exception {
+        System.setSecurityManager(oldManager);
+        oldManager = null;
+        super.tearDown();
+    }
+
+    public void testInSecureClassLoader() {
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        pm.createExtent(RuntimeTest1.class, true).iterator().hasNext();
+        endTx(pm);
+        endEm(pm);
+    }
+
+    public class StrictSecurityManager
+        extends SecurityManager {
+
+        private void debug(String msg) {
+            // log.debug (msg);
+        }
+
+        public void checkAccept(String host, int port) {
+            debug("checkAccept: " + host + "," + port);
+            super.checkAccept(host, port);
+        }
+
+        public void checkAccess(Thread t) {
+            debug("checkAccess: " + t);
+            super.checkAccess(t);
+        }
+
+        public void checkAccess(ThreadGroup g) {
+            debug("checkAccess: " + g);
+            super.checkAccess(g);
+        }
+
+        public void checkAwtEventQueueAccess() {
+            debug("checkAwtEventQueueAccess");
+            super.checkAwtEventQueueAccess();
+        }
+
+        public void checkConnect(String host, int port) {
+            debug("checkConnect: " + host + "," + port);
+            super.checkConnect(host, port);
+        }
+
+        public void checkConnect(String host, int port, Object context) {
+            debug("checkConnect: " + host + "," + port + "," + context);
+            super.checkConnect(host, port, context);
+        }
+
+        public void checkCreateClassLoader() {
+            debug("checkCreateClassLoader");
+            super.checkCreateClassLoader();
+        }
+
+        public void checkDelete(String file) {
+            debug("checkDelete: " + file);
+            super.checkDelete(file);
+        }
+
+        public void checkExec(String cmd) {
+            debug("checkExec: " + cmd);
+            super.checkExec(cmd);
+        }
+
+        public void checkExit(int status) {
+            debug("checkExit: " + status);
+            super.checkExit(status);
+        }
+
+        public void checkLink(String lib) {
+            debug("checkLink: " + lib);
+            super.checkLink(lib);
+        }
+
+        public void checkListen(int port) {
+            debug("checkListen: " + port);
+            super.checkListen(port);
+        }
+
+        public void checkMemberAccess(Class clazz, int which) {
+            debug("checkMemberAccess: " + clazz + "," + which);
+            super.checkMemberAccess(clazz, which);
+        }
+
+        public void checkMulticast(InetAddress maddr) {
+            debug("checkMulticast: " + maddr);
+            super.checkMulticast(maddr);
+        }
+
+        public void checkMulticast(InetAddress maddr, byte ttl) {
+            debug("checkMulticast: " + maddr + "," + ttl);
+            super.checkMulticast(maddr, ttl);
+        }
+
+        public void checkPackageAccess(String pkg) {
+            debug("checkPackageAccess: " + pkg);
+            super.checkPackageAccess(pkg);
+        }
+
+        public void checkPackageDefinition(String pkg) {
+            debug("checkPackageDefinition: " + pkg);
+            super.checkPackageDefinition(pkg);
+        }
+
+        public void checkPermission(Permission perm) {
+            debug("checkPermission: " + perm);
+            super.checkPermission(perm);
+        }
+
+        public void checkPermission(Permission perm, Object context) {
+            debug("checkPermission: " + perm + "," + context);
+            super.checkPermission(perm, context);
+        }
+
+        public void checkPrintJobAccess() {
+            debug("checkPrintJobAccess");
+            super.checkPrintJobAccess();
+        }
+
+        public void checkPropertiesAccess() {
+            debug("checkPropertiesAccess");
+            super.checkPropertiesAccess();
+        }
+
+        public void checkPropertyAccess(String key) {
+            debug("checkPropertyAccess: " + key);
+            super.checkPropertyAccess(key);
+        }
+
+        public void checkRead(FileDescriptor fd) {
+            debug("checkRead: " + fd);
+            super.checkRead(fd);
+        }
+
+        public void checkRead(String file) {
+            debug("checkRead: " + file);
+            super.checkRead(file);
+        }
+
+        public void checkRead(String file, Object context) {
+            debug("checkRead: " + file + "," + context);
+            super.checkRead(file, context);
+        }
+
+        public void checkSecurityAccess(String target) {
+            debug("checkSecurityAccess: " + target);
+            super.checkSecurityAccess(target);
+        }
+
+        public void checkSetFactory() {
+            debug("checkSetFactory");
+            super.checkSetFactory();
+        }
+
+        public void checkSystemClipboardAccess() {
+            debug("checkSystemClipboardAccess");
+            super.checkSystemClipboardAccess();
+        }
+
+        public boolean checkTopLevelWindow(Object window) {
+            debug("checkTopLevelWindow: " + window);
+            return super.checkTopLevelWindow(window);
+        }
+
+        public void checkWrite(FileDescriptor fd) {
+            debug("checkWrite: " + fd);
+            super.checkWrite(fd);
+        }
+
+        public void checkWrite(String file) {
+            debug("checkWrite: " + file);
+            super.checkWrite(file);
+        }
+
+        protected int classDepth(String name) {
+            debug("classDepth: " + name);
+            return super.classDepth(name);
+        }
+
+        protected int classLoaderDepth() {
+            debug("classLoaderDepth");
+            return super.classLoaderDepth();
+        }
+
+        protected ClassLoader currentClassLoader() {
+            debug("currentClassLoader");
+            return super.currentClassLoader();
+        }
+
+        protected Class currentLoadedClass() {
+            debug("currentLoadedClass");
+            return super.currentLoadedClass();
+        }
+
+        protected Class[] getClassContext() {
+            debug("getClassContext");
+            return super.getClassContext();
+        }
+
+        public boolean getInCheck() {
+            debug("getInCheck");
+            return super.getInCheck();
+        }
+
+        public Object getSecurityContext() {
+            debug("getSecurityContext");
+            return super.getSecurityContext();
+        }
+
+        public ThreadGroup getThreadGroup() {
+            debug("getThreadGroup");
+            return super.getThreadGroup();
+        }
+
+        protected boolean inClass(String name) {
+            debug("inClass: " + name);
+            return super.inClass(name);
+        }
+
+        protected boolean inClassLoader() {
+            debug("inClassLoader");
+            return super.inClassLoader();
+        }
+    }
+}

Added: openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSequence.java
URL: http://svn.apache.org/viewvc/openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSequence.java?rev=627979&view=auto
==============================================================================
--- openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSequence.java (added)
+++ openjpa/trunk/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/kernel/TestSequence.java Fri Feb 15 01:19:55 2008
@@ -0,0 +1,66 @@
+/*
+ * TestSequence.java
+ *
+ * Created on October 13, 2006, 5: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 org.apache.openjpa.persistence.kernel.common.apps.AImplB;
+
+import org.apache.openjpa.persistence.Generator;
+import org.apache.openjpa.persistence.OpenJPAEntityManager;
+
+public class TestSequence extends BaseKernelTest {
+
+    /**
+     * Creates a new instance of TestSequence
+     */
+    public TestSequence() {
+    }
+
+    public TestSequence(String name) {
+        super(name);
+    }
+
+    public void testSequence() {
+        OpenJPAEntityManager pm = getPM();
+        startTx(pm);
+        Generator seq = pm.getIdGenerator(AImplB.class);
+        assertNotNull(seq);
+        Number val = (Number) seq.next();
+        assertNotNull(val);
+        AImplB aib = new AImplB("x", val.intValue(), "y");
+        pm.persist(aib);
+
+        for (int i = 0; i < 100; i++)
+            assertEquals(((Number) pm.getIdGenerator(AImplB.class).
+                next()).longValue() + 1,
+                ((Number) pm.getIdGenerator(AImplB.class).
+                    next()).longValue());
+
+        endTx(pm);
+    }
+}



Mime
View raw message