Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SCOVector.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SCOVector.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SCOVector.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SCOVector.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,233 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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.jdo.test; + +import java.util.ArrayList; +import java.util.Vector; + +import javax.jdo.PersistenceManager; +import javax.jdo.Transaction; + +import org.apache.jdo.pc.PCCollections; +import org.apache.jdo.pc.PCPoint; +import org.apache.jdo.sco.SCOCollection; +import org.apache.jdo.test.util.JDORITestRunner; + +/** +* Tests that SCO Vector correctly performs all update operations +* in both datastore and optimistic transactions. +* +* @author Marina Vatkina +* @version 1.0.1 +*/ +public class Test_SCOVector extends Test_SCO_Base { + + /** */ + public static void main(String args[]) { + JDORITestRunner.run(Test_SCOVector.class); + } + + /** */ + public void test() { + insertObjects(); + runVectorTest(false, false); + } + + /** */ + public void testRetainValues() { + insertObjects(); + runVectorTest(false, true); + } + + /** */ + public void testOptimistic() { + insertObjects(); + runVectorTest(true, false); + } + + /** */ + public void testOptimisticRetainValues() { + insertObjects(); + runVectorTest(true, true); + } + + /** */ + protected void runVectorTest(boolean optimistic, boolean retainValues) { + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + if (debug) + logger.debug("Running " + (optimistic?"optimistic":"datastore") + + " transactions with retainValues = " + retainValues); + tx.setOptimistic(optimistic); + tx.setRetainValues(retainValues); + + ArrayList c = new ArrayList(); + PCPoint p = new PCPoint(1, 1); + c.add(p); + p = new PCPoint(2, 2); + c.add(p); + + tx.begin(); + PCCollections pcCollections = + (PCCollections) pm.getObjectById(oid_collections, true); + tx.commit(); + + tx.begin(); + Vector arr = null; + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector: ", arr, 9); + arr.add(p); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after add: ", arr, 10); + arr.remove(p); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after remove: ", arr, 9); + arr.addElement(p); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after addElement: ", arr, 10); + if (debug) logger.debug("Element added as #: " + arr.indexOf(p)); + assertEquals("Element added as #: ", 9, arr.indexOf(p)); + boolean b = arr.removeElement(p); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after removeElement: ", arr, 9); + if (debug) logger.debug("Element was removed: " + b); + assertTrue("Element not removed", b); + arr.setElementAt(p, 1); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after setElementAt: ", arr, 9); + if (debug) logger.debug("Element set as #: " + arr.indexOf(p)); + assertEquals("Element set as #: ", 1, arr.indexOf(p)); + arr.removeElementAt(1); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after removeElementAt #1: ", arr, 8); + arr.add(1, p); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after add #1: ", arr, 9); + Object o = arr.remove(1); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after remove #1: ", arr, 8); + if (debug) logger.debug("removed #1: " + o); + assertEquals("removed #1: ", p, o); + arr.addAll(c); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after addAll 2: ", arr, 10); + arr.removeAll(c); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after removeAll 2: ", arr, 8); + arr.addAll(1, c); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after addAll 2 from 1: ", arr, 10); + arr.retainAll(c); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after retainAll 2: ", arr, 2); + arr.insertElementAt(p, 1); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after insertElementAt #1: ", arr, 3); + Vector v = (Vector) arr.clone(); + v.add(p); + assertNotIsDirty("Is dirty: ", pcCollections); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after clone: ", arr, 3); + assertNullOwner("Owner of clone: ", (SCOCollection)v); + arr.removeAllElements(); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after removeAllElements: ", arr, 0); + pcCollections.setSCOVector(new Vector()); + arr = pcCollections.getSCOVector(); + o = arr.set(1, p); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after restore and set #1: ", arr, 8); + if (debug) logger.debug("Replaced #1: " + o); + assertEquals("Replaced #1: ", "Call me Ishmael.", o); + arr.clear(); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector after clear: ", arr, 0); + pcCollections.setSCOVector(new Vector()); + PCPoint pcPoint = new PCPoint(42, 99); + pcCollections.getSCOVector().add(pcPoint); + tx.commit(); + + tx.begin(); + arr = pcCollections.getSCOVector(); + assertCollectionSize("Vector restored: ", arr, 9); + tx.commit(); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + + /** */ + protected void insertObjects() { + insertAllTypes(); + } +}
Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SCO_Base.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SCO_Base.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SCO_Base.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SCO_Base.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,419 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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.jdo.test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.LinkedList; +import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.Vector; + +import javax.jdo.JDOHelper; +import javax.jdo.PersistenceManager; +import javax.jdo.Transaction; + +import org.apache.jdo.impl.sco.Freezer; +import org.apache.jdo.pc.PCCollections; +import org.apache.jdo.pc.PCPoint; +import org.apache.jdo.pc.PCSCO; +import org.apache.jdo.sco.SCO; + +/** +* This test is a base class for all SCO tests. It cannot be run itself. +* +* @author Craig Russell +*/ +public class Test_SCO_Base extends Test_Fetch { + + protected Object oid_point = null; + protected Object oid_date = null; + protected Object oid_collections = null; + + protected PCPoint pcPoint = null; + protected PCCollections pcCollections = null; + protected PCSCO pcSCO = null; + + /** this method can be called from insertObjects in subclasses */ + protected void insertDate() { + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + tx.begin(); + insertDateWithoutCommit(pm); + tx.commit(); + + oid_date = pm.getObjectId(pcSCO); + if (debug) logger.debug("inserted pcSCO: " + oid_date); + oids.add(oid_date); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + + /** Allows to commit or rollback the transaction. + * This method can be called from insertObjects in subclasses + */ + protected void insertDateWithoutCommit(PersistenceManager pm) { + pcSCO = createDate(); + if (debug) logger.debug("Before makePersistent: " + pcSCO); + pm.makePersistent(pcSCO); + if (debug) logger.debug("After makePersistent: " + pcSCO); + } + + /** this method can be called from insertObjects in subclasses */ + protected void insertAllTypes() { + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + tx.begin(); + insertAllTypesWithoutCommit(pm); + tx.commit(); + + // Next 2 statements allow this to work whether or not + // reachability or navigation work. + oid_point = pm.getObjectId(pcPoint); + oids.add(oid_point); + + oid_collections = pm.getObjectId(pcCollections); + if (debug) + logger.debug("inserted pcCollections: " + oid_collections); + oids.add(oid_collections); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + + /** Allows to commit or rollback the transaction. + * this method can be called from insertObjects in subclasses + */ + protected void insertAllTypesWithoutCommit(PersistenceManager pm) { + + pcPoint = createPoint(); + pcCollections = createAllTypes(pcPoint); + if (debug) logger.debug("Before makePersistent: " + pcCollections); + + // Next statement allows this to work whether or not reachability or + // navigation work. + pm.makePersistent(pcPoint); + + // The order of this and the previous statements is important! + pm.makePersistent(pcCollections); + + if (debug) logger.debug("After makePersistent: " + pcCollections); + + } + + /** */ + protected PCSCO createDate() { + PCSCO pcSCO = new PCSCO(); + pcSCO.init(); + // Note, the value of the specified Date is changed by setSCODate + pcSCO.setSCODate(new Date()); + return pcSCO; + } + + /** */ + protected PCPoint createPoint() { + return new PCPoint(42, 99); + } + + /** */ + protected PCCollections createAllTypes(PCPoint pcPoint) { + PCCollections pcCollections = new PCCollections(); + pcCollections.init(); + + ArrayList al = new ArrayList(3); + pcCollections.setSCOArrayList(al); + + Vector v = new Vector(3); + pcCollections.setSCOVector(v); + + HashSet hs = new HashSet(3); + pcCollections.setSCOHashSet(hs); + + LinkedList ll = new LinkedList(); + pcCollections.setSCOLinkedList(ll); + + HashMap hm = new HashMap(3); + pcCollections.setSCOHashMap(hm); + + Hashtable ht = new Hashtable(3); + pcCollections.setSCOHashtable(ht); + + TreeMap tm = new TreeMap(); + pcCollections.setSCOTreeMap(tm); + + TreeSet ts = new TreeSet(); + pcCollections.setSCOTreeSet(ts); + + pcCollections.addPoint(pcPoint); + + return pcCollections; + } + + /** */ + protected void assertEqualsPCSCO(PCSCO expected, Object actual) + { + assertNotNull("Actual instance is null", actual); + assertTrue("Expected PCSCO instance; instance has type " + + actual.getClass().getName(), (actual instanceof PCSCO)); + + // Note, this implementation + // - assumes all _nullXXX fields are null + // - assumes all _XXX fields are not null in this instance + // - compares the time for all date fields + + PCSCO other = (PCSCO)actual; + assertEquals("Wrong _date value", expected._date, other._date); + assertEquals("Wrong _nullDate value", + expected._nullDate, other._nullDate); + assertEquals("Wrong _scoDate value", expected._scoDate, other._scoDate); + assertEquals("Wrong _nullSCODate value", + expected._nullSCODate, other._nullSCODate); + assertEquals("Wrong _sqlDate value", expected._sqlDate, other._sqlDate); + assertEquals("Wrong _nullSqlDate value", + expected._nullSqlDate, other._nullSqlDate); + assertEquals("Wrong _bigDecimal value", + expected._bigDecimal, other._bigDecimal); + assertEquals("Wrong _nullBigInteger value", + expected._nullBigInteger, other._nullBigInteger); + assertEquals("Wrong _bigInteger value", + expected._bigInteger, other._bigInteger); + assertEquals("Wrong _nullBigInteger value", + expected._nullBigInteger, other._nullBigInteger); + assertEquals("Wrong _bitSet value", expected._bitSet, other._bitSet); + assertEquals("Wrong _nullBitSet value", + expected._nullBitSet, other._nullBitSet); + assertEquals("Wrong _locale value", expected._locale, other._locale); + assertEquals("Wrong _nullLocale value", + expected._nullLocale, other._nullLocale); + } + + /** */ + protected void assertEqualsPCCollections(PCCollections expected, + Object actual) + { + assertNotNull("Actual instance is null", actual); + assertTrue("Expected PCCollections instance; instance has type " + + actual.getClass().getName(), + (actual instanceof PCCollections)); + + PCCollections other = (PCCollections)actual; + + assertEqualsCollection("Wrong _arrayList value", + expected._arrayList, other._arrayList); + assertEquals("Wrong _emptyArrayList value", + expected._emptyArrayList, other._emptyArrayList); + assertEquals("Wrong _nullArrayList value", + expected._nullArrayList, other._nullArrayList); + assertEqualsCollection("Wrong _sco_arrayList value", + expected._sco_arrayList, other._sco_arrayList); + assertEquals("Wrong _sco_emptyArrayList value", + expected._sco_emptyArrayList, other._sco_emptyArrayList); + assertEquals("Wrong _sco_nullArrayList value", + expected._sco_nullArrayList, other._sco_nullArrayList); + assertEqualsCollection("Wrong _vector value", + expected._vector, other._vector); + assertEquals("Wrong _emptyVector value", + expected._emptyVector, other._emptyVector); + assertEquals("Wrong _nullVector value", + expected._nullVector, other._nullVector); + assertEqualsCollection("Wrong _sco_vector value", + expected._sco_vector, other._sco_vector); + assertEquals("Wrong _sco_emptyVector value", + expected._sco_emptyVector, other._sco_emptyVector); + assertEquals("Wrong _sco_nullVector value", + expected._sco_nullVector, other._sco_nullVector); + assertEqualsMap("Wrong _hashMap value", + expected._hashMap, other._hashMap); + assertEquals("Wrong _emptyHashMap value", + expected._emptyHashMap, other._emptyHashMap); + assertEquals("Wrong _nullHashMap value", + expected._nullHashMap, other._nullHashMap); + assertEqualsMap("Wrong _sco_hashMap value", + expected._sco_hashMap, other._sco_hashMap); + assertEquals("Wrong _sco_emptyHashMap value", + expected._sco_emptyHashMap, other._sco_emptyHashMap); + assertEquals("Wrong _sco_nullHashMap value", + expected._sco_nullHashMap, other._sco_nullHashMap); + assertEqualsMap("Wrong _hashtable value", + expected._hashtable, other._hashtable); + assertEquals("Wrong _sco_emptyHashtable value", + expected._sco_emptyHashtable, other._sco_emptyHashtable); + assertEquals("Wrong _sco_nullHashtable value", + expected._sco_nullHashtable, other._sco_nullHashtable); + assertEqualsCollection("Wrong _hashSet value", + expected._hashSet, other._hashSet); + assertEquals("Wrong _emptyHashSet value", + expected._emptyHashSet, other._emptyHashSet); + assertEquals("Wrong _nullHashSet value", + expected._nullHashSet, other._nullHashSet); + assertEqualsCollection("Wrong _sco_hashSet value", + expected._sco_hashSet, other._sco_hashSet); + assertEquals("Wrong _sco_emptyHashSet value", + expected._sco_emptyHashSet, other._sco_emptyHashSet); + assertEquals("Wrong _sco_nullHashSet value", + expected._sco_nullHashSet, other._sco_nullHashSet); + assertEqualsCollection("Wrong _linkedList value", + expected._linkedList, other._linkedList); + assertEquals("Wrong _emptyLinkedList value", + expected._emptyLinkedList, other._emptyLinkedList); + assertEquals("Wrong _nullLinkedList value", + expected._nullLinkedList, other._nullLinkedList); + assertEqualsCollection("Wrong _sco_linkedList value", + expected._sco_linkedList, other._sco_linkedList); + assertEquals("Wrong _sco_emptyLinkedList value", + expected._sco_emptyLinkedList, other._sco_emptyLinkedList); + assertEquals("Wrong _sco_nullLinkedList value", + expected._sco_nullLinkedList, other._sco_nullLinkedList); + assertEqualsMap("Wrong _treeMap value", + expected._treeMap, other._treeMap); + assertEquals("Wrong _emptyTreeMap value", + expected._emptyTreeMap, other._emptyTreeMap); + assertEquals("Wrong _nullTreeMap value", + expected._nullTreeMap, other._nullTreeMap); + assertEqualsMap("Wrong _sco_treeMap value", + expected._sco_treeMap, other._sco_treeMap); + assertEquals("Wrong _sco_emptyTreeMap value", + expected._sco_emptyTreeMap, other._sco_emptyTreeMap); + assertEquals("Wrong _sco_nullTreeMap value", + expected._sco_nullTreeMap, other._sco_nullTreeMap); + assertEqualsCollection("Wrong _treeSet value", + expected._treeSet, other._treeSet); + assertEquals("Wrong _emptyTreeSet value", + expected._emptyTreeSet, other._emptyTreeSet); + assertEquals("Wrong _nullTreeSet value", + expected._nullTreeSet, other._nullTreeSet); + assertEqualsCollection("Wrong _sco_treeSet value", + expected._sco_treeSet, other._sco_treeSet); + assertEquals("Wrong _sco_emptyTreeSet value", + expected._sco_emptyTreeSet, other._sco_emptyTreeSet); + assertEquals("Wrong _sco_nullTreeSet value", + expected._sco_nullTreeSet, other._sco_nullTreeSet); + } + + /** */ + protected void assertEqualsCollection(String msg, Collection expected, + Collection actual) + { + if (expected == null && actual == null) + return; + int expectedSize = expected.size(); + int actualSize = actual.size(); + assertEquals(msg + " collection size differs ", expectedSize, actualSize); + Object[] expectedFrozen = Freezer.freeze(expected, expectedSize); + Object[] actualFrozen = Freezer.freeze(actual, actualSize); + for (int i = 0; i < expectedSize; i++) { + Object expectedElement = expectedFrozen[i]; + Object actualElement = actualFrozen[i]; + assertEqualsExtended(msg + " element", expectedFrozen[i], + actualFrozen[i]); + } + } + + /** */ + protected void assertEqualsMap(String msg, Map expected, Map actual) + { + if (expected == null && actual == null) + return; + int expectedSize = expected.size(); + int actualSize = actual.size(); + assertEquals(msg + " map size differs ", expectedSize, actualSize); + Map.Entry[] expectedFrozen = Freezer.freeze(expected, expectedSize); + Map.Entry[] actualFrozen = Freezer.freeze(actual, actualSize); + for (int i = 0; i < expectedSize; i++) { + assertEqualsExtended(msg + " key", expectedFrozen[i].getKey(), actualFrozen[i].getKey()); + assertEqualsExtended(msg + " value", expectedFrozen[i].getValue(), actualFrozen[i].getValue()); + } + } + + /** */ + protected void assertEqualsExtended(String msg, Object expected, Object actual) { + if (expected == null && actual == null) + return; + if ((expected instanceof Collection) && (actual instanceof Collection)) + assertEqualsCollection(msg, (Collection)expected, (Collection)actual); + else if ((expected instanceof Map) && (actual instanceof Map)) + assertEqualsMap(msg, (Map)expected, (Map)actual); + else if ((expected instanceof Date) && (actual instanceof Date)) + assertEquals(msg, ((Date)expected).getTime(), ((Date)actual).getTime()); + else if ((expected instanceof Object[]) && (actual instanceof Object[])) + assertTrue(msg, Arrays.equals((Object[])expected, (Object[])actual)); + else if ((expected instanceof boolean[]) && (actual instanceof boolean[])) + assertTrue(msg, Arrays.equals((boolean[])expected, (boolean[])actual)); + else if ((expected instanceof byte[]) && (actual instanceof byte[])) + assertTrue(msg, Arrays.equals((byte[])expected, (byte[])actual)); + else if ((expected instanceof char[]) && (actual instanceof char[])) + assertTrue(msg, Arrays.equals((char[])expected, (char[])actual)); + else if ((expected instanceof int[]) && (actual instanceof int[])) + assertTrue(msg, Arrays.equals((int[])expected, (int[])actual)); + else if ((expected instanceof long[]) && (actual instanceof long[])) + assertTrue(msg, Arrays.equals((long[])expected, (long[])actual)); + else if ((expected instanceof float[]) && (actual instanceof float[])) + assertTrue(msg, Arrays.equals((float[])expected, (float[])actual)); + else if ((expected instanceof double[]) && (actual instanceof double[])) + assertTrue(msg, Arrays.equals((double[])expected, (double[])actual)); + else if ((expected instanceof Object[]) && (actual instanceof Object[])) + assertTrue(msg, Arrays.equals((Object[])expected, (Object[])actual)); + else + assertEquals(msg, expected, actual); + } + + /** */ + protected void assertCollectionSize(String msg, + Collection collection, int expected) { + int size = collection == null ? 0 : collection.size(); + if (debug) logger.debug(msg + size); + assertEquals("Wrong size of " + msg, expected, size); + } + + /** */ + protected void assertMapSize(String msg, Map map, int expected) { + int size = map == null ? 0 : map.size(); + if (debug) logger.debug(msg + size); + assertEquals("Wrong size of " + msg, expected, size); + } + + /** */ + protected void assertNotIsDirty(String msg, Object pc) { + boolean isDirty = JDOHelper.isDirty(pc); + if (debug) logger.debug(msg + isDirty); + assertFalse("Unexpected dirty instance " + pc, isDirty); + } + + /** */ + protected void assertNullOwner(String msg, SCO sco) { + Object owner = sco.getOwner(); + if (debug) logger.debug(msg + owner); + assertNull(msg, owner); + } +} Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerialPMs.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerialPMs.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerialPMs.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerialPMs.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,96 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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.jdo.test; + +import javax.jdo.PersistenceManager; +import javax.jdo.Transaction; + +import org.apache.jdo.pc.PointFactory; +import org.apache.jdo.test.util.AbstractTest; +import org.apache.jdo.test.util.Factory; +import org.apache.jdo.test.util.JDORITestRunner; + +/** +* Tests that we can insert objects into a database. Creates objects as per +* Test_ActivateClass, and writes their OIDs into a file. +* Test_FetchInserted reads that file, and fetches the objects by OID. +* +* Both this and Test_Insert can be instructed (via the "insert" JVM property) +* to insert some number of objects. If that is greater than one, Test_Insert +* inserts all its instances using one PersistenceManager. Test_SerialPMs, on +* the other hand, uses a different PM for each insert. +* +* @author Dave Bristor +*/ +public class Test_SerialPMs extends AbstractTest { + /** */ + public static void main(String args[]) { + JDORITestRunner.run(Test_SerialPMs.class); + } + + /** */ + protected void insertObjects() { + PersistenceManager[] pms = new PersistenceManager[numInsert]; + Transaction[] txs = new Transaction[numInsert]; + + try { + if (debug) logger.debug("INSERT"); + for (int i = 0; i < numInsert; i++) { + pms[i] = pmf.getPersistenceManager(); + txs[i] = pms[i].currentTransaction(); + txs[i].begin(); + } + + for (int i = 0; i < numInsert; i++) { + Object pc = factory.create(i); + pms[i].makePersistent(pc); + } + for (int i = 0; i < numInsert; i++) { + txs[i].commit(); + } + } + finally { + for (int i = 0; i < numInsert; i++) { + Transaction tx = txs[i]; + if (tx != null && tx.isActive()) + tx.rollback(); + PersistenceManager pm = pms[i]; + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + if (debug) logger.debug("inserted " + numInsert + " objects"); + } + + protected int getDefaultInsert() { + return 50; + } + + /** + * Inserts some number of objects in the database + */ + public void test() { + insertObjects(); + checkExtent(factory.getPCClass(), numInsert); + } + + protected Factory getFactory(int verify) { + PointFactory rc = new PointFactory(); + rc.setVerify(verify); + return rc; + } +} Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Serialize.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Serialize.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Serialize.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Serialize.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,93 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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.jdo.test; + +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import javax.jdo.PersistenceManager; +import javax.jdo.Transaction; + +import org.apache.jdo.pc.PCPoint; +import org.apache.jdo.test.util.AbstractTest; +import org.apache.jdo.test.util.JDORITestRunner; + +/** +* Tests that we can serialize PCPoint instances and read them back correctly. +* +* @author Marina Vatkina +*/ +public class Test_Serialize extends AbstractTest { + Object o = null; + + /** */ + public static void main(String args[]) { + JDORITestRunner.run(Test_Serialize.class); + } + + /** */ + public void test() throws Exception { + runTestSerialization(false); + } + + /** */ + public void testRetainValues() throws Exception { + runTestSerialization(true); + } + + + /** Inserts a point instance, and serializes it. */ + protected void runTestSerialization(boolean retainValues) throws Exception { + PersistenceManager pm = null; + Transaction tx = null; + try { + if (debug) logger.debug("\nINSERT"); + + pm = pmf.getPersistenceManager(); + tx = pm.currentTransaction(); + tx.setRetainValues(retainValues); + tx.begin(); + + PCPoint p = new PCPoint(1, 10); + pm.makePersistent(p); + if (debug) logger.debug("Created: " + p); + + tx.commit(); + + if (debug) + logger.debug("\nSERIALIZE " + ((retainValues)?"P-NONTX":"HOLLOW")); + + String f = "myfile.tmp"; + ObjectOutputStream out = getObjectOutputStream(f); + out.writeObject(p); + out.flush(); + if (debug) logger.debug("Wrote: " + p); + + ObjectInputStream in = getObjectInputStream(f); + PCPoint p1 = (PCPoint)in.readObject(); + if (debug) logger.debug("Read: " + p1); + assertEquals("Unexpected deserialzed object", p, p1); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + +} Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerializeComplex.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerializeComplex.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerializeComplex.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerializeComplex.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,225 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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.jdo.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import javax.jdo.PersistenceManager; +import javax.jdo.Transaction; + +import org.apache.jdo.pc.serializable.PCClass1; +import org.apache.jdo.pc.serializable.PCClass2A; +import org.apache.jdo.pc.serializable.PCClass2B; +import org.apache.jdo.pc.serializable.PCSub3; +import org.apache.jdo.pc.serializable.PCSub4A; +import org.apache.jdo.pc.serializable.PCSub4B; +import org.apache.jdo.pc.serializable.PCSuper; +import org.apache.jdo.test.util.AbstractTest; +import org.apache.jdo.test.util.JDORITestRunner; +/** +* Tests that the enhancer adds method writeObject or adds a call of +* jdoPreSerialize to an existing method writeObject or writeReplace. +* +* @author Michael Bouschen +*/ +public class Test_SerializeComplex extends AbstractTest { + + /** name of the writeObject method */ + public static String WRITE_OBJECT_NAME = "writeObject"; + /** parameter types of the writeObject method */ + public static Class[] WRITE_OBJECT_PARAMS = { ObjectOutputStream.class }; + + /** */ + public static void main(String args[]) { + JDORITestRunner.run(Test_SerializeComplex.class); + } + + /** + * This method checks whether the enhanced pc classes have or have not + * the method writeObject. + */ + public void testSerializationSupportMethods() + { + // PCClass1 must have writeObject + try { + PCClass1.class.getDeclaredMethod(WRITE_OBJECT_NAME, WRITE_OBJECT_PARAMS); + if (debug) + logger.debug("OK: Class PCClass1 has method " + WRITE_OBJECT_NAME); + } + catch (NoSuchMethodException ex) { + fail("ERROR: missing method " + WRITE_OBJECT_NAME + " in class PCClass1"); + } + + // PCClass2A must have writeObject + try { + PCClass2A.class.getDeclaredMethod(WRITE_OBJECT_NAME, WRITE_OBJECT_PARAMS); + if (debug) + logger.debug("OK: Class PCClass2A has method " + WRITE_OBJECT_NAME); + } + catch (NoSuchMethodException ex) { + fail("ERROR: missing method " + WRITE_OBJECT_NAME + " in class PCClass2A"); + } + + // PCClass2B must NOT have writeObject + try { + PCClass2B.class.getDeclaredMethod(WRITE_OBJECT_NAME, WRITE_OBJECT_PARAMS); + fail("ERROR: Class PCClass1 must not have method " + WRITE_OBJECT_NAME); + } + catch (NoSuchMethodException ex) { + if (debug) + logger.debug("OK: Class PCClass2B does not have method " + WRITE_OBJECT_NAME); + } + + // PCSuper must NOT have writeObject + try { + PCSuper.class.getDeclaredMethod(WRITE_OBJECT_NAME, WRITE_OBJECT_PARAMS); + fail("ERROR: Class PCSuper must not have method " + WRITE_OBJECT_NAME); + } + catch (NoSuchMethodException ex) { + if (debug) + logger.debug("OK: Class PCSuper does not have method " + WRITE_OBJECT_NAME); + } + // PCSub4A must have writeObject + try { + PCSub4A.class.getDeclaredMethod(WRITE_OBJECT_NAME, WRITE_OBJECT_PARAMS); + if (debug) + logger.debug("OK: Class PCSub4A has method " + WRITE_OBJECT_NAME); + } + catch (NoSuchMethodException ex) { + fail("ERROR: missing method " + WRITE_OBJECT_NAME + " in class PCSub4A"); + } + + // PCSub4B must NOT have writeObject + try { + PCSub4B.class.getDeclaredMethod(WRITE_OBJECT_NAME, WRITE_OBJECT_PARAMS); + fail("ERROR: Class PCSub4B must not have method " + WRITE_OBJECT_NAME); + } + catch (NoSuchMethodException ex) { + if (debug) + logger.debug("OK: Class PCSub4B does not have method " + WRITE_OBJECT_NAME); + } + } + + /** + * This method creates pc instances, commits the transaction and then + * seralizes the pc instances. + */ + public void testSerialization() throws Exception { + PersistenceManager pm = null; + Transaction tx = null; + try { + if (debug) logger.debug("\nINSERT"); + pm = pmf.getPersistenceManager(); + tx = pm.currentTransaction(); + tx.setRetainValues(false); + + tx.begin(); + PCClass1 o1 = new PCClass1(1, 1); + pm.makePersistent(o1); + Object o1Oid = pm.getObjectId(o1); + PCClass2A o2 = new PCClass2A(2, 2); + pm.makePersistent(o2); + Object o2Oid = pm.getObjectId(o2); + PCClass2B o3 = new PCClass2B(3, 3); + pm.makePersistent(o3); + Object o3Oid = pm.getObjectId(o3); + PCSub3 o4 = new PCSub3(4, 4, "4", "4"); + pm.makePersistent(o4); + Object o4Oid = pm.getObjectId(o4); + PCSub4A o5 = new PCSub4A(5, 5, "5", "5"); + pm.makePersistent(o5); + Object o5Oid = pm.getObjectId(o5); + PCSub4B o6 = new PCSub4B(6, 6, "6", "6"); + pm.makePersistent(o6); + Object o6Oid = pm.getObjectId(o6); + tx.commit(); tx = null; + pm.close(); pm = null; + + if (debug) logger.debug("\nSERIALIZE HOLLOW instances"); + doSerialize(o1Oid, false, new PCClass1(1, 0)); + doSerialize(o1Oid, true, new PCClass1(Integer.MIN_VALUE, 0)); + doSerialize(o2Oid, false, new PCClass2A(2, 0)); + doSerialize(o2Oid, true, new PCClass2A(Integer.MIN_VALUE, 0)); + doSerialize(o3Oid, false, new PCClass2B(3, 0)); + doSerialize(o3Oid, true, new PCClass2B(Integer.MIN_VALUE, 0)); + doSerialize(o4Oid, false, new PCSub3(Integer.MIN_VALUE, + Integer.MIN_VALUE, "4", null)); + doSerialize(o4Oid, true, new PCSub3(Integer.MIN_VALUE, + Integer.MIN_VALUE, "empty", null)); + doSerialize(o5Oid, false, new PCSub4A(Integer.MIN_VALUE, + Integer.MIN_VALUE, "5", null)); + doSerialize(o5Oid, true, new PCSub4A(Integer.MIN_VALUE, + Integer.MIN_VALUE, "empty", null)); + doSerialize(o6Oid, false, new PCSub4B(Integer.MIN_VALUE, + Integer.MIN_VALUE, "6", null)); + doSerialize(o6Oid, true, new PCSub4B(Integer.MIN_VALUE, + Integer.MIN_VALUE, "empty", null)); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + + /** + * + */ + protected void doSerialize(Object oid, + boolean makeTransient, + Object expected) throws Exception + { + PersistenceManager pm = null; + try { + // get the object + pm = pmf.getPersistenceManager(); + Object o = pm.getObjectById(oid, false); + + // makeTransient? + if (makeTransient) + pm.makeTransient(o); + + // serialize + ByteArrayOutputStream bout = new ByteArrayOutputStream (); + ObjectOutputStream oout = new ObjectOutputStream (bout); + oout.writeObject(o); + oout.flush (); + if (debug) logger.debug("Wrote: " + o); + byte[] bytes = bout.toByteArray(); + oout.close (); + + // deserialize + ByteArrayInputStream bin = new ByteArrayInputStream (bytes); + ObjectInputStream oin = new ObjectInputStream (bin); + Object read = oin.readObject(); + if (debug) logger.debug("Read: " + read); + oin.close (); + + assertEquals("Unexpected deserialized object", expected, read); + } + finally { + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + + +} Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerializeInher.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerializeInher.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerializeInher.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_SerializeInher.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,109 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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.jdo.test; + +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +import javax.jdo.PersistenceManager; +import javax.jdo.Transaction; + +import org.apache.jdo.pc.PCFullTimeEmployee1; +import org.apache.jdo.test.util.JDORITestRunner; + +/** +* Tests that we can serialize PC instances with classes that extend another +* PC class and read them back correctly. +* +* @author Marina Vatkina +*/ +public class Test_SerializeInher extends Test_ActivateClass { + Object o = null; + + private static GregorianCalendar born; + private static GregorianCalendar hired; + + static { + born = new GregorianCalendar(TimeZone.getTimeZone("America/New_York")); + born.set(1969, 7, 20); + hired = new GregorianCalendar(TimeZone.getTimeZone("America/New_York")); + hired.set(1982, 5, 5); + } + + /** */ + public static void main(String args[]) { + JDORITestRunner.run(Test_SerializeInher.class); + } + + /** */ + public void test() throws Exception { + runTestSerialization(false); + } + + /** */ + public void testRetainValues() throws Exception { + runTestSerialization(true); + } + + /** Inserts a point instance, and serializes it. */ + protected void runTestSerialization(boolean retainValues) throws Exception { + PersistenceManager pm = null; + Transaction tx = null; + try { + if (debug) logger.debug("\nINSERT"); + pm = pmf.getPersistenceManager(); + tx = pm.currentTransaction(); + tx.setRetainValues(retainValues); + tx.begin(); + + PCFullTimeEmployee1 p = new PCFullTimeEmployee1( + "Scott", "McNealy", born.getTime(), 1L, hired.getTime(), + 200000.00, 15); + + pm.makePersistent(p); + if (debug) logger.debug("Created: " + p); + tx.commit(); + + if (debug) + logger.debug("\nSERIALIZE " + + ((retainValues)? "P-NONTX" : "HOLLOW")); + + String f = "myfile.tmp"; + + ObjectOutputStream out = getObjectOutputStream(f); + out.writeObject(p); + out.flush(); + if (debug) logger.debug("Wrote: " + p); + + ObjectInputStream in = getObjectInputStream(f); + PCFullTimeEmployee1 p1 = (PCFullTimeEmployee1)in.readObject(); + + if (debug) logger.debug("Read: " + p1); + assertEquals("Unexpected string repr of deserialized object", + "PCFullTimeEmployee1: Emp: McNealy, Scott, id=1, born 20/Aug/1969, hired 5/Jun/1982 $200000.0 manager: none dept: none emps: 0 insurance: null range: 15", + p1.toString()); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } +} Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_StringOID.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_StringOID.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_StringOID.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_StringOID.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,74 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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. + */ + +/* + * Test_StringOID.java + * + * Created on August 22, 2001, 10:49 AM + */ + +package org.apache.jdo.test; + +/** + * + * @author Craig Russell + */ +import java.util.Iterator; + +import javax.jdo.JDOHelper; +import javax.jdo.PersistenceManager; + +import org.apache.jdo.test.util.JDORITestRunner; + +/** +* Test getting OIDs and creating new OIDs from them. +*/ +public class Test_StringOID extends EmpDeptSupport { + + /** */ + public static void main(String args[]) { + JDORITestRunner.run(Test_StringOID.class); + } + + /** The idea is that we're going to write a bunch of stuff to a data + * output stream, then read it back in; we should get the same data + * back. + */ + public void test() { + insertObjects(); + } + + /** This method can be overridden by a subclass to perform special checks. + */ + protected void checkObjects(PersistenceManager pm) { + if (debug) logger.debug ("Verifying OIDs of all instances"); + for (Iterator it = persistentInstances.iterator(); it.hasNext();) { + Object oldObject = it.next(); + Object oldOid = JDOHelper.getObjectId(oldObject); + Object newOid = pm.newObjectIdInstance(oldObject.getClass(), oldOid.toString()); + Object newObject = pm.getObjectById(newOid, false); + if (debug) { + logger.debug (" ---------------"); + logger.debug (" old object id: " + oldOid.toString()); + logger.debug (" new object id: " + newOid.toString()); + logger.debug (" old object: " + oldObject.toString()); + logger.debug (" new object: " + newObject.toString()); + } + assertNotNull("Null returned by getObjectById", newObject); + assertSame("Mismatch between old and new objects", oldObject, newObject); + } + } +} Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Stroke.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Stroke.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Stroke.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Stroke.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,127 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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.jdo.test; + +import java.util.ArrayList; + +import javax.jdo.JDOHelper; +import javax.jdo.PersistenceManager; +import javax.jdo.Transaction; + +import org.apache.jdo.pc.PCPoint; +import org.apache.jdo.pc.PCStroke; +import org.apache.jdo.test.util.JDORITestRunner; + +/** +* Test a PC that contains a Collection of PC's. +* +* @author Dave Bristor +*/ +public class Test_Stroke extends Test_Fetch { + + /** */ + public static void main(String args[]) { + JDORITestRunner.run(Test_Stroke.class); + } + + /** */ + public void test() throws Exception { + insertObjects(); + readObjects(); + checkExtent(PCPoint.class, 2); + checkExtent(PCStroke.class, 1); + } + + /** */ + protected void insertObjects() { + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + tx.begin(); + + PCPoint p1 = new PCPoint(1, 3); + PCPoint p2 = new PCPoint(13, 42); + ArrayList points = new ArrayList(); + points.add(p1); + points.add(p2); + PCStroke pcStroke = new PCStroke(points); + + if (debug) logger.debug("Before insert: " + pcStroke); + // Next 2 statements allow this test to work whether or not + // reachability or navigation work. + pm.makePersistent(p1); + pm.makePersistent(p2); + + pm.makePersistent(pcStroke); + tx.commit(); + + // Next 4 statements allow this test to work whether or not + // reachability or navigation work. + Object oid_p1 = JDOHelper.getObjectId(p1); + Object oid_p2 = JDOHelper.getObjectId(p2); + oids.add(oid_p1); + oids.add(oid_p2); + + Object oid1 = JDOHelper.getObjectId(pcStroke); + if (debug) logger.debug("inserted pcStroke: " + oid1); + oids.add(oid1); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + + /** + * redefine verify called by readObjects to check whether the read + * instance is correct. + */ + protected void verify(int i, Object pc) { + if (debug) logger.debug("verify (i = " + i + ") " + pc); + PCPoint p1 = null; + PCPoint p2 = null; + // PCPoint and PCRefArrays do not redefine equals, + // so use the string representation. + switch(i) { + case 0 : + p1 = new PCPoint(1, 3); + assertEquals("Wrong instance returned from datastore", + p1.toString(), pc.toString()); + break; + case 1: + p2 = new PCPoint(13, 42); + assertEquals("Wrong instance returned from datastore", + p2.toString(), pc.toString()); + break; + case 2: + p1 = new PCPoint(1, 3); + p2 = new PCPoint(13, 42); + ArrayList points = new ArrayList(); + points.add(p1); + points.add(p2); + PCStroke pcStroke = new PCStroke(points); + assertEquals("Wrong instance returned from datastore", + pcStroke.toString(), pc.toString()); + break; + default: + fail("Wrong number of inserted objects, expected three"); + break; + } + } +} Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Update.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Update.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Update.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_Update.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,168 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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.jdo.test; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.jdo.Extent; +import javax.jdo.JDOHelper; +import javax.jdo.PersistenceManager; +import javax.jdo.Transaction; + +import org.apache.jdo.pc.PCPoint; +import org.apache.jdo.pc.PointFactory; +import org.apache.jdo.test.util.AbstractTest; +import org.apache.jdo.test.util.Factory; +import org.apache.jdo.test.util.JDORITestRunner; + +/** +* Tests that we can update objects in a database. Reads an extent of PCPoint +* objects, and set the coordinate values in them to all be x = 555, y = 1212. +* +* @author Dave Bristor +*/ +public class Test_Update extends AbstractTest { + + /** */ + public static void main(String args[]) { + JDORITestRunner.run(Test_Update.class); + } + + /** */ + public void test() throws Exception { + insertObjects(); + update(false); + checkExtent(factory.getPCClass(), numInsert); + } + + /** */ + public void testOptimistic() throws Exception { + insertObjects(); + update(true); + checkExtent(factory.getPCClass(), numInsert); + } + + // Gets an extent of points, and changes them. + protected void update(boolean optimistic) { + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + if (debug) + logger.debug("UPDATE in " + (optimistic?"OPTIMISTIC":"DATASTORE") + + " Transaction"); + tx.setOptimistic(optimistic); + tx.setNontransactionalRead(true); + + tx.begin(); + Extent e = pm.getExtent(PCPoint.class, false); + + // Increase the existing values by a well known (phone) number + // Use ArrayList to store objects. This allows to verify fields + // without going to the database. + List arr = new ArrayList(); + List oids = new ArrayList(); + int count = 0; + for (Iterator i = PCPoint.getSortedIterator(e.iterator()); i.hasNext();) { + PCPoint p = (PCPoint)i.next(); + arr.add(p); + oids.add(pm.getObjectId(p)); + + // Change every *other* value + if (count++ % 2 == 1) { + continue; + } + + int x = p.getX() + 555; + Integer yi = p.getY(); + int y = 0; + if (null != yi) { // should not happen, but ignore it and continue + y = yi.intValue(); + } + y += 1212; + + if (debug) logger.debug("updated to x=" + x + ", y=" + y + ": " + p); + + p.setX(x); + p.setY(new Integer(y)); + assertTrue("IsDirty: ", JDOHelper.isDirty(p)); + assertEquals("getX before commit", x, p.getX()); + assertEquals("getY before commit", new Integer(y), p.getY()); + } + tx.commit(); tx = null; + + // verify updated values in same pm + + count = 0; + for (Iterator i = arr.iterator(); i.hasNext();) { + PCPoint p = (PCPoint)i.next(); + verifyPCPoint(p, count); + count++; + } + pm.close(); pm = null; + + // re-read objects in a new pm and verify updated values + + pm = pmf.getPersistenceManager(); + tx = pm.currentTransaction(); + tx.begin(); + count = 0; + for (Iterator i = oids.iterator(); i.hasNext();) { + PCPoint p = (PCPoint)pm.getObjectById(i.next(), true); + verifyPCPoint(p, count); + count++; + } + tx.commit(); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + + /** */ + private void verifyPCPoint(PCPoint p, int count) + { + if (debug) logger.debug("verify " + p); + assertFalse("isDirty after commit", JDOHelper.isDirty(p)); + assertFalse("isDeleted after commit", JDOHelper.isDeleted(p)); + int x = count; + int y = count; + if (count % 2 != 1) { + x += 555; + y += 1212; + } + assertEquals("getX after rollback", x, p.getX()); + assertEquals("getY after rollback", new Integer(y), p.getY()); + } + + /** */ + protected Factory getFactory(int verify) { + PointFactory rc = new PointFactory(); + rc.setVerify(verify); + return rc; + } + + /** */ + protected int getDefaultInsert() + { + return 5; + } +} Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_UserHashCode.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_UserHashCode.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_UserHashCode.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_UserHashCode.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,184 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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.jdo.test; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + +import javax.jdo.Extent; +import javax.jdo.PersistenceManager; +import javax.jdo.Transaction; + +import org.apache.jdo.pc.PCCollection; +import org.apache.jdo.pc.PCId; +import org.apache.jdo.test.util.AbstractTest; +import org.apache.jdo.test.util.JDORITestRunner; + +/** +* +* See bugid 4833532. Tests that a Set/Map containing PC instances which have +* a user-supplied hashCode() referencing persistent fields works. +* +* @author Dave Bristor +* @version 1.0.1 +*/ +public class Test_UserHashCode extends AbstractTest { + + private static final int NUMBER_TO_INITIALIZE = 2; + + private static final int NUMBER_TO_ADD = 2; + + /** */ + public static void main(String args[]) { + JDORITestRunner.run(Test_UserHashCode.class); + } + + /** */ + public void test() { + populate(); + update(false); + update(true); + traverse(); + } + + /** Traverse an extent of objects, printing each one along the way. */ + protected void traverse() { + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + tx.setOptimistic(false); + + if (debug) logger.debug("Begin traverse"); + + tx.begin(); + + if (debug) logger.debug("Traverse: getExtent"); + Extent e = pm.getExtent(PCCollection.class, true); + + if (debug) + logger.debug("Traverse: begin iteration of PCCollection Extent"); + int nrOfPCs = 0; + int nrOfSetElements = 0; + int nrOfMapEntries = 0; + for (Iterator i = e.iterator(); i.hasNext();) { + PCCollection c = (PCCollection)i.next(); + if (debug) logger.debug(c.toString()); + nrOfPCs++; + Iterator j = c.getSet().iterator(); + while (j.hasNext()) { + Object o = j.next(); + if (debug) logger.debug("Set element: " + o.toString()); + nrOfSetElements++; + } + assertEquals("Wrong number of set elements", + (NUMBER_TO_INITIALIZE + NUMBER_TO_ADD * 2), + nrOfSetElements); + + Iterator k = c.getMap().entrySet().iterator(); + while (k.hasNext()) { + Map.Entry p = (Map.Entry)k.next(); + if (debug) + logger.debug("Map entry: " + p.getKey()+ ";" + + p.getValue()); + nrOfMapEntries++; + } + assertEquals("Wrong number of set elements", + (NUMBER_TO_INITIALIZE + NUMBER_TO_ADD * 2), + nrOfSetElements); + } + assertEquals("Wrong number of PCCollection instances", 1, nrOfPCs); + + tx.commit(); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + + /** Traverse an extent of objects, updating each one along the way. */ + protected void update(boolean optimistic) { + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + if (debug) + logger.debug("Running " + (optimistic?"optimistic":"datastore") + + " transactions."); + tx.setOptimistic(optimistic); + + if (debug) logger.debug("Begin update"); + + tx.begin(); + + if (debug) logger.debug("Update: getExtent"); + Extent e = pm.getExtent(PCCollection.class, true); + + if (debug) logger.debug("Update: begin iteration for update"); + for (Iterator i = e.iterator(); i.hasNext();) { + if (debug) logger.debug("Update: before PCCollection.next()"); + PCCollection c = (PCCollection)i.next(); + if (debug) logger.debug(c.toString()); + for (int a = 0; a < NUMBER_TO_ADD; ++a) { + if (debug) logger.debug("Update: before Set.add()"); + c.getSet().add(new PCId()); + if (debug) logger.debug("Update: before Map.put()"); + c.getMap().put(new PCId(), new PCId()); + } + } + if (debug) logger.debug("Update: before commit()"); + tx.commit(); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } + + /** Populate an extent of objects. */ + protected void populate() { + PersistenceManager pm = pmf.getPersistenceManager(); + Transaction tx = pm.currentTransaction(); + try { + if (debug) logger.debug("Begin populate"); + PCCollection pcCollection = new PCCollection(); + pcCollection.setSet(new HashSet()); + pcCollection.setMap(new HashMap()); + pcCollection.setId(0); + for (int i = 0; i < NUMBER_TO_INITIALIZE; i++) { + pcCollection.getSet().add(new PCId()); + pcCollection.getMap().put(new PCId(), new PCId()); + } + tx.setOptimistic(false); + tx.begin(); + pm.makePersistent(pcCollection); + tx.commit(); + if (debug) logger.debug("End populate"); + } + finally { + if (tx != null && tx.isActive()) + tx.rollback(); + if (pm != null && !pm.isClosed()) + pm.close(); + } + } +} Added: incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_WeakHashSet.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_WeakHashSet.java?view=auto&rev=158176 ============================================================================== --- incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_WeakHashSet.java (added) +++ incubator/jdo/trunk/ri11/test/java/org/apache/jdo/test/Test_WeakHashSet.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,326 @@ +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed 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. + */ + +/* + * TestWeakHashSet.java + * + */ + +package org.apache.jdo.test; + +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.jdo.test.util.AbstractTest; +import org.apache.jdo.test.util.JDORITestRunner; +import org.apache.jdo.util.WeakHashSet; + + +/** + * + * @author Michael Bouschen + * @author Markus Fuchs + */ +public class Test_WeakHashSet extends AbstractTest { + + static boolean verbose = Boolean.getBoolean("verbose"); + + /** */ + public static void main(String args[]) { + JDORITestRunner.run(Test_WeakHashSet.class); + } + + /** */ + protected void setUp() { } + + /** */ + protected void tearDown() { } + + /** */ + public void testContains() { + // WeakHashSet + Set weakSet = new WeakHashSet(); + + X x11 = new X("x11"); + weakSet.add(x11); + weakSet.add(new X("x12")); + weakSet.add(null); + + // Regular HashSet + Set set = new HashSet(); + X x21 = new X("x21"); + set.add(x21); + set.add(new X("x22")); + set.add(null); + + // check whether instance is included in set + assertTrue("FAILURE: weakSet does not contain x11", weakSet.contains(x11)); + assertTrue("FAILURE: weakSet does not contain x12", weakSet.contains(new X("x12"))); + assertTrue("FAILURE: weakSet does not contain null", weakSet.contains(null)); + assertTrue("FAILURE: set does not contain x21", set.contains(x21)); + assertTrue("FAILURE: set does not contain x22", set.contains(new X("x22"))); + assertTrue("FAILURE: set does not contain null", set.contains(null)); + + if (verbose) System.out.println("\nTest GC:"); + if (verbose) System.out.println("Before GC: " + new XTreeSet(weakSet)); + + // now gc + gc(); + + if (verbose) System.out.println("After GC: " + new XTreeSet(weakSet)); + + // x11 should still be in weakSet + assertTrue("FAILURE: weakSet does not contain x11 after gc", weakSet.contains(x11)); + // x12 should not be in weakSet + assertTrue("FAILURE: weakSet still contains x12 after gc", !weakSet.contains(new X("x12"))); + assertTrue("FAILURE: weakSet does not contain null", weakSet.contains(null)); + + // set should not be affected by gc + assertEquals("FAILURE: set has wrong size ", 3, set.size()); + assertTrue("FAILURE: set does not contain x21 after gc", set.contains(x21)); + assertTrue("FAILURE: set does not contain x22 after gc", set.contains(new X("x22"))); + assertTrue("FAILURE: set does not contain null", set.contains(null)); + + weakSet.clear(); + if (verbose) System.out.println("After Clear: " + new XTreeSet(weakSet)); + } + + /** */ + public void testRemove() { + // WeakHashSet + gc(); + Set weakSet = new WeakHashSet(); + + X x11 = new X("x11"); + weakSet.add(x11); + weakSet.add(new X("x12")); + weakSet.add(null); + + // check whether instance is included in set + assertTrue("FAILURE: weakSet does not contain x11", weakSet.contains(x11)); + assertTrue("FAILURE: weakSet does not contain x12", weakSet.contains(new X("x12"))); + assertTrue("FAILURE: weakSet does not contain null", weakSet.contains(null)); + + if (verbose) System.out.println("\nTest Remove: " + new XTreeSet(weakSet)); + if (verbose) System.out.println("Size = " + weakSet.size()); + assertEquals("Unexpected size of weakSet", 3, weakSet.size()); + + weakSet.remove(x11); + if (verbose) System.out.println("After Remove(x11): " + new XTreeSet(weakSet)); + if (verbose) System.out.println("Size = " + weakSet.size()); + assertEquals("Unexpected size of weakSet", 2, weakSet.size()); + + weakSet.remove(new X("x12")); + if (verbose) System.out.println("After Remove(x12): " + new XTreeSet(weakSet)); + if (verbose) System.out.println("Size = " + weakSet.size()); + assertEquals("Unexpected size of weakSet", 1, weakSet.size()); + + weakSet.remove(null); + if (verbose) System.out.println("After Remove(null): " + new XTreeSet(weakSet)); + if (verbose) System.out.println("Size = " + weakSet.size()); + assertEquals("Unexpected size of weakSet", 0, weakSet.size()); + + weakSet.add(x11); + weakSet.add(new X("x12")); + weakSet.add(null); + + XTreeSet xts = new XTreeSet(weakSet); + if (verbose) System.out.println("\nTest Iterator: " + xts); + if (verbose) System.out.println("Size = " + weakSet.size()); + assertEquals("Unexpected size of weakSet", 3, weakSet.size()); + + int size = 3; + for (Iterator i = weakSet.iterator(); i.hasNext();) { + Object o = i.next(); + if (verbose) System.out.println("iterator.remove: " + o); + i.remove(); + size--; + if (verbose) System.out.println("After remove: " + new XTreeSet(weakSet)); + if (verbose) System.out.println("Size = " + weakSet.size()); + assertEquals("Unexpected size of weakSet", size, weakSet.size()); + } + + weakSet.clear(); + } + + /** */ + public void testAll() { + // WeakHashSet + gc(); + Set weakSet = new WeakHashSet(); + + X x11 = new X("x11"); + weakSet.add(x11); + weakSet.add(new X("x12")); + weakSet.add(null); + + // Regular HashSet + Set set = new HashSet(); + set.add(x11); + set.add(new X("x12")); + set.add(null); + + if (verbose) System.out.println("\nTest containsAll: "); + if (verbose) System.out.println("Weak set Set1: " + new XTreeSet(weakSet)); + if (verbose) System.out.println("Regular set Set2: " + new XTreeSet(set)); + if (verbose) System.out.println("Set1.containsAll(Set2): " + weakSet.containsAll(set)); + assertTrue("Set1.containsAll(Set2) should return true", weakSet.containsAll(set)); + if (verbose) System.out.println("Set2.containsAll(Set1): " + set.containsAll(weakSet)); + assertTrue("Set2.containsAll(Set1) should return true", set.containsAll(weakSet)); + if (verbose) System.out.println("Set2.equals(Set1): " + set.equals(weakSet)); + assertTrue("Set2.equals(Set1) should return true", set.equals(weakSet)); + if (verbose) System.out.println("Set1.equals(Set2): " + weakSet.equals(set)); + assertTrue("Set1.equals(Set2) should return true", weakSet.equals(set)); + + weakSet.add(new X("x13")); + set.add(new X("x14")); + + if (verbose) System.out.println("\nTest containsAll: "); + if (verbose) System.out.println("Weak set Set1: " + new XTreeSet(weakSet)); + if (verbose) System.out.println("Regular set Set2: " + new XTreeSet(set)); + if (verbose) System.out.println("Set1.containsAll(Set2): " + weakSet.containsAll(set)); + assertFalse("Set1.containsAll(Set2) should return false", weakSet.containsAll(set)); + if (verbose) System.out.println("Set2.containsAll(Set1): " + set.containsAll(weakSet)); + assertFalse("Set2.containsAll(Set1) should return false", set.containsAll(weakSet)); + if (verbose) System.out.println("Set2.equals(Set1): " + set.equals(weakSet)); + assertFalse("Set2.equals(Set1) should return false", set.equals(weakSet)); + if (verbose) System.out.println("Set1.equals(Set2): " + weakSet.equals(set)); + assertFalse("Set1.equals(Set2) should return false", weakSet.equals(set)); + + weakSet.remove(new X("x13")); + set.remove(new X("x14")); + + boolean result; + if (verbose) System.out.println("\nTest removeAll: "); + if (verbose) System.out.println("Weak set Set1: " + new XTreeSet(weakSet)); + if (verbose) System.out.println("Regular set Set2: " + new XTreeSet(set)); + result = weakSet.removeAll(set); + if (verbose) System.out.println("Set1.removeAll(Set2): " + result); + assertTrue("weakSet.removeAll(set) should change the weakSet", result); + if (verbose) System.out.println("Weak set Set1: " + new XTreeSet(weakSet)); + assertTrue("weakSet should be empty", weakSet.isEmpty()); + gc(); + + weakSet.add(x11); + weakSet.add(new X("x12")); + weakSet.add(null); + + result = set.removeAll(weakSet); + if (verbose) System.out.println("Set2.removeAll(Set1): " + result); + assertTrue("set.removeAll(weakSet) should change the set", result); + if (verbose) System.out.println("Regular set Set2: " +new XTreeSet( set)); + assertTrue("set should be empty", set.isEmpty()); + + set.add(x11); + set.add(new X("x12")); + set.add(null); + set.add(new X("x14")); + weakSet.add(new X("x13")); + + if (verbose) System.out.println("\nTest removeAll: "); + if (verbose) System.out.println("Weak set Set1: " + new XTreeSet(weakSet)); + if (verbose) System.out.println("Regular set Set2: " + new XTreeSet(set)); + result = weakSet.removeAll(set); + if (verbose) System.out.println("Set1.removeAll(Set2): " + result); + assertTrue("weakSet.removeAll(set) should change the weakSet", result); + if (verbose) System.out.println("Weak set Set1: " + new XTreeSet(weakSet)); + assertEquals("Unexpected size of weakSet", 1, weakSet.size()); + + weakSet.add(x11); + weakSet.add(new X("x12")); + weakSet.add(null); + weakSet.add(new X("x13")); + + result = set.removeAll(weakSet); + if (verbose) System.out.println("Set2.removeAll(Set1): " + result); + assertTrue("set.removeAll(weakSet) should change the set", result); + if (verbose) System.out.println("Regular set Set2: " + new XTreeSet(set)); + assertEquals("Unexpected size of set", 1, set.size()); + + weakSet.clear(); + } + + private static class X { + private String name; + public X(String name) { this.name = name; } + public String toString() { return this.name; } + public int hashCode() { return (name == null) ? 0 : name.hashCode(); } + public boolean equals(Object o) + { + // compare by name only + if ((o == null) || !(o instanceof X)) + return false; + else if (name == null) + return ((X)o).name == null; + else + return name.equals(((X)o).name); + } + } + + /** + * A Sorted set of X instances. + */ + private static class XTreeSet extends TreeSet { + private static final Comparator c = new Comparator() { + public int compare(Object o1, Object o2) { + if (o1 == null) { + return -1; + } else if (o2 == null) { + return 1; + } else { + String s1 = ((X)o1).toString(); + String s2 = ((X)o2).toString(); + if (s1 == null) { + return -1; + } else if (s2 == null) { + return 1; + } else { + return s1.compareTo(s2); + } + } + } + + public boolean equals(Object obj) { + return true; + } + }; + + XTreeSet(Set s) { + super(c); + this.addAll(s); + } + } + + private static void gc() { + //System.out.print("gc: "); + Runtime rt = Runtime.getRuntime(); + long oldfree; + long newfree = rt.freeMemory(); + do { + oldfree = newfree; + rt.runFinalization(); rt.gc(); + newfree = rt.freeMemory(); + //System.out.print('.'); + } while (newfree > oldfree); + //System.out.println(); + } + +} + +